// -----------------------------------------------------------------------------
// Script:  ProfileValidation.js
// Project : NPD/5994 Imperative, Imperative Health Limited.
// Copyright ©2006-2007 Imperative Health Limited. All rights reserved. 
//	
// Description: validates user input for the profile on client side
// Example:
//		
//	
//			
// Dependencies:
//  Modification History
//
//  Version		Date				By			Description
//  V1R1M0		14-MAY-2007			STUT		Created	
//  V1R1M1      04/10/2007          HERA        Added user introduction validation
//----------------------------------------------------------------

var parentID;
regexValidators = new Array();
inputIDs = new Array();

 //Basic UA detection
var isIE = document.all ? true : false;
var textStore = "";
//global error message to be displayed
var errorMessage = "";
//info for generating pop up prior to postback
popUpPriorToPostbackArray = new Array();
popUpPriorToPostbackArray = {'anchor':null,
					         'isVisible':false,
                             'btnID': null,
                             'linkBtn': null,
                             'rightPanel': null,
                             'leftPanel':null,
                             'messageTxt': '',
                             'eventTarget':'',
                             'eventArgs': null,
                             'top': 0,
                             'left': 0,
                             'flag': false                            
                             };
                             
// -----------------------------------------------------------------------------
// Description: 
//		initialise global variables
//		
// IN:	parent ID
// OUT: none
// -----------------------------------------------------------------------------
function Initialise_Validation(masterPageID)
{
    parentID = masterPageID;
    
    //array dictionary of key, value pairs. key identifies input and value is regex expression
    for(var key in regVal)
    {
        var regex = regVal[key].toString();
        var regex2 = regex.replace(/#/ig,"'");
        regexValidators[key] = regex2;        
    }    
}

// -----------------------------------------------------------------------------
// Description: 
//		checks key press events and stops unwanted characters from being entered
//		
// IN:	event , key of regex for input text box
// OUT: none
// -----------------------------------------------------------------------------
function inputTextValidation(evnt, key)
{
    if (regexValidators[key])
    {
        return ValidateToRegex(regexValidators[key], evnt);
    }
    return true;
}

// -----------------------------------------------------------------------------
// Description: 
//		checks paste event and stops unwanted data
//		
// IN:	event, key of regex
// OUT: none
// -----------------------------------------------------------------------------
function pasteTextValidation(evnt, key)
{
    var keyIndex = 0;
    var strRegex = null;

    if (regexValidators[key])
    {
        strRegex = regexValidators[key];
    }

    if (strRegex == null) return true;

    var textIn = getTextFromClipboard();

    // Generate regex expression from string
    var myregexp = new RegExp(strRegex);

    // Test contents of text box with additional character against expression
    if (!myregexp.test(textIn)) {
        // If test fails stop event propagation and thus appearance of character in text input
        if (isIE) {
            evnt.returnValue = false;
        }
        else {
            evnt.preventDefault();
        }
        return false;
    }

    return true;
}

// -----------------------------------------------------------------------------
// Description: 
//		returns data from clipboard
//		
// IN:	none
// OUT: clipboard text
// -----------------------------------------------------------------------------
function getTextFromClipboard()
{
    if(window.clipboardData) //IE
    {
        return window.clipboardData.getData("text") || "";
    }
    else
    {
        var textarea = document.createElement("textarea");
        if(textarea.createTextRange) //IE
        {
            textarea.createTextRange().execCommand("paste");
            return textarea.innerText;
        }
    }
    return "";
}

// -----------------------------------------------------------------------------
// Description: 
//		allows character by character input validation against a regex expression 
//		
// IN:	regex expression for validation
// IN:  event generated by input
// OUT: none
// -----------------------------------------------------------------------------
function ValidateToRegex(strRegex, evnt)
{
    var source; 
    var textIn;
    var charCode;

    // Obtain event
	if (!evnt) 
	    var evnt = window.event;

    // Identify key pressed
	if (evnt.charCode != null) 
	    charCode = evnt.charCode;
	else if (evnt.keyCode != null) 
	    charCode = evnt.keyCode;
	else if (evnt.which != null) 
	    charCode = evnt.which;

    // Control char key pressed so do not check
    if (charCode == null ||  // No key
        charCode < 32 ||     // Control key
        charCode > 60000)    // Mac Safari arrow keys
    {
        return true;
    }

    // Identify source	
    if (evnt.srcElement) 
	    source = evnt.srcElement;
	else if (evnt.target) 
	    source = evnt.target;
	if (source.nodeType == 3) // defeat Safari bug
		source = source.parentNode;
		
    // Look-up text
    textIn = source.value + String.fromCharCode(charCode);

    // Generate regex expression from string
    var myregexp = new RegExp(strRegex);
    
    // Test contents of text box with additional character against expression
    if (!myregexp.test(textIn))
    { 
        // If test fails stop event propagation and thus appearance of character in text input
        if (isIE)
        {
            evnt.returnValue = false;
        }
        else
        {
            evnt.preventDefault();
        }        
        return false;
    }

    return true;       
}

// -----------------------------------------------------------------------------
// Description: 
//		checks key press event and stops unwanted characters from being entered
//		
// IN:  Event generated by input
// IN:	Regular expression key for validation
// OUT: none
// -----------------------------------------------------------------------------
function inputKeyValidation(evnt, key)
{
    ValidateKeyToRegex(regexValidators[key], evnt);
    return true;
}

// -----------------------------------------------------------------------------
// Description: 
//		Allows single character input validation against a regex expression 
//		
// IN:	regex expression for validation
// IN:  event generated by input
// OUT: none
// -----------------------------------------------------------------------------
function ValidateKeyToRegex(strRegex, evnt)
{
    var source; 
    var charIn;
    var charCode;

    // Obtain event
	if (!evnt) 
	    var evnt = window.event;

    // Identify key pressed
	if (evnt.charCode != null) 
	    charCode = evnt.charCode;
	else if (evnt.keyCode != null) 
	    charCode = evnt.keyCode;
	else if (evnt.which != null) 
	    charCode = evnt.which;

    // Control char key pressed so do not check
    if (charCode == null ||  // No key
        charCode < 32 ||     // Control key
        charCode > 60000)    // Mac Safari arrow keys
    {
        return true;
    }

    // Look-up character	
    charIn = String.fromCharCode(charCode);
    
    // Generate regex expression from string
    var myregexp = new RegExp(strRegex);
    
    // Test contents of text box with additional character against expression
    if (!myregexp.test(charIn))
    { 
        // If test fails stop event propagation and thus appearance of character in text input
        if (isIE)
        {
            evnt.returnValue = false;
        }
        else
        {
            evnt.preventDefault();
        }        
        return false;
    }

    return true;       
}

// -----------------------------------------------------------------------------
// -------------------------------- Depricated ---------------------------------
// Description: 
//		validates whole profile on hitting save button. extra variables are to allow the 
//      systemButtonClicked() to be run again if a pre-postback pop-up is needed
//		
// IN:  event target, event argument, button id , link button id, left panel, right panel
// OUT: none
// -----------------------------------------------------------------------------
function ValidateProfile(eventTarget, eventArgument, btnId, lnkbtnId, leftPanel, rightPanel)
{
    
    //fill array for disclaimer notice to be shown prior to postback
    popUpPriorToPostbackArray['btnID'] = btnId;
    popUpPriorToPostbackArray['linkBtn'] = lnkbtnId;
    popUpPriorToPostbackArray['rightPanel'] = leftPanel;
    popUpPriorToPostbackArray['leftPanel'] = rightPanel;
    popUpPriorToPostbackArray['eventTarget'] = eventTarget;
    popUpPriorToPostbackArray['eventArgs'] = eventArgument;
    
    //log out requested or back button clicked so bypass validate
    if (eventTarget.toLowerCase().indexOf("login") > -1 || 
        eventTarget.toLowerCase().indexOf("back") > -1)
    {
         return true;
    }
    
    errorMessage = "";
    
    var rootAddressAboutMe;        
    var rootAddressVitalStatistics;        
    var rootAddressContactDetails;        

    var rootAddressMyForum; 
    var rootAddressHealthDetails;       

    var rootAddressMyForum;        
    var rootAddressPersonalDetails;
    
    //normal profile
    if(profileWizardPage == "")
    {
        rootAddressAboutMe = tabIDs[0];        //tabbed panel root id
        rootAddressVitalStatistics = tabIDs[1];        //tabbed panel root id
        rootAddressContactDetails = tabIDs[2];        //tabbed panel root id
        rootAddressMyForum = tabIDs[3];        //tabbed panel root id
        rootAddressHealthDetails = tabIDs[4];  
        rootAddressPersonalDetails = null;
    }
    else
    {
        rootAddressAboutMe = parentID;        
        rootAddressVitalStatistics = parentID;       
        rootAddressContactDetails = parentID;       
        rootAddressMyForum = parentID;  
        rootAddressHealthDetails = parentID;
        rootAddressMyForum = parentID;
        rootAddressPersonalDetails = parentID;       
    }
    
    //error panels on tabs
    var aboutmeErrors = findElementById(rootAddressAboutMe + "_aboutMeErrorsText");
    var vitalStatsErrors = findElementById(rootAddressVitalStatistics  + "_vitalStatsErrorsText");
    var contactErrors = findElementById(rootAddressContactDetails + "_contactErrorsText");
    var myForumErrors = findElementById(rootAddressMyForum + "_myForumErrorsText");
    var healthDetailsErrors = findElementById(rootAddressHealthDetails + "_healthDetailsErrorsText");
    //determines if a postback will occur
    var returnValue = true;
    //global set by page to determine whether in wizard
    var wizardPage = profileWizardPage; 
    
    // Check for file input if responding to MyPhoto buttons
    if (eventTarget.indexOf('changeMyPhotoButton') >= 0)
    {
        var fileInput = findElementById(rootAddressMyForum + "_photoFileUpload").value;
        if (!fileInput)
        {
            errorMessage += profileValidationErrorText[19];; 
            returnValue = false;
        }
    }
    
    //about me
    if(profileWizardPage == "WizardAboutMe" || profileWizardPage == "")
    {
        returnValue = ValidateAboutMe(rootAddressAboutMe) && returnValue ? true : false;
    }
    
    //personal details ------------------------------------------------------------------------------
    if(profileWizardPage == "WizardPersonalDetails")
    {
        returnValue = ValidatePersonalDetails(rootAddressPersonalDetails) && returnValue ? true : false;
    }
    //---------------------------------------------------------------------------------------------------

    // vital statistics
    if(profileWizardPage == "WizardVitalStatistics" || profileWizardPage == "")
    {
         returnValue = ValidateVitalStatistics(rootAddressVitalStatistics) && returnValue ? true : false;
    }
    //---------------------------------------------------------------------------------------------------

    //contact details
    if(profileWizardPage == "WizardContactDetails" || profileWizardPage == "")
    { 
        returnValue = ValidateContactDetails(rootAddressContactDetails) && returnValue ? true : false;
    }
    //---------------------------------------------------------------------------------------------------

    //My Forum
    if(profileWizardPage == "WizardMyForum" || profileWizardPage == "")
    { 
        returnValue = ValidateMyForum(rootAddressMyForum) && returnValue ? true : false;
    }
    //----------------------------------------------------------------------------------------------------    
        //healthDetails
    if(profileWizardPage == "WizardHealthDetails" || profileWizardPage == "")
    { 
        returnValue = ValidateHealthDetails(rootAddressHealthDetails, profileWizardPage) && returnValue ? true : false;;
    }
    //----------------------------------------------------------------------------------------
    if (errorMessage != "")
    {
        errorMessage = "<ul>" + errorMessage + "</ul>";
    }

    //add any error messages to the visible message panel (id not an empty string)
    if (aboutmeErrors!= null)
    {
        aboutmeErrors.innerHTML = errorMessage;
    }
    if (vitalStatsErrors != null)
    {
        vitalStatsErrors.innerHTML = errorMessage;
    }
    if (contactErrors != null)
    {
        contactErrors.innerHTML = errorMessage;
    }
    if (myForumErrors != null)
    {
        myForumErrors.innerHTML = errorMessage;
    }
    if (healthDetailsErrors!= null)
    {
        healthDetailsErrors.innerHTML = errorMessage;
    }
    
    //this will show a pop up. the pop up can call systembuttonclicked again
    // the flag is set to true if ok clicked on pop up (see PopUpPostBack())
    if(returnValue == true && popUpPriorToPostbackArray['isVisible'] == true &&
        popUpPriorToPostbackArray['flag'] == false)
    {
        returnValue = false;
        ShowPopUp();
    }

    return returnValue;
        
}

// -----------------------------------------------------------------------------
// Description: 
//		validates the about me panel
//		
// IN:  wizard page name ("" in tabbed panel)
// OUT: true/false for validation
// -----------------------------------------------------------------------------

function ValidateAboutMe(rootAddress)
{
    var firstName = ValidateByKeyWord(findElementById(rootAddress+ "_firstnameInputValidatedInput").value,"FIRST_NAME");
    var lastName = ValidateByKeyWord(findElementById(rootAddress+ "_lastnameInputValidatedInput").value,"LAST_NAME");
    var ethnicity = ValidateEthnicity(findElementById(rootAddress  + "_ethnicityDropDown").selectedIndex);
    var genderMale;
    var genderFemale;
    var returnValue = true;

    
    
    if(isIE)
    {
        genderMale = findElementById(rootAddress + "_genderRadioButtonListTableRow_0").status;
        genderFemale = findElementById(rootAddress + "_genderRadioButtonListTableRow_1").status;
    }
    else
    {
        genderMale = findElementById(rootAddress + "_genderRadioButtonListTableRow_0").checked;
        genderFemale = findElementById(rootAddress + "_genderRadioButtonListTableRow_1").checked;

    }
    
    var dobValue = findElementById(rootAddress + "_dateOfBirthTextbox").value;
    var dob = ValidateByKeyWord(dobValue,"DATE_OF_BIRTH");
    var dobRange = ValidateDOB("dateOfBirth",dobValue);
    
    if(!firstName)
    {
        errorMessage += profileValidationErrorText[0]; 
        returnValue = false;
    }
    if(!lastName)
    {
        errorMessage += profileValidationErrorText[1];
        returnValue = false;
    }
    if(!(genderMale || genderFemale) )
    {
        errorMessage += profileValidationErrorText[2];
        returnValue = false; 
    }
     if(!ethnicity)
    {
        errorMessage += profileValidationErrorText[3];
        returnValue = false; 
    }
   
    if((!dob) || (!dobRange))
    {
      errorMessage += profileValidationErrorText[4]; 
      returnValue = false;
    }
    
    return returnValue;
}

// -----------------------------------------------------------------------------
// Description: 
//		validates the personal details panel
//		
// IN:  wizard page name ("" in tabbed panel)
// OUT: true/false for validation
// -----------------------------------------------------------------------------
function ValidatePersonalDetails(rootAddress)
{
    var address1 = ValidateByKeyWord(findElementById(rootAddress+ "_address1ValidatedInput").value,"ADDRESS_ONE");
    var address2 = ValidateByKeyWord(findElementById(rootAddress+ "_address2ValidatedInput").value,"REGEX_ALPHANUMERIC");
    var address3 = ValidateByKeyWord(findElementById(rootAddress+ "_address3ValidatedInput").value,"REGEX_ALPHANUMERIC");
    var county = ValidateByKeyWord(findElementById(rootAddress+ "_countyValidatedInput").value,"FIRST_NAME");
    var postCodeStr = new String(findElementById(rootAddress+ "_postCodeValidatedInput").value);
    var postCode = ValidateByKeyWord(postCodeStr.toUpperCase(),"POST_CODE");
    var homePhone = ValidateByKeyWord(findElementById(rootAddress+ "_homePhoneValidatedInput").value,"HOME_PHONE");
    var mobilePhone = ValidateByKeyWord(findElementById(rootAddress+ "_mobilePhoneValidatedInput").value,"MOBILE_NUMBER");
    var boxId = ValidateByKeyWord(findElementById(rootAddress+ "_boxIdValidatedInput").value,"REGEX_ALPHANUMERIC");
    var pamId = ValidateByKeyWord(findElementById(rootAddress+ "_pamIdValidatedInput").value,"REGEX_ALPHANUMERIC");
    var scalesId = ValidateByKeyWord(findElementById(rootAddress+ "_scalesIdValidatedInput").value,"REGEX_ALPHANUMERIC");
    
    var returnValue = true;
    
    if(!address1)
    {
        errorMessage += profileValidationErrorText[5];
        returnValue = false;
    }
    if(!county)
    {
        errorMessage += profileValidationErrorText[6];
        returnValue = false;
    }
    if(!postCode)
    {
        errorMessage += profileValidationErrorText[7];
        returnValue = false;
    }
    if(!homePhone)
    {
        errorMessage += profileValidationErrorText[8];
        returnValue = false;
    }
    if(!boxId)
    {
        errorMessage += profileValidationErrorText[9];
        returnValue = false;
    }
    if(!pamId)
    {
        errorMessage += profileValidationErrorText[10];
        returnValue = false;
    }
    if(!scalesId)
    {
        errorMessage += profileValidationErrorText[11];
        returnValue = false;
    }
    
    return returnValue;
}

// -----------------------------------------------------------------------------
// Description: 
//		validates the vital statistics panel
//		
// IN:  wizard page name ("" in tabbed panel)
// OUT: true/false for validation
// -----------------------------------------------------------------------------
function ValidateVitalStatistics(rootAddress)
{
    var returnValue = true;

    //Weight
    if (!Validateweight(rootAddress))
    {
        returnValue = false;
    }
    
    //Height
    if (!ValidateHeight(rootAddress))
    {
        returnValue = false;
    }
    
    //Waist
    if (!Validatewaist(rootAddress))
    {
        returnValue = false;
    }
    
    return returnValue;
}

// -----------------------------------------------------------------------------
// Description: 
//		validates the health vital statistics panel
//		
// IN:  wizard page name ("" in tabbed panel)
// OUT: true/false for validation
// -----------------------------------------------------------------------------
function ValidateHealthVitalStatistics(rootAddress) {
    var returnValue = true;

    //Weight
    if (!Validateweight(rootAddress)) {
        returnValue = false;
    }

    //Height
    if (!ValidateHeight(rootAddress)) {
        returnValue = false;
    }

    return returnValue;
}

// -----------------------------------------------------------------------------
// Description: 
//		validates the height int the vital statistics panel
//		
// IN:  wizard page name ("" in tabbed panel)
// OUT: true/false for validation
// -----------------------------------------------------------------------------
function ValidateHeight(rootAddress) {
    var returnValue = true;

    //Height
    if (!validateSystemInputWithUnits("BodyHeight", rootAddress + "_heightInputSelectedUnitIndex")) {
        errorMessage += "<li>" + validationErrorTextheightInput + "</li>";
        returnValue = false;
    }

    return returnValue;
}

// -----------------------------------------------------------------------------
// Description: 
//		validates the weight int the vital statistics panel
//		
// IN:  wizard page name ("" in tabbed panel)
// OUT: true/false for validation
// -----------------------------------------------------------------------------
function Validateweight(rootAddress) {
    var returnValue = true;

    //Weight
    if (!validateSystemInputWithUnits("BodyWeight", rootAddress + "_weightInputSelectedUnitIndex")) {
        errorMessage += "<li>" + validationErrorTextweightInput + "</li>";
        returnValue = false;
    }

    return returnValue;
}

// -----------------------------------------------------------------------------
// Description: 
//		validates the waist int the vital statistics panel
//		
// IN:  wizard page name ("" in tabbed panel)
// OUT: true/false for validation
// -----------------------------------------------------------------------------
function Validatewaist(rootAddress) {
    var returnValue = true;

    var waistIndex = rootAddress + "_waistInputSelectedUnitIndex";


    //Waist
    if (findElementById(waistIndex) != null) {
        if (!validateSystemInputWithUnits("BodyWaist", waistIndex)) {
            errorMessage += "<li>" + validationErrorTextwaistInput + "</li>";
            returnValue = false;
        }
    }
    return returnValue;
}

// -----------------------------------------------------------------------------
// Description: 
//		validates the contact details panel
//		
// IN:  wizard page name ("" in tabbed panel)
// OUT: true/false for validation
// -----------------------------------------------------------------------------
function ValidateContactDetails(rootAddress)
{
   var mobileInput = findElementById(rootAddress + "_mobileValidatedInput").value;
   var email = ValidateByKeyWord(findElementById(rootAddress + "_emailValidatedInput").value,"REGEX_EMAIL");
   var mobileNumber = ValidateByKeyWord(mobileInput,"MOBILE_NUMBER");
   var returnValue = true;
   
   if(!email)
   {
      errorMessage += profileValidationErrorText[12];
      returnValue = false;
   }
   //mobile number is optional but any input must be validated
   if(!mobileNumber && mobileInput != "")
   {
      errorMessage += profileValidationErrorText[13];
      returnValue = false;   
   }
   
   return returnValue;

}

// -----------------------------------------------------------------------------
// Description: 
//		applies regex validation by key word
//		
// IN:  text to validate and key word for regex array
// OUT: true/false for regex test
// -----------------------------------------------------------------------------
function ValidateByKeyWord(textToValidate,key)
{
    //generate regex expression from string
    var myregexp = new RegExp(regexValidators[key]);

    //test contents of text box with additional character against expression
    return myregexp.test(textToValidate);
}

// -----------------------------------------------------------------------------
// Description: 
//		validates the my forum panel
//		
// IN:  wizard page name ("" in tabbed panel)
// OUT: true/false for validation
// -----------------------------------------------------------------------------
function ValidateMyForum(rootAddress)
{
    var introductionInput = findElementById(rootAddress + "_introductionInputTextBox").value;
    var returnValue = true;

    // Check value is no greater than specified length
    if (introductionInput)
    {
        if (introductionInput.length > maxIntroductionLength)
        {
            errorMessage += profileValidationErrorText[14] + 
                maxIntroductionLength + 
                profileValidationErrorText[15] +
                introductionInput.length + profileValidationErrorText[16];
            returnValue = false;
        }
        else
        if (!ValidateByKeyWord(introductionInput, "REGEX_MULTI_LINE_TEXT"))
        {
            errorMessage += profileValidationErrorText[17];
            returnValue = false;
        }
    }

    return returnValue;
}
// -----------------------------------------------------------------------------
// Description: 
//		validates the health assessment panel
//		
// IN:  root address
// OUT: true/false for validation
// -----------------------------------------------------------------------------
function ValidateHealthDetails(rootAddress, profileType)
{

        var returnValue = true;
		var selObjects=document.getElementsByTagName("INPUT");
		var disclaimer = false;
		var anchorProfile = null;
		questions = new Array();
		var noOfQuestions = 0;
		var noOfAnswers = 0;
		var topOne = null;
		
	    for(var i=0;i<selObjects.length;i++)
		{	
			var index = selObjects[i].id.indexOf("healthDetailsRadioButtonList_");
			if(index > -1)
			{   //top question
			    if(topOne == null)
			    {
			        topOne = selObjects[i];
			    }
			    var index2 = selObjects[i].id.indexOf("TableRow");
			    //collect question keys and count distinct number of questions
			    var key = selObjects[i].id.substring(index+29,index2);
                if(questions[key] == null)
                {
                    questions[key] = key;
                    noOfQuestions++;
                }
                //count no of answers
                if(selObjects[i].checked == true)
				{
                    noOfAnswers++;
                    //show disclaimer if any answer is yes (yes/no) 
                    if(selObjects[i].value.toLowerCase().indexOf("yes") > -1 && disclaimer == false)
				    {
				        disclaimer = true;
				        anchorProfile = topOne;
				    }
                    
				}
		    }
		}
		if(profileType == "")
		{
		    //if profile never been filled out don't flag up unless some questions already answered
		    if(noOfAnswers > 0 && noOfQuestions != noOfAnswers)
		    {
		        returnValue = false;
		        errorMessage += profileValidationErrorText[18];
		    }

		}
		else
		{
		    if(noOfQuestions != noOfAnswers)
		    {
		        returnValue = false;
		        errorMessage += profileValidationErrorText[18];
		    }
		}
		
		//disclaimer if any of the answers is yes
		if(returnValue == true && disclaimer == true)
		{            
            var disclaimerTitle = "Disclaimer";
            var disclaimer = "Disclaimer Text could not be found. Please contact the administrator";
            var disclaimerHidden = findElementById(rootAddress + "_disclaimerText");
            if(disclaimerHidden != null)
            {
                disclaimerArray = disclaimerHidden.value.split('#');
                if(disclaimerArray[0] != null)
                {
                    disclaimerTitle = disclaimerArray[0];
                }
                if(disclaimerArray[1] != null)
                {
                    disclaimer = disclaimerArray[1];
                }
            }
            var messageTxt = "<table align=\"center\"><tr><td align=\"center\" class=\"disclaimerTitle\">"+disclaimerTitle+"</td></tr><tr><td align=\"center\">"+disclaimer+"</td></tr><tr><td align=\"center\" ><input type=\"button\" class=\"btnstylelogout\" value=\"OK\" onclick=\"PopUpPostBack()\"/></td>" +
                     "</tr></table>";
            
            popUpPriorToPostbackArray['top'] = 150;
            popUpPriorToPostbackArray['left'] = -200;
            popUpPriorToPostbackArray['anchor'] = anchorProfile;
            popUpPriorToPostbackArray['messageTxt'] = messageTxt;
            //popUpPriorToPostbackArray['isVisible'] = true;

		}
		else
		{
		    //hide pop up if showing
		    if(popUpPriorToPostbackArray['isVisible'] == true)
		    {
		        help.Hide();
		        popUpPriorToPostbackArray['isVisible'] = false;
		    }
		}

    return returnValue;
}
// -----------------------------------------------------------------------------
// Description: 
//		shows a pop up defined by popUpPriorToPostbackArray array
//		
// IN:  none
// OUT: none
// -----------------------------------------------------------------------------
function ShowPopUp() {

    help.autoHide=false;
    help.autoAway=false;
    help.showAnchor=false;
    help.helpPopUpPanelClassHeight = "helpPopupHeight_autoheight";
    help.Show({message:popUpPriorToPostbackArray['messageTxt'],
                anchor: findElementById(popUpPriorToPostbackArray['btnID']),
                top:popUpPriorToPostbackArray['top'],
                left:popUpPriorToPostbackArray['left']});
}
// -----------------------------------------------------------------------------
// Description: 
//		causes another button click event without profile validation
//		
// IN:  none
// OUT: none
// -----------------------------------------------------------------------------
function PopUpPostBack()
{
    var btnId = popUpPriorToPostbackArray['btnID'];

    //show that ok button has been clicked for next run through profile validation
    popUpPriorToPostbackArray['flag'] = true;

    if (btnId != null) {

        var args = new Array();
        args.IsValid = true;
        MyProfileValidationFunction(source, args);
        if (!args.IsValid) return;
    
        while (btnId.indexOf("_") >= 0) {
            btnId = btnId.replace("_", "$");
        }
        __doPostBack(btnId, '');
    }
}


// -----------------------------------------------------------------------------
// Description: 
//		applies regex validation to input text boxes
//		
// IN:  text to validate and key word for regex array
// OUT: true/false for regex test
// -----------------------------------------------------------------------------

function ValidateInputWithUnits(source, arguments)
{
    if(ValidateByKeyWord(arguments.Value, "REGEX_DECIMAL_POSITIVE"))
    {
        arguments.IsValid=true;
    }
    else
    {
        arguments.IsValid=false;  
    }
}
// -----------------------------------------------------------------------------
// Description: 
//		applies regex validation to calender
//		
// IN:  text to validate and key word for regex array
// OUT: true/false for regex test
// -----------------------------------------------------------------------------
function ValidateDateOfBirth(source, arguments)
{
    if(ValidateByKeyWord(arguments.Value, "DATE_OF_BIRTH"))
    {
        arguments.IsValid=true;
    }
    else
    {
        arguments.IsValid=false;  
    }
}

// -----------------------------------------------------------------------------
// Description: 
//		applies regex validation to name
//		
// IN:  text to validate and key word for regex array
// OUT: true/false for regex test
// -----------------------------------------------------------------------------
function ValidateName(source, arguments)
{
    if(ValidateByKeyWord(arguments.Value, "FIRST_NAME"))
    {
        arguments.IsValid=true;
    }
    else
    {
        arguments.IsValid=false;  
    }
}

// -----------------------------------------------------------------------------
// Description: 
//		applies regex validation to name
//		
// IN:  text to validate and key word for regex array
// OUT: true/false for regex test
// -----------------------------------------------------------------------------
function ValidateEthnicity(indexToValidate)
{
    var isValid = false;
    if(indexToValidate && indexToValidate != 0)
    {
        isValid=true;
    }
    return isValid;
}


// -----------------------------------------------------------------------------
// Description: 
//		Swaps the visibility of two elements (rows) and sets a hidden variable
//		
// IN:  row to hide
// IN:  row to show
// IN:  hidden variable
// IN:  value to set hidden variable to (corresponds to row number of the visible row)
// OUT: none
// -----------------------------------------------------------------------------

function swapVisibility(id1, id2, id3, selectedUnit)
{
   var unit1= findElementById(id1);
   var unit2= findElementById(id2);   
   var selectedIndex= findElementById(id3);
   unit1.className='hidden'; 
   unit2.className='visible';
   selectedIndex.value = selectedUnit;
   
   refreshRoundedCorners();
}

// -----------------------------------------------------------------------------
// Description: 
//		Swaps the visibility of two elements (rows), sets a hidden variable and
//          transfers the selected index between two drop down lists
//		
// IN:  row to hide
// IN:  row to show
// IN:  hidden variable
// IN:  dropdown to hide (get selected index from)
// IN:  dropdown to show (set selected index of)
// IN:  value to set hidden variable to (corresponds to row number of the visible row)
// OUT: none
// -----------------------------------------------------------------------------

function swapVisibilityWithSelection(id1Hide, id2Show, id3Hidden,dropDownHide,dropDownShow, selectedUnitIndex)
{
   var unit1= findElementById(id1Hide);
   var unit2= findElementById(id2Show);   
   var selectedIndex= findElementById(id3Hidden);

   
   //Get selected index on drop down to be hidden
   var ddHide = findElementById(dropDownHide);
   var ddShow = findElementById(dropDownShow);
   
   var optionCounter;
   
   if (ddHide != null &&ddHide.selectedIndex != null)
   {
   
    var selectedOption = ddHide.selectedIndex;

    //Set selected index on drop down to show  
    if (ddShow != null && ddShow.length > selectedOption)
    {
            ddShow.options[selectedOption].selected = true;
    }
   }
    
   unit1.className='hidden'; 
   unit2.className='visible';
    
   selectedIndex.value = selectedUnitIndex;
   
   refreshRoundedCorners();
}


// -----------------------------------------------------------------------------
// Description: 
//      Refresh rounded corners if we are using Safari
//		
// IN:  none
// OUT: none
// -----------------------------------------------------------------------------
function refreshRoundedCorners()
{
    if (navigator.userAgent.indexOf("Safari") > -1)
    {
        roundCorners('roundedInputWithUnits');
        roundCorners('roundedInputDropDown');
        roundCorners('roundedInput');
        roundCorners('roundedInputDisabled')    
    }
}

// -----------------------------------------------------------------------------
// Description:
//		procedure copying inserted value to hidded field for store exact value
//
// -----------------------------------------------------------------------------
function copyValueToHiddenField(originalField, hiddenField) 
{
    //get controls
    var input0 = findElementById(originalField);
    var inputValue0 = findElementById(hiddenField);

    try
    {
        inputValue0.value = input0.value;
    }
    catch (e) {
        //quiet catch - no subunit present
    }
}

// -----------------------------------------------------------------------------
// Description: 
//		Takes values from the deselected row (to be hidden) and puts them in the
//          selected row (to show). Converted to correct unit using a javascript array
//          (conversionArray ..) on the page.
//		
// IN:  type of input (sees SystemValidatedInputWith Units for enumeration)
// IN:  hidden variable (which row currently displayed)
// IN:  MultipleInputControlID (does nothing)
// OUT: none
// -----------------------------------------------------------------------------

function convertValues(inputType, selectedUnitID, MultipleInputControlID, unitsLength)
{
    //get root ID and text box ids
    var rootID = selectedUnitID.replace("SelectedUnitIndex", "");
    
    //get selected unit - this is what has just been selected (ie deselected has just been changed by user)
    var selected = parseInt(findElementById(selectedUnitID).value,10);

    var deselected;
    if(selected == 0)
    {
        deselected = unitsLength - 1;
    }
    else
    {
        deselected = selected - 1;
    }
    
    //get controls
    var subInput0  =  findElementById(rootID + "InputSubUnit" + selected);
    var mainInput0 = findElementById(rootID + "InputMainUnit" + selected);
    var subInputValue0 = findElementById(rootID + "InputSubUnitValue" + selected);
    var mainInputValue0 = findElementById(rootID + "InputMainUnitValue" + selected);

    // only continue if value in text box is not empty
    if (mainInput0 != null) {

        //get values from array - array depends on input type passed
        var conversionMainSelected = "conversionArray" + inputType + "['M" + selected + "']";
        var conversionMainSelectedValue = 0;

        var conversionSubSelected = "conversionArray" + inputType + "['S" + selected + "']";
        var conversionSubSelectedValue = 0;

        eval("conversionMainSelectedValue = " + conversionMainSelected);

        try {
            eval("conversionSubSelectedValue = " + conversionSubSelected);

        }
        catch (e) {
            //quiet catch - no subunit present
        }

        //value in base units
        var intermediateValue = getValueInBaseUnits(inputType, rootID, deselected);
        var newMainValue;
        var newSubValue;

        //Set text boxes with new value from deselected text boxes (convert to new unit)
        newMainValue = intermediateValue / conversionMainSelectedValue;
        if (subInput0 != null) {
            var numberofSubUnitsToMain = Math.round(conversionMainSelectedValue / conversionSubSelectedValue);
            newSubValue = (newMainValue - parseInt(newMainValue, 10)) * conversionMainSelectedValue / conversionSubSelectedValue;

            subInputValue0.value = newSubValue;

            // if its cholesterol or glucose show 1 digit after decimal separator, else round to integer value
            if (inputType == "Cholesterol" || inputType == "BloodGlucose") {
                newSubValue = Math.round(10 * newSubValue) / 10;
            }
            else {
                newSubValue = Math.round(newSubValue);
            }

            newMainValue = parseInt(newMainValue, 10);
            mainInputValue0.value = newMainValue;

            if (newSubValue >= numberofSubUnitsToMain) {
                newMainValue += 1;
                newSubValue -= numberofSubUnitsToMain;
            }
            subInput0.value = newSubValue;
        }
        else {
            mainInputValue0.value = newMainValue;
        }

        // if its cholesterol or glucose show 1 digit after decimal separator, else round to integer value
        if (inputType == "Cholesterol" || inputType == "BloodGlucose") {
            mainInput0.value = Math.round(10 * newMainValue) / 10;
        }
        else {
            mainInput0.value = Math.round(newMainValue);
        }
    }
}

// -----------------------------------------------------------------------------
// Description: 
//		Validates the input of a SystemValidatedInputWithUnits. The min and max
//      are written as javascript variables to the page, selected row in hidden
//      variable
//		
// IN:  type of input (sees SystemValidatedInputWith Units for enumeration)
// IN:  hidden variable (which row currently displayed)
// OUT: true if valid input
// -----------------------------------------------------------------------------

function validateSystemInputWithUnits(inputType,selectedUnitID)
{
    //get root ID 
    var rootID = selectedUnitID.replace("SelectedUnitIndex", "");
    
    //get selected unit - this is what has just been selected (ie deselected has just been changed by user)
    var selected = parseInt(findElementById(selectedUnitID).value,10);
    
    var underscore = rootID.lastIndexOf("_");
    
    if (underscore > -1)
    {
        shortRootID = rootID.substr(underscore+1);
    }else
    {
        shortRootID = rootID;
    }

    //Get variable names that hold max and min
    var minimumValueVariable = "minValue" + shortRootID;
    var maximumValueVariable = "maxValue" + shortRootID;
    
    eval("minimumValue =" + minimumValueVariable);
    eval("maximumValue =" + maximumValueVariable);

    var quantity = getValueInBaseUnits(inputType,rootID,selected);

    if (quantity > maximumValue)
    {
        return false;
    }else if (quantity < minimumValue)
    {
        return false;
    }
    
    return true;
}

// -----------------------------------------------------------------------------
// Description: 
//		Gets the value in the input boxes in the base Unit using conversion
//      values in the conversionArray. User provides the row number to use
//      and the root id of SystemValidatedInputWithUnits elements.
//		
// IN:  type of input (sees SystemValidatedInputWith Units for enumeration)
// IN:  integer of which row currently displayed to convert to base value
// OUT: the value in this row converted to the base unit (or 0)
// -----------------------------------------------------------------------------

function getValueInBaseUnits(inputType, rootID, selectedUnit)
{
    
    //get selected unit - this is what has just been selected (ie deselected has just been changed by user)
    var selected = parseInt(selectedUnit,10);
    
    if (isNaN(selected))
    {
        return 0;
    }
    
    //get controls
    var subInput0  =  findElementById(rootID + "InputSubUnitValue" + selected);
    var mainInput0 = findElementById(rootID + "InputMainUnitValue" + selected);
    
    
    //get values from array - array depends on input type passed
    var conversionMainSelected = "conversionArray" + inputType + "['M" + selected + "']";
    var conversionMainSelectedValue = 0;

    var conversionSubSelected = "conversionArray" + inputType + "['S" + selected + "']";
    var conversionSubSelectedValue = 0;

    eval("conversionMainSelectedValue = " + conversionMainSelected);

    try
    {
        eval("conversionSubSelectedValue = " + conversionSubSelected);
        
    }
    catch(e)
    {
        //quiet catch - no subunit present
    }
    
    
    //value in base units
    var intermediateValue;

    //do conversion calculation and add to the input controls
    var mainValue = parseFloat(mainInput0.value);
    
    //check is a number
    if (isNaN(mainValue))
    {
        return 0;
    }

    //convert main value
    intermediateValue = mainValue * conversionMainSelectedValue;
    
    // flag for legality of sub value
    var amLegal = true;
    
    //get subunit if there
    if(subInput0 != null)
    {
        var subValue = parseFloat(subInput0.value);
        
        if (! isNaN(subValue))
        {
            intermediateValue += subValue * conversionSubSelectedValue;
            
            // finally check that sub input value is not over valid range
            // RegEx is called inputType + selectedUnit, e.g. BODY_HEIGHT1
            var regKeyword = inputType + selectedUnit;
            // no validation for just kgs
            if(regKeyword == 'BODY_WEIGHT2')
            {
                amLegal = ValidateByKeyWord(subValue, regKeyword);
            }

        }
    }
    
    // and return value
    if(amLegal)
    {
        return intermediateValue;
    }
    else
    {
        return 0;
    }
}

// -----------------------------------------------------------------------------
// Description: 
//		Compares the date in the textBoxString with the earliestValue and latestValue
//  variables on the page for the SystemCalendar with this calendarID.
//		
// IN:  ID of the SystemCalendar
// IN:  the date string from the text box (expect dd/mm/yy or dd/mm/yyyy)
// OUT: true if date is between (inclusive) the earliest and latest dates stored on the page
// -----------------------------------------------------------------------------

function ValidateDOB(calendarID,textBoxString)
{
    var languageinfo = GetLocale();
	    
    //Get min and max from page
    //Get variable names that hold max and min
    var minimumValueVariable = "earliestValue" + calendarID;
    var maximumValueVariable = "latestValue" + calendarID;
    
    try{
    
    eval("minimumValue =" + minimumValueVariable);
    eval("maximumValue =" + maximumValueVariable);
    
    }catch(e)
    {
        //quiet catch, error with validation
        return true;
    }
    
    //Get dates for min and max
    var earliestDate = ParseDate(minimumValue, languageinfo);
    var latestDate = ParseDate(maximumValue, languageinfo)
    var enteredDate = ParseDate(textBoxString, languageinfo)
    
    //Compare to entered date
    if (earliestDate == null || latestDate == null || enteredDate == null)
    {
        // could not parse dates in validator
        return false;
    }

    if (enteredDate >= earliestDate && enteredDate <= latestDate)
    {
        return true;    //valid
    }else{
        return false;
    }

}

// -----------------------------------------------------------------------------
// Description: 
//		Returns browser locale
//		
// OUT: Broswer locale
// ----------------------------------------------------------------------------
function GetLocale()
{   
    var rootAddressAboutMe; 
    //normal profile
    if(profileWizardPage == "")
    {
        rootAddressAboutMe = tabIDs[0];        //tabbed panel root id
    }
    else
    {
        rootAddressAboutMe = parentID;        
    }
    
    var hidCulture = findElementById(rootAddressAboutMe + "_currentCulture");
    return hidCulture.value;
}


// -----------------------------------------------------------------------------
// Description: 
//		Parses date according to locale and returns millisecond version
// IN: dateToParse (dd/mm/yyyy or mm/dd/yyyyy)
// IN: Broswer locale
// OUT: date as miliiseconds since 01/01/1970
// ----------------------------------------------------------------------------
function ParseDate(dateToParse, localeStr)
{
    var dateStr = new String(dateToParse);
    var dayStr = "1";
    var monthStr = "1";
    var yearStr = "1970";
    var arrDateStrs = dateStr.split("/");
    
    if(localeStr == "en-US")
    {
        monthStr = arrDateStrs[0];
        dayStr = arrDateStrs[1];
        yearStr = arrDateStrs[2];
    }
    else
    {
        dayStr = arrDateStrs[0];
        monthStr = arrDateStrs[1];
        yearStr = arrDateStrs[2];
    }
    
    var objdate = new Date(yearStr, monthStr, dayStr);
    return objdate.getTime();
}


// -----------------------------------------------------------------------------
// Description: 
//		Handles My Profile page validation event. Used from ProfileMyPrifile.aspx as handler in CustomValidator
// IN: validator object
// IN: validator arguments
// OUT: none
// ----------------------------------------------------------------------------
function MyProfileValidationFunction(source, args) {
    errorMessage = "";

    var rootAddressAboutMe;
    var rootAddressVitalStatistics;
    var rootAddressContactDetails;

    var rootAddressMyForum;
    var rootAddressHealthDetails;

    var rootAddressMyForum;
    var rootAddressPersonalDetails;

    //normal profile
    if (profileWizardPage == "") {
        rootAddressAboutMe = tabIDs[0];               //tabbed panel root id
        rootAddressVitalStatistics = tabIDs[1];       //tabbed panel root id
        rootAddressContactDetails = tabIDs[2];        //tabbed panel root id
        rootAddressMyForum = tabIDs[3];               //tabbed panel root id
        rootAddressHealthDetails = tabIDs[4];
        rootAddressPersonalDetails = null;
    }
    else {
        rootAddressAboutMe = parentID;
        rootAddressVitalStatistics = parentID;
        rootAddressContactDetails = parentID;
        rootAddressMyForum = parentID;
        rootAddressHealthDetails = parentID;
        rootAddressMyForum = parentID;
        rootAddressPersonalDetails = parentID;
    }

    //error panels on tabs
    var aboutmeErrors = findElementById(rootAddressAboutMe + "_aboutMeErrorsText");
    var vitalStatsErrors = findElementById(rootAddressVitalStatistics + "_vitalStatsErrorsText");
    var contactErrors = findElementById(rootAddressContactDetails + "_contactErrorsText");
    var myForumErrors = findElementById(rootAddressMyForum + "_myForumErrorsText");
    var healthDetailsErrors = findElementById(rootAddressHealthDetails + "_healthDetailsErrorsText");
    //determines if a postback will occur
    var returnValue = true;
    //global set by page to determine whether in wizard
    var wizardPage = profileWizardPage;

    //about me
    if (profileWizardPage == "WizardAboutMe" || profileWizardPage == "") {
        returnValue = ValidateAboutMe(rootAddressAboutMe) && returnValue ? true : false;
    }

    //personal details ------------------------------------------------------------------------------
    if (profileWizardPage == "WizardPersonalDetails") {
        returnValue = ValidatePersonalDetails(rootAddressPersonalDetails) && returnValue ? true : false;
    }
    //---------------------------------------------------------------------------------------------------

    // vital statistics
    if (profileWizardPage == "WizardVitalStatistics" || profileWizardPage == "") {
        returnValue = ValidateVitalStatistics(rootAddressVitalStatistics) && returnValue ? true : false;
        if (profileWizardPage == "WizardVitalStatistics") {
            // the wizard page also includes contact details
            returnValue = ValidateContactDetails(rootAddressContactDetails) && returnValue ? true : false;
        }
    }
    //---------------------------------------------------------------------------------------------------

    // hra vital statistics
    if (profileWizardPage == "HRAWizardVitalStatistics" || profileWizardPage == "") {
        returnValue = ValidateHealthVitalStatistics(rootAddressVitalStatistics) && returnValue ? true : false;
        if (profileWizardPage == "HRAWizardVitalStatistics") {
            // the wizard page also includes contact details
            returnValue = ValidateContactDetails(rootAddressContactDetails) && returnValue ? true : false;
        }
    }
    
    //---------------------------------------------------------------------------------------------------

    //contact details
    if (profileWizardPage == "WizardContactDetails" || profileWizardPage == "") {
        returnValue = ValidateContactDetails(rootAddressContactDetails) && returnValue ? true : false;
    }
    //---------------------------------------------------------------------------------------------------

    //My Forum
    if ((profileWizardPage == "WizardMyForum" || profileWizardPage == "") && rootAddressMyForum != null) {
        returnValue = ValidateMyForum(rootAddressMyForum) && returnValue ? true : false;
    }
    //----------------------------------------------------------------------------------------------------    
    //healthDetails
    if (profileWizardPage == "WizardHealthDetails" || profileWizardPage == "") {
        returnValue = ValidateHealthDetails(rootAddressHealthDetails, profileWizardPage) && returnValue ? true : false; ;
    }
    //----------------------------------------------------------------------------------------
    if (errorMessage != "") {
        errorMessage = "<ul>" + errorMessage + "</ul>";
    }

    //add any error messages to the visible message panel (id not an empty string)
    if (aboutmeErrors != null) {
        aboutmeErrors.innerHTML = errorMessage;
    }
    if (vitalStatsErrors != null) {
        vitalStatsErrors.innerHTML = errorMessage;
    }
    if (contactErrors != null) {
        contactErrors.innerHTML = errorMessage;
    }
    if (myForumErrors != null) {
        myForumErrors.innerHTML = errorMessage;
    }
    if (healthDetailsErrors != null) {
        healthDetailsErrors.innerHTML = errorMessage;
    }

    //this will show a pop up. the pop up can call systembuttonclicked again
    // the flag is set to true if ok clicked on pop up (see PopUpPostBack())
    if (returnValue == true && popUpPriorToPostbackArray['isVisible'] == true &&
        popUpPriorToPostbackArray['flag'] == false) {
        returnValue = false;
        ShowPopUp();
    }

    args.IsValid = returnValue;
}

// -----------------------------------------------------------------------------
// Description: 
//		Sets button id which initiates postback process
// IN: object that initiates postback
// OUT: none
// ----------------------------------------------------------------------------
function SetButtonIdForPopupPostback(element) {
    popUpPriorToPostbackArray['btnID'] = element.id;
}
