/***************************************
 * Register Globals
 ***************************************/
var _txt_FirstNameId;
var _txt_LastNameId;
var _txt_UserNameId;
var _txt_EmailId;
var _txt_ConfirmEmailId;
var _txt_PasswordId;
var _txt_ConfrimPasswordId;
var _txt_PhoneAreaCodeId;
var _txt_PhoneExchangeId;
var _txt_PhoneLastFourId;
var _txt_CompanyNameId;
var _txt_CompanyResellerId;
var _txt_CompanyUrlId;
var _tabStrip_AddressId;
/*var _chk_SameAddressId;
var _txt_BillingAddress1Id;
var _txt_BillingAddress2Id;
var _txt_BillingCityId;
var _ddl_BillingStateId;
var _txt_BillingZipId;*/
var _txt_ShippingAddress1Id;
var _txt_ShippingAddress2Id;
var _txt_ShippingCityId;
var _ddl_ShippingStateId;
var _txt_ShippingZipId;
var _btn_SubmitId = 'btnRegister';

var _req_lblUserNameId      = 'reqUserName';
var _req_lblLastNameId      = 'reqLastName';
var _req_lblFirstNameId     = 'reqFirstName';
var _req_lblEmailId         = 'reqEmail';
var _req_lblConfirmEmailId  = 'reqConfirmEmail';
var _req_lblPasswordId      = 'reqPassword';
var _req_lblConfirmPasswordId = 'reqConfirmPassword';
var _req_lblEmailSameId     = 'reqEmailSame';
var _req_lblPassowrdSameId  = 'reqPassowrdSame';
var _req_lblPhoneId         = 'reqPhone';
var _req_lblShipAddId       = 'reqShipAddress1';
var _req_lblShipCityId      = 'reqShipCity';
var _req_lblShipStateId     = 'reqShipState';
var _req_lblShipZipId       = 'reqShipZip';

//var _error_Messages                             = new Array();
var _txt_CustomerKeyId      = 'txtCustomerKey';
var _isValid                                    = false;
var _loginExists                                = false;
var _btn_submit_clicked                         = false;
var ciGrow                                      = null;
var ciShrink                                    = null;

function btnSubmit_Click()
{
    if(!_isValid && !_btn_submit_clicked)
    {
        _btn_submit_clicked = true;
        CheckIfLoginExists($('txtUserName').value);
        _btn_submit_clicked = false;
    }
    
    return false;
}

//----------------------------------------------------------//
//	IsValidEmail:											//
//	bool													//
//----------------------------------------------------------//
function IsValidEmail(val)
{
	var emailRegex = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
	return emailRegex.test(val);
}

function ValidateRegister()
{
    var fn = $('txtFirstName');
    var ln = $('txtLastName');
    var cn = $('txtCompanyName');
    var ad = $('txtAddress');
    var ct = $('txtCity');
    var st = $('ddlState');
    var zp = $('txtZip');
    var ri = $('txtResellerId');
    var pnac = $('txtPhoneNumberAreaCode');
    var pnex = $('txtPhoneNumberExchange');
    var pnlf = $('txtPhoneNumberLastFour');
    var cu = $('txtCompanyURL');
    var em = $('txtEmail');
    var emc = $('txtEmailConfirm');
    var un = $('txtUserName');
    var pw = $('txtPassword');
    var pc = $('txtPasswordConfirm');
    
    if(!(fn) && (ln) && (ad) && (ct) && (st) && (zp) && (pnac) && (pnex) && (pnlf) && (em) && (emc) && (un) && (pw) && (pw) && (pc))
    {
        MessageBox("One of the elements required for validation does not exist.",0,0,_messagebox_yellow);
        PreventPostBack(event);
        return;
    }
    else
    {
        if (fn.value == null || fn.value == "" || fn.value.length == 0)
        {
            MessageBox("Please enter a first name.",0,0,_messagebox_yellow);
            PreventPostBack(event);
            return;
        }
        
        if (ln.value == null || ln.value == "" || ln.value.length == 0)
        {
            MessageBox("Please enter a last name.",0,0,_messagebox_yellow);
            PreventPostBack(event);
            return;
        }
        
        if (ad.value == null || ad.value == "" || ad.value.length == 0)
        {
            MessageBox("Please enter an address.",0,0,_messagebox_yellow);
            PreventPostBack(event);
            return;
        }
        
        if (ct.value == null || ct.value == "" || ct.value.length == 0)
        {
            MessageBox("Please enter a city.",0,0,_messagebox_yellow);
            PreventPostBack(event);
            return;
        }
        
        if (st.selectedIndex == 0)
        {
            MessageBox("Please select a state.",0,0,_messagebox_yellow);
            PreventPostBack(event);
            return;
        }
        
        if (zp.value == null || zp.value == "" || zp.value.length == 0 || isNaN(zp.value) || zp.value.length < 5)
        {
            MessageBox("Please enter a zip code.",0,0,_messagebox_yellow);
            PreventPostBack(event);
            return;
        }
        
        if (pnac.value == null || pnac.value == "" || pnac.value.length < 3 || isNaN(pnac.value))
        {
            MessageBox("Please enter an area code.",0,0,_messagebox_yellow);
            PreventPostBack(event);
            return;
        }
        
        if (pnex.value == null || pnex.value == "" || pnex.value.length < 3|| isNaN(pnex.value))
        {
            MessageBox("Please enter a telephone exchange.",0,0,_messagebox_yellow);
            PreventPostBack(event);
            return;;
        }
        
        if (pnlf.value == null || pnlf.value == "" || pnlf.value.length < 4|| isNaN(pnlf.value))
        {
            MessageBox("Please enter a phone number.",0,0,_messagebox_yellow);
            PreventPostBack(event);
            return;
        }
        
        if (!(IsValidEmail(em.value)))
        {
            MessageBox("Please enter an email address.",0,0,_messagebox_yellow);
            PreventPostBack(event);
            return;
        }
        
        if (!(em.value == emc.value))
        {
            MessageBox("The email addresses do not match.",0,0,_messagebox_yellow);
            PreventPostBack(event);
            return;
        }
        
        if (un.value == null || un.value == "" || un.value.length == 0)
        {
            MessageBox("Please enter your desired username.",0,0,_messagebox_yellow);
            PreventPostBack(event);
            return;
        }
        else
        {
            if(_loginExists)
            {
                MessageBox("This username already exists. Please enter another username.",0,0,_messagebox_yellow);
            PreventPostBack(event);
            return;
            }
        }
        
        if (pw.value == null || pw.value == "" || pw.value.length == 0)
        {
            MessageBox("Please enter a password.",0,0,_messagebox_yellow);
            PreventPostBack(event);
            return;
        }
        
        if (!(pc.value == pw.value))
        {
            MessageBox("The passwords do not match.",0,0,_messagebox_yellow);
            PreventPostBack(event);
            return;
        }
        
        if (cn.value == null || cn.value == "" || cn.value.length == 0)
        {
            if(ri.value != null && ri.value.length > 0)
            {
                MessageBox("You must provide a company name when entering a reseller Id.",0,0,_messagebox_yellow);
                PreventPostBack(event);
                return;
            }
            if(cu.value != null && cu.value.length > 0)
            {
                MessageBox("You must provide a company name when entering a company URL.",0,0,_messagebox_yellow);
                PreventPostBack(event);
                return;
            }
        }
    }
    
//    if (_error_Messages.length > 0)
//    {
//        alert(_error_Messages.join("\n"));  //display all errors, each on their own line
//        _error_Messages = new Array();      //clear the array so we don't get duplicate error messages
//        return false;
//    }
    return true;
}

/*********************************************************************************
* These functions perform two tasks
*  1. If a company name has been entered, then display the reseller & URL fields
*  2. Check to see if the company already exists
* E. Smith 10/23/2008
*********************************************************************************/
function CheckCompanyName()
{
    var cn = $('txtCompanyName');
    var ri = $('txtResellerId');
    var cu = $('txtCompanyURL');
    var _customerKey = $(_txt_CustomerKeyId).value;
    
    if(ciGrow != null) clearInterval(ciGrow);
    if(ciShrink != null) clearInterval(ciShrink); 
     
    if(cn.value == null || cn.value.length == 0)
    {
//        ciShrink = setInterval("shrinkCompanyInfo()", 50);
        shrinkCompanyInfo();
        ri.value = "";
        cu.value = "";
        return;
    }
        
//    ciGrow = setInterval("growCompanyInfo()", 50);
    growCompanyInfo();
    
    //Create an ajax call to get company info if it exists
    var params = "company=" + cn.value + "&custkey=" + _customerKey;
    new Ajax.Request('shopping.asmx/CheckIfCompanyExists',
    {
        method:'post',
        parameters: params,
        onComplete: function(transport)
        {
            if(transport.status == 200)
            {
                var response = ((transport.responseXML.text) ? transport.responseXML.text : transport.responseXML.lastChild.textContent);
                CheckCompanyNameComplete(response);
            }
            else
            {
                 __logError('Load CheckCompanyName Complete Failed:'+ transport.status, '', '', _customerKey, personId, false);
            }
        },
        onFailure: function(transport) { __logError('Load CheckCompanyName Ajax Failed:'+ transport.status, '', '', _customerKey, personId, false); }
     });
}

function growCompanyInfo()
{
    try
    {
        var ci = $('divCompanyInfo');
        ci.style.height = '55px';
        ci.className = "";
//        var ri = $('txtResellerId');
//        var hgt = ci.offsetHeight;
//        if(hgt < 50)
//        {
//            hgt = hgt + 5;
//            ci.style.height = hgt + 'px';
//        }
//        else
//        {
//            clearInterval(ciGrow);
//            ci.className = "";
//            ri.focus();
//            
//        }
        return;
    }
    catch(err)
    {
        alert (err.message);
    }
}

function shrinkCompanyInfo()
{
    try
    {
        var ci = $('divCompanyInfo');
        ci.style.height = '0px';
        ci.className = "hide";
//        var btn = $(_btn_SubmitId);
//        var hgt = ci.offsetHeight;
//        
//        ci.className = "hide";
//        
//        if(hgt > 0)
//        {
//            hgt = hgt - 5;
//            if( hgt < 0)
//                hgt = 0;
//            ci.style.height = hgt + 'px';
//        }
//        else
//        {
//            clearInterval(ciShrink);
//            btn.focus();
//        }
        return;
    }
    catch (err)
    {
        alert (err.message);
    }
}

function CheckCompanyNameComplete(result)
{
    jsres = result.evalJSON();
    var cn = $('txtCompanyName');
    var ri = $('txtResellerId');
    var cu = $('txtCompanyURL');
       
    if(jsres.CompanyRead.CompanyId != 0)
    {
        if(jsres.CompanyRead.CompanyName)
        {
            cn.value = jsres.CompanyRead.CompanyName;
        }
        if(jsres.CompanyRead.CompanyTIN)
        {
            ri.value = jsres.CompanyRead.CompanyTIN;
        }
        if(jsres.CompanyRead.CompanyURL)
        {
            cu.value = jsres.CompanyRead.CompanyURL;
        }
    }
}

/*********************************************************************************
* These functions check to see if there is company information and if not
* advances focus to the next visible field
* E. Smith 11/3/2008
*********************************************************************************/
function HandleResellerIdFocus()
{
    var cn = $('txtCompanyName');
    var ad = $('txtAddress');
    
    if(cn.value == null || cn.value.length == 0)
    {
        ad.focus();
    }
    
    return;
}

function HandleCompanyURLFocus()
{
    var cn = $('txtCompanyName');
    if(cn.value == null || cn.value.length == 0)
    {
        cn.focus();
    }
    
    return;

}


/**************************************
* This fucntion checks if the entered user id already exits
* D.Lozano
* 8/4/08
**************************************/
function CheckIfLoginExists(userName)
{
    var _customerKey = $(_txt_CustomerKeyId).value;
    var params = "handle=" + userName + "&customerKey=" + _customerKey;
    new Ajax.Request('shopping.asmx/CheckIfLoginExists',
    {
        method:'post',
        parameters: params,
        onComplete: function(transport)
        {
            if(transport.status == 200)
            {
                var response = ((transport.responseXML.text) ? transport.responseXML.text : transport.responseXML.lastChild.textContent);
                CheckIfLoginExistsComplete(response);
            }
            else
            {
                 __logError('Load CheckIfLoginExists Complete Failed:'+ transport.status, '', '', _customerKey, personId, false);
            }
        },
        onFailure: function(transport) { __logError('Load CheckIfLoginExists Ajax Failed:'+ transport.status, '', '', _customerKey, personId, false); }
     });
}

function CheckIfLoginExistsComplete(response)
{
    _loginExists = SafeBool(response);
    
    //** Run the validate after the async call
    if(ValidateRegister())
    {
        _isValid = true;
        $('btnSubmitServer').click();
        //__doPostBack('btnSubmitServer','');
    }   
}
/***************************************
 * Register Screen Events
 ***************************************/
 function ToggleSameAddress(ev)
 {
    /*try
    {
        //Get Checkbox
        var sameAddress = $get(_chk_SameAddressId).checked;
       
        //Get variables
        var sh_add1 = $(_txt_ShippingAddress1Id);
        var sh_add2 = $(_txt_ShippingAddress2Id);
        var sh_city = $(_txt_ShippingCityId);
        var sh_state = $find(_ddl_ShippingStateId);
        var sh_zip = $(_txt_ShippingZipId);

        var bl_add1 = $(_txt_BillingAddress1Id);
        var bl_add2 = $(_txt_BillingAddress2Id);
        var bl_city = $(_txt_BillingCityId);
        var bl_state = $find(_ddl_BillingStateId);
        var bl_zip = $(_txt_BillingZipId);

        if(sameAddress)
        {
            //Set new values
            sh_add1.value = bl_add1.value;
            sh_add2.value = bl_add2.value;
            sh_city.value = bl_city.value;
            sh_state.set_value(bl_state.get_value());
            sh_state.set_text(bl_state.get_text());
            sh_zip.value = bl_zip.value;
            
            //Disable controls
            sh_add1.disabled =true;
            sh_add2.disabled =true;
            sh_city.disabled =true;
            sh_state.disable();
            sh_zip.disabled =true;
        }
        else
        {
            //enable controls
            sh_add1.disabled = false;
            sh_add2.disabled = false;
            sh_city.disabled = false;
            sh_state.enable();
            sh_zip.disabled = false;
        }
    }
    catch(err)
    {
        alert(err.message);
    }*/
 }
 
/***************************************
 * Register Screen Event
 ***************************************/
 function Validate_Registration(ev)
 {
    var isValid = true;
    
    var fname = $(_req_lblFirstNameId);
    var lname = $(_req_lblLastNameId);
    var handle = $(_req_lblUserNameId);
    var email = $(_req_lblEmailId);
    var email2 = $(_req_lblConfirmEmailId);
    var samemail = $(_req_lblEmailSameId);
    var pass = $(_req_lblPasswordId);
    var pass2 = $(_req_lblConfirmPasswordId);
    var samepass = $(_req_lblPassowrdSameId);
    var phone = $(_req_lblPhoneId);
    var shipAdd = $(_req_lblShipAddId);
    var shipCity = $(_req_lblShipCityId);
    var shipState = $(_req_lblShipStateId);
    var shipZip = $(_req_lblShipZipId);
    
    //First NAme
    if($(_txt_FirstNameId).value.length == 0)
    {
        fname.className = 'req';
        isValid = false;
    }
    else
        fname.className = 'hide';
    
    //Last NAme
    if($(_txt_LastNameId).value.length == 0)
    {
        lname.className = 'req';
        isValid = false;
    }
    else
        lname.className = 'hide';
    
    //Handle
    if($(_txt_UserNameId).value.length == 0)
    {
        handle.className = 'req';
        isValid = false;
    }
    else
        handle.className = 'hide';
        
    //Email
    if (!(IsValidEmail($(_txt_EmailId).value)))
    {
        email.className = 'req';
        isValid = false;
    }
    else
        email.className = 'hide';
    
    //Email 2
    if($(_txt_ConfirmEmailId).value.length == 0)
    {
        email2.className = 'req';
        isValid = false;
    }
    else
        email2.className = 'hide';
       
    //same email
    if ($(_txt_EmailId).value != $(_txt_ConfirmEmailId).value)
    {
        samemail.className = 'req';
        isValid = false;
    }
    else
        samemail.className = 'hide';
        
        
    //Password
    if($(_txt_PasswordId).value.length == 0)
    {
        pass.className = 'req';
        isValid = false;
    }
    else
        pass.className = 'hide';
        
    //Password 2
    if($(_txt_ConfrimPasswordId).value.length == 0)
    {
        pass2.className = 'req';
        isValid = false;
    }
    else
        pass2.className = 'hide';
        
    //same password
    if ($(_txt_PasswordId).value != $(_txt_ConfrimPasswordId).value)
    {
        samepass.className = 'req';
        isValid = false;
    }
    else
        samepass.className = 'hide';
    
    //Phone
    if (($(_txt_PhoneAreaCodeId).value.length > 0 && !IsOnlyNumeric($(_txt_PhoneAreaCodeId).value))
        || ($(_txt_PhoneExchangeId).value.length > 0 && !IsOnlyNumeric($(_txt_PhoneExchangeId).value))
        || ($(_txt_PhoneLastFourId).value.length > 0 && !IsOnlyNumeric($(_txt_PhoneLastFourId).value)))
    {
        phone.className = 'req'
        isValid = false;
    }
    else
    {
        phone.className = 'hide'
    }
    
    //Shipping Street Address 1
    if($(_txt_ShippingAddress1Id).value.length == 0)
    {
        shipAdd.className = 'req';
        isValid = false;
    }
    else
        shipAdd.className = 'hide';
        
    //Shipping City
    if($(_txt_ShippingCityId).value.length == 0)
    {
        shipCity.className = 'req';
        isValid = false;
    }
    else
        shipCity.className = 'hide';
        
    //Shipping State
    if($find(_ddl_ShippingStateId).get_value() == '0')
    {
        shipState.className = 'req';
        isValid = false;
    }
    else
        shipState.className = 'hide';
        
    //Shipping Zip
    if($(_txt_ShippingZipId).value.length == 0)
    {
        shipZip.className = 'req';
        isValid = false;
    }
    else
        shipZip.className = 'hide';
    
    if (!isValid && ev != null)
        PreventPostBack(ev);
 }
 
/***************************************
 * Register Screen Event
 ***************************************/
 function Clear_Registration(ev)
 {
    if (ev != null)
        PreventPostBack(ev);
    
    $(_txt_FirstNameId).value = '';
    $(_txt_LastNameId).value = '';
    $(_txt_UserNameId).value = '';
    $(_txt_EmailId).value = '';
    $(_txt_ConfirmEmailId).value = '';
    $(_txt_PasswordId).value = '';
    $(_txt_ConfrimPasswordId).value = '';
    $(_txt_PhoneAreaCodeId).value = '';
    $(_txt_PhoneExchangeId).value = '';
    $(_txt_PhoneLastFourId).value = '';
    $(_txt_CompanyNameId).value = '';
    $(_txt_CompanyResellerId).value = '';
    $(_txt_CompanyUrlId).value = '';
    /*$(_chk_SameAddressId).checked = false;
    $(_txt_BillingAddress1Id).value = '';
    $(_txt_BillingAddress2Id).value = '';
    $(_txt_BillingCityId).value = '';
    $(_txt_BillingZipId).value = '';*/
    $(_txt_ShippingAddress1Id).value = '';
    $(_txt_ShippingAddress2Id).value = '';
    $(_txt_ShippingCityId).value = '';
    $(_txt_ShippingZipId).value = '';
    
    $(_req_lblFirstNameId).className = 'hide';
    $(_req_lblLastNameId).className = 'hide';
    $(_req_lblUserNameId).className = 'hide';
    $(_req_lblEmailId).className = 'hide';
    $(_req_lblConfirmEmailId).className = 'hide';
    $(_req_lblPasswordId).className = 'hide';
    $(_req_lblConfirmPasswordId).className = 'hide';
    $(_req_lblEmailSameId).className = 'hide';
    $(_req_lblPassowrdSameId).className = 'hide';
    $(_req_lblShipAddId).className = 'hide';
    $(_req_lblShipCityId).className = 'hide';
    $(_req_lblShipStateId).className = 'hide';
    $(_req_lblShipZipId).className = 'hide';
    
    //$find(_ddl_BillingStateId).get_items().getItem(0).select();
    $find(_ddl_ShippingStateId).get_items().getItem(0).select();
 }
 
/***************************************
 * Register Screen Event
 ***************************************/
 function btnCancel_click(ev)
 {
    var resp = confirm('Are you sure you would like to cancel?');
    if  (resp == null || resp == false)
    {
        if (ev != null)
            PreventPostBack(ev);  
    }
 }
 function Toggle_Button_Class(ctrl)
 {
    //Do nothing
 }
