﻿// JScript File
//
// Global constants
var bscPaginatorTemplate = "<div class='bscCurrentPageReport'>{CurrentPageReport}</div><div class='bscPageLinks'>{FirstPageLink}&nbsp;&nbsp;{PreviousPageLink}&nbsp;&nbsp;{PageLinks}&nbsp;&nbsp;{NextPageLink}&nbsp;&nbsp;{LastPageLink}</div><br class='clear' />";
var bscPaginatorPageReportTemplate = "{startRecord} - {endRecord} of {totalRecords} items";
var bscPaginatorSearchPageReportTemplate = "{startRecord} - {endRecord} of {totalRecords} matches";
var pulseColor = "#ecd0c1";
var pulseColorGreen = "#769c01";

//catch Enter key event
function catchReturn(e, isAjax) {
    if (!e) var e = window.event;
    var kCode;
    if (e.keyCode)
        kCode = e.keyCode;
    else
        if (e.which)
        kCode = e.which;

    if (kCode == 13) {
        if (isAjax) {
            try {
                if (e.target.id == "searchQuery") {
                    doSearch();
                } else {
                    if (e.target.id == "firstname" || e.target.id == "lastname" || e.target.id == "aoeid")
                    { EL.updList(); }
                }
            }
            catch (err) { }
            try {
                if (e.srcElement.id == "searchQuery") {
                    doSearch();
                } else {
                    if (e.srcElement.id == "firstname" || e.srcElement.id == "lastname" || e.srcElement.id == "aoeid")
                    { EL.updList(); }
                }
            }
            catch (err) { }

            document.forms[0].onsubmit = returnFalse;
        }
        else
            document.forms[0].submit();
        return false;
    }
    else
        return true;
}

function returnFalse() {
    return false;
}

//formatting

function GlobalFormatNumericString(val) {
    var isNeg = (val < 0);
    var num = Math.abs(val) + "";
    var rgx = /(\d+)(\d{3})/;

    while (rgx.test(num)) {
        num = num.replace(rgx, '$1' + ',' + '$2');
    }
    return (isNeg) ? -num : num;
}

//helper functions
function fixCellClassForAnimation(elTable, elRow) {
    var elCell = elTable.getFirstTdEl(elRow);
    do {
        if (elCell.className.indexOf("yui-dt-asc") > 0) {
            elCell.className = elCell.className.replace("yui-dt-asc", "");
            break;
        }
        if (elCell.className.indexOf("yui-dt-desc") > 0) {
            elCell.className = elCell.className.replace("yui-dt-desc", "");
            break;
        }
        elCell = elTable.getNextTdEl(elCell);
    }
    while (elCell)
}

function AddCacheBuster(val) {
    var cb = "rand=" + new Date().getTime();
    return (val.indexOf("?") > -1 || val.indexOf("&") > -1) ? val + "&" + cb : val + "?" + cb;
}

function getQuerystring(key, default_) {
    if (default_ == null) default_ = "";
    key = key.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
    var regex = new RegExp("[\\?&]" + key + "=([^&#]*)");
    var qs = regex.exec(window.location.href);
    if (qs == null)
        return default_;
    else
        return unescape(qs[1]).replace("+", " ");
}

function validateUSZip(strValue) {
    /************************************************
    DESCRIPTION: Validates that a string a United
    States zip code in 5 digit format or zip+4
    format. 99999 or 99999-9999

PARAMETERS:
    strValue - String to be tested for validity

RETURNS:
    True if valid, otherwise false.

*************************************************/
    var objRegExp = /(^\d{5}$)|(^\d{5}-\d{4}$)/;

    //check for valid US Zipcode
    return objRegExp.test(strValue);
}


function validateUSDate(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 validateEmail( strValue) {
/************************************************
DESCRIPTION: Validates that a string contains a
  valid email pattern.

 PARAMETERS:
   strValue - String to be tested for validity

RETURNS:
   True if valid, otherwise false.

REMARKS: Accounts for email with country appended
  does not validate that email contains valid URL
  type (.com, .gov, etc.) or valid country suffix.
*************************************************/
var objRegExp  = /[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?/gi;

  //check for valid email
  return objRegExp.test(strValue);
}

function validateUSPhone( strValue ) {
/************************************************
DESCRIPTION: Validates that a string contains valid
  US phone pattern.
  Ex. (999) 999-9999 or (999)999-9999

PARAMETERS:
   strValue - String to be tested for validity

RETURNS:
   True if valid, otherwise false.
*************************************************/
  var objRegExp  = /^\([1-9]\d{2}\)\s?\d{3}\-\d{4}$/;

  //check for valid us phone with or without space between
  //area code
  return objRegExp.test(strValue);
}

function validateURL(strValue) {
    /************************************************
    DESCRIPTION: Validates that a string contains valid
    URL.
    Ex. http://www.DOMAIN.EXT

PARAMETERS:
    strValue - String to be tested for validity

RETURNS:
    True if valid, otherwise false.
    *************************************************/
    var objRegExp = /(http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/;

    //check for valid us phone with or without space between
    //area code
    return objRegExp.test(strValue);
}

function validateAddress(strValue) {
    /************************************************
    DESCRIPTION: Validates that a string contains valid
    Address. No PO boxes allowed.

PARAMETERS:
    strValue - String to be tested for validity

RETURNS:
    True if invalid, otherwise false.
    *************************************************/
    
    var re = /((P\.?O\.?(B\.?)?(\s+Box)?)|(Post\s+Office(\s+Box)?))+/gi;
    
    return re.test(strValue);
}

function cleanNumeric(strValue) {
    /************************************************
    DESCRIPTION: removes (',' and '.') from a potential number.

PARAMETERS:
    strValue - String to be cleaned

RETURNS:
    the cleaned string.
    *************************************************/
    strValue = strValue.replace(/[\. \,]/, '');
    return strValue;
}

/**
*
*  Base64 encode / decode
*  http://www.webtoolkit.info/
*
**/
var ua = navigator.userAgent.toLowerCase();
if (ua.indexOf(" chrome/") >= 0 || ua.indexOf(" firefox/") >= 0 || ua.indexOf(' gecko/') >= 0) {
    var StringMaker = function() {
        this.str = "";
        this.length = 0;
        this.append = function(s) {
            this.str += s;
            this.length += s.length;
        }
        this.prepend = function(s) {
            this.str = s + this.str;
            this.length += s.length;
        }
        this.toString = function() {
            return this.str;
        }
    }
} else {
    var StringMaker = function() {
        this.parts = [];
        this.length = 0;
        this.append = function(s) {
            this.parts.push(s);
            this.length += s.length;
        }
        this.prepend = function(s) {
            this.parts.unshift(s);
            this.length += s.length;
        }
        this.toString = function() {
            return this.parts.join('');
        }
    }
}


var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";

function encode64(input) {
	var output = new StringMaker();
	var chr1, chr2, chr3;
	var enc1, enc2, enc3, enc4;
	var i = 0;

	while (i < input.length) {
		chr1 = input.charCodeAt(i++);
		chr2 = input.charCodeAt(i++);
		chr3 = input.charCodeAt(i++);

		enc1 = chr1 >> 2;
		enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
		enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
		enc4 = chr3 & 63;

		if (isNaN(chr2)) {
			enc3 = enc4 = 64;
		} else if (isNaN(chr3)) {
			enc4 = 64;
		}

		output.append(keyStr.charAt(enc1) + keyStr.charAt(enc2) + keyStr.charAt(enc3) + keyStr.charAt(enc4));
   }
   
   return output.toString();
}

function decode64(input) {
	var output = new StringMaker();
	var chr1, chr2, chr3;
	var enc1, enc2, enc3, enc4;
	var i = 0;

	// remove all characters that are not A-Z, a-z, 0-9, +, /, or =
	input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");

	while (i < input.length) {
		enc1 = keyStr.indexOf(input.charAt(i++));
		enc2 = keyStr.indexOf(input.charAt(i++));
		enc3 = keyStr.indexOf(input.charAt(i++));
		enc4 = keyStr.indexOf(input.charAt(i++));

		chr1 = (enc1 << 2) | (enc2 >> 4);
		chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
		chr3 = ((enc3 & 3) << 6) | enc4;

		output.append(String.fromCharCode(chr1));

		if (enc3 != 64) {
			output.append(String.fromCharCode(chr2));
		}
		if (enc4 != 64) {
			output.append(String.fromCharCode(chr3));
		}
	}

	return output.toString();
}


