/*Login and register javascript functions*/
var iCustid;
var sHttpRequestURL = "callBackProcedures.aspx";

function pageLoad(){

    checkHTTPS();
    
    var url = document.location.href;
	if (url.indexOf("timeout=yes") > 0) {
	    alert ("Your session has been idle for more than 20 minutes, please login again to access the Customer Care website.")
	} 
}


function checkHTTPS() {

	var url = document.location.href;
	if (url.indexOf("http:") == 0 && url.indexOf("redesign") == -1  && url.indexOf("local") == -1 && url.indexOf("staging") == -1) {
		url = url.replace("http:", "https:");
		document.location.href = url;
	}
}

objectAttachEvent(window, "load", pageLoad);


// Update DOB fields to only allow real dates to be selected
//function DateOfBirth()
//{			
//    alert ('DateOfBirth');
//	// Get the selected month and year
//	var day = document.forms[0].ctl00_cphPageContent_ddlDOBDay.value
//	var month = document.forms[0].ctl00_cphPageContent_ddlDOBMonth.value
//	var year = document.forms[0].ctl00_cphPageContent_ddlDOBYear.value
//	
//	DDL_Days = eval("document.forms[0].ctl00_cphPageContent_ddlDOBDay");
//	DaysDisplayed = DDL_Days.length;
//	
//	// Find out how many days there are in selected month
//	var DaysInMonth = 31;
//	if (month == "April" || month == "June" || month == "September" || month == "November") DaysInMonth = 30;
//	
//	// Check for leap year
//	if (month == "February" && (year/4) != Math.floor(year/4)) {	
//		DaysInMonth = 28;
//	}
//	if (month == "February" && (year/4) == Math.floor(year/4)) {
//		DaysInMonth = 29;
//	}

//	// If more days are displayed than exisit in this month, remove them
//	if (DaysDisplayed > DaysInMonth)
//	{
//		for (i=0; i<(DaysDisplayed-DaysInMonth); i++)
//		{
//			DDL_Days.options[DDL_Days.options.length - 1] = null
//		}
//	}
//	
//	// If more days exisit than are shown for this month, added them
//	if (DaysInMonth > DaysDisplayed)
//	{
//		for (i=0; i<(DaysInMonth-DaysDisplayed); i++)
//		{
//			NewOption = new Option(DDL_Days.options.length + 1);
//			DDL_Days.add(NewOption);
//		}
//	}
//	
//	// If an invalid day in the month is selected, reset it to the 1st
//	if (DDL_Days.selectedIndex < 0) 
//		DDL_Days.selectedIndex = 0;				
//}

function RegisterLogindetails()
{
	var xmlDoc;
	var sResponse;
	var sPostData;
    var oDivUsernamePassword = document.getElementById('divUsernamePassword');
    var oTblUserDetails = document.getElementById('tbluserdetails');
    var oTblUsernamePassword = document.getElementById('tblUsernamePassword');
    var oLoginMsg = document.getElementById('hLoginMsg');
	var oRegUserName = document.getElementById('ctl00_cphPageContent_txtRegUsername');
    var oRegPassword = document.getElementById('ctl00_cphPageContent_txtRegPassword');
	var oRegPassword2 = document.getElementById('ctl00_cphPageContent_txtRegPassword2');
	var oPostcode= document.getElementById('ctl00_cphPageContent_txtPostcode');
	var oSurname = document.getElementById('ctl00_cphPageContent_txtSurname');
    var oDay = 	document.forms[0].ctl00_cphPageContent_ddlDOBDay;
	var oYear = document.forms[0].ctl00_cphPageContent_ddlDOBYear;
	var oMonth = document.forms[0].ctl00_cphPageContent_ddlDOBMonth;
	
	var sPostcode = oPostcode.value;
    var sSurname = oSurname.value;
	var sDOB = oDay.value + '/' +  oMonth.value.substring(0,3) + '/' + oYear.value;
	
	//remove text from user name and password fields before continuing
	document.getElementById('ctl00_cphPageContent_txtUserName').value = ""
	document.getElementById('ctl00_cphPageContent_txtPassword').value = ""

	if (oDivUsernamePassword.style.display=='block')
	{
	
		//new registration,validate user name
		if (oRegUserName.value.length==0 || oRegUserName.value.length < 5)
		{
			alert('Invalid user name, your user name must be between 5 and 50 letters in length, an email address is preferred');
			oRegUserName.focus();
			return false;
		}
		else if (oRegPassword.value.length==0 || oRegPassword.value.length < 5)
		{
			alert('Your password must be between 5 and 50 letters in length.');
			oRegPassword.focus();
			return false;
		}
		else if (oRegPassword2.value.length==0)
		{
			alert('Please confirm your password');
			oRegPassword2.focus();
			return false;
		}
		else if (oRegPassword.value != oRegPassword2.value)
		{
			alert('Passwords do not match');
			oRegPassword.focus();
			return false;
		}
		else
		{
			// register details
			var sUsername = oRegUserName.value;
			var sPassword = oRegPassword.value;

            sPostData = 'Procedure=createlogin&login=no&custid=' + iCustid + '&dob=' + sDOB + '&postcode=' + sPostcode + '&surname=' + sSurname;
			sPostData = sPostData + '&username=' + sUsername + '&password=' +  sPassword;
            sResponse = SendHttpRequest(sHttpRequestURL, sPostData, '', false);  

			if (sResponse==4)
			{
				// user name already taken
				
				oLoginMsg.innerHTML='User name has already been used, please enter a different user name and try again';
				oTblUserDetails.style.display='block';
				oTblUsernamePassword.style.display='none';								
				
				return false;
			}
			else if (sResponse>0)
			{
				// login created successfully

				// disable rest of the controls
				oSurname.disabled='true';
				oDay.disabled='true';
				oMonth.disabled='true';
				oYear.disabled='true';
				oPostcode.disabled='true';
				oRegUserName.disabled='true';
				oRegPassword.disabled='true';
				oRegPassword2.disabled='true';

				// display the message
				oLoginMsg.innerHTML='Login created successfully, <a href="default.aspx">click here </a> to continue.'
				oTblUserDetails.style.display='block';
				oTblUsernamePassword.style.display='none';								
				document.getElementById('btnGetDetails').style.display='none';
			}
			else
			{
				oLoginMsg.innerHTML='Failed to create login, please try again';
				oTblUserDetails.style.display='block';
				oTblUsernamePassword.style.display='none';								
				
				return false;
			}

			return false;
		}
	}
	
	//postcode to uppercase
    oPostcode.value = sPostcode.toLocaleUpperCase();

    if (sSurname.length==0)
    {
	    alert('Invalid surname');
	    oSurname.focus();
	    return false;

    }
    else if (sPostcode.match('^([A-Z,a-z]{1,2}[0-9]{1,2}|[A-Z,a-z]{3}|[A-Z,a-z]{1,2}[0-9][A-Z,a-z])( |-|)[0-9][A-Z,a-z]{2}')==null)
    {
	    alert('Invalid Postcode');
	    oPostcode.focus();
	    return false;
    }

    // look for customer id
    sResponse = ''
    sPostData ='Procedure=findcustomerid&login=no&dob=' + sDOB + '&postcode=' + sPostcode + '&surname=' + sSurname;
    sResponse = SendHttpRequest(sHttpRequestURL, sPostData, '', false);  
    
    // customer id found
    if (sResponse > 0)
    {
	    // do a login look up
	    // disable login box
	    document.getElementById('ctl00_cphPageContent_txtUserName').disabled = 'true';
	    document.getElementById('ctl00_cphPageContent_txtPassword').disabled = 'true';
	    document.getElementById('ctl00_cphPageContent_chkRememberID').disabled = 'true';
	    document.getElementById('ctl00_cphPageContent_btnLogin').disabled = 'true';
    	
	    // store the customerid
	    iCustid = sResponse

        sResponse = ''
	    sPostData = 'Procedure=getlogindetails&login=no&dob=' + sDOB + '&postcode=' + sPostcode;
	    sResponse = SendHttpRequest(sHttpRequestURL, sPostData, '', false);  

	    if (sResponse=='error')
	    {	
		    // register user for CCI
		    alert("We could not find your login details, please enter a user name and password to proceed.");								
		    document.getElementById('ctl00_cphPageContent_btnRegister').value='Register';				
		    oDivUsernamePassword.style.display='block';
		    oRegUserName.focus();
	    }
        else
        {
            xmlDoc = LoadXMLDocument(sResponse);

            try 
            {
	            // Login details found, show on the screen
		        document.getElementById('tdusername').innerHTML = xmlDoc.getElementsByTagName("login")[0].firstChild.data;
		        document.getElementById('tdpassword').innerHTML = xmlDoc.getElementsByTagName("password")[0].firstChild.data;
					
		        // store the customerid in local variable						
		        iCustid = xmlDoc.getElementsByTagName("custid")[0].firstChild.data;
		        
		        oSurname.disabled='true';
		        oDay.disabled='true';
		        oMonth.disabled='true';
		        oYear.disabled='true';
		        oPostcode.disabled='true';

		        oLoginMsg.innerHTML='Your login details are'
		        document.getElementById('tdmessage').innerHTML='Please <a href="default.aspx?view=os">click here </a> to proceed';
					
		        oTblUsernamePassword.style.display='block';
		        oTblUserDetails.style.display='block';
		        document.getElementById('btnGetDetails').style.display='none';
			
			    xmlDoc=null;				
		        return false;
            }
            catch (exc) 
            {
	            alert(exc.message);
	            bValidateBankDetails=false;
	            return false;
            }
	    }
    }
    else
    {
	    // could not find the customer in dap,
	    oLoginMsg.innerHTML='We could not find your details in our system, please amend and try again'
	    oTblUserDetails.style.display='block';
	    oTblUsernamePassword.style.display='none';
	    return false;
    }
    		
    return false;
}

function showError(httpRequest)
{
  alert(httpRequest.responseText);
}
