// File: $callWave/web/web site/htdocs/widgets/login/resources/js/LoginView.js
// Desc: View-controller class for Login widget.
// $Revision: 10$
// $Date: 6/20/2008 1:01:52 PM$
// $Author: Amy Love$

// Constructor ---------------------------------------------------------------------------------------------
function LOGIN_ViewController(environment, uri, source, ver, os, showCountry, phoneNumber, onSuccess)
{
    // Attributes
    this.m_environment = environment; 
    this.m_targetService = 'web';
    this.m_serverURI = uri;
    this.m_showCountry = showCountry; 
    this.m_mobileNumberControl = null;     
    this.m_j2LoginHandler = new LoginHandler(source, ver, os); 
    this.m_loginHandler = new LoginHandler(source, ver, os);
    this.m_onSuccess = onSuccess; 
    this.m_phoneNumber = phoneNumber;
    
    var self = this;
    
    // ACC_AccountHandler Callbacks
    this.m_j2LoginHandler.m_onAuthenticateSucceeded = function(responseMessage) {self.onAuthenticateSucceeded(responseMessage);};
    this.m_j2LoginHandler.m_onAuthenticateFailed = function(statusMessage) {self.onJ2AuthenticateFailed(statusMessage);};
    this.m_loginHandler.m_onAuthenticateSucceeded = function(responseMessage) {self.onAuthenticateSucceeded(responseMessage);};
    this.m_loginHandler.m_onAuthenticateFailed = function(statusMessage) {self.onAuthenticateFailed(statusMessage);};
}

// Prototype -----------------------------------------------------------------------------------------------
LOGIN_ViewController.prototype.ELEM_ID_MSG = 'LOGIN_Msg';
LOGIN_ViewController.prototype.ELEM_ID_COUNTRY_ROW = 'LOGIN_CountryRow';
LOGIN_ViewController.prototype.ELEM_ID_COUNTRY = 'LOGIN_CountryCd';
LOGIN_ViewController.prototype.ELEM_ID_PHONE = 'LOGIN_PhoneNumber';
LOGIN_ViewController.prototype.ELEM_ID_PIN = 'LOGIN_PIN';
LOGIN_ViewController.prototype.ELEM_ID_SUBMIT = 'LOGIN_SubmitButton';
LOGIN_ViewController.prototype.ELEM_ID_REMEMBER_ME = 'LOGIN_RememberMe';

LOGIN_ViewController.prototype.init = function()
{
    this.m_j2LoginHandler.setProxyPath(this.m_serverURI + '/web/proxy.aspx?url=http%3A%2F%2Fwww2wxlogin.callwave.com%2Fv2w');
    this.m_loginHandler.setProxyPath(this.m_serverURI + '/web/proxy.aspx?url=http%3A%2F%2Fwx0.callwave.com%2Fv2w');
	    
    if (this.m_showCountry) {
        this.m_mobileNumberControl = new SMS_MobileNumberControl( this.ELEM_ID_COUNTRY, this.ELEM_ID_PHONE );
    }
    else
    {
        this.getElement(this.ELEM_ID_COUNTRY_ROW).style.display = 'none';
    }
    
    this.display();
    this.getElement(this.ELEM_ID_PHONE).value = this.m_phoneNumber;
    this.m_mobileNumberControl.OnNumberFieldLoseFocus();	 
}
      
// Display ------------------------------------------------------------------------------------------------- 
LOGIN_ViewController.prototype.display = function()
{  
    // Ready the form for data entry.
    this.enableForm();
    
    this.setStatusMsgInfo("To access this section, you must be logged in. Please enter your <br />registered phone number, country and password to continue.")
}

LOGIN_ViewController.prototype.getElement = function(id) {
    return document.getElementById(id);
}

LOGIN_ViewController.prototype.displayElement = function(id) {
    this.getElement(id).style.display = 'block';
}

LOGIN_ViewController.prototype.hideElement = function(id) {
    this.getElement(id).style.display = 'none';
}

LOGIN_ViewController.prototype.enableElement = function(id) {
    this.getElement(id).removeAttribute("disabled");
}

LOGIN_ViewController.prototype.disableElement = function(id) {
    this.getElement(id).setAttribute("disabled", "true");        
}

LOGIN_ViewController.prototype.setCursorWait = function() {
    document.body.style.cursor = 'wait';
}

LOGIN_ViewController.prototype.setCursorDefault = function() {
    document.body.style.cursor = 'default';
}

LOGIN_ViewController.prototype.enableForm = function()
{
    if (this.m_showCountry) {
        this.enableElement(this.ELEM_ID_COUNTRY);
    }
    this.enableElement(this.ELEM_ID_PHONE);        
    this.enableElement(this.ELEM_ID_PIN);
    this.enableElement(this.ELEM_ID_SUBMIT);
    this.setCursorDefault();  
}    
    
LOGIN_ViewController.prototype.disableForm = function()
{
    if (this.m_showCountry) {
        this.disableElement(this.ELEM_ID_COUNTRY);
    }
    this.disableElement(this.ELEM_ID_PHONE);        
    this.disableElement(this.ELEM_ID_PIN);
    this.disableElement(this.ELEM_ID_SUBMIT);
    this.setCursorWait();                
}

LOGIN_ViewController.prototype.setStatusMsgInfo = function(msg)
{
    this.setStatusMsg(1, msg);
}

LOGIN_ViewController.prototype.setStatusMsgError = function(msg)
{
    this.setStatusMsg(2, msg);
}

LOGIN_ViewController.prototype.setStatusMsg = function(type, msg)
{
    switch (type) {
        case 1:
	    {
		    // set style for info msg
		    this.getElement(this.ELEM_ID_MSG).style.color = "black"
		    break;
	    }	    
	    case 2:
	    {
		    // set style for error msg
		    this.getElement(this.ELEM_ID_MSG).style.color = "#bf0000"
		    break;
	    }	    
    }
    
    this.getElement(this.ELEM_ID_MSG).innerHTML = msg;
}
   
LOGIN_ViewController.prototype.getCountryCd = function()
{
    if (this.m_showCountry) {
        return this.m_mobileNumberControl.GetCountryCode()
    }
    else
    {
        return '1';
    }   
}

LOGIN_ViewController.prototype.selectCountryCd = function()
{
    this.getElement(this.ELEM_ID_COUNTRY).focus();
}

LOGIN_ViewController.prototype.getPhoneNumber = function()
{
    if (this.m_showCountry) {
        var numberValidationData = this.m_mobileNumberControl.GetValidatedNumber( );

    	if ( ! numberValidationData.ERROR_MESSAGE )
    	{
           return numberValidationData.PHONE_NUMBER.GetFullyQualifiedString();
        }

        this.setStatusMsgError(numberValidationData.ERROR_MESSAGE);
    }
    else
    {
        return getElement(this.ELEM_ID_PHONE).value; 
    }
}

LOGIN_ViewController.prototype.selectPhoneNumber = function()
{
    this.getElement(this.ELEM_ID_PHONE).focus();
    this.getElement(this.ELEM_ID_PHONE).select();
}

LOGIN_ViewController.prototype.getPIN = function()
{
    return this.getElement(this.ELEM_ID_PIN).value;
}

LOGIN_ViewController.prototype.setPIN = function(val)
{
    return this.getElement(this.ELEM_ID_PIN).value = val;
}


LOGIN_ViewController.prototype.selectPIN = function()
{
    this.getElement(this.ELEM_ID_PIN).focus();
    this.getElement(this.ELEM_ID_PIN).select();
}

LOGIN_ViewController.prototype.handleKeyDown = function(evt) {           
    if (this.keyDownIsEnter(evt)) {
        this.getElement(this.ELEM_ID_SUBMIT).focus(); 
        this.handleLoginSubmit();
    }
}

LOGIN_ViewController.prototype.keyDownIsEnter = function(evt)
{
	evt = (evt) ? evt : event;

    var charCode = (evt.charCode) ? evt.charCode : ((evt.which) ? evt.which : evt.keyCode);

    return (charCode == 13 || charCode == 3);
}

LOGIN_ViewController.prototype.handleLoginSubmit = function()
{
    try
    {
        this.disableForm();

        var countryCd = this.getCountryCd();
        var phoneNumber = this.getPhoneNumber();
        var pin = this.getPIN();        
              
        // Run input fields through basic validation.
        // If failed, exit here.
        if (!this.validateFormEntry(countryCd, phoneNumber, pin))
        {
            return;
        }                     
                   
        this.setStatusMsgInfo("Connecting...please wait...");     
             
        // Use J2 login handler initially; if that fails, will resort to standard one
        this.m_j2LoginHandler.authenticate(phoneNumber, pin);
    }
    catch (e)
    {    
      //alert(UTILS.dump(e));
        this.enableForm();        
        this.setStatusMsgError("Login failed.");                     
    }
}

LOGIN_ViewController.prototype.validateFormEntry = function(countryCd, phoneNumber, pin)
{       
    if (phoneNumber === undefined)
    {
        this.setStatusMsgError("Invalid mobile number.");
        this.enableForm();       
        this.selectPhoneNumber();            
        return false;
    }

    if (phoneNumber.length == 0)
    {
        this.setStatusMsgError("Invalid mobile number.");
        this.enableForm();       
        this.selectPhoneNumber();            
        return false;
    }
    
    if (countryCd == "-1") {               
        this.setStatusMsgError("Please select your country.");
        this.enableForm();
        this.selectCountryCd();        
	    return false;
    }
        
    if (pin.length < 4 || pin.length > 10 || !this.isNumeric(pin)) {
        this.setPIN("");            
        this.setStatusMsgError("Invalid PIN.");
        this.enableForm();
        this.selectPIN();
        
        return false;
    }
      
    return true;        
}

LOGIN_ViewController.prototype.isNumeric = function(sText)
{
    var validChars = "0123456789";
    var isNumber = true;
    var chr;

    for (i = 0; i < sText.length && isNumber == true; i++) 
    { 
      chr = sText.charAt(i); 
      if (validChars.indexOf(chr) == -1) 
         {
            isNumber = false;
         }
    }
    
    return isNumber;
}

LOGIN_ViewController.prototype.onAuthenticateSucceeded = function(responseMessage)
{
   this.enableForm();
    
    try
    { 
        switch (responseMessage.m_status) {
	        case MSG_ResponseStatus.SUCCESS:
	        // Success
	        {              
	            // Return authentication info to caller.		        
		        this.m_onSuccess(responseMessage.m_uString);
    		    				
		        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.setStatusMsgError(responseMessage.m_statusMsg);
    	        
                break;
            }

            case 17:
            // J2 fax account
            {
                // Redirect to J2
                window.location = 'http://www.eFax.com/login?CMP=4callwave';

                break;
            }

	        default:
	        // Unexpected error.
            { 
                // Display generic message.
		        this.setStatusMsgError("Login failed.  Please try again.");
    			
		        break;
	        }
        }      
    }
    catch (e)
    {
        this.setStatusMsgError("Login failed.");
    }             
}

LOGIN_ViewController.prototype.onJ2AuthenticateFailed = function(statusMessage)
{
    try
    { 
        this.enableForm();
    
        // Resort to standard standard login handler since J2 one failed
        this.m_loginHandler.authenticate(this.getPhoneNumber(), this.getPIN());
    }
    catch (e)
    {
        this.setStatusMsgError("Login failed.");
    }             
}

LOGIN_ViewController.prototype.onAuthenticateFailed = function(statusMessage)
{
    try
    { 
        this.enableForm();
    
        if (statusMessage.substring(0, 30) == 'Unable to process HTTP request')
        {
            this.setStatusMsgError("Connection failed.  Please try again later.");
        }
        else
        {
            this.setStatusMsgError("Login failed.  Please try again later.");
        }
    }
    catch (e)
    {
        this.setStatusMsgError("Login failed.");
    }             
}

