﻿function trimString(value) {
    return ((value != null) ? value.replace(/^\s+|\s+$/g, '') : value);
}

//Note this function is necessary because s.search() has
//compatibility issues in IE.  
function findChar(ch, value) {
    var i = 0;

    while (i < value.length) {
        if (value.charAt(i) == ch)
            return i;

        i++;
    }

    return -1;
}

function combineString(str1, str2) {
    return str1 + '' + str2;
}

function replaceAllInString(str, search, replacement) {
    if (str == null) {
        return str;
    }
    
    var match = new RegExp(search, "g");
    return str.replace(match, replacement);    
}

function validateInteger(value) {
    return (value != null && !isNaN(value) && findChar('.', value) < 0);
}

function validateIntegerNonNegative(value) {
    return (value != null && !isNaN(value) && findChar('.', value) < 0 && parseInt(value,10) >= 0);
}

function validateFloat(value) {
    return (value != null && !isNaN(value));
}

function validateFloatNonNegative(value) {
    return (value != null && !isNaN(value) && parseFloat(value) >= 0);
}

// rounds "num" to "dec" decimal places
// usage: x = roundNumber(123.83738,2);  yields 123.84
function roundNumber(num, dec) {
    var result = Math.round(num * Math.pow(10, dec)) / Math.pow(10, dec);
    return result;
}

function formatCurrency(value) {
    if (isNaN(value))
        return '';

    var curVal = '$' + roundNumber(value, 2);
    var idx = curVal.indexOf('.');

    //Pad right zeros if necessary
    if (idx < 0) {
        curVal = curVal + '.00';
    } else if (idx == curVal.length - 2) {
        curVal = curVal + '0';
    }

    return curVal;   
}

function formatShortDate(value) {
    return (value.indexOf(' ') > 0 ? value.substring(0, value.indexOf(' ')) : '');
}

function formatPhone(value) {
    if (value == null || trimString(value).length != 10)
        return value;

    var output = '';

    output = combineString(output, '(');
    output = combineString(output, value.substring(0, 3));
    output = combineString(output, ') ');
    output = combineString(output, value.substring(3, 6));
    output = combineString(output, '-');
    output = combineString(output, value.substring(6));

    return output;
}

// Checks if a given date string is in    
// one of the valid formats:   
// a) M/D/YYYY format   
// b) M-D-YYYY format   
function validateDate(s) {
    // regular expression to match required date format
    re = /^\d{1,2}\/\d{1,2}\/\d{4}$/;

    return (s.match(re));
}

// Original JavaScript code by Chirp Internet: www.chirp.com.au
// Please acknowledge use of this code by including this header.
function validateTime(s) {
    if (s == null)
        return false;
    
    var retVal = true;
    
    // regular expression to match required time format
    re = /^(\d{1,2}):(\d{2})(:00)?([ap]m)?$/;
    
    if (regs = s.match(re)) {
        if (regs[4]) {
            // 12-hour time format with am/pm
            if (regs[1] < 1 || regs[1] > 12) {
                retVal = false;
            }
        } else {
            // 24-hour time format
            if (regs[1] > 23) {
                retVal = false;
            }
        }
        if (retVal && regs[2] > 59) {
            retVal = false;
        }
    } else {
        retVal = false;
    }
            
    return retVal;
}

function padDateTimeChars(num) {
    return num < 10 ? '0' + num : num;
}

function createISODateString(date) {    
    return date.getUTCFullYear() + '-' + padDateTimeChars(date.getUTCMonth()+1) + '-'
	    + padDateTimeChars(date.getUTCDate()) + ' ' + padDateTimeChars(date.getUTCHours()) + ':'
        + padDateTimeChars(date.getUTCMinutes()) + ':' + padDateTimeChars(date.getUTCSeconds());
}

function parseISODateString(dateString) {
    var dateTimeParts = dateString.split(' ');
    var dateParts = dateTimeParts[0].split('-');
    var timeParts = dateTimeParts[1].split(':');
    var date = new Date();
    
    for (var i = 0; i < dateParts.length; i++) {    
        if (dateParts[i].charAt(0) == '0') {            
            dateParts[i] = dateParts[i].substr(1);            
        }
    }

    for (var i = 0; i < timeParts.length; i++) {
        if (timeParts[i].charAt(0) == '0') {
            timeParts[i] = timeParts[i].substr(1);
        }
    }
    
    date.setUTCFullYear(dateParts[0]);
    date.setUTCMonth(parseInt(dateParts[1])-1);
    date.setUTCDate(dateParts[2]);

    date.setUTCHours(timeParts[0]);
    date.setUTCMinutes(timeParts[1]);
    date.setUTCSeconds(timeParts[2]);
    
    return date;
}

function querySearch(key) {
    var txt = window.location.search.substring(1);
    var parts = txt.split("&");
    var curr;
    for (i = 0; i < parts.length; i++) {
        curr = parts[i].split("=");
        if (curr[0] == key) {
            return curr[1];
        }
    }

    return '';
}

function toggleTextEnabled(identifier, disabled) {
    document.getElementById(identifier).disabled = disabled;
}

function createHiddenHoldingTag(hdnId, hdnValue) {
    var str = '';

    str = combineString(str, "<input type='hidden' id='");
    str = combineString(str, hdnId);
    str = combineString(str, "' value='");

    if (hdnValue != null) {
        str = combineString(str, encodeQuoteString(hdnValue));        
    }
    
    str = combineString(str, "' />");

    return str;
}

function appendDivChild(sourceDivId, targetDivId) {
    var srcObj = document.getElementById(sourceDivId);
    var tgtObj = document.getElementById(targetDivId);

    if (srcObj != null && tgtObj != null) {
        srcObj.appendChild(tgtObj);
    }
}

//Encodes single and double quote values in a string so 
//that it can be set as a value in script
function encodeQuoteString(value) {
    if (value == null || !isNaN(value))
        return value;

    var finalValue = value;

    //Literalize all double quotes
    finalValue = replaceAllInString(finalValue, '"', "&#34");

    //Literalize all single quotes
    finalValue = replaceAllInString(finalValue, "'", "&#39");

    return finalValue;    
}

var base64KeyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";

function encodeBase64(input) {
    var output = '';
    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 = combineString(output, base64KeyStr.charAt(enc1) + base64KeyStr.charAt(enc2) + base64KeyStr.charAt(enc3) + base64KeyStr.charAt(enc4));
    }

    return output;
}

function decodeBase64(input) {    
    var output = '';
    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 = base64KeyStr.indexOf(input.charAt(i++));
        enc2 = base64KeyStr.indexOf(input.charAt(i++));
        enc3 = base64KeyStr.indexOf(input.charAt(i++));
        enc4 = base64KeyStr.indexOf(input.charAt(i++));

        chr1 = (enc1 << 2) | (enc2 >> 4);
        chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
        chr3 = ((enc3 & 3) << 6) | enc4;

        output = combineString(output, String.fromCharCode(chr1));

        if (enc3 != 64) {
            output = combineString(output, String.fromCharCode(chr2));
        }
        if (enc4 != 64) {
            output = combineString(output, String.fromCharCode(chr3));
        }
    }
    
    return output;
}

function hideMasterNavMenu() {
    var elem = document.getElementById('mainNavigationMenu');
    
    if( elem != null )
        elem.style.display = 'none'
}

function loadSynchUrl(strURL, callbackFunc) {
    if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
        xmlhttp = new XMLHttpRequest();
    }
    else {// code for IE6, IE5
        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
    }
    
    xmlhttp.open("GET", strURL, false);
    xmlhttp.send();
    eval(callbackFunc)(xmlhttp.responseText);    
}

function loadAjaxUrl(strURL, callbackFunc) {
    if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
        xmlhttp = new XMLHttpRequest();
    }
    else {// code for IE6, IE5
        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
    }
    xmlhttp.onreadystatechange = function() {
        if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
            eval(callbackFunc)(xmlhttp.responseText);            
        }
    }
    xmlhttp.open("GET", strURL, true);
    xmlhttp.send();
}


