﻿function addLoadEvent(func) {
    var oldonload = window.onload;

    if (typeof window.onload != 'function')
        window.onload = func;
    else {
        window.onload = function() {
            if (oldonload)
                oldonload();
            func();
        }
    }
}
function SampleAlert() { alert('Working'); }
var MainPaneWidth; var MainPaneHeight;
function ResizePage() {
    var FrameTable = document.getElementById('FrameTable');
    var offsetHeight = 0;
    var mainPaneStartHeight = 0;
    var mainPaneStartWidth = 0;
    var tft = document.getElementById('tft');
    var ftrt = document.getElementById('ftrt');
    var tnft = document.getElementById('tnft');
    var lnft = document.getElementById('lnft');
    var ploading = document.getElementById('ploading');
    if (typeof (tft) != 'undefined' && tft != null) { offsetHeight += tft.offsetHeight; mainPaneStartHeight += tft.offsetHeight; }
    if (typeof (ftrt) != 'undefined' && ftrt != null) { offsetHeight += ftrt.offsetHeight; }
    if (typeof (tnft) != 'undefined' && tnft != null) { offsetHeight += tnft.offsetHeight; mainPaneStartHeight += tnft.offsetHeight; }
    if (typeof (lnft) != 'undefined' && lnft != null) { mainPaneStartWidth += lnft.offsetWidth; }

    if (typeof (FrameTable) != 'undefined' && FrameTable != null) {
        var height = getheight();
        if ((height - offsetHeight - 5) > 0) {
            FrameTable.style.height = (height - offsetHeight - 5) + 'px';
            MainPaneHeight = (height - offsetHeight - 5);
        }

        var width = getwidth();
        MainPaneWidth = width - mainPaneStartWidth;
        
        if (typeof (ploading) != 'undefined' && ploading != null) {
            if (((height - mainPaneStartHeight) / 2) > 0)
                ploading.style.top = ((height - mainPaneStartHeight) / 2) + 'px';

            var width = getwidth();
            if (((width - mainPaneStartWidth) / 2) + mainPaneStartWidth - 100 > 0)
                ploading.style.left = (((width - mainPaneStartWidth) / 2) + mainPaneStartWidth - 100) + 'px';
        }
    }
}

function getheight() {
    if (/Firefox[\/\s](\d+\.\d+)/.test(navigator.userAgent)) {
        return window.innerHeight;
    }
    else if (/Chrome[\/\s](\d+\.\d+)/.test(navigator.userAgent)) {
        return window.innerHeight;
    }
    else {
        var d = document.documentElement;
        var b = document.body;
        var who = d.offsetHeight ? d : b;
        return Math.max(who.scrollHeight, who.offsetHeight);
    }
}

function getwidth() {
    if (/Firefox[\/\s](\d+\.\d+)/.test(navigator.userAgent)) {
        return window.innerWidth;
    }
    else if (/Chrome[\/\s](\d+\.\d+)/.test(navigator.userAgent)) {
    return window.innerWidth;
    }
    else {
        var d = document.documentElement;
        var b = document.body;
        var who = d.offsetWidth ? d : b;
        return Math.max(who.scrollWidth, who.offsetWidth);
    }
}

function addElement(section, template, counter, identifier) {
    var section = document.getElementById(section);
    var template = document.getElementById(template);
    var counter = document.getElementById(counter);

    if (typeof (section) != 'undefined' && section != null && typeof (template) != 'undefined' && template != null && typeof (counter) != 'undefined' && counter != null) {
        var regexp = new RegExp(identifier, 'g');
        var newdiv = document.createElement('div');
        newdiv.setAttribute('id', template.id + ((counter.value - 1) + 2));
        newdiv.innerHTML = template.innerHTML.replace(regexp, ((counter.value - 1) + 2));
        section.appendChild(newdiv);
        counter.value = ((counter.value - 1) + 2);
    }
}

function removeElement(section, template) {
    var section = document.getElementById(section);
    var template = document.getElementById(template);
    if (typeof (section) != 'undefined' && section != null && typeof (template) != 'undefined' && template != null) {
        section.removeChild(template);
    }
}

function isEmpty(str) {
    var chr;

    if (str.length == 0)
        return true;
    for (var i = 0; i < str.length; i++) {
        chr = str.substring(i, i + 1);
        if (chr != ' ')
            return false;
    }
    return true;
}

function isCurrency(str) {
    return RegExp(/^\$?[0-9\,]+(\.\d{0,2})?$/).test(String(str).replace(/^\s+|\s+$/g, ""));
}

function isEmailAddress(str) {
    var regexp = /^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/;
    return (regexp.test(str));
}

function isPhoneNumberNA(str) {
    var regexp = /((\(\d{3}\) ?)|(\d{3}-))?\d{3}-\d{4}/;
    return (regexp.test(str));
}

function isPhoneNumberCA(str) {
    str = str.replace(/[^0-9]/g, '');
    return (str.length >= 10 && str.length <= 20)
}

function isZipCodeUS(str) {
    var regexp = /(^\d{5}$)|(^\d{5}-\d{4}$)/;
    return (regexp.test(str));
}

function isCVV(str) {
    str = str.replace(/[^0-9]/g, '');
    return (str.length == 3 || str.length == 4)
}

function isCC(CC) {
    if (CC.length > 19)
        return (false);

    var sum = 0;
    var mul = 1;
    var l = CC.length;
    var digit, tproduct;

    for (i = 0; i < l; i++) {
        digit = CC.substring(l - i - 1, l - i);
        tproduct = parseInt(digit, 10) * mul;
        if (tproduct >= 10)
            sum += (tproduct % 10) + 1;
        else
            sum += tproduct;

        if (mul == 1)
            mul++;
        else
            mul--;
    }

    if ((sum % 10) == 0)
        return (true);
    else
        return (false);
}

function isZipCodeCA(str) {
    var regexp = /^\s*[a-ceghj-npr-tvxy]\d[a-ceghj-npr-tv-z](\s)?\d[a-ceghj-npr-tv-z]\d\s*$/i;
    return (regexp.test(str));
}

function isSSNCA(str) {
    str = str.replace(/[^0-9]/g, '');
    return (str.length == 9)
}

function isYear(str) {
    str = str.replace(/[^0-9]/g, '');
    return (str.length == 4)
}

function isValidUSDate(strValue) {
    /************************************************
    DESCRIPTION: Validates that a string contains only
    valid dates with 2 digit month, 2 digit day,
    4 digit year. Date separator can be ., -, or /.
    Uses combination of regular expressions and
    string parsing to validate date.
    Ex. mm/dd/yyyy or mm-dd-yyyy or mm.dd.yyyy

PARAMETERS:
    strValue - String to be tested for validity

RETURNS:
    True if valid, otherwise false.

REMARKS:
    Avoids some of the limitations of the Date.parse()
    method such as the date separator character.
    *************************************************/
    var objRegExp = /^\d{1,2}(\-|\/|\.)\d{1,2}\1\d{4}$/

    //check to see if in correct format
    if (!objRegExp.test(strValue))
        return false; //doesn't match pattern, bad date
    else {
        var strSeparator = strValue.substring(2, 3)
        var arrayDate = strValue.split(strSeparator);
        //create a lookup for months not equal to Feb.
        var arrayLookup = { '01': 31, '03': 31,
            '04': 30, '05': 31,
            '06': 30, '07': 31,
            '08': 31, '09': 30,
            '10': 31, '11': 30, '12': 31
        }
        var intDay = parseInt(arrayDate[1], 10);

        //check if month value and day value agree
        if (arrayLookup[arrayDate[0]] != null) {
            if (intDay <= arrayLookup[arrayDate[0]] && intDay != 0)
                return true; //found in lookup table, good date
        }

        //check for February (bugfix 20050322)
        //bugfix  for parseInt kevin
        //bugfix  biss year  O.Jp Voutat
        var intMonth = parseInt(arrayDate[0], 10);
        if (intMonth == 2) {
            var intYear = parseInt(arrayDate[2]);
            if (intDay > 0 && intDay < 29) {
                return true;
            }
            else if (intDay == 29) {
                if ((intYear % 4 == 0) && (intYear % 100 != 0) ||
             (intYear % 400 == 0)) {
                    // year div by 4 and ((not div by 100) or div by 400) ->ok
                    return true;
                }
            }
        }
    }
    return false; //any other values, bad date
}
  

function ProcessCancel() {
    return confirm('Are you sure you want to cancel?. Your changes will not be saved.');
}

function ProcessUndo() {
    return confirm('Are you sure you want to undo changes?. Undo will revert back to the original values. Your changes will not be saved.');
}

function ProcessDelete() {
    return confirm("Are you sure to delete?");
}

function ProcessCopy() {
    return confirm("Are you sure to copy?");
}

function onDateSelectionChanged(sender, eventArgs) {
    var clickedControl = sender;
    var clickedControlId = sender.get_clientControlId();
    var associatedControlId = window.controlMappings[clickedControlId];
    var associatedControl = window[associatedControlId];
    associatedControl.setSelectedDate(clickedControl.getSelectedDate());
    var validationControlId = window.controlMappings[clickedControlId + 'Validation'];
    var validationControl = document.getElementById(validationControlId)
    validationControl.value = clickedControl.formatDate(clickedControl.getSelectedDate(), 'MM/dd/yyyy');
}

function PopupCalendar(element, event) {
    var calendarId = window.controlMappings[element.id];
    var calendar = window[calendarId];
    if (calendar.get_popUpShowing()) {
        calendar.hide();
    }
    else {
        var pickerId = window.controlMappings[calendarId];
        var picker = window[pickerId];
        calendar.setSelectedDate(picker.getSelectedDate());
        calendar.show(element);
    }
}

function TurnAutoCompleteOff(sender) {

    document.getElementById(sender.get_id() + "_Input").setAttribute('autocomplete', 'off');
}

function ValidateComboCA(controlid) {

    var sender = document.getElementById(controlid + '_Input');
    var selectedIndex = document.getElementById(controlid + '_SelectedIndex');

    var IsValid;
    if (selectedIndex.value > 0)
        IsValid = true;
    else
        IsValid = false;
        
    return (IsValid);
}

function trim(str) {
    return str.replace(/^\s+|\s+$/g, '');
}

function ValidateCommon(vObject) {
    var control = document.getElementById(vObject.controlid);
    var focuscontrol = control;
    if (vObject.setfocusid.length > 0)
        focuscontrol = document.getElementById(vObject.setfocusid);

    switch(vObject.controltype.toUpperCase()) {

        case "COMBOBOX":
            if (vObject.isreq && (control.value < 0 || control.value == vObject.initialvalue)) {
                vObject.errormsg += '* ' + vObject.reqmsg + ' \n';
                if (vObject.setfocus && !focuscontrol.disabled) {
                    focuscontrol.focus();
                    vObject.setfocus = false;
                }
                vObject.isvalid = false;
                return false;
            }
            break;

        case "PASSWORD":
            if (vObject.isreq && (control.value < 0 || control.value == vObject.initialvalue)) {
                vObject.errormsg += '* ' + vObject.reqmsg + ' \n';
                if (vObject.setfocus && !focuscontrol.disabled) {
                    control.focus();
                    vObject.setfocus = false;
                }
                vObject.isvalid = false;
                return false;
            }
            break;

        default:
            if (vObject.isreq && (control.value.trim().length == 0 || control.value == vObject.initialvalue)) {
                vObject.errormsg += '* ' + vObject.reqmsg + ' \n';
                if (vObject.setfocus && !focuscontrol.disabled) {
                    focuscontrol.focus();
                    vObject.setfocus = false;
                }
                vObject.isvalid = false;
                return false;
            }
            break;
    }

    switch (vObject.controltype.toUpperCase()) {
        case "PHONE":
        case "EMAILADDRESS":
        case "ZIPCODE":
        case "POSTALCODE":
        case "SSN":
        case "DATE":
        case "CURRENCY":
        case "YEAR":
        case "CC":
        case "CVV":
            if (control.value.trim().length > 0 && control.value != vObject.initialvalue && !ValidateWidget(vObject.controltype.toUpperCase(), control.value)) {
                vObject.errormsg += '* ' + vObject.regmsg + ' \n';
                if (vObject.setfocus && !focuscontrol.disabled) {
                    focuscontrol.focus();
                    vObject.setfocus = false;
                }
                vObject.isvalid = false;
                return false;
            }
            break;
        case "PASSWORD":
            if (control.value.trim().length > 0 && control.value != focuscontrol.value) {
                vObject.errormsg += '* Passwords don\'t match, please re-enter your new password. \n';
                if (vObject.setfocus && !focuscontrol.disabled) {
                    focuscontrol.focus();
                    vObject.setfocus = false;
                }
                vObject.isvalid = false;
                return false;
            }
            else if (control.value.trim().length > 0 && control.value == focuscontrol.value && (control.value.trim().length < 6 || control.value.trim().length > 20)) {
                vObject.errormsg += '* Password should be between 6 and 20 characters long. \n';
                if (vObject.setfocus && !focuscontrol.disabled) {
                    control.focus();
                    vObject.setfocus = false;
                }
                vObject.isvalid = false;
                return false;
            }
            break;
    }
    
    return true;
}

function ValidateWidget(controltype, controlvalue)
{
    
    switch (controltype.toUpperCase()) {
        case "PHONE":
            return isPhoneNumberCA(controlvalue);
        case "EMAILADDRESS":
            return isEmailAddress(controlvalue);
        case "ZIPCODE":
            return isZipCodeUS(controlvalue);
        case "POSTALCODE":
            return isZipCodeCA(controlvalue);
        case "SSN":
            return isSSNCA(controlvalue);       
        case "DATE":
            return isValidUSDate(controlvalue);
        case "CURRENCY":
            return isCurrency(controlvalue);
        case "YEAR":
            return isYear(controlvalue);       
        case "CC":
            return isCC(controlvalue);
        case "CVV":
            return isCVV(controlvalue);       
        default:
            return false;   
    }
}

function ValidationObject(controltype, controlid, isreq, setfocus, setfocusid, reqmsg, regmsg, errormsg, isvalid, regexpress, initialvalue) {
    this.controltype = controltype;
    this.controlid = controlid; 
    this.isreq = isreq;
    this.setfocus = setfocus;
    this.setfocusid = setfocusid;
    this.reqmsg = reqmsg;
    this.regmsg = regmsg;
    this.errormsg = errormsg;
    this.isvalid = isvalid;
    this.regexpress = regexpress;
    this.initialvalue = initialvalue;
}

function CopyValidationObject(vObject, controltype, controlid, isreq, setfocus, setfocusid, reqmsg, regmsg, errormsg, isvalid, regexpress, initialvalue) {
    vObject.controltype = controltype;
    vObject.controlid = controlid;
    vObject.isreq = isreq;
    vObject.setfocus = setfocus;
    vObject.setfocusid = setfocusid;
    vObject.reqmsg = reqmsg;
    vObject.regmsg = regmsg;
    vObject.errormsg = errormsg;
    vObject.isvalid = isvalid;
    vObject.regexpress = regexpress;
    vObject.initialvalue = initialvalue;
}
function ValidationSummary(errormsg) {
    alert(errormsg);
}
function UploadError(sender, args) {
    alert(args.get_errorMessage());
}
function UploadComplete(sender, args) {
    var fileSize = parseInt(args.get_length());
    var filename = args.get_fileName();
    var filext = '';
    if (filename != "") {
        var arr1 = new Array;
        arr1 = filename.split("\\");
        var len = arr1.length;
        var img1 = arr1[len - 1];
        if (img1.indexOf(".") > 0)
            filext = img1.substring(img1.lastIndexOf(".") + 1);
    }

    switch ('.' + filext.toUpperCase()) {
        case ".JPG":
        case ".JPEG":
        case ".GIF":
        case ".PNG":
        case ".TIF":
        case ".TIFF":
        case ".DOC":
        case ".DOCX":
        case ".MSG":
        case ".RTF":
        case ".TXT":
        case ".CSV":
        case ".DAT":
        case ".PPT":
        case ".XML":
        case ".XLS":
        case ".XSLT":
        case ".ZIP":
        case ".RAR":
        case ".PDF":
            alert("Upload has been completed successfully. \nPlease click 'OK' to continue, click 'Cancel' to cancel or select another file.");
            break;

        default:
            var err = new Error();
            err.name = 'My API Input Error';
            err.message = 'Please select an acceptable file type.';
            throw (err);
            return false;
    }
}

function UploadStarted(sender, args) {
    var filename = args.get_fileName();
    var filext = '';
    if (filename != "") {
        var arr1 = new Array;
        arr1 = filename.split("\\");
        var len = arr1.length;
        var img1 = arr1[len - 1];
        if (img1.indexOf(".") > 0)
            filext = img1.substring(img1.lastIndexOf(".") + 1);
    }

    switch ('.' + filext.toUpperCase()) {
        case ".JPG":
        case ".JPEG":
        case ".GIF":
        case ".PNG":
        case ".TIF":
        case ".TIFF":
        case ".DOC":
        case ".DOCX":
        case ".MSG":
        case ".RTF":
        case ".TXT":
        case ".CSV":
        case ".DAT":
        case ".PPT":
        case ".XML":
        case ".XLS":
        case ".XSLT":
        case ".ZIP":
        case ".RAR":
        case ".PDF":
            return true;
            break;

        default:
            var err = new Error();
            err.name = 'My API Input Error';
            err.message = 'Please select an acceptable file type.';
            throw (err);
            return false;
    }
}

function ShowModalPopup(modalPopupId, zIndex) {

    try {
        if (modalPopupId == null) throw new Error(0, 'Incorrect value of param modalPopupId!');

        var modalPopupBehavior = $find(modalPopupId);

        if (modalPopupBehavior == null) throw new Error(0, 'Not found modal popup ' + modalPopupId + '!');

        zIndex = typeof (zIndex) != 'undefined' ? zIndex : null;

        if (zIndex != null) {
            //alert(modalPopupBehavior._backgroundElement.style.zIndex);
            modalPopupBehavior._backgroundElement.style.zIndex = zIndex;
            modalPopupBehavior._foregroundElement.style.zIndex = zIndex + 1;
            //alert(zIndex);
        }

        //modalPopupBehavior.show();
    }
    catch (ex) {
        alert('Exception in ShowModalPopup: ' + ex.message);
    }
}

function GetTime(hour, min, ampm) {
    var now = new Date("01/01/2011");
    var hourvalue = parseInt(hour, 10);
    
    if (hourvalue == 12) {
        if (ampm == 'AM')
            hourvalue = 0;
    }
    else if(ampm == 'PM') {
        hourvalue = hourvalue + 12;
    }
    now.setHours(hourvalue, parseInt(min, 10), 0, 0);   
    return now;
}

function GetDateAndTime(entrydate, hour, min, ampm) {
    var now = new Date(entrydate);
    var hourvalue = parseInt(hour, 10);

    if (hourvalue == 12) {
        if (ampm == 'AM')
            hourvalue = 0;
    }
    else if (ampm == 'PM') {
        hourvalue = hourvalue + 12;
    }
    now.setHours(hourvalue, parseInt(min, 10), 0, 0);
    return now;
}

function pad(number, length) {
    var str = '' + number;
    while (str.length < length) {
        str = '0' + str;
    }
    return str;
}

function SelectAll(MainCheckBox) {
    for (i = 0; i < document.forms[0].elements.length; i++) {
        if (document.forms[0].elements[i].type == "checkbox" && document.forms[0].elements[i].id != MainCheckBox.id && document.forms[0].elements[i].id.indexOf("_Select") >= 0)
            document.forms[0].elements[i].checked = MainCheckBox.checked;
    }
}

function SelectAllOff() {
    for (i = 0; i < document.forms[0].elements.length; i++) {
        if (document.forms[0].elements[i].type == "checkbox" && document.forms[0].elements[i].id.indexOf("_SelectAll") >= 0)
            document.forms[0].elements[i].checked = false;
    }
}
