﻿

// ***
// * Base64 encoding/decoding
// * 
// * Example:
// * var x = Base64.encode('This is Josh')
// ***
var Base64 = {

    // private property
    _keyStr : "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",

    // public method for encoding
    encode : function (input) {
        var output = "";
        var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
        var i = 0;

        input = Base64._utf8_encode(input);

        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 = output +
            this._keyStr.charAt(enc1) + this._keyStr.charAt(enc2) +
            this._keyStr.charAt(enc3) + this._keyStr.charAt(enc4);

        }

        return output;
    },

    // public method for decoding
    decode : function (input) {
        var output = "";
        var chr1, chr2, chr3;
        var enc1, enc2, enc3, enc4;
        var i = 0;

        input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");

        while (i < input.length) {

            enc1 = this._keyStr.indexOf(input.charAt(i++));
            enc2 = this._keyStr.indexOf(input.charAt(i++));
            enc3 = this._keyStr.indexOf(input.charAt(i++));
            enc4 = this._keyStr.indexOf(input.charAt(i++));

            chr1 = (enc1 << 2) | (enc2 >> 4);
            chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
            chr3 = ((enc3 & 3) << 6) | enc4;

            output = output + String.fromCharCode(chr1);

            if (enc3 != 64) {
                output = output + String.fromCharCode(chr2);
            }
            if (enc4 != 64) {
                output = output + String.fromCharCode(chr3);
            }

        }

        output = Base64._utf8_decode(output);

        return output;

    },

    // private method for UTF-8 encoding
    _utf8_encode : function (string) {
        string = string.replace(/\r\n/g,"\n");
        var utftext = "";

        for (var n = 0; n < string.length; n++) {

            var c = string.charCodeAt(n);

            if (c < 128) {
                utftext += String.fromCharCode(c);
            }
            else if((c > 127) && (c < 2048)) {
                utftext += String.fromCharCode((c >> 6) | 192);
                utftext += String.fromCharCode((c & 63) | 128);
            }
            else {
                utftext += String.fromCharCode((c >> 12) | 224);
                utftext += String.fromCharCode(((c >> 6) & 63) | 128);
                utftext += String.fromCharCode((c & 63) | 128);
            }

        }

        return utftext;
    },

    // private method for UTF-8 decoding
    _utf8_decode : function (utftext) {
        var string = "";
        var i = 0;
        var c = c1 = c2 = 0;

        while ( i < utftext.length ) {

            c = utftext.charCodeAt(i);

            if (c < 128) {
                string += String.fromCharCode(c);
                i++;
            }
            else if((c > 191) && (c < 224)) {
                c2 = utftext.charCodeAt(i+1);
                string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
                i += 2;
            }
            else {
                c2 = utftext.charCodeAt(i+1);
                c3 = utftext.charCodeAt(i+2);
                string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
                i += 3;
            }

        }

        return string;
    }

}

// ***
// * Keeps the value of a field limited to a certain number of characters.
// ***
function textcharacter_count(field, maxlimit) {
	var count = maxlimit - field.value.length;
	if (count <= 0){
        field.value = field.value.substring(0,maxlimit)
		alert('You have reached the maximum number of characters allowed!');
	}
}


// ***
// * Returns a comma separated string of the ascii codes for the string
// ***
function getASCIIString(str){
    var code = str.split("");

    for (var i = 0; i < code.length; i++){
        code[i] = code[i].charCodeAt(0);
    }

    return code.toString()
}

function getCharFromASCIIString(str){
    var code = str.split(",");

    for (var i = 0; i < code.length; i++){
        code[i] = String.fromCharCode(code[i]);
    }

    return code.join("") // This returns the delimiter of choice.
    //return code.toString() // This returns comma separated.
}

function asc(s){
    return s.charCodeAt(0);
}

function chr(d){
    return String.fromCharCode(d);
}

function d2h(d){
    return d.toString(16);
}

function d2b(d){
    return d.toString(2);
}

function h2d(h){
    return parseInt(h,16);
}

function b2d(h){
    return parseInt(h,2);
}

// ***
// * Replaces all underscores in a string with spaces
// ***
function KillUnderscores(myXXHTML){
    return myXXHTML.replace(/_/g, ' ')
}


// ***
// * Removes all dashes from a string
// ***
function KillDashes(myXXHTML){
    return myXXHTML.replace(/-/g, '')
}


// ***
// * Removes all white spaces from a string
// ***
function KillWhiteSpaces(myXXHTML){
    return myXXHTML.replace(/ /g, '')
}

// ***
// * Replaces all spaces with &nbsp;
// ***
function replaceSpaces(myXXHTML){
    return myXXHTML.replace(/ /g, '&nbsp;')
}


// ***
// * Trims leading and trailing spaces from a string
// *
// * This is my understanding of the breakdown - Josh
// * Breakdown:
// * /^\s+|\s+$/g
// * /xxx/g This would replace all instances of xxx
// * ^ in matching means at the beginning.
// * $ in matching means at the end.
// * \s in matching means white space.
// * + in matching means one or more.
// * | in matching means alternative...(or)
// * Reading left to right:
// * (/)search begins...(^)look at the beginning...(\s)for whitespace...(+)one or more times...(|)or...(\s)for whitespace...(+)one or more times...($)at the end...(/g) all instances
// *
// * Reference: http://www.webreference.com/js/column5/rules.html
// ***
function alltrim(str) {
    return str.replace(/^\s+|\s+$/g, '');
}


// ***
// * Takes an HTML string, looks for links, and replaces
// * them with <strikes> thus invalidating the links.
// * Search for <a...> and replace with <strike>
// * Search for </a> and replace with </strike>
// ***
function KillLinks(myXXHTML){
    for(x=0;x=-1;x++){
	    // * Infinite Loop

	    var myXXHTMLNew = "";
	    var myPos = -1;

	    myPos = myXXHTML.indexOf('<A')
	    if(myPos!=-1){
		    myPos2 = myXXHTML.indexOf('>', myPos)
		    if(myPos2 != -1){
			    myXXHTMLNew = myXXHTML.substring(0, myPos)
			    myXXHTMLNew = myXXHTMLNew + '<strike>'
			    myXXHTMLNew = myXXHTMLNew + myXXHTML.substring(myPos2+1)
		    }
		    myXXHTML = myXXHTMLNew
	    }

	    myPos = myXXHTML.indexOf('</A>')
	    if(myPos!=-1){
		    myXXHTMLNew = myXXHTML.substring(0, myPos)
		    myXXHTMLNew = myXXHTMLNew + '</strike>'
		    myXXHTMLNew = myXXHTMLNew + myXXHTML.substring(myPos+4)
		    myXXHTML = myXXHTMLNew
	    }

	    if(myPos==-1){
		    break;
	    }
    }

    return myXXHTML
}

// ***
// * Pads a string to the right with a specific character
// * until the entire string equals the length passed
// *
// * Example padright("Josh", "x", 10) would produce "Joshxxxxxx"
// *
// * Note:
// * This Only returns the left most 10 characters...thus:
// * padright("Josh is the best", "x", 10) would produce "Josh is th"
// ***
function padright(val, ch, num){
    var re = new RegExp('^.{' + num + '}');
    var pad = '';

    do {
        pad += ch;
    } while (pad.length < num)

    var retval = re.exec(val + pad);
    return retval[0]
}

// ***
// * Pads a string to the left with a specific character
// * until the entire string equals the length passed
// *
// * Example padleft("Josh", "x", 10) would produce xxxxxxJosh
// *
// * Note:
// * This Only returns the right most 10 characters...thus:
// * padleft("Josh is the best", "x", 10) would produce "s the best"
// ***
function padleft(val, ch, num) {
	var re = new RegExp('.{' + num + '}$');
	var pad = '';

	do  {
		pad += ch;
	}while(pad.length < num)

    var retval = re.exec(pad + val);
	return retval[0]
}


// ***
// * Marks label as red if empty and required.
// ***
function checkit(myControl, myLabel, myColorGood, myColorBad){
    if(alltrim(myControl.value)=='' || alltrim(myControl.value)=='--choose--'){
        // '<%=System.Configuration.ConfigurationManager.AppSettings("InvalidColor")%>'
        document.getElementById(myLabel).style.color = myColorBad
    }
    else{
        // '<%=System.Configuration.ConfigurationManager.AppSettings("ValidColor")%>'
        document.getElementById(myLabel).style.color = myColorGood
    }
}


//*** Brigette added on 2/13/2008
//************* fix this...
function getNumbersOnly(str){
    var retString = "";
    for(var i=0; i<str.length; i++){
        if(isNaN(str.charAt(i))){
        }
        else{
            retString = retString + str.charAt(i);
        }
    }
    return retString;
}

// ***
// * Moves the carat (cursor) to the first _ position.
// ***
function setCaretPosition(elemId){
    var elem = document.getElementById(elemId);
    var caretPos = elem.value.indexOf("_");

    if(caretPos==-1){
        return;
    }

    if(elem != null){
        if(elem.createTextRange){
            var range = elem.createTextRange();
            range.move('character', caretPos);
            range.select();
        }
        else{
            if(elem.selectionStart){
                elem.focus();
                elem.setSelectionRange(caretPos, caretPos);
            }
            else{
                elem.focus();
            }
        }
    }
}


// ***
// * Returns the number of years old a person is when their birthdate is passed in.
// ***
function CalculateAge(xdate){

/*
    !!!!!!!!!!!!
    This was commented out because it isn't accurate.
    It doesn't take into consideration leap years....
    It just calculates the number of days old you are and then divides by 365
    !!!!!!!!!!!!
    var xmonth = parseInt(xdate.substring(0,2))-1;
    var xday = xdate.substring(3,5);
    var xyear = xdate.substring(6,10);
    var date1 = new Date(xyear, xmonth, xday);
    var date2 = new Date();

    var count = date2 - date1

    alert(Math.round((count/31536000000)*100)/100); // 31536000000 = 1000*60*60*24*365

    if(count/31536000000<18){
*/

    // * This just returns years...it calculates if you haven't had your birthday yet.
    var monthborn = parseInt(xdate.substring(0,2))-1;
    var dayborn = parseInt(xdate.substring(3,5));
    var yearborn = parseInt(xdate.substring(6,10));

    var today = new Date();
    var thismonth = today.getMonth();
    var thisday = today.getDate();
    var thisyear = today.getFullYear();

    var yearsold = thisyear-yearborn

    if(thismonth < monthborn){
        yearsold = yearsold - 1
    }
    
    if(thismonth == monthborn && thisday < dayborn){
        yearsold = yearsold-1
    }

    return yearsold;
}

// * Adds an item to an array
function addToArray(myArray,myValue){
    myArray[myArray.length] = myValue
}

// * Removes an item from an array
function removeFromArray(myArray,myValue){
    var i;
    for(i=0;i<myArray.length;i++){
        if(myValue==myArray[i]){
            myArray.splice(i, 1);
            break;
        }
    }
}

// * Clear a dropdown box
function clearDropDown(myCmb){
    for(x=myCmb.options.length;myCmb.options.length=0;x--){
        myCmb.options[x] = null;
    }
}


// ***
// * Adds an option to a combo box.
// ***
function addOption(myCmbx, myTextx, myValuex){
    var myCmb = document.getElementById(myCmbx);
    var newOption = document.createElement('OPTION');
    newOption.setAttribute('value',myValuex);
    newOption.innerHTML = myTextx
    myCmb.appendChild(newOption);
}


// ***
// * Collection
// *
// * Examples:
// ***

//var x = new Collection();

//var bb = new Object
//bb[0]=1
//bb[1]=2
//bb[2]=3

//x.add("key1", "value1")
//x.add("key2", 55)
//x.add("key3", bb)

//x.remove(0)
//alert(x[0])
//alert(x.keys[0])
//alert(x.values[0])
//alert(x.getValue("key1"))
//y = x.clone()
//x.clear()

function Collection() {
    var lsize = 0;
    this.add = _add;
    this.remove = _remove;
    this.values = new Object;
    this.keys = new Object;
    this.getValue = _getValue;
    this.isEmpty = _isEmpty;
    this.length = _length;
    this.clear = _clear;
    this.clone = _clone;

    function _add(newKey, newValue) {
        if(newKey == null){
            return;
        }
        if(newValue == null){
            return;
        }
        lsize++;
        
        this[(lsize-1)]=newValue
        this.values[lsize-1]=newValue
        this.keys[lsize-1]=newKey
    }

    function _remove(index) {
        if (index < 0 || index > this.length - 1){
            return;
        }

        this[index] = null;
        this.values[index]=null;
        this.keys[index]=null;

        for (var i=index; i<=lsize; i++){
            this[i] = this[i + 1];
            this.values[i] = this.values[i + 1];
            this.keys[i] = this.keys[i + 1];
        }

        lsize--;
    }

    function _getValue(myKey) {
        var zz=0;
        var xx=0
        for(zz=0;zz<10;zz++){
            zz--
            if(this.keys[xx]==null){
                return null;
            }
            if(this.keys[xx]==myKey){
                return this.values[xx];
            }
            xx++
        }
    }

    function _isEmpty() { return lsize == 0 }

    function _length() { return lsize }

    function _clear() {
        for (var i = 0; i < lsize; i++){
            this[i] = null;
            this.values[i] = null;
            this.keys[i] = null;
        }                       

        lsize = 0;
    }

    function _clone() {
        var c = new Collection();

        for (var i = 0; i < lsize; i++){
            c.add(this.keys[i] ,this[i]);
        }
        return c;
    }
}
