﻿function SetRTPTextBoxRequired(validatorControl, textBoxControl, labelIndicatorControl, isRequired) {
    validatorControl.enabled = isRequired;
    ValidatorUpdateDisplay(validatorControl);

    if (isRequired) {
        textBoxControl.className = 'textBoxRequired';
        if (labelIndicatorControl != null) {
            labelIndicatorControl.style.display = 'inline';
            labelIndicatorControl.style.visibility = '';
        }
    }
    else {
        textBoxControl.className = 'textBox';
        if (labelIndicatorControl != null) {
            labelIndicatorControl.style.display = 'none';
            labelIndicatorControl.style.visibility = 'hidden';
        }
    }
}

function ScrollView(controlId) {
    var el = $get(controlId);
    if (el != null) {
        try{
            el.scrollIntoView();
            el.focus();
        }
        catch(err){
        
        }
    }
}


function firePasswordsMatchEvent(sender, args) 
{
    var masterValidatorID = sender.attributes["masterValidatorID"].value;
    var masterValidator = $get(masterValidatorID);
    ValidatorValidate(masterValidator);
}

function PasswordsMatch(sender, args)
{
    var Password1ID = sender.attributes["Password1ID"].value;
    var Password2ID = sender.attributes["Password2ID"].value;

    var Password1TextBox = $get(Password1ID);
    var Password2TextBox = $get(Password2ID);


    if (Password1TextBox.value == Password2TextBox.value ||
            Password1TextBox.value == '' ||
            Password2TextBox.value == '')
    {
        args.IsValid = true;
    }
    else
    {
        args.IsValid = false;
    }
}

function IncrementClickCount(ctrl, validationGroup) {
    var validated = Page_ClientValidate(validationGroup);
    if (validated) {
        ctrl.attributes['clickcount'].value++;
    }
}

function RadioSelectionRequired(sender, args) {
    var radioButtonIds = sender.attributes["radioButtonIds"].value.split("|");
    for (i = 0; i < radioButtonIds.length; i++) {
        alert($get(radioButtonIds[i]).checked);
        if ($get(radioButtonIds[i]).checked)
        {
            args.IsValid = true;
            return;
        }
    }
    args.IsValid = false;
}

function DateComparison(sender, args) {
    var startDateID = sender.attributes["startDateID"].value;
    var endDateID = sender.attributes["endDateID"].value;

    var startDateTextBox = $get(startDateID);
    var endDateTextBox = $get(endDateID);

    if (startDateTextBox.value == '' ||
            endDateTextBox.value == '') {
        args.IsValid = true;
    }
    else 
    {
        var startDate = Date.parse(startDateTextBox.value);
        var endDate = Date.parse(endDateTextBox.value);

        args.IsValid = (startDate <= endDate);
    }
}

function getDateObject(dateString, dateSeperator) {
    //This function return a date object after accepting 
    //a date string ans dateseparator as arguments
    var curValue = dateString;
    var sepChar = dateSeperator;
    var curPos = 0;
    var cDate, cMonth, cYear;

    //extract day portion
    curPos = dateString.indexOf(sepChar);
    cDate = dateString.substring(0, curPos);

    //extract month portion				
    endPos = dateString.indexOf(sepChar, curPos + 1); cMonth = dateString.substring(curPos + 1, endPos);

    //extract year portion				
    curPos = endPos;
    endPos = curPos + 5;
    cYear = curValue.substring(curPos + 1, endPos);

    //Create Date Object
    dtObject = new Date(cYear, cMonth, cDate);
    return dtObject;
}

function ExpandCollapse(collapserID) {
    var collPanel = $find(collapserID);
    if (collPanel.get_Collapsed())
        collPanel.set_Collapsed(false);
    else
        collPanel.set_Collapsed(true);
}
var test;
function LoadProvincesForCountry(countryControlId, stateDropDownControlId, stateTextBoxControlId) {
    var countryControl = $get(countryControlId);
    var countryValue = countryControl[countryControl.selectedIndex].text;

    var stateControls = new Array()
    stateControls[0] = stateDropDownControlId;
    stateControls[1] = stateTextBoxControlId;

    RTP.Web.WebStore.Site.Scripts.Services.WebStore.GetProvincesForState(countryValue, SuccessGetProvincesForCountry, FailedGetProvincesForCountry, stateControls);
}

function SuccessGetProvincesForCountry(result, stateControls, methodName) {
    var txtState = $get(stateControls[1]);
    var ddState = $get(stateControls[0]);

    // Page element to display feedback.
    SetControlVisibility(txtState, result == null);
    SetControlVisibility(ddState, result != null);

    if (result != null) {
        ddState.options.length = 0;
        for (var i = 0; i < result.length; ++i) {
            AddDropDownOption(ddState, result[i][0], result[i][1]);
        }
        txtState.value = ddState.value;
    }
}

function FailedGetProvincesForCountry(result, stateControls, methodName) {
    alert('unable to load provinces');
}

function SetControlVisibility(control, visible) {
    if (visible) {
            control.style.display = 'inline';
            control.style.visibility = '';
    }
    else {
            control.style.display = 'none';
            control.style.visibility = 'hidden';
    }
}

function AddDropDownOption(selectbox, text, value) {
    var optn = document.createElement("OPTION");
    optn.text = text;
    optn.value = value;
    selectbox.options.add(optn);
}

function GetRadioButtonListValue(id) {
    var radio = document.getElementsByName(id);
    
    for (var ii = 0; ii < radio.length; ii++) {
        if (radio[ii].checked)

            return radio[ii].value;
    }
}

function HandleModalBehavior(controlId) {
    var el = $get(controlId);
    var currentClass;

    if (el != null) {
        currentClass = el.className;
        if (CurrentScreenWidth() < el.clientWidth || CurrentScreenHeight() < el.clientHeight) {
            if (currentClass.indexOf('modalScrollWithBrowser') == -1)
            {
                el.className = currentClass + ' modalScrollWithBrowser';
            }
            window.scrollTo(0, 0);
        }
        else {
            if (currentClass.indexOf('modalScrollWithBrowser') != -1)
            {
                el.className = currentClass.replace(' modalScrollWithBrowser', '');
            }
        }
    }
}

function GetCurrentScreenY() {
    var winY = (document.all) ? window.screenTop : window.screenY;
    return winY;
}

function GetCurrentScreenX() {
    var winX = (document.all) ? window.screenLeft : window.screenX;
    return winX;
}

function CurrentScreenWidth() {
    var viewportwidth;

    // the more standards compliant browsers (mozilla/netscape/opera/IE7) use window.innerWidth and window.innerHeight

    if (typeof window.innerWidth != 'undefined') {
        viewportwidth = window.innerWidth;
    }

    // IE6 in standards compliant mode (i.e. with a valid doctype as the first line in the document)

    else if (typeof document.documentElement != 'undefined'
     && typeof document.documentElement.clientWidth !=
     'undefined' && document.documentElement.clientWidth != 0) {
        viewportwidth = document.documentElement.clientWidth;
    }

    // older versions of IE

    else {
        viewportwidth = document.getElementsByTagName('body')[0].clientWidth;
    }
    
    return viewportwidth;
}

function CurrentScreenHeight() {
    var viewportheight;

    // the more standards compliant browsers (mozilla/netscape/opera/IE7) use window.innerWidth and window.innerHeight

    if (typeof window.innerWidth != 'undefined') {
        viewportheight = window.innerHeight;
    }

    // IE6 in standards compliant mode (i.e. with a valid doctype as the first line in the document)

    else if (typeof document.documentElement != 'undefined'
     && typeof document.documentElement.clientWidth !=
     'undefined' && document.documentElement.clientWidth != 0) {
    viewportheight = document.documentElement.clientHeight;
    }

    // older versions of IE

    else {
        viewportheight = document.getElementsByTagName('body')[0].clientHeight;
    }
    
    return viewportheight;
}

/* The following funcitons allow us to execute code after an async postback */
Sys.Application.add_init(appl_init);

function appl_init() {
    var pgRegMgr = Sys.WebForms.PageRequestManager.getInstance();
    pgRegMgr.add_endRequest(EndRequestHandler);
    pgRegMgr.add_endRequest(PostAsyncScoll);
}

//Handles scroll functionality on async postback
function PostAsyncScoll(sender, args) {
    var controlId = $get('handleModalBehaviorControlId').value;
    if (controlId != '') {
        setTimeout('HandleModalBehavior(\'' + controlId + '\');', 0);
        $get('handleModalBehaviorControlId').value = '';
    }
}

//handles async postback errors.
function EndRequestHandler(sender, args) {
    if (args.get_error() != undefined) {
        var error = args.get_error();
        var errorMessage = error.message;
        args.set_errorHandled(true);

        if (error.name != "Sys.WebForms.PageRequestManagerServerErrorException" && error.httpStatusCode != 0) {
            alert(asnycErrorMessage);
        }
        document.location = document.location;
    }
}

function pause(milliseconds) {
    var dt = new Date();
    while ((new Date()) - dt <= milliseconds) { /* Do nothing */ }
}

function HideValidators() {
    //Hide all validation errors  
    if (window.Page_Validators)
        for (var vI = 0; vI < Page_Validators.length; vI++) {
        var vValidator = Page_Validators[vI];
        vValidator.isvalid = true;
        ValidatorUpdateDisplay(vValidator);
    }
    //Hide all validaiton summaries  
    if (typeof (Page_ValidationSummaries) != "undefined") { //hide the validation summaries  
        for (sums = 0; sums < Page_ValidationSummaries.length; sums++) {
            summary = Page_ValidationSummaries[sums];
            summary.style.display = "none";
        }
    }
}

String.prototype.format = function () {
    var args = arguments;
    return this.replace(/{(\d+)}/g, function (match, number) {
        return typeof args[number] != 'undefined'
      ? args[number]
      : '{' + number + '}'
    ;
    });
};

function OpenDialogueWindow(url) {
    var width = 1020;
    var height = CurrentScreenHeight() * .90;
    var left = GetCurrentScreenX() + ((CurrentScreenWidth() - width) / 2);
    var top = GetCurrentScreenY() + (CurrentScreenHeight() * .1);

    window.open(url, '_blank', 'scrollbars=yes, menubar=no, location=no, status=no, titlebar=no, toolbar=no, width=' + width + ', height=' + height + ', top=' + top + ', left=' + left);
}

function CloseWindowAndRefreshParent() {
    window.opener.location.reload();
    window.close();
}

function DisableEnableValidator(clientID, isBeingDisabled) {
    var myVal = document.getElementById(clientID);
    ValidatorEnable(myVal, isBeingDisabled);
}
