// $Revision: 27$
// $Date: 8/28/2007 3:33:20 PM$

var SESSION = new Session();

//////////////////////////////////////////////////////////////////////////////////////////
// Display message type enum.
//
//////////////////////////////////////////////////////////////////////////////////////////
var SMS_DisplayMessageType =
{
    INFORMATION :0,
    ERROR       :1
};

//////////////////////////////////////////////////////////////////////////////////////////
// View Controller constructor.
//
//////////////////////////////////////////////////////////////////////////////////////////
function SMS_GadgetViewController(source, ver, os)
{
    this.m_source = source;
    this.m_ver = ver;
    this.m_os = os;

    var self = this;

    this.m_downloadTracker = new DownloadTracker( );

    this.LoginAndRegisterControlSynchronizer = new MPC_MobileNumberControlSynchronizer( );

    // Create Auto-login View
    this.AutoLoginView = new SMS_GadgetAutoLoginView(self);
    this.AutoLoginView.m_onGetAccountInfoSuccess = function(responseMessage) {self.onAutoAuthenticateSucceeded(responseMessage);};

    // Create Login View
    this.LoginView = new SMS_GadgetLoginView(self);
    this.LoginView.m_onAuthenticateSuccess = function(responseMessage) {self.onAuthenticateSucceeded(responseMessage);};
    this.LoginView.m_onAuthenticateFail = function(statusMessage) {self.onAuthenticateFailed(statusMessage);};

    // Create Registration View
    this.RegistrationView = new SMS_GadgetRegistrationView(self);
    this.RegistrationView.m_onRegisterAccountSuccess = function(responseMessage) {self.onRegisterSucceeded(responseMessage);};
    this.RegistrationView.m_onRegisterAccountFail = function(statusMessage) {self.onRegisterFailed(statusMessage);};

    // Create Verification View
    this.VerificationView = new SMS_GadgetVerifyView(self);
    this.VerificationView.m_onVerificationSuccess = function(responseMessage) {self.onVerifySucceeded(responseMessage);};
    this.VerificationView.m_onVerificationFail = function(statusMessage) {self.onVerifyFailed(statusMessage);};

    // Create Message View
    this.MessageView = new SMS_GadgetMessageView(self);
}

//////////////////////////////////////////////////////////////////////////////////////////
// View Controller prototype.
//
//////////////////////////////////////////////////////////////////////////////////////////
SMS_GadgetViewController.prototype =
{
    //////////////////////////////////////////////////////////////////////////////////////////
    // int()
    // The init() function is called by the document body's onload function.
    //////////////////////////////////////////////////////////////////////////////////////////
    init : function()
    {
        // Init all of the views.
        this.AutoLoginView.init();
        this.LoginView.init();
        this.RegistrationView.init();
        this.VerificationView.init();
        this.MessageView.init();

        this.LoginAndRegisterControlSynchronizer.Initialize( );

        // Check for stored preferences.
        var acctNumber   = VM_GetPreference( PREF_KEY_ACCOUNT );
        var uString      = VM_GetPreference( PREF_KEY_U_STRING );
        
        // Check the authentication credentials to determine whether auto-connect is possible.
        if (! ( acctNumber == null || uString == null || acctNumber.length == 0 || uString.length == 0 ) )
        {
            // Attempt auto-connect.
            this.displayAutoLoginView();
            return;
        }

        // One or more are missing.  Clear both and proceed to the Login screen.
        this.clearStoredCredentials( );

        var phoneData = SMS_MobileNumberControlPersistentState.prototype.CreateFromString( VM_GetPreference( PREF_KEY_SENDER_MOBILE ) );

        // Is there user info in the preferences?
        if ( ! phoneData.IsEmpty( ) )
        {
            // Display Login screen, since this user has been authenticated previously.
            this.displayManualLoginView();
        }
        else
        {
            // Display Registration screen.
            this.displayRegistrationView();
        }
    },


    //////////////////////////////////////////////////////////////////////////////////////////
    // View-management functions.
    // These functions control UI display and content behaviors.
    //////////////////////////////////////////////////////////////////////////////////////////

    // Control the title bar.  Reserved area for screen title.
    showTitle : function(msg)
    {
        document.getElementById('MAIN_Title').innerHTML = msg;

        // Try table-row value, which works well for Firefox in this context.
        // It will throw an exception for IE, and that will be caught and the block
        // value will be used.
        try
        {
            document.getElementById('MAIN_TitleRow').style.display = 'table-row';
            document.getElementById('MAIN_SpacerRow1').style.display = 'table-row';
            document.getElementById('MAIN_SpacerRow2').style.display = 'table-row';
        }
        catch (e)
        {
            document.getElementById('MAIN_TitleRow').style.display = 'block';
            document.getElementById('MAIN_SpacerRow1').style.display = 'block';
            document.getElementById('MAIN_SpacerRow2').style.display = 'block';
        }
    },

    hideTitle : function()
    {
        document.getElementById('MAIN_TitleRow').style.display = 'none';
        document.getElementById('MAIN_SpacerRow1').style.display = 'none';
        document.getElementById('MAIN_SpacerRow2').style.display = 'none';
    },

    // Control status message bar.  Reserved area for info/error status messages.
    setStatusMsgInfo : function(msg)
    {
        this.setStatusMsg(SMS_DisplayMessageType.INFORMATION, msg);
    },

    setStatusMsgError : function(msg)
    {
        this.setStatusMsg(SMS_DisplayMessageType.ERROR, msg);
    },

    setStatusMsg : function(type, msg)
    {
        switch (type) {
            case SMS_DisplayMessageType.ERROR:
            {
                // set style for error msg
                document.getElementById('MAIN_StatusMessage').className = "statusMsgError"
                break;
            }
            case SMS_DisplayMessageType.INFORMATION:
            {
                // set style for info msg
                document.getElementById('MAIN_StatusMessage').className = "statusMsgInfo"
                break;
            }
        }

        document.getElementById('MAIN_StatusMessage').innerHTML = msg;

        // Call IG_AdjustIFrameHeight() in case the message wraps and we need to re-size the
        // container.
        GOOGLE_IG_AdjustIFrameHeight();
    },

    resetDisplay : function() {
        this.clearStatusMsg();
        this.AutoLoginView.hide();
        this.LoginView.hide();
        this.RegistrationView.hide();
        this.VerificationView.hide();
        this.MessageView.hide();
    },

    clearStatusMsg : function() {
        document.getElementById('MAIN_StatusMessage').innerHTML = '&nbsp;';
    },

    // Control screen display.
    displayAutoLoginView : function()
    {
        this.resetDisplay();
        this.showTitle("Auto-connect");
        this.AutoLoginView.display();

        GOOGLE_IG_AdjustIFrameHeight();
    },

    displayManualLoginView : function()
    {
        this.resetDisplay();
        this.showTitle("Log In");
        this.LoginView.display();

        GOOGLE_IG_AdjustIFrameHeight();
    },

    displayManualLoginViewRegPINMismatch : function(phoneNumber, countryCd)
    {
        this.resetDisplay();
        this.showTitle("Log In");
        this.LoginView.displayManualLoginViewRegPINMismatch(phoneNumber, countryCd);

        GOOGLE_IG_AdjustIFrameHeight();
    },

    displayRegistrationView : function()
    {
        this.resetDisplay();
        this.showTitle("Register");
        this.RegistrationView.display();

        GOOGLE_IG_AdjustIFrameHeight();
    },

    displayVerificationView : function()
    {
        this.resetDisplay();
        this.showTitle("Verify Phone");
        this.VerificationView.display();

        GOOGLE_IG_AdjustIFrameHeight();
    },

    displayMessageView : function()
    {
        this.resetDisplay();
        this.hideTitle();
        this.MessageView.display();

        GOOGLE_IG_AdjustIFrameHeight();
    },


    //////////////////////////////////////////////////////////////////////////////////////////
    // AUTO LOGIN - AUTHENTICATION
    //
    //////////////////////////////////////////////////////////////////////////////////////////
    onAutoAuthenticateSucceeded : function(responseMessage)
    {
        try {
            switch (responseMessage.m_status) {
                case MSG_ResponseStatus.SUCCESS:
                // Success
                {
                    // Store user info in the preferences.
                    this.storeUserInfo(responseMessage.m_name, 
                                       responseMessage.m_phoneCC + responseMessage.m_phoneNN, 
                                       responseMessage.m_phoneCC, 
                                       responseMessage.m_email);

                    // Load the session object with account-related information and SMS parameters.
                    SESSION.setVal(Session_Key.WX_PHONE_VERIFIED, responseMessage.m_phoneVerified);
                    SESSION.setVal(Session_Key.WX_PHONE_CC, responseMessage.m_phoneCC);
                    SESSION.setVal(Session_Key.WX_PHONE_NN, responseMessage.m_phoneNN);
                    SESSION.setVal(Session_Key.WX_CARRIER, responseMessage.m_carrierId);
                    SESSION.setVal(Session_Key.WX_SHOW_CARRIERS, responseMessage.m_showCarriers);
                    SESSION.setVal(Session_Key.WX_HIDE_REG_CARRIERS, responseMessage.m_hideRegCarrier);
                    SESSION.setVal(Session_Key.WX_EMAIL, responseMessage.m_email);
                    SESSION.setVal(Session_Key.WX_MAX_SMS_PARTS, responseMessage.m_maxSMSParts);
                    SESSION.setVal(Session_Key.WX_SMS_BODY_OH, responseMessage.m_smsBodyOH);

                    // Has this phone already been verified?
                    if (responseMessage.m_phoneVerified == 1)
                    {
                        // Yes.  Go straight to the SMS screen.
                        this.displayMessageView();
                    }
                    else {
                        // No.  To verify account/carrier, the user must request a V-Code...and after receiving it must verify/activate
                        // the phone and account for SMS.  This will be handled at the Verify screen.
                        this.displayVerificationView();
                    }

                    break;
                }

                default:
                // Error.
                {
                    // Show Login screen.
                    this.displayManualLoginView("Please enter your registered phone number and PIN to log in.");

                    break;
                }
            }
        }
        catch (e)
        {
            this.setStatusMsgError("Application exception.");
        }
    },
    //
    //////////////////////////////////////////////////////////////////////////////////////////


    //////////////////////////////////////////////////////////////////////////////////////////
    // MANUAL LOGIN - AUTHENTICATION
    //
    //////////////////////////////////////////////////////////////////////////////////////////
    onAuthenticateSucceeded : function(responseMessage)
    {
        try
        {
            switch (responseMessage.m_status)
            {
                case MSG_ResponseStatus.SUCCESS:
                {
                    // Store user info in the preferences.
                    this.storeUserInfo(responseMessage.m_name, 
                                       responseMessage.m_phoneCC + responseMessage.m_phoneNN, 
                                       responseMessage.m_phoneCC, 
                                       responseMessage.m_email);

                    // Load the session object with account-related information and SMS parameters.
                    // acctNumber and uString are set by the LoginView class.
                    SESSION.setVal(Session_Key.WX_PHONE_VERIFIED, responseMessage.m_phoneVerified);
                    SESSION.setVal(Session_Key.WX_PHONE_CC, responseMessage.m_phoneCC);
                    SESSION.setVal(Session_Key.WX_PHONE_NN, responseMessage.m_phoneNN);
                    SESSION.setVal(Session_Key.WX_CARRIER, responseMessage.m_carrierId);
                    SESSION.setVal(Session_Key.WX_SHOW_CARRIERS, responseMessage.m_showCarriers);
                    SESSION.setVal(Session_Key.WX_HIDE_REG_CARRIERS, responseMessage.m_hideRegCarrier);
                    SESSION.setVal(Session_Key.WX_EMAIL, responseMessage.m_email);
                    SESSION.setVal(Session_Key.WX_MAX_SMS_PARTS, responseMessage.m_maxSMSParts);
                    SESSION.setVal(Session_Key.WX_SMS_BODY_OH, responseMessage.m_smsBodyOH);

                    // Has this phone already been verified?
                    if (responseMessage.m_phoneVerified == 1)
                    {
                        // Yes.  Go straight to the SMS screen.
                        this.displayMessageView();
                    }
                    else {
                        // No.  To verify account/carrier, the user must request a V-Code...and after receiving it must verify/activate
                        // the phone and account for SMS.  This will be handled at the Verify screen.
                        this.displayVerificationView();
                    }

                    break;
                }

                case MSG_ResponseStatus.GENERAL_ERROR:
                case MSG_ResponseStatus.AUTH_PIN_MISMATCH:
                case MSG_ResponseStatus.AUTH_ACCOUNT_LOCKED:
                // Login failure.
                // In these cases, display the message that comes back with the response,
                // since these are known conditions.
                {
                    // Display the response status message.
                    this.setStatusMsg(SMS_DisplayMessageType.ERROR, responseMessage.m_statusMsg);

                    break;
                }

                default:
                {
                    this.setStatusMsg(SMS_DisplayMessageType.ERROR, "Login failed.  Please try again.");

                    break;
                }
            }
        }
        catch (e)
        {
            this.setStatusMsgError("Application exception.");
        }
    },

    onAuthenticateFailed : function(statusMessage)
    {
        try
        {
            this.setStatusMsg(SMS_DisplayMessageType.ERROR, "Login failed. Please try again.");
        }
        catch (e)
        {
            this.setStatusMsgError("Application exception.");
        }
    },
    //
    //////////////////////////////////////////////////////////////////////////////////////////


    //////////////////////////////////////////////////////////////////////////////////////////
    // REGISTER
    //
    //////////////////////////////////////////////////////////////////////////////////////////
    onRegisterSucceeded : function(responseMessage)
    {
        try
        {
            switch(responseMessage.m_status)
            {
                case MSG_ResponseStatus.SUCCESS:
                // Success
                {
                    // Store user info in the preferences.
                    this.storeUserInfo(responseMessage.m_name, 
                                       responseMessage.m_phoneCC + responseMessage.m_phoneNN, 
                                       responseMessage.m_phoneCC, 
                                       responseMessage.m_email);
                                       
                    // Load the session object with account-related information and SMS parameters.
                    // acctNumber and uString are set by the RegisterView class.
                    SESSION.setVal(Session_Key.WX_PHONE_VERIFIED, responseMessage.m_phoneVerified);
                    SESSION.setVal(Session_Key.WX_PHONE_CC, responseMessage.m_phoneCC);
                    SESSION.setVal(Session_Key.WX_PHONE_NN, responseMessage.m_phoneNN);
                    SESSION.setVal(Session_Key.WX_CARRIER, responseMessage.m_carrierId);
                    SESSION.setVal(Session_Key.WX_SHOW_CARRIERS, responseMessage.m_showCarriers);
                    SESSION.setVal(Session_Key.WX_HIDE_REG_CARRIERS, responseMessage.m_hideRegCarrier);
                    SESSION.setVal(Session_Key.WX_EMAIL, responseMessage.m_email);
                    SESSION.setVal(Session_Key.WX_MAX_SMS_PARTS, responseMessage.m_maxSMSParts);
                    SESSION.setVal(Session_Key.WX_SMS_BODY_OH, responseMessage.m_smsBodyOH);

                    // Has this phone already been verified?
                    if (responseMessage.m_phoneVerified == 1)
                    {
                        // Yes.  Go straight to the SMS screen.
                        this.displayMessageView();
                    }
                    else {
                        // No.  To verify account/carrier, the user must request a V-Code...and after receiving it must verify/activate
                        // the phone and account for SMS.  This will be handled at the Verify screen.
                        this.displayVerificationView();
                    }

                    break;
                }

                case MSG_ResponseStatus.REGA_PIN_MISMATCH:
                // This error would come back for a Re-reg situation.  Here the account exists
                // but the PIN doesn't match the one we have on file.
                // Display the Manual Login View and present the status message returned by
                // the server.
                {
                    this.displayManualLoginView(responseMessage.m_statusMsg);

                    break;
                }

                default:
                // Other error.
                // Stay on the Registration Screen and present server error message.
                {
                    this.setStatusMsg(SMS_DisplayMessageType.ERROR, responseMessage.m_status);

                    break;
                }
            }
        }
        catch (e)
        {
            this.setStatusMsgError("Application exception.");
        }
    },

    onRegisterFailed : function(statusMessage)
    {
        try
        {
            this.setStatusMsg(SMS_DisplayMessageType.ERROR, "Registration failed.  Please try again later.");
        }
        catch (e)
        {
            this.setStatusMsgError("Application exception.");
        }
    },
    //
    //////////////////////////////////////////////////////////////////////////////////////////


    //////////////////////////////////////////////////////////////////////////////////////////
    // VERIFY PHONE
    //
    //////////////////////////////////////////////////////////////////////////////////////////
    onVerifySucceeded : function(responseMessage)
    {
        try
        {
            switch (responseMessage.m_status)
            {
                // Success.
                case MSG_ResponseStatus.SUCCESS:
                {
                    // Display the SMS screen.
                    this.displayMessageView();

                    break;
                }

                // Login failure.
                case MSG_ResponseStatus.VPHO_LOGIN_FAILURE:
                {
                    // Display Manual Login View, and present the message returned by the server.
                    this.displayManualLoginView(responseMessage.m_statusMsg);

                    break;
                }

                // Country not supported.
                case MSG_ResponseStatus.VPHO_COUNTRY_NOT_SUPPORTED:
                {
                    // Display Manual Login View, and present the message returned by the server.
                    this.setStatusMsg(SMS_DisplayMessageType.ERROR, responseMessage.m_statusMsg);

                    break;
                }

                case MSG_ResponseStatus.GENERAL_ERROR:
                {
                    // Present the message returned by the server.
                    this.setStatusMsg(SMS_DisplayMessageType.ERROR, responseMessage.m_statusMsg);

                    break;
                }

                default:
                {
                    // Present the message returned by the server.
                    this.setStatusMsg(SMS_DisplayMessageType.ERROR, responseMessage.m_statusMsg);

                    break;
                }
            }
        }
        catch (e)
        {
            this.setStatusMsgError("Application exception.");
        }
    },

    onVerifyFailed : function(statusMessage)
    {
        try
        {
            this.setStatusMsg(SMS_DisplayMessageType.ERROR, "Account verification failed.  Please try again.");
        }
        catch (e)
        {
            this.setStatusMsgError("Application exception.");
        }
    },
    //
    //////////////////////////////////////////////////////////////////////////////////////////


    //////////////////////////////////////////////////////////////////////////////////////////
    // Miscellaneous
    //
    //////////////////////////////////////////////////////////////////////////////////////////
    cancelAutoConnect : function(exception)
    {
        // Do nothing with the exception, if there is one, as of this release.
        this.displayManualLoginView();
    },

    startOverRegistration : function()
    {
        this.clearStoredCredentials( );

        SESSION.setVal(Session_Key.WX_PHONE_VERIFIED, null);
        SESSION.setVal(Session_Key.WX_PHONE_CC, null);
        SESSION.setVal(Session_Key.WX_PHONE_NN, null);
        SESSION.setVal(Session_Key.WX_CARRIER, null);
        SESSION.setVal(Session_Key.WX_SHOW_CARRIERS, null);
        SESSION.setVal(Session_Key.WX_HIDE_REG_CARRIERS, null);
        SESSION.setVal(Session_Key.WX_EMAIL, null);
        SESSION.setVal(Session_Key.WX_MAX_SMS_PARTS, null);
        SESSION.setVal(Session_Key.WX_SMS_BODY_OH, null);

        // Display Registration View.
        this.displayRegistrationViewStartOver();
    },

    handleRegPINMismatch : function(phoneNumber, countryCd)
    {
        this.displayManualLoginViewRegPINMismatch(phoneNumber, countryCd);
        this.setStatusMsgError("Phone already registered. Please log in using the same PIN.")
    },

    logOff : function()
    {
        // Re-set the session object.
        SESSION.clear();

        // Clear the acctNumber and uString from the preferences.
        this.clearStoredCredentials();

        // Display the Login screen.
        this.displayManualLoginView();
    },

    storeUserInfo : function(name, phoneNumber, countryCd, emailAddress )
    {
        VM_SetPreference( PREF_KEY_SENDER_NAME, name );

        VM_SetPreference( PREF_KEY_SENDER_MOBILE,
                          new SMS_MobileNumberControlPersistentState( countryCd, '', phoneNumber ).AsString( ) );

        VM_SetPreference( PREF_KEY_SENDER_EMAIL, emailAddress );
    },

    storeCredentials : function(acctNumber, uString)
    {
        VM_SetPreference( PREF_KEY_ACCOUNT , acctNumber );
        VM_SetPreference( PREF_KEY_U_STRING, uString );
    },

    clearStoredCredentials : function()
    {
        VM_SetPreference( PREF_KEY_ACCOUNT , '' );
        VM_SetPreference( PREF_KEY_U_STRING, '' );
    },

    openURL : function(url)
    {
        window.open(url, '');
    },

    getDefaultUrlQueryParameters : function()
    {
        var uParam = '';

        var uString = VM_GetPreference( PREF_KEY_U_STRING );

        if ( uString !== null && uString != '' )
        {
            uParam = "u=" + uString + "&";
        }

        return "?" + uParam + "src=" + this.m_source + "&ver=" + this.m_ver + "&os=" + this.m_os;
    }
}
