﻿
var ASPprefix = 'ctl00_ContentPlaceHolder1_WizardSurvey_';
var ASPprefixShort = 'ctl00_ContentPlaceHolder1_';
                      


var disableNonSubmitValidation = false;

// will not be enabled if disableNonSubmitValidation is true
var enablePayPageMicroValidation = true;

function toggleAllValidators(isEnable)
{
    
    if ( disableNonSubmitValidation )
    {
        for (i = 0; i < Page_Validators.length; i++)   
        {
            Page_Validators[i].enabled = isEnable;
        }
        
        enablePayPageMicroValidation = isEnable;
    }
}

function attachValidationEvents ( disable )
{
        
    if ( disable )
    {        
        toggleAllValidators(false);
        
        var st1 = $(ASPprefix + 'StartNavigationTemplateContainerID_StepNextButton');
        var st2 = $(ASPprefix + 'StepNavigationTemplateContainerID_StepNextButton');
        var st3 = $(ASPprefix + 'FinishNavigationTemplateContainerID_FinishButton');
        
        
        if ( st1 )
            EventUtil.addEventHandler( st1, 'click', function (){ toggleAllValidators(true); });
        
        if ( st2 )
            EventUtil.addEventHandler( st2, 'click', function (){ toggleAllValidators(true); });
        
        if ( st3 )
            EventUtil.addEventHandler( st3, 'click', function (){ toggleAllValidators(true); });

//        // top navigation buttons
//        var is1 = $(ASPprefixShort + 'ImageStep1');
//        var is2 = $(ASPprefixShort + 'ImageStep2');
//        var is3 = $(ASPprefixShort + 'ImageStep3');
//        var is4 = $(ASPprefixShort + 'ImageStep4');
//        var is5 = $(ASPprefixShort + 'ImageStep5');
//        
//        if ( is1 )
//        {
//            EventUtil.addEventHandler( is1, 'click', function (){ toggleAllValidators(true); });
//        }    
//        if ( is2 )
//        {
//            EventUtil.addEventHandler( is2, 'click', function (){ toggleAllValidators(true); });
//        }    
//        if ( is3 )
//        {
//            EventUtil.addEventHandler( is3, 'click', function (){ toggleAllValidators(true); });
//        }    
//        if ( is4 )
//        {
//            EventUtil.addEventHandler( is4, 'click', function (){ toggleAllValidators(true); });
//        }    
//        if ( is5 )
//        {
//            EventUtil.addEventHandler( is5, 'click', function (){ toggleAllValidators(true); });
//        }    


    }
}


function initialisePages()
{
    String.prototype.trim = function() { return this.replace(/^\s+|\s+$/g, ''); };
    
    var l = window.location.toString().toLowerCase();
    if( l.indexOf('completed.aspx') > -1 )
    {
        switchValidation();
        EventUtil.addEventHandler($(ASPprefixShort + 'btnSubmit'), 'click', skipToTop);

        EventUtil.addEventHandler($(ASPprefixShort + 'JobTitle_txtJobTitle'), 'change', changeJobTitleLabel);
        EventUtil.addEventHandler($(ASPprefixShort + 'WorkplaceLocation_txtWorkplaceLocation'), 'change', changeWorkplaceLocationLabel);
        
        
        setWatermarkEvents();

        
    }    
    if ( l.indexOf('survey.aspx') > -1 )        
    {
        showStudying();
        attachLongServiceLeaveDdl();
        
        
        setWatermarkEvents();
        attachValidationEvents ( disableNonSubmitValidation );
        
        
        if($(ASPprefix + 'StartNavigationTemplateContainerID_StepNextButton'))
            EventUtil.addEventHandler($(ASPprefix + 'StartNavigationTemplateContainerID_StepNextButton'), 'click', skipToTop);
        if($(ASPprefix + 'StepNavigationTemplateContainerID_StepNextButton'))
            EventUtil.addEventHandler($(ASPprefix + 'StepNavigationTemplateContainerID_StepNextButton'), 'click', skipToTop);
        
        
        if($(ASPprefix + 'BasePay_ddlBasePay'))
        {
            if(isIE)
            {
                $(ASPprefix + 'BasePay_txtBasePay').style.height = 
                $(ASPprefix + 'Superannuation_txtSuperannuation').style.height = 
                $(ASPprefix + 'AnnualBonus_txtAnnualBonus').style.height = 
                $(ASPprefix + 'LastPayRise_txtLastPayRise').style.height = '13px';
            }
        }
        

    }        
}

function skipToTop()
{
        if(!Page_IsValid)
            window.location = '#scrollToTopPlcHldr';
}


function  changeJobTitleLabel()
{
    var el = $(ASPprefixShort + 'JobTitle_txtJobTitle');
    var txt = el.value;
    if(txt != '')
    {
        if (isMoz)
            $(ASPprefixShort + 'lblSalaryReportFor').textContent = txt;
        else
            $(ASPprefixShort + 'lblSalaryReportFor').innerText = txt;
    }
}

function  changeWorkplaceLocationLabel()
{
    var el = $(ASPprefixShort + 'WorkplaceLocation_txtWorkplaceLocation');
    var txt = el.value;
    if(txt != '')
    {
        if (isMoz)
            $(ASPprefixShort + 'lblSalaryReportLocation').textContent = txt;
        else
            $(ASPprefixShort + 'lblSalaryReportLocation').innerText = txt;
    }
        
}
        


function disableEnableValidator(id, isEnable)
{
    if ( enablePayPageMicroValidation )
    {

        var validatorID = id.replace('txt', 'cv');
        
        for (i = 0; i < Page_Validators.length; i++)   
        {
            if (Page_Validators[i].id == validatorID)
            {
                Page_Validators[i].enabled = isEnable;
                
                if (isEnable)
                    swapValidationCss(true, validatorID);
                
                break; 
            }
        }

    }
}


function showHidePageErrorMsg()
{
    var element; 
    
    element = $(ASPprefix + 'pnlPageErrorMessage1');
    if (element === null)
        element = $(ASPprefix + 'pnlPageErrorMessage2');
    if (element === null)   
        element = $(ASPprefix + 'pnlPageErrorMessage3');
    if (element === null)   
        element = $(ASPprefix + 'pnlPageErrorMessage4');
    if (element === null)   
        element = $(ASPprefix + 'pnlPageErrorMessage5');
    if (element === null)   
        element = $(ASPprefixShort + 'pnlPageErrorMessage1'); // completed.aspx page

    if(element)
    {
        element.style.display = 'none';
        for (i = 0; i < Page_Validators.length; i++)  
        {
            var a = Page_Validators[i];
            if (Page_Validators[i].isvalid == false)
            {
                element.style.display = 'block';
                return;
            }
        }
    }
}


function ValidateRadioList(source, clientside_arguments)
{

    var id = source.id;
    var idxLast = id.lastIndexOf('_');
    var prefix = id.substring(0, idxLast);
    var actualID = id.substring(idxLast);
    var IDtoReplace = prefix + actualID.replace('_cv', '_div');

    var condition = clientside_arguments.Value > 0;

    changeCssClass(IDtoReplace, condition ? 'questionContainer' : 'validationHighlight');
    clientside_arguments.IsValid = condition;

    showHidePageErrorMsg();
}

function ValidateDropDownList(source, clientside_arguments)
{ 
    var result = (clientside_arguments.Value > 0);
    
    swapValidationCss(result, source.id);
    
    clientside_arguments.IsValid = result;
    
    showHidePageErrorMsg();
}

function validateDropDownListStudying(source, clientside_arguments)
{ 
    var result = false;

    var element = $(ASPprefix + 'AreYouStudying_rblAreYouStudying_0');
    if (element.checked == true)
    {
        result = true;
    }
    else
    {
        result = (clientside_arguments.Value > 0);
    }
    swapValidationCss(result, source.id);
    showHidePageErrorMsg();
    
    clientside_arguments.IsValid = result;

}

function ValidateText(source, clientside_arguments)
{   
    var text = clientside_arguments.Value.trim();
    var result = (text.length > 0);
    
    swapValidationCss(result, source.id);
        
    showHidePageErrorMsg();
    
    clientside_arguments.IsValid = result;
    return result;
}



//Validators for "Other" text boxes

function validateITcertification(source, clientside_arguments)
{
    clientside_arguments.IsValid = validateOther('ITCertification_ddlITCertification', source, clientside_arguments);
}

function validateLevelOfEducation(source, clientside_arguments)
{
    clientside_arguments.IsValid = validateOther('LevelOfEducation_ddlLevelOfEducation', source, clientside_arguments);
}

function validateWhatQualificationStudying(source, clientside_arguments)
{
    var element = $(ASPprefix + 'AreYouStudying_rblAreYouStudying_0');
    if (element.checked == true)
        clientside_arguments.IsValid = true;
    else
        clientside_arguments.IsValid = validateOther('WhatQualificationStudying_ddlWhatQualificationStudying', source, clientside_arguments);
}

function validateWhyAreYouStudying(source, clientside_arguments)
{
    var element = $(ASPprefix + 'AreYouStudying_rblAreYouStudying_0');
    if (element.checked == true)
        clientside_arguments.IsValid = true;
    else
        clientside_arguments.IsValid = validateOther('WhyAreYouStudying_ddlWhyAreYouStudying', source, clientside_arguments);
}

function validateOther(ddlId, source, clientside_arguments)
{
    var ddl = $(ASPprefix + ddlId);
    
    var result = isAnswerOther(ddl);
    if (result == true)
        return ValidateText(source, clientside_arguments);
    else
    {
        swapValidationCss(true, source.id);
        return true;
    }
}

function isAnswerOther(element)
{
    var answer = element[element.selectedIndex].text;

    return (answer == 'Other')
}

////////////////////

function validateEmail(str)
{
    var sRE = /\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*/;
    //var sRE = /^[a-zA-Z][\w\.-]*[a-zA-Z0-9]@[a-zA-Z0-9][\w\.-]*[a-zA-Z0-9]\.[a-zA-Z][a-zA-Z\.]*[a-zA-Z]$/;
    var oRE = new RegExp(sRE);
    
    var a = str.search(oRE);
    return a == -1 ? false : true;        
}


function clientValidateEmail(source, clientside_arguments)
{
    var result = false;

    var idOfMessge = '';
    var questionID = '';
    var srcId = source.id;

    idOfMessge = srcId.substring(srcId.lastIndexOf('_') + 3);
    questionID = idOfMessge; 
    idOfMessge = 'div' + questionID + 'Message';

    if ( validateEmail( clientside_arguments.Value ) && clientside_arguments.Value != '' )
    {
        result = true;
    }
    else
    {
        if ($(idOfMessge))
            removeChildrenFromNode($(idOfMessge));

        var msg = DOMelement('span', null, null);
        if(clientside_arguments.Value != "")
            msg = appendText(msg,' Doesn\'t look like an email address');            
        else
            msg = appendText(msg,' Looks like you missed this one');            
            
        deleteCookie(source.id);
            
        $(idOfMessge).appendChild(msg);

        result = false;
    }
    
    swapValidationCss(result, srcId);
    
    clientside_arguments.IsValid = result;

}


function validateFeedbackEmail(email)
{
    if (email.value != '')
    {
        if(!validateEmail(email.value))
        {
            alert('Doesn\'t look like an email address.');
            email.focus();
            return;
        }        
    }
}

/*function validateFriendsEmail(email)
{
    if (email.value != '')
    {
        if(!validateEmail(email.value))
        {
            alert('Doesn\'t look like an email address.');
            email.focus();
            return;
        }        
    
        if (email.value == $(ASPprefixShort + 'YourEmail_txtYourEmail').value ||
            email.value == $(ASPprefixShort + 'YourEmailCompetitionSignUp_txtYourEmailCompetitionSignUp').value )
        {
            alert('You cannot enter your own email address in friends\' addresses.');
            email.value = '';
            email.focus();
            return;
        }
                
        var i = 1;
        var emailElement;
        do 
        {
            emailElement = $(ASPprefixShort + 'txtEmailFriend' + i);
            if (emailElement)
            {
                if (emailElement.id != email.id)
                {
                    if (emailElement.value != '')
                    {
                        if(emailElement.value == email.value)
                        {
                            alert('You have already entered this email address');
                            email.value = '';
                            email.focus();
                            return;
                        }
                    }
                }    
            }
            i++;                        
        }
        while (emailElement)
        
    }
}*/


function showIncludeSalaryReport(checked, id)
{
    var element = $(id);
    element.style.display = (checked == true) ? 'block' : 'none';
    //$('show2ndEmail').style.display = (checked == true) ? 'none' : 'block';

    $(ASPprefixShort + 'hfIncludeReport').value = (checked == true) ? "1" : "0";
    switchValidation();
}

function showHideIncludeSalaryReportControls()
{
    var isAsSoonAsPublished = $(ASPprefixShort + 'chkNotifyWhenPublished').checked;
    var isNotifyBeforePayReview = $(ASPprefixShort + 'chkNotifyBeforePayReview').checked;

    if (isAsSoonAsPublished == false && isNotifyBeforePayReview == false)
    {
        $(ASPprefixShort + 'hfNotify').value = "0";
        $(ASPprefixShort + 'hfIncludeReport').value = "0";
        
        $('divCompletedEmailWrapper').style.display = 
        $('divIncludeSalaryReportWrapper').style.display = 
        $('ShowIncludeSalaryReport').style.display = 'none';
        
        $('divAccNotifyChk').style.backgroundImage = "url('/Images/checkbox_unchecked.png')";

        $(ASPprefixShort + 'YourEmail_cvYourEmail').enabled = false;

        expandByElement($('divAccNotifyTitle'));

    }
    else
    {
        $('divCompletedEmailWrapper').style.display = 
        $('divIncludeSalaryReportWrapper').style.display = 'block';

        $('divAccNotifyChk').style.backgroundImage = "url('/Images/checkbox_checked.png')"
    }
    
    toggleDisplayButtonOrLink();
    
    switchValidation();
    accordionIni(false); 

}

function switchValidation()
{
    //$('show2ndEmail').style.display = 'none';

    var isNotify = $(ASPprefixShort + 'hfNotify').value;
    //var isIncludeReport = $(ASPprefixShort + 'chkIncludeSalaryReport').checked;
    var isIncludeReport = $(ASPprefixShort + 'hfIncludeReport').value == "1";
    
    //var isSignUp = $(ASPprefixShort + 'hfSignUp').value;

    var isAsSoonAsPublished = $(ASPprefixShort + 'chkNotifyWhenPublished').checked;
    var isNotifyBeforePayReview = $(ASPprefixShort + 'chkNotifyBeforePayReview').checked;


    if (isNotify == "1")
    {
        if(isIncludeReport  && isAsSoonAsPublished && isNotifyBeforePayReview )
        {
            for (i = 0; i < Page_Validators.length; i++)   
            {
                Page_Validators[i].enabled = true;
            }    
            //$(ASPprefixShort + 'YourEmailCompetitionSignUp_cvYourEmailCompetitionSignUp').enabled = false;
        }
        else
        {
            for (i = 0; i < Page_Validators.length; i++)   
            {
                Page_Validators[i].enabled = false;
            }
            if(isAsSoonAsPublished || isNotifyBeforePayReview)
            {
                $(ASPprefixShort + 'YourEmail_cvYourEmail').enabled = true;
            }
        }
        //$('show2ndEmail').style.display = 'none';

        //$(ASPprefixShort + 'YourEmailCompetitionSignUp_cvYourEmailCompetitionSignUp').enabled = false;

    }
   /* else
    {
            for (i = 0; i < Page_Validators.length; i++)   
            {
                Page_Validators[i].enabled = false;
            }    
                       
            if($(ASPprefixShort + 'YourEmailCompetitionSignUp_txtYourEmailCompetitionSignUp').value == '')
               $(ASPprefixShort + 'YourEmailCompetitionSignUp_txtYourEmailCompetitionSignUp').value = $(ASPprefixShort + 'YourEmail_txtYourEmail').value;

            
            $('show2ndEmail').style.display = (isSignUp == "1") ? 'block' :'none';
            
    }*/
    /*if (isSignUp == "1")
    {
        if(isNotify == "0")
            $(ASPprefixShort + 'YourEmailCompetitionSignUp_cvYourEmailCompetitionSignUp').enabled = true;
        
        $(ASPprefixShort + 'YourName_cvYourName').enabled = true;
    }
    else
    {
        $(ASPprefixShort + 'YourEmailCompetitionSignUp_cvYourEmailCompetitionSignUp').enabled = false;
        $(ASPprefixShort + 'YourName_cvYourName').enabled = false;
    }*/
    
}


function enableDisableValidationOnAccordionClick(id, className)
{
    var isOn = (className == 'accordion_on') ? "1" : "0";
    
    if(id == 'divAccNotifyTitle')
    {
        $('divAccNotifyChk').style.backgroundImage = (isOn == "1") ? "url('/Images/checkbox_checked.png')" : "url('/Images/checkbox_unchecked.png')";
        $(ASPprefixShort + 'hfNotify').value = isOn;
        
        showHideNotifyControls(isOn);
        
        if(isOn == "1")
        {
            //$('notifyCheckBoxWrapper').style.display = 'block';
            $(ASPprefixShort + 'chkNotifyWhenPublished').checked = true;
            $(ASPprefixShort + 'chkNotifyBeforePayReview').checked = true;
            $(ASPprefixShort + 'chkIncludeSalaryReport').checked = true;
            
            $('divCompletedEmailWrapper').style.display = 
            $('divIncludeSalaryReportWrapper').style.display = 'block';    

            
            switchValidation();

            showHideIncludeSalaryReportControls();
                   
            
            $(ASPprefixShort + 'hfNotify').value = $(ASPprefixShort + 'chkNotifyWhenPublished').checked ? "1" : "0";

            setTimeout('accordionIni(false)', 400);
        }
        else
        {
            $(ASPprefixShort + 'chkNotifyWhenPublished').checked = false;
            $(ASPprefixShort + 'chkNotifyBeforePayReview').checked = false;
            $(ASPprefixShort + 'chkIncludeSalaryReport').checked = false;
            switchValidation();
            
        }        

    }
    else if(id == 'divAccSignUpTitle')
    {
        $('divAccSignUpChk').style.backgroundImage = (isOn == "1") ? "url('/Images/checkbox_checked.png')" : "url('/Images/checkbox_unchecked.png')";
        $(ASPprefixShort + 'hfSignUp').value = isOn;
        
        setTimeout('accordionIni(true)', 400);
        switchValidation();
        

    }
    toggleDisplayButtonOrLink();
    
    accordionIni(true); 
}

function toggleDisplayButtonOrLink()
{
    if($(ASPprefixShort + 'hfNotify').value == '0')// && $(ASPprefixShort + 'hfSignUp').value == '0')
    {
        $(ASPprefixShort + 'btnSubmit').style.display = 'none';
        $('spanDoneOptOut').style.display = 'block';
        $(ASPprefixShort + 'pnlPageErrorMessage1').style.display = 'none';    
    }
    else
    {
        $('spanDoneOptOut').style.display = 'none';    
        $(ASPprefixShort + 'btnSubmit').style.display = 'block';
    }

}


function showHideNotifyControls(isOn)
{
    $('accTopContent').style.visibility = (isOn == '1') ? 'visible' : 'hidden';
}

function validateCompletedForm()
{
    var chkIncludeSalaryReport = $(ASPprefixShort + 'chkIncludeSalaryReport');
    
    if(chkIncludeSalaryReport.checked == false)
    {
        for (i = 0; i < Page_Validators.length; i++)   
        {
            Page_Validators[i].isvalid = true;
            ValidatorEnable(Page_Validators[i], false); 
        }
        
        Page_BlockSubmit = !Page_IsValid;
    }
    else
    {
        Page_BlockSubmit = !Page_IsValid;
        alert(Page_IsValid);
        
    }
    ValidatorCommonOnSubmit();
    return !Page_IsValid;
}


function ValidateAmountAllowBlank(source, clientside_arguments)
{
    if (clientside_arguments.Value.length > 0)
        ValidateAmount(source, clientside_arguments);
    else
    {
        swapValidationCss(true, source.id);
        clientside_arguments.IsValid = true;
    }
}

var arrValidators = new Array(); // used by function ValidateAmount(source, clientside_arguments)
function ValidateAmount(source, clientside_arguments)
{
    var idOfMessge = '';
    var questionID = '';
    var srcId = source.id;

    idOfMessge = srcId.substring(srcId.lastIndexOf('_') + 3);
    questionID = idOfMessge; 
    idOfMessge = 'div' + questionID + 'Message';

        
    if (!getCookie(source.id))
        setCookie(source.id,'');

    var idxCurrentValidator;
    
    for (i = 0; i < Page_Validators.length; i++)   
    {
        if (Page_Validators[i].id == source.id)
        {
            idxCurrentValidator = i;
            break; 
        }
    }

    for (i = 0; i < Page_Validators.length; i++)   
    {
        if (arrValidators.toString().indexOf(Page_Validators[i].id) > -1)
        {   
            clientside_arguments.IsValid = true;
            swapValidationCss(clientside_arguments.IsValid, Page_Validators[i].id);

            clientside_arguments.IsValid = true;
            arrValidators = removeFromArray(Page_Validators[i].id, arrValidators);
            
            return true;
        }
    }

    var result = false;
//    val = to2DecimalPlaces(clientside_arguments.Value);

    val = formatAmount( clientside_arguments.Value ) ;
         
//    val = (clientside_arguments.Value).replace(",", "");
    
    if (val != '')
    {
        if (validateDecimal_WithComas(val))
        {
            if(getCookie(source.id) == '' || getCookie(source.id) != val)
            {

                var rangeValidationMsg = validateRange(parseInt( val.replace(/,/g , "" ) ), questionID);
                if (rangeValidationMsg != '')
                {
                    removeChildrenFromNode($(idOfMessge));

                    
                    var txtID = srcId.replace("_cv", "_txt");
                    $(txtID).value = val;

                    var msg = DOMelement('span', null, null);
                    msg = appendText(msg, rangeValidationMsg);            
                    
                    var click = DOMelement('span', null, null);
                    click.className = 'yesClick';
                    click = appendText(click,'Yes');
                    click.onclick = function(){
                                                val = formatAmount( clientside_arguments.Value );
                                                arrValidators.push(source.id)
                                                clientside_arguments.IsValid = true;
                                                ValidatorValidate( Page_Validators[idxCurrentValidator], 'vgrSalarySurvey', null);
                                                setCookie(source.id, val);
                                              };            
                    msg.appendChild(click);
                    
                    $(idOfMessge).appendChild(msg);
                    result = false;
                }
                else
                {
                    result = true;
                }
            }
            else if (getCookie(source.id) == val)
                result = true;
        }
        else
        {
            removeChildrenFromNode($(idOfMessge));

            var msg = DOMelement('span', null, null);
            msg = appendText(msg,'Please enter a valid amount');            
            
            deleteCookie(source.id);
            
            $(idOfMessge).appendChild(msg);
            
            result = false;
        }
    }
    else
    {
        $(idOfMessge).firstChild.data = 'Looks like you missed this one';
        result = false;
    }   
        
    swapValidationCss(result, source.id);

    clientside_arguments.IsValid = result;
}


function reValidate(element)
{
    if (enablePayPageMicroValidation )
    {
        var validatorID = element.id.replace('ddl', 'cv');

        for (i = 0; i < Page_Validators.length; i++)   
        {
            if ( Page_Validators[i].id == validatorID)
            {   
                Page_Validators[i].isvalid = false;
                ValidatorValidate(Page_Validators[i], 'vgrSalarySurvey', null);
                return;    
            }            
        }
        
    }   
}


function ValidatePage()
{
    if (!Page_Validators)
        return true;

    for (i = 0; i < Page_Validators.length; i++)   
    {
        try
        {
        
         ValidatorValidate(Page_Validators[i], 'vgrSalarySurvey', null);
            
           
        
            if (Page_Validators[i].isvalid == false)
            {
                var aaa = $(Page_Validators[i].id);
                aaa.evaluationfunction(aaa);
                
                return false;
            }
        }
        catch(exception)
        {

        }    
    }
       
    return true;   

}

function swapValidationCss(condition, id)
{
    var idxLast = id.lastIndexOf('_');
    var prefix = id.substring(0, idxLast);
    var actualID = id.substring(idxLast);
    var IDtoReplace = prefix + actualID.replace('_cv', '_div');

    changeCssClass(IDtoReplace, condition ? 'questionContainer' : 'validationHighlight');
}


function validateRange(val, questionId)
{
    var result = '';

    switch(questionId)
    {
        case 'BasePay':
        {
            result = checkBasePayRange(parseInt(val));
            break;
        }
        case 'Superannuation':
        {
            result = checkSuperannuationRange(parseInt(val));
            break;
        }
        case 'AnnualBonus':
        {
            result = checkAnnualBonusRange(parseInt(val));
            break;
        }
        case 'LastPayRise':
        {
            result = checkLastPayRiseRange(parseInt(val));
            break;
        }
    
    }
       
    return result;            
}       


function validateNumber(str)
{
    return /^\d+$/.test(str) ? true : false;
}

function validateDecimal(str)
{
    return /^[-]?([1-9]{1}[0-9]{0,}(\.[0-9]{0,2})?|0(\.[0-9]{0,2})?|\.[0-9]{1,2})$/.test(str) ? true : false;
}


function validateDecimal_WithComas(str)
{

    return /^\$?([0-9]{1,3},([0-9]{3},)*[0-9]{3}|[0-9]+)(.[0-9][0-9])?$/.test(str) ? true : false;
    
}

function formatAmount ( val )
{
    var result = val.toString();


    var countOfComas = CountValue ( result, "," );
    var countOfDots = CountValue ( result, "." );

    var indexOfLastDot = result.lastIndexOf('.');
    var indexOfLastComa = result.lastIndexOf(',');
    
    
    var lngth = (result.toString()).length; 
    
    var digitsAfterLastDot = indexOfLastDot > -1 ? (lngth - indexOfLastDot - 1) : 0;
    var digitsAfterLastComa = indexOfLastComa > -1 ? (lngth - indexOfLastComa - 1) : 0;

    if ( countOfComas == 0 && countOfDots == 0 )
        return result;
    
    if ( countOfComas > 0 && countOfDots == 0 )
    {
        if (digitsAfterLastComa == 2)
            return result = replaceLastComaWithDot( result );

        if (digitsAfterLastComa == 3)
            return result;    
    }
    
    if ( countOfComas == 0 && countOfDots > 0 )
    {
        if (digitsAfterLastDot == 2)
        {
           result = result.replace (/\./g, ",");    
           return replaceLastComaWithDot( result );
        }
        
        if (digitsAfterLastDot == 3)
            return result.replace (/\./g, ",");    
    }
    

    if ( countOfComas > 0 && countOfDots > 0 )
    {
        if (digitsAfterLastDot == 2)
        {
            return result;
        }
        
        if (digitsAfterLastComa == 2)
        {
           result = result.replace (/\./g, ",");    
           return replaceLastComaWithDot( result );
        }
    
    }

    // this will get validate by validateDecimal_WithComas anyway to prevent really bad entries
    return result;
}

function replaceLastComaWithDot ( val )
{
    var indexOfLastComa = val.lastIndexOf(',');
    
    var c = val.toString();
    
    var a = c.substring( 0, indexOfLastComa );
    var b = c.substring( indexOfLastComa + 1 );
    
    return a + "." + b;
    
}


function CountValue( strText, splitter )
{
    var intCount = 0;
 
    var a = strText.split( splitter );
 
    if ( a.length > 0 )
        intCount = a.length - 1;

    return  intCount ;
}



function to2DecimalPlaces(amount) 
{
    var result = amount;
    var idx = amount.lastIndexOf('.');
    var idx0 = amount.indexOf('.');
    
    if(idx > -1)
    {
        if (idx0 != idx)
            return 'xx'; // value to break validation
            
        var xx = amount.split('.');
        var pre = xx[0];
        var post = xx[1];
    
        if (validateNumber(pre) && validateNumber(post) )
        {
            if (post.length > 0)
                result = pre + '.' + post.substring(0, 2);
            else if (idx0 > -1 && post.length == 0)
                result = "xx"; // value to break validation when . is last character
            else 
                result = pre;                            
        }
        else
            result = "xx";
        
    }
    return result;
}


var lowMsg = 'Seems a bit low, are you sure? ';
var highMsg = 'Seems a bit high, are you sure? ';


function checkBasePayRange(val)
{

    var maxValue = 500000;
    var minValue = 5000;


    var result = '';
    var ddlFrequency = $(ASPprefix + 'BasePay_ddlBasePay');
    var payFrequency = ddlFrequency[ddlFrequency.selectedIndex].text;
    
    var payYear = calculateYearlyPay(val);
    var multiplicator = 1;
    
    switch (payFrequency)
    {
        case 'Year':
        {
            maxValue = 500000;
            minValue = 5000;
            
            multiplicator = 1;    
            break;
        }
        case 'Month':
        {
            maxValue = 41667;
            minValue = 417;
            
            multiplicator = 12;
            break;
        }
        case 'Week':
        {
            maxValue = 9615;
            minValue = 96;
            
            multiplicator = 52;
            break;
        }
        case 'Day':
        {
            maxValue = 1923;
            minValue = 19;
            
            multiplicator = 260;
            break;
        }
        case 'Hour':
        {
            maxValue = 240;
            minValue = 2;
            
            multiplicator = 10400;
            break;
        }
    }
    if ( val  > maxValue )
        result = highMsg;
    else if (val < minValue )
        result = lowMsg;
    
    return result;
}

function checkSuperannuationRange(val)
{
    var result = '';
    
    var maxValue = 20;
    var minValue = 8;
    
    dividor = 1;
    
    var ddlSuperFrequency = $(ASPprefix + 'Superannuation_ddlSuperannuation');
    var superFrequency = ddlSuperFrequency[ddlSuperFrequency.selectedIndex].text;
    
    if (superFrequency == '% of pay')
    {
        maxValue = 20;
        minValue = 8;
        
        if (val > maxValue)
            result= highMsg;
        else if (val < minValue)
            result = lowMsg;                    
    }
    else
    {
        switch (superFrequency)
        {
            case '$ yearly':
            {
                maxValue = 100000;
                minValue = 400;
                
                dividor = 1;    
                break;
            }
            case '$ monthly':
            {
                maxValue = 8333;
                minValue = 33;
                
                dividor = 12;    
                break;
            }
            case '$ fortnightly':
            {
                maxValue = 3846;
                minValue = 15;
                
                dividor = 26;    
                break;
            }
            case '$ weekly':
            {
                maxValue = 1923;
                minValue = 8;
                
                dividor = 52;    
                break;
            }
        }        
        
        if (val > maxValue)
            result = highMsg;
        else if (val < minValue)
            result = lowMsg;                    
    }
    
    return result;
}
function checkAnnualBonusRange(val)
{
    var result = '';

    var maxValue = 80;
    var minValue = 0;

    var percentage = 0;
    
    var ddlBonusMode = $(ASPprefix + 'AnnualBonus_ddlAnnualBonus');
    var bonusMode = ddlBonusMode[ddlBonusMode.selectedIndex].text;
    
    switch (bonusMode)
    {
        case '% of pay':
        {
            maxValue = 80;
            minValue = 0;
            
            break;
        }
        case '$ amount':
        {
            maxValue = 400000;
            minValue = 0;
            
            break;
        }
    }

    if (val > maxValue)
        result= highMsg;
    else if (val < minValue)
        result = lowMsg;                    
    
    return result;
}
function checkLastPayRiseRange(val)
{
    var result = '';
    
    var maxValue = 80;
    var minValue = 0;

    var ddlPayRiseMode = $(ASPprefix + 'LastPayRise_ddlLastPayRise');
    var payRiseMode = ddlPayRiseMode[ddlPayRiseMode.selectedIndex].text;
    
    switch (payRiseMode)
    {
        case '% of pay':
        {
            maxValue = 80;
            minValue = 1;
            
            percentage = val;
            break;
        }
        case '$ amount':
        {
            maxValue = 400000;
            minValue = 50;
            
            break;
        }
    }

    if (val > maxValue)
        result = highMsg;
    else if (val < minValue)
        result = lowMsg;                    
    
    return result;
}

function calculateYearlyPay(val)
{
    var result = 0;
    var ddlFrequency = $(ASPprefix + 'BasePay_ddlBasePay');
    var payFrequency = ddlFrequency[ddlFrequency.selectedIndex].text;
    
    switch (payFrequency)
    {
        case 'Year':
        {
            result = val;
            break;
        }
        case 'Month':
        {
            result = val * 12;
            break;
        }
        case 'Week':
        {
            result = val * 52;
            break;
        }
        case 'Day':
        {
            result = val * 260;
            break;
        }
        case 'Hour':
        {
            result = val * 10400;
            break;
        }
        
    }
    return result;
    
}



