// PSW 20071214 - change error reporting.  Depends on message.js
// Changes SetNodeContent(ctl,msg) to ErrorReport(msg)
function ErrorReport(msg)
{ 
  UPRError.Report(msg); 
}

function BRServerModuleSuccessFunction(status, ctx)
{
    var commands = status.split('$');
    var postback = true;
    for (i = 0; i < commands.length; i++)
    {
        var command = commands[i].split('#');
        if (command[0] == "url")
        {
            postback = false;
            window.location.href = command[1];
        }   
    } 
    if (postback)
    {
        __doPostBack("Dummy", "Form");
    }
}
function BRServerModuleErrorFunction(result, ctx)
{
    alert('error:' + result + '(' + ctx.id + ')');
}

/*
* Onkeypress event handlers &
* regular expressions for keystroke
* validation
*/
function ExclusiveWith(controlid)
{
    var status = true;
    var control = document.getElementById(controlid);
    if (control)
    {
        if (control.value)
        {
            var trimmedValue = control.value.replace(/^\s+|\s+$/g, '') ;
            if (trimmedValue.length > 0)
            {
                status = false;
            }
        }
    }
    return status;
}
function Numeric(e)
{
	var regex = /[\d\b]/;
	return Validator(e, regex);
}

function AlphaNumeric(e)
{
	var regex = /[\w\b]/;
	return Validator(e, regex);
}

function Sentence(e)
{
	var regex = /[\s\w\b]/;
	return Validator(e, regex);
}
function Email(e)
{
	var regex = /[\w-@\.\b]/;
	return Validator(e, regex);
}
/*
* Validate keystrokes - called by the onkeypress hooks above
*/
function Validator(e, regex)
{
	var keynum;
	var keychar;
	
	if(window.event) // IE
	{
		keynum = e.keyCode;
	}
	else if(e.which) // Netscape/Firefox/Opera
	{
		keynum = e.which;
	}
	keychar = String.fromCharCode(keynum);
	return regex.test(keychar);
}

/*
* Regular expressons for form validation
*/
function ValidateEmail(email)
{
	var regex = /^([\w-\.]+)@(([\w-]+\.)+[\w-]{2,4})$/
    return regex.test(email);	
}

function ValidatePostcode(postCode)
{
	var regex = /^[a-zA-Z]{1,2}[1-9]([0-9A-Za-z]{0,1})\s[0-9]([a-zA-Z]{2})$/
  return regex.test(postCode);
}

function ValidatePassword(password)
{
// PSW 20071211 - simplify password requirements 
// Minimum 8 characters long, mixture of [A-Z][a-z][0-9]    
//  var regex = /^.*(?=.{8,})(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).*$/

// Minimum 6 characters long - alphanumeric + space
  var regex = /^[0-9A-Za-z ]{6,}$/
  return regex.test(password);
}
/*
* Validates a form
* 
* - checks against any <input name="myName" type=text.. element provided it is accompannied 
*   by a span called "myNameError"
* - returns a false response & fills the span with "*" if the input is blank
* - returns a false if the input is called *email* and field does not contain a valid email
* - returns a false if the input is called "*postcode" and field does not contain a valid postcode
* - SD 28/sep/07 : bug 1006,1115 - added code to print the details of the validation
*     dependency :Printing the details will depend on the ValidationDetail element
*/
function ValidateForm()
{
    //adding new variables for printing detailed validation problem
   	var Validator_Details=new String();  
	var validPassword = true;
	var validEmail = true;
  // PSW 2007/12/14
  //  InitializeValidationReport();    
  Validator_Details = "";    

	var elements = document.getElementsByTagName("input");
	var valid = true;
        
	// PSW 20071214 - only need one error message
  var errorReportElement = null;
//	var errorReportElement = document.getElementById("ErrorReport");
//    if (errorReportElement)
//    {
//        SetNodeContent(errorReportElement, " ");
//    }
	for (i = 0; i < elements.length; i++)
	{
        var element = elements[i];
        var errorElement = document.getElementById(element.name+"Error");
        
        if (errorElement)
        {
            /* reset the error display */

            errorElement.style.color = "#254369";        
		    if ((element.type) && ((element.type == "text") || (element.type == "password")))
            {
		        if ((!element.value) || (element.value == ""))
                {
			        /* SetNodeContent(errorElement, "*"); */
			        errorElement.style.color="#ff0000";
              // PSW 20071214 - only need one error message
//                    SetNodeContent(errorReportElement, "A required field is missing or invalid.");
			        
			        valid = false;
		        }
		        else if (element.name.toLowerCase().match("email"))
		        {
			        if (!ValidateEmail(element.value))
			        {
			            /* SetNodeContent(errorElement, "*"); */
			            errorElement.style.color="#ff0000";
			            // PSW 20071214 - only need one error message
//                    SetNodeContent(errorReportElement, "A required field is missing or invalid.");
			        
			            valid = false;
			            validEmail = false;
			        }
                }
                else if (element.name.toLowerCase().match("password"))
		        {
			        if (!ValidatePassword(element.value))
			        {
			            /* SetNodeContent(errorElement, "*"); */
			            errorElement.style.color="#ff0000";
			            // PSW 20071214 - only need one error message
//                    SetNodeContent(errorReportElement, "A required field is missing or invalid.");
			        
			            valid = false;
			            validPassword=false;
			        }
                }
                /*
                    Not needed at current time
                */
                /**
		        else if (element.name.toLowerCase().match("postcode"))
		        {
			        if (!ValidatePostcode(element.value))
			        {
			            SetNodeContent(errorElement, "*");
			            SetNodeContent(errorReportElement, "A required field is missing or invalid.");
			            valid = false;
			        }
                }
                **/
		    }
	    }
	}
	
	//this is to validate select boxes
	 if(!ValidateSelect())
	{
		valid = false;
	}
    //this is to validate textareas
	if (!ValidateTextArea()) {
	    valid = false;
	}
	//code used to print details of validation problem
	// PSW 2007/12/14
  if(!valid)
		Validator_Details=Validator_Details+"A required field is missing or invalid.<br/>";

  if(!validPassword)
	    Validator_Details=Validator_Details+"Password must be at least 6 characters long and alphanumeric and space characters only, for example Pas5w0rd<br/>";		
//	{
//		Validator_Details=Validator_Details+"* Password must be at least of 8 characters long and include a mixture of upper case(A-Z) lower case(a-z) and numeric(0-9) characters only, for example Abcdefg9<br/>";		
//	}
	if(!validEmail)
    Validator_Details=Validator_Details+"Please enter a  valid email address<br/>";
//	{
//		Validator_Details=Validator_Details+"* Please enter a  vaild email address<br/>";
//	}

	//code used to print details of validation problem
	
	if(!valid)
	{
	   SetValidationReport(Validator_Details);
  }
	// Move to top of the window.
  //  window.scrollTo(0,0);
    return valid;
}

/* this function is used to validate the select boxes */
function ValidateSelect()
{   
	var elements = document.getElementsByTagName("select");
	var valid = true;
	for (i = 0; i < elements.length; i++)
	{
        	var element = elements[i];
	        var errorElement = document.getElementById(element.name+"Error");		
        	if (errorElement)
	        {
	            errorElement.style.color = "#254369";  
        	        if(element.selectedIndex<1)
			        {
				        valid=false;
				        errorElement.style.color="#ff0000";
			        }
		    }
	}  
    return valid;
}

/* this function is used to validate the select boxes */
function ValidateTextArea() {
    var elements = document.getElementsByTagName("textarea");
    var valid = true;
    for (i = 0; i < elements.length; i++) {
        var element = elements[i];
        var errorElement = document.getElementById(element.name + "Error");
        if (errorElement) {
            errorElement.style.color = "#254369";
            if (element.value == "") {
                valid = false;
                errorElement.style.color = "#ff0000";
            }
        }
    }
    return valid;
}

function InitializeValidationReport()
{
    if(document.getElementById("ValidationDetail"))
    {
        document.getElementById("ValidationDetail").innerHTML="";
    }

}
function SetValidationReport(validationErrorReport)
{
	if(validationErrorReport.length>1)
	{
    ErrorReport(validationErrorReport);
  }

  /*
	if(document.getElementById("ValidationDetail"))
	{
		var validation = document.getElementById("ValidationDetail");	
		if(validationErrorReport.length>1)
       	{
            
    			document.getElementById("ValidationDetail").style.color="#ff0000";
                //SetNodeContent(validation, Validator_Details);//this was throwing error for span element
			    document.getElementById("ValidationDetail").innerHTML=document.getElementById("ValidationDetail").innerHTML+"<br/>"+validationErrorReport;
	    }
		
	}
  */
}



/*
* set the content of a node
*/
function SetNodeContent(node, content)
{
  // PSW - 20071214 hack to test new error reporting.  Need to change calling code.
  ErrorReport(content);
  /*
    if (node)
    {
        if (node.innerText) // IE
        {
	    node.innerText = content;
        }		
        else                // Firefox, Opera etc.
        {
            node.firstChild.nodeValue = content;
        }
    }
  */    
}

/*
* Ensure a single filed has content
*/
function ValidateRequiredField(controlID, errorMessage)
{
    var status = true;
    var errorReportElement = document.getElementById("ErrorReport");
    var control = document.getElementById(controlID);
    var errorControl = document.getElementById(controlID + "Error");
    if (errorControl)
    {
        errorControl.style.color = "#254369";
    }
    if (control)
    {
        if (control.value)
        {
            var trimmedValue = control.value.replace(/^\s+|\s+$/g, '');
            if (trimmedValue == '')
            {
                if (errorControl)
                {
                    errorControl.style.color="#ff0000";
                }
                SetNodeContent(errorReportElement, errorMessage);
                status = false;
            }
        }
        else
        {
            if (errorControl)
            {
                errorControl.style.color="#ff0000";
            }
            SetNodeContent(errorReportElement, errorMessage);
            status = false;
        } 
    }
    return status
}

function ValidateRegistration() {
    var errorReportElement = document.getElementById("ErrorReport");
    var valid = ValidateForm();
    if (valid) {
        valid = MatchFields("email", "re_email");
        if (valid) {
            valid = MatchFields("password", "re_password");
            if (!valid) {
                document.getElementById("passwordError").style.color = "#ff0000";
                document.getElementById("re_passwordError").style.color = "#ff0000";
                SetNodeContent(errorReportElement, "The password and re-typed password must match.");
            }
            else {
                document.getElementById("passwordError").style.color = "#254369";
                document.getElementById("re_passwordError").style.color = "#254369";
            }
        }
        else {
            SetNodeContent(errorReportElement, "The email and re-typed email must match.");
        }
    }
    return valid;
}

function MatchFields(field1Name, field2Name)
{
    var field1 = document.getElementById(field1Name);
    var field2 = document.getElementById(field2Name);
    if (field1 && field2)
    {
    	if (field1.value == field2.value)
    	{
        	return true;
    	} 
    	SetValidationReport("* Fields entered do not match");
    	return false;
    }
    return true;
}

function InitializeCardForm()
{
        document.getElementById("CardHolderNameSpan").innerText ="";
        document.getElementById("CardNumberError").innerText ="";
        document.getElementById("CardTypeError").innerText ="";
        document.getElementById("CardExpiryDateError").innerText ="";
        document.getElementById("CardStartDateError").innerText ="";
        document.getElementById("ValidationDetail").innerHTML="";
}

function ValidateCardForm()
{       
    var IsBlank;
    IsBlank=false;
    //InitializeCardForm();
     var Validator_Details=new String();      
     if(document.getElementById("CardHolderName").value=="")
     {   
          IsBlank=true;
     }
     if(document.getElementById("CardNumber").value=="")
     {      
          IsBlank=true;
     }
     /*
     if(document.getElementById("securitycode").value=="")
     {
          document.getElementById("securitycodeError").innerText ="*";
          document.getElementById("securitycodeError").style.color="#ff0000"; 
          IsBlank=true;
     }
     */
     var SelectBox = document.getElementById('CardType');
     if(SelectBox.selectedIndex<1)
     {      
          IsBlank=true;
     }
     SelectBox = document.getElementById('CardExpiryDateMonth');
     if(SelectBox.selectedIndex<1)
     {      
          IsBlank=true;
     }
     SelectBox = document.getElementById('CardExpiryDateYear');
     if(SelectBox.selectedIndex<1)
     {      
          IsBlank=true;
     }     
     SelectBox = document.getElementById('CardStartDateMonth');
     if(SelectBox.selectedIndex<1)
     {      
          IsBlank=true;
     }
     SelectBox = document.getElementById('CardStartDateYear');
     if(SelectBox.selectedIndex<1)
     {      
          IsBlank=true;
     }
     if(document.getElementById("ValidationDetail")!=null)
      {            
            if(IsBlank==true)
            {              
                Validator_Details="Fields marked with * cannot be blank.<br/>"                
            }  
            if(Validator_Details.length>1)
            {
            
                document.getElementById("ValidationDetail").style.color="#ff0000";
                document.getElementById("ValidationDetail").innerHTML=Validator_Details;
                return false;
             }
       }
       else
       {            
            return true;    
       }
}

function PasswordValidator(fieldname)
{
					var password=new String();
                    password=document.getElementById(fieldname).value;
                    var capital=false;
                    var numeric=false;
                    var lower=false;
                    var min_length=true;
                    if(password.length<8)                    {
                       
                       // Validator_Details=Validator_Details+"* Password length must be atleast 8 characters<br/>";
                        min_length=false;
                    }
                    
                    
                    var i;                                         
                    for(i=0;i<password.length;i++)
                    {
                        if((password.charCodeAt(i)>47)&&(password.charCodeAt(i)<58))
                        {                            
                            numeric=true;
                        }                        
                        if((password.charCodeAt(i)>96)&&(password.charCodeAt(i)<123))
                        {                            
                            lower=true;
                        }                        
                        if((password.charCodeAt(i)>64)&&(password.charCodeAt(i)<91))
                        {                            
                            capital=true;
                        }                                                                       
                        
                    }
                    if(!(capital==true && lower==true && numeric==true && min_length==true )) 
                    {
						return false;
                    }
                    else
                    {
                        return true;
                    }
}

function InitializPasswordScreen()
{
    var colorText = "#254369";
    //rest color of error msg
    document.getElementById("Tagpasswordold").style.color=colorText;
    document.getElementById("passwordValidatorDetailsold").style.color=colorText;
    document.getElementById("passwordValidator").style.color=colorText; 
    document.getElementById("passwordValidatorDetails").style.color=colorText;
    //clear fields
    document.getElementById("passwordValidatorDetailsold").innerText="";
    document.getElementById("passwordValidatorDetails").innerText="";
     
}

/*
Function	:	ValidateUpdatePassword
leslie suggest there could be clinet api, if time permits should spend more time on that than optimizing this
*/
function ValidateUpdatePassword()
{
    var colorError="#ff0000";
	InitializPasswordScreen();
	var errorReportElement = document.getElementById("ErrorReport");	                     
    var IsBlank;
    IsBlank=false;
	    if(document.getElementById("passwordold").value=="")
	    {       
            document.getElementById("Tagpasswordold").style.color=colorError;             
            IsBlank=true;
	    }			
	    else
	    {
	        if(!(PasswordValidator("passwordold")))
	        {
	            document.getElementById("Tagpasswordold").style.color=colorError;
	            document.getElementById("passwordValidatorDetailsold").style.color=colorError;
                document.getElementById("passwordValidatorDetailsold").innerText ="Password must be at least of 8 characters long and include a mixture of upper case(A-Z) lower case(a-z) and numeric(0-9) characters only, for example Abcdefg9";
                IsBlank=true;	 
	        }    	    
	    }
       if(document.getElementById("password").value=="")
       {    
            document.getElementById("Tagpassword").style.color=colorError;             
            IsBlank=true;
       }
       else               
       {
            if(!(PasswordValidator("password")))
            {
                document.getElementById("Tagpassword").style.color=colorError;
                document.getElementById("passwordValidatorDetails").style.color=colorError;
                document.getElementById("passwordValidatorDetails").innerText ="Password must be at least of 8 characters long and include a mixture of upper case(A-Z) lower case(a-z) and numeric(0-9) characters only, for example Abcdefg9";
                IsBlank=true;    
            }       
       }       
        if(document.getElementById("re_password").value!=document.getElementById("password").value)
        {      
            document.getElementById("re_Tagre_password").style.color=colorError;
            document.getElementById("re_passwordValidatorDetails").style.color=colorError;
            document.getElementById("re_passwordValidatorDetails").innerText="New Password and re-typed password are not same";             
            IsBlank=true        
        }
        if(IsBlank==true)
        {   
            SetNodeContent(errorReportElement,"A required field is missing or invalid.");
            document.getElementById("re_password").value="";
            document.getElementById("password").value="";
            document.getElementById("passwordold").value="";
        }       
        return !(IsBlank);        
}
       
function SelectedAddress(SelectedAddress)
{  
    var addval="AddressField"+SelectedAddress;
    var townval="TownField"+SelectedAddress
    var postcodeval="PostcodeField"+SelectedAddress
    
    document.getElementById("street").value=document.getElementById(addval).value;
    document.getElementById("town").value=document.getElementById(townval).value;
    document.getElementById("postcode").value=document.getElementById(postcodeval).value;
}   
/*
Update password needs to call two functions, BRConfig is not able to call two functions hence writing single function to call two methods
*/
function ValidateUpdateLoginForm()
{
    if(ValidateForm() && MatchFields("password","re_password") && MatchFields("UserName","re_userid"))
    {
        return true;
    }
    else
    {
        return false;
    }

}

