/*_______________________________________________________________________________________________________
Functions used through out the Web Application.
The sections are
	- Navigation: Ajax based functions
		- GetPage(url, element, Options): Used to return infromation from a page and insert it into a element
			-url: page requested
			-element: name of element to insert the information into.
			-Options: a string of options seperated by a & to POST to the url
		- PostForm(url, Form, hndler, destination): Used to Post form data to a Page
			-url: page requested
			-Form: form that contains the information to be posted.
			-hndler(optional): function used to handle alertbox response
			-destination(optional): element used to display the information returned
		- UpdateDB(table, ind, newvalue, whereind, whereval, hndler): Updates the database
			-table: table to update
			-ind: column to update
			-newvalue: new value
			-whereind: column to filter on
			-whereval: value to filter on
			-hndler(optional): function used to handle alertbox response
	- Display
	- Misc


________________________________________________________________________________________________________*/


function Activate(pg)
{

}

function Populate(value)
{
    var self = this;
    var a = new sack();
    a.requestFile = 'php/ajaxquery';
    a.setVar("SQL", value);
    a.setVar("Type", "RAW");
    a.onCompletion = function(){
        var data = a.response;
        if(data.substring(0, 5) === "Error"){
            exit;
        }

        for (i = self.length - 1; i>=0; i--)
        {
            self.remove(i);
        }

        var rows = data.split("\n");

        for(i = 0; i < rows.length; i++)
        {
            var tcol = rows[i].split(',');
            var elOptNew = document.createElement('option');
            elOptNew.text = tcol[0];
            elOptNew.value = tcol[1];

            try {
                self.add(elOptNew, null); // standards compliant; doesn't work in IE
            }
            catch(ex) {
                self.add(elOptNew); // IE only
            }
        }
    };
    a.runAJAX();
}

function UpdateDB(table, ind, newvalue, whereind, whereval, hndler)
{
    //log event
    Navigator.Log("UpdateDB called -"+table+", "+ind+", "+newvalue+", "+whereind+", "+whereval, "Info", "jsfunctions");

    //create class instance
    var a = new sack();
    var sql = "update "+table+" set "+ind+" = \'"+newvalue+"\' where "+whereind+" = "+whereval+"";
    a.requestFile = "php/ajaxquery.php";
    //Set post items to send to the page
    a.setVar('SQL', sql);
    a.setVar('Type', "update");
    a.setVar('Where', whereind+"="+whereval);
    a.setVar('Set', ind+"="+newvalue);
    a.setVar('Table', table);

    var cmp = hndler || function(success){};
    var x = new AlertBox("Updating Infomation.", 4, cmp);
    x.Display();
    a.onCompletion = hndler || function(){
        a.sethtml2(x.ReturnMsgBox().id);
        //log success
        Navigator.Log("UpdateDB done -"+a.response, "Debug", "jsfunctions");

        x.Close();
    };
    a.runAJAX();
}


//Function to get mouse position on the screen
function getMousePosition(e) {
    var posx = 0;
    var posy = 0;
    var pos = new Array();
    if (!e)
    e = window.event;
    if (e.pageX || e.pageY)
    {
        posx = e.pageX;
        posy = e.pageY;
    }
    else if (e.clientX || e.clientY)
    {
        posx = e.clientX + document.body.scrollLeft
            + document.documentElement.scrollLeft;
        posy = e.clientY + document.body.scrollTop
            + document.documentElement.scrollTop;
    }

    pos[0]=posx;
    pos[1] =posy;
    return pos;
}

//Functions for dealing with the style of an element
//________________________________________________________________________________________________________________________________
function getStyle(el, style) {
    if(!el) return "NotWorking";

    var value = el.style[toCamelCase(style)];

    if(!value)
        if(document.defaultView)
            value = document.defaultView.
            getComputedStyle(el, "").getPropertyValue(style);

        else if(el.currentStyle)
            value = el.currentStyle[toCamelCase(style)];

    if(parseInt(value)!=value-0 && style=="width"){
        value = el.offsetWidth;
    }
    if(parseInt(value)!=value-0 && style=="height"){
        value = el.offsetHeight;
    }
    if(parseInt(value)!=value-0 && style=="left"){
        value = el.offsetLeft;
    }
    return value;
}

function setStyle(obj, style, value) {
    if(obj){
        if(navigator.appName === "Microsoft Internet Explorer"){
            var cssString;

            cssString = obj.style.cssText;
            if( typeof(cssString) != 'string' ) {
                cssString = obj.getAttribute('style');
            }
            var tarray = cssString.split(';');
            cssString = '';
            while(tarray.length > 0){
                var topt = tarray.pop().split(':');
                var debug = topt[0].toUpperCase().trim();
                var nopt = style.toUpperCase().trim();
                if(debug !== nopt)
                {
                    if(topt.length > 1){
                        cssString += topt[0]+":"+topt[1]+";";
                    }
                }
            }
            cssString += style+":"+value+";";
            obj.style.cssText = cssString;
            obj.setAttribute('style',cssString);
        } else {
            obj.style[style] = value;
        }
    }
}

function toCamelCase( sInput ) {
    var oStringList = sInput.split('-');
    if(oStringList.length == 1)
        return oStringList[0];
    var ret = sInput.indexOf("-") == 0 ?
    oStringList[0].charAt(0).toUpperCase() + oStringList[0].substring(1) : oStringList[0];
    for(var i = 1, len = oStringList.length; i < len; i++){
        var s = oStringList[i];
        ret += s.charAt(0).toUpperCase() + s.substring(1)
    }
    return ret;
}

function widthto(newWidth, whichDiv){
    setStyle(whichDiv, "width", newWidth + "px");
}

function heightto(newWidth, whichDiv){
    setStyle(whichDiv, "height", newWidth + "px");
}

function leftto(newLeft, whichDiv){
    setStyle(whichDiv, "left", newLeft + "px");
}

function centerx(div)
{
    //div.style.marginLeft = "-" + parseInt(div.offsetWidth / 2) + "px";
    //div.style.marginTop = "-" + parseInt(div.offsetHeight / 2) + "px";
    var winW;
    var winH;
    var x;
    var y;

    if (parseInt(navigator.appVersion)>3) {
        if (navigator.appName === "Netscape") {
            winW = window.innerWidth;
            winH = window.innerHeight;
        }
        if (navigator.appName.indexOf("Microsoft")!== -1) {
            winW = document.body.offsetWidth;
            winH = document.body.offsetHeight;
        }
    }
    //setStyle(div, "width", getStyle(document.getElementById('MessageDiv'), "width")+50);
    x = (winW-getStyle(div,  "width"))/2;

    setStyle(div, "position", "fixed");
    leftto(x, div);
}

function resizefooter()
{
    //	var Sleft = parseInt(getStyle(document.getElementById("Menu"), "left"));
    var Sheight = parseInt(getStyle(document.getElementById("Content"), "height"));

    heightto(Sheight, document.getElementById("Menu"));
    centerx(document.getElementById("Footer"));
}

/*  Functions for inserting data into a textbox
myField accepts an object reference, myValue accepts the text string to insert at the cursor
*/
function insertatcursor(myField, myValue) {
    if (document.selection) {
        myField.focus();
        sel = document.selection.createRange();
        sel.text = myValue;
    }
    else if (myField.selectionStart == 0 || myField.selectionStart == '0') {
        var startPos = myField.selectionStart;
        var endPos = myField.selectionEnd;
        myField.value = myField.value.substring(0,startPos) + myValue + myField.value.substring(endPos, myField.value.length);
    }
    else {
        myField.value += myValue;
    }
}

//Function used to create random numbber
function random(lower, basenum)
{
    basenum = basenum || 11;
    var randomnumber=Math.floor(Math.random()*basenum)
    return randomnumber+lower;
}

//		function setStyle(objId, style, value) {
//		    document.getElementById(objId).style[style] = value;
//		}

function resizemenu()
{
    var Swidth = parseInt(getStyle(document.getElementById("header"), "width"));
    var Mwidth = parseInt(getStyle(document.getElementById("menulist"), "width"));

    widthto(Mwidth + parseInt(30), "menuback");
    leftto((Swidth - Mwidth) / parseInt(2), "menulist");

    leftto(((Swidth - Mwidth) / parseInt(2))-parseInt(15), "menuback");
}

function printr(array)
{
    var tOutput = "";
    for(var i=0;i<array.length;i++)
    {
        if(isArray(array[i])){
            try{
                tOutput = tOutput+"<br>["+printr(array[i])+"], <br>";
            }
            catch(err){
                txt="There was an error on this page.\n\n";
                txt+="Error description: " + err.description + "\n\n";
                txt+="Click OK to continue.\n\n";
                alert(txt);
            }
        } else {
            tOutput = tOutput+array[i]+", ";
        }
    }
    return tOutput;
}

function isArray(obj) {
    //returns true is it is an array
    if (obj.constructor.toString().indexOf('Array') == -1)
        return false;
    else
        return true;
}

function MD5(string) {

    function RotateLeft(lValue, iShiftBits) {
        return (lValue<<iShiftBits) | (lValue>>>(32-iShiftBits));
    }

    function AddUnsigned(lX,lY) {
        var lX4,lY4,lX8,lY8,lResult;
        lX8 = (lX & 0x80000000);
        lY8 = (lY & 0x80000000);
        lX4 = (lX & 0x40000000);
        lY4 = (lY & 0x40000000);
        lResult = (lX & 0x3FFFFFFF)+(lY & 0x3FFFFFFF);
        if (lX4 & lY4) {
            return (lResult ^ 0x80000000 ^ lX8 ^ lY8);
        }
        if (lX4 | lY4) {
            if (lResult & 0x40000000) {
                return (lResult ^ 0xC0000000 ^ lX8 ^ lY8);
            } else {
                return (lResult ^ 0x40000000 ^ lX8 ^ lY8);
            }
        } else {
            return (lResult ^ lX8 ^ lY8);
        }
    }

    function F(x,y,z) {
        return (x & y) | ((~x) & z);
    }
    function G(x,y,z) {
        return (x & z) | (y & (~z));
    }
    function H(x,y,z) {
        return (x ^ y ^ z);
    }
    function I(x,y,z) {
        return (y ^ (x | (~z)));
    }

    function FF(a,b,c,d,x,s,ac) {
        a = AddUnsigned(a, AddUnsigned(AddUnsigned(F(b, c, d), x), ac));
        return AddUnsigned(RotateLeft(a, s), b);
    };

    function GG(a,b,c,d,x,s,ac) {
        a = AddUnsigned(a, AddUnsigned(AddUnsigned(G(b, c, d), x), ac));
        return AddUnsigned(RotateLeft(a, s), b);
    };

    function HH(a,b,c,d,x,s,ac) {
        a = AddUnsigned(a, AddUnsigned(AddUnsigned(H(b, c, d), x), ac));
        return AddUnsigned(RotateLeft(a, s), b);
    };

    function II(a,b,c,d,x,s,ac) {
        a = AddUnsigned(a, AddUnsigned(AddUnsigned(I(b, c, d), x), ac));
        return AddUnsigned(RotateLeft(a, s), b);
    };

    function ConvertToWordArray(string) {
        var lWordCount;
        var lMessageLength = string.length;
        var lNumberOfWords_temp1=lMessageLength + 8;
        var lNumberOfWords_temp2=(lNumberOfWords_temp1-(lNumberOfWords_temp1 % 64))/64;
        var lNumberOfWords = (lNumberOfWords_temp2+1)*16;
        var lWordArray=Array(lNumberOfWords-1);
        var lBytePosition = 0;
        var lByteCount = 0;
        while ( lByteCount < lMessageLength ) {
            lWordCount = (lByteCount-(lByteCount % 4))/4;
            lBytePosition = (lByteCount % 4)*8;
            lWordArray[lWordCount] = (lWordArray[lWordCount] | (string.charCodeAt(lByteCount)<<lBytePosition));
            lByteCount++;
        }
        lWordCount = (lByteCount-(lByteCount % 4))/4;
        lBytePosition = (lByteCount % 4)*8;
        lWordArray[lWordCount] = lWordArray[lWordCount] | (0x80<<lBytePosition);
        lWordArray[lNumberOfWords-2] = lMessageLength<<3;
        lWordArray[lNumberOfWords-1] = lMessageLength>>>29;
        return lWordArray;
    };

    function WordToHex(lValue) {
        var WordToHexValue="",WordToHexValue_temp="",lByte,lCount;
        for (lCount = 0;lCount<=3;lCount++) {
            lByte = (lValue>>>(lCount*8)) & 255;
            WordToHexValue_temp = "0" + lByte.toString(16);
            WordToHexValue = WordToHexValue + WordToHexValue_temp.substr(WordToHexValue_temp.length-2,2);
        }
        return WordToHexValue;
    };

    function Utf8Encode(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;
    };

    var x=Array();
    var k,AA,BB,CC,DD,a,b,c,d;
    var S11=7, S12=12, S13=17, S14=22;
    var S21=5, S22=9 , S23=14, S24=20;
    var S31=4, S32=11, S33=16, S34=23;
    var S41=6, S42=10, S43=15, S44=21;

    string = Utf8Encode(string);

    x = ConvertToWordArray(string);

    a = 0x67452301;
    b = 0xEFCDAB89;
    c = 0x98BADCFE;
    d = 0x10325476;

    for (k=0;k<x.length;k+=16) {
        AA=a;
        BB=b;
        CC=c;
        DD=d;
        a=FF(a,b,c,d,x[k+0], S11,0xD76AA478);
        d=FF(d,a,b,c,x[k+1], S12,0xE8C7B756);
        c=FF(c,d,a,b,x[k+2], S13,0x242070DB);
        b=FF(b,c,d,a,x[k+3], S14,0xC1BDCEEE);
        a=FF(a,b,c,d,x[k+4], S11,0xF57C0FAF);
        d=FF(d,a,b,c,x[k+5], S12,0x4787C62A);
        c=FF(c,d,a,b,x[k+6], S13,0xA8304613);
        b=FF(b,c,d,a,x[k+7], S14,0xFD469501);
        a=FF(a,b,c,d,x[k+8], S11,0x698098D8);
        d=FF(d,a,b,c,x[k+9], S12,0x8B44F7AF);
        c=FF(c,d,a,b,x[k+10],S13,0xFFFF5BB1);
        b=FF(b,c,d,a,x[k+11],S14,0x895CD7BE);
        a=FF(a,b,c,d,x[k+12],S11,0x6B901122);
        d=FF(d,a,b,c,x[k+13],S12,0xFD987193);
        c=FF(c,d,a,b,x[k+14],S13,0xA679438E);
        b=FF(b,c,d,a,x[k+15],S14,0x49B40821);
        a=GG(a,b,c,d,x[k+1], S21,0xF61E2562);
        d=GG(d,a,b,c,x[k+6], S22,0xC040B340);
        c=GG(c,d,a,b,x[k+11],S23,0x265E5A51);
        b=GG(b,c,d,a,x[k+0], S24,0xE9B6C7AA);
        a=GG(a,b,c,d,x[k+5], S21,0xD62F105D);
        d=GG(d,a,b,c,x[k+10],S22,0x2441453);
        c=GG(c,d,a,b,x[k+15],S23,0xD8A1E681);
        b=GG(b,c,d,a,x[k+4], S24,0xE7D3FBC8);
        a=GG(a,b,c,d,x[k+9], S21,0x21E1CDE6);
        d=GG(d,a,b,c,x[k+14],S22,0xC33707D6);
        c=GG(c,d,a,b,x[k+3], S23,0xF4D50D87);
        b=GG(b,c,d,a,x[k+8], S24,0x455A14ED);
        a=GG(a,b,c,d,x[k+13],S21,0xA9E3E905);
        d=GG(d,a,b,c,x[k+2], S22,0xFCEFA3F8);
        c=GG(c,d,a,b,x[k+7], S23,0x676F02D9);
        b=GG(b,c,d,a,x[k+12],S24,0x8D2A4C8A);
        a=HH(a,b,c,d,x[k+5], S31,0xFFFA3942);
        d=HH(d,a,b,c,x[k+8], S32,0x8771F681);
        c=HH(c,d,a,b,x[k+11],S33,0x6D9D6122);
        b=HH(b,c,d,a,x[k+14],S34,0xFDE5380C);
        a=HH(a,b,c,d,x[k+1], S31,0xA4BEEA44);
        d=HH(d,a,b,c,x[k+4], S32,0x4BDECFA9);
        c=HH(c,d,a,b,x[k+7], S33,0xF6BB4B60);
        b=HH(b,c,d,a,x[k+10],S34,0xBEBFBC70);
        a=HH(a,b,c,d,x[k+13],S31,0x289B7EC6);
        d=HH(d,a,b,c,x[k+0], S32,0xEAA127FA);
        c=HH(c,d,a,b,x[k+3], S33,0xD4EF3085);
        b=HH(b,c,d,a,x[k+6], S34,0x4881D05);
        a=HH(a,b,c,d,x[k+9], S31,0xD9D4D039);
        d=HH(d,a,b,c,x[k+12],S32,0xE6DB99E5);
        c=HH(c,d,a,b,x[k+15],S33,0x1FA27CF8);
        b=HH(b,c,d,a,x[k+2], S34,0xC4AC5665);
        a=II(a,b,c,d,x[k+0], S41,0xF4292244);
        d=II(d,a,b,c,x[k+7], S42,0x432AFF97);
        c=II(c,d,a,b,x[k+14],S43,0xAB9423A7);
        b=II(b,c,d,a,x[k+5], S44,0xFC93A039);
        a=II(a,b,c,d,x[k+12],S41,0x655B59C3);
        d=II(d,a,b,c,x[k+3], S42,0x8F0CCC92);
        c=II(c,d,a,b,x[k+10],S43,0xFFEFF47D);
        b=II(b,c,d,a,x[k+1], S44,0x85845DD1);
        a=II(a,b,c,d,x[k+8], S41,0x6FA87E4F);
        d=II(d,a,b,c,x[k+15],S42,0xFE2CE6E0);
        c=II(c,d,a,b,x[k+6], S43,0xA3014314);
        b=II(b,c,d,a,x[k+13],S44,0x4E0811A1);
        a=II(a,b,c,d,x[k+4], S41,0xF7537E82);
        d=II(d,a,b,c,x[k+11],S42,0xBD3AF235);
        c=II(c,d,a,b,x[k+2], S43,0x2AD7D2BB);
        b=II(b,c,d,a,x[k+9], S44,0xEB86D391);
        a=AddUnsigned(a,AA);
        b=AddUnsigned(b,BB);
        c=AddUnsigned(c,CC);
        d=AddUnsigned(d,DD);
    }

    var temp = WordToHex(a)+WordToHex(b)+WordToHex(c)+WordToHex(d);
    temp = temp.toLowerCase();
    return temp;
};

String.prototype.contains = function(cmp) {
    var tempStr = this.toLowerCase();
    cmp = cmp.toLowerCase();
    return tempStr.indexOf(cmp);
}

String.prototype.displayDate = function(rtn) {
    var proc = this;
    rtn = rtn || this;
    if(proc.indexOf("-") > -1 && proc.indexOf(":"))
    {
        proc = proc.split(' ');
        var tdate = proc[0];
        tdate = tdate.split('-');
        if(tdate.length == 3){
            return tdate[1]+'/'+tdate[2]+'/'+tdate[0];
        } else {
            return rtn;
        }
    } else {
        return rtn;
    }
}

function dateAddExtention(p_Interval, p_Number){


    var thing = new String();


    //in the spirt of VB we'll make this function non-case sensitive
    //and convert the charcters for the coder.
    p_Interval = p_Interval.toLowerCase();

    if(isNaN(p_Number)){

        //Only accpets numbers
        //throws an error so that the coder can see why he effed up
        throw "The second parameter must be a number. \n You passed: " + p_Number;
        return false;
    }

    p_Number = new Number(p_Number);
    switch(p_Interval.toLowerCase()){
        case "yyyy": {// year
            this.setFullYear(this.getFullYear() + p_Number);
            break;
        }
        case "q": {        // quarter
            this.setMonth(this.getMonth() + (p_Number*3));
            break;
        }
        case "m": {        // month
            this.setMonth(this.getMonth() + p_Number);
            break;
        }
        case "y":        // day of year
        case "d":        // day
        case "w": {        // weekday
            this.setDate(this.getDate() + p_Number);
            break;
        }
        case "ww": {    // week of year
            this.setDate(this.getDate() + (p_Number*7));
            break;
        }
        case "h": {        // hour
            this.setHours(this.getHours() + p_Number);
            break;
        }
        case "n": {        // minute
            this.setMinutes(this.getMinutes() + p_Number);
            break;
        }
        case "s": {        // second
            this.setSeconds(this.getSeconds() + p_Number);
            break;
        }
        case "ms": {        // second
            this.setMilliseconds(this.getMilliseconds() + p_Number);
            break;
        }
        default: {

            //throws an error so that the coder can see why he effed up and
            //a list of elegible letters.
            throw    "The first parameter must be a string from this list: \n" +
                    "yyyy, q, m, y, d, w, ww, h, n, s, or ms. You passed: " + p_Interval;
            return false;
        }
    }
    return this;
}
Date.prototype.getFullMonth = function()
{
    var months = new Array(
                            'January',
                            'February',
                            'March',
                            'April',
                            'May',
                            'June',
                            'July',
                            'August',
                            'September',
                            'October',
                            'November',
                            'December'
                            );
    return months[this.getMonth()];
};
Date.prototype.getAbvMonth = function()
{
    var months = new Array(
                            'Jan',
                            'Feb',
                            'Mar',
                            'Apr',
                            'May',
                            'Jun',
                            'Jul',
                            'Aug',
                            'Sep',
                            'Oct',
                            'Nov',
                            'Dec'
                            );
    abr = months[this.getMonth()];
    return abr;
};
Date.prototype.format = function(fmt)
{
    fmt = fmt.replace("YYYY", this.getFullYear() );
    fmt = fmt.replace("d", this.getDate() );
    fmt = fmt.replace("D", this.getDate() );
    fmt = fmt.replace("MM", this.getFullMonth() );
    fmt = fmt.replace("mm", this.getAbvMonth() );
    fmt = fmt.replace("m", this.getMonth()+1 );

    return fmt;
}


Date.prototype.dateAdd = dateAddExtention;

String.prototype.isDate = function() {
    var proc = this;
    if((proc.indexOf("-") > -1 && proc.indexOf(":") > -1) || (proc.indexOf("/") > -1) )
    {
        return true;
    } else {
        return false;
    }
}

String.prototype.displayTime = function() {
    return new Date("h:m:s", this);
}

String.prototype.trim = function() {
    return this.replace(/^\s+|\s+$/g,"");
}
String.prototype.ltrim = function() {
    return this.replace(/^\s+/,"");
}
String.prototype.rtrim = function() {
    return this.replace(/\s+$/,"");
}

String.prototype.urlSafe = function() {
    var tstr = this;
    while(tstr.indexOf('/'))
    {
        tstr = tstr.replace("/", '*' );
    }
    return tstr;
}

String.prototype.sqlPrep = function(vals) {
    var tstr = this;
    while(vals.length > 0)
    {
        var t = vals.pull();
        tstr = tstr.replace("?", t );
    }
    return tstr;
}

String.prototype.isNumeric = function() {
    if (isNaN(parseFloat(this)))return false;
    else return true;
}

String.prototype.removeHTMLTags = function()
{
    var strInputCode = this;

    strInputCode = strInputCode.replace(/&(lt|gt);/g, function (strMatch, p1){
            return (p1 == "lt")? "<" : ">";
    });
    var strTagStrippedText = strInputCode.replace(/<\/?[^>]+(>|$)/g, "");
    return strTagStrippedText;
}

String.prototype.fixMoney = function(opt) {
    var val = this;
    opt = opt || {'Decimal':2, 'Seperator':',', 'Currency':'$'};
    if(val == 0 || val == 'N/A' || val == 'na' || val == 'n/a' || val == 'NA')
    {
            if(val == 'N/A' || val == 'na' || val == 'n/a' || val == 'NA')
                    return true;
            else
            {
            // parse error
            //status= 'The '+fieldname(fld)+' field must contain a number greater than 0.';
            //return false;
            }
    }
    if(opt.Seperator) val= val.replace(new RegExp(opt.Seperator,'g'),'');
    if(val.indexOf(opt.Currency) == 0)
            val= parseFloat(val.substring(1,40));
    else
            val= parseFloat(val);
    if(isNaN(val))
    { // parse error
            val = '0.00';
            return val;
    }
    var sign= ( val < 0 ? '-': '' );
    val= Number(Math.round(Math.abs(val)*100)).toString();
    while(val.length < opt.Decimal) val= '0'+val;
    var len= val.length;
    val= sign + ( len == opt.Decimal ? '0' : val.substring(0,len-opt.Decimal) ) + '.' + val.substring(len-opt.Decimal,len+1);

    return val;
}


Array.prototype.pull = function() {
    var tstr = this[0];
    var tarr = this;
    for(var i = tarr.length - 1 ; i > 0 ; i--)
    {
        this[i-1] = tarr[i];
    }
    this.pop();
    return tstr;
}

Array.prototype.last = function() {
    return this[this.length-1];
}

Array.prototype.contains = function(needle, ind) {
    var rtn = -1;
    ind = ind || 0;
    for(var i = 0; i < this.length; i++)
    {
        if(isArray(this[i]))
        {
            if(this[i][ind] === needle)
                rtn = i;
        } else {
            if(this[i] === needle)
                rtn = i;
        }
    }
    return rtn;
}

Array.prototype.multiSort = function(index){
// Written By: WillyDuitt@hotmail.com | 03-10-2005 \\;
    for(var i=0; i<this.length; i++){
        var temp = this[i].splice(index,1);
        this[i].unshift(temp);
    }
    return this.sort();
}

Array.prototype.multiFind = function(index, value){
    var tmp = new Array();
    for(var i=0; i<this.length; i++){
        if(this[i][index] === value){
            tmp.push(this[i]);
        }
    }
    return tmp;
}


Array.prototype.trim = function(){
    for(var i = 0; i < this.length; i++){
        this[i] = this[i].trim();
    }
    return this;
}

Array.prototype.split = function(del){
    for(var i = 0; i < this.length; i++){
        this[i] = this[i].split(del);
    }
    return this;
}

Date.prototype.addMonth = function(n){
    n = n || 1;
    var eDate = new Date(this.getTime() + (n*31*24*60*60*1000));
    eDate.setDate(this.getDate());
    this.setFullYear(eDate.getFullYear(), eDate.getMonth(), eDate.getDate());
    this.setHours(eDate.getHours(), eDate.getMinutes(), eDate.getSeconds(), eDate.getMilliseconds());

    return this;
}

Date.prototype.addDay = function(n){
    n = n || 1;
    var eDate = new Date(this.getTime() + (n*1*24*60*60*1000));
    this.setFullYear(eDate.getYear(), eDate.getMonth(), eDate.getDate());
    this.setHours(eDate.getHours(), eDate.getMinutes(), eDate.getSeconds(), eDate.getMilliseconds());

    return this;
}

Date.prototype.addWeek = function(n){
    n = n || 1;
    var eDate = new Date(this.getTime() + (n*7*24*60*60*1000));
    this.setFullYear(eDate.getYear(), eDate.getMonth(), eDate.getDate());
    this.setHours(eDate.getHours(), eDate.getMinutes(), eDate.getSeconds(), eDate.getMilliseconds());

    return this;
}

function isArray(obj) {
    if (obj.constructor.toString().indexOf('Array') == -1)
        return false;
    else
        return true;
}

function KeyCheck(e, fnc)
{
    var key;

    if(window.event)
        key = window.event.keyCode;     //IE
    else
        key = e.which;     //firefox

    if (key == 13)
    {
        //Get the button the user wants to have clicked
        if (fnc)
        { //If we find the button click it
            fnc();
            try{
                e.keyCode = 0;
            } catch (e1) {
                e.cancelBubble=true;
            }
        }
    }
}

var FormAjax = {
    addOption: function(element, value) {
        if(element.type.indexOf("select") > -1)
        {
            var elOptNew = document.createElement('option');
            elOptNew.text = value[0];
            elOptNew.value = value[1];

            try {
                element.add(elOptNew, null); // standards compliant; doesn't work in IE
            }
            catch(ex) {
                element.add(elOptNew); // IE only
            }
        } else {
            element.value = value;
        }
    },

    Populate: function(element, value) {
        var self = element;
        //$(self).enable();
        var a = new sack();
        a.requestFile = "php/ajaxquery.php";
        a.setVar("SQL", value);
        a.setVar("type", "RAW");
        a.onCompletion = function(){
            var data = a.response;
            var obj = a.responseJSON;
            if(data.substring(0, 5) === "Error"){
                exit;
            }
            for (i = self.length - 1; i>=0; i--) {
                self.remove(i);
            }
            if(obj)
            {
                var rows = obj;

                if(rows.length < 1){
                    $(self).disable();
                } else {
                    for(i = 0; i < rows.length-1; i++)
                    {
                        if(self.type.indexOf("select") > -1)
                        {
                            self.addOption(Array(rows[i].text, rows[i].value));
                        } else if(self.type == "password") {
                            self.value = "";
                        } else {
                            self.value = rows[i].value;
                        }
                    }
                }
            }
            else{
                var rows = data.split("^");

                if(rows.length < 1){
                    $(self).disable();
                } else {
                    for(i = 0; i < rows.length-1; i++)
                    {
                        var tcol = rows[i].split(',').trim();
                        if(self.type.indexOf("select") > -1)
                        {
                            self.addOption(Array(tcol[0], tcol[1]));
                        } else if(self.type == "password") {
                            self.value = "";
                        } else {
                            self.value = tcol[0].displayDate();
                        }
                    }
                }
            }
            self.onUpdate();
        };
        a.runAJAX();
    },



    onUpdate: function(element) {

    },

    heatPopulate: function(element, value) {
        var self = element;
        //$(self).enable();
        var a = new sack();
        a.requestFile = "php/ajaxquery.php";
        a.setVar("SQL", value);
        a.setVar("type", "RAW");

        a.setVar("dbname", "Heat_live");
        a.setVar("username", "HEAT8");
        a.setVar("password", "$dH3@t#8");
        a.setVar("hostname", "grrp573a.amcs.tld");
        a.setVar("dbtype", "mssql2005");

        a.onCompletion = function(){
            var data = a.response;
            if(data.substring(0, 5) === "Error"){
                exit;
            }
            for (i = self.length - 1; i>=0; i--) {
                self.remove(i);
            }

            var rows = data.split("^").trim();

            if(rows.length <= 1){
                $(self).value = rows[0];
            } else {
                for(i = 0; i < rows.length-1; i++)
                {
                    var tcol = rows[i].split(',').trim();
                    if(self.type.indexOf("select") > -1)
                    {
                        self.addOption(Array(tcol[0], tcol[1]));
                    } else if(self.type == "password") {
                        self.value = "";
                    } else {
                        self.value = tcol[0].displayDate();
                    }
                }
            }
        };
        a.runAJAX();
    },

    heatRetrieve: function(element, value) {
        var self = element;
        $(self).enable();
        var a = new sack();
        a.requestFile = "php/ajaxquery.php";
        a.setVar("SQL", value);
        a.setVar("type", "RAW");

        a.setVar("dbname", "Heat_live");
        a.setVar("username", "HEAT8");
        a.setVar("password", "$dH3@t#8");
        a.setVar("hostname", "grrp573a.amcs.tld");
        a.setVar("dbtype", "mssql2005");

        a.onCompletion = function(){
            var data = a.response;
            if(data.substring(0, 5) === "Error"){
                exit;
            }
            var rows = data.split("^");
            rows = rows[0].split(',').trim();
            $(self).selectValue(rows[0]);
        };
        a.runAJAX();
    },

    heatCheck: function(element, table, col, act) {
        var self = element;
        $(self).enable();
        var a = new sack();
        a.requestFile = "php/ajaxquery.php";
        a.setVar("SQL", "select * from "+table+" where "+col+" = '"+self.value+"'");
        a.setVar("type", "RAW");

        a.setVar("dbname", "Heat_live");
        a.setVar("username", "HEAT8");
        a.setVar("password", "$dH3@t#8");
        a.setVar("hostname", "grrp573a.amcs.tld");
        a.setVar("dbtype", "mssql2005");

        a.onCompletion = function(){
            var data = a.response;
            if(data.substring(0, 5) === "Error"){
                return false;
            }
            if(data === ""){
                return false;
            }
            act(self.value);
            return true;
        };
        a.runAJAX();
    },

    PopulateLabel: function(element, value) {
        var self = element;
        var a = new sack();
        a.requestFile = "php/ajaxquery.php";
        a.setVar("SQL", value);
        a.setVar("type", "RAW");
        a.onCompletion = function(){
            var data = a.response;
            if(data.substring(0, 5) === "Error"){
                exit;
            }

            var rows = data.split("^");
            var cells = rows[0].split(",");
            self.innerHTML = cells[0].trim();
        };
        a.runAJAX();
    },

    Update: function(element, value) {
        var a = new sack();
        a.requestFile = "php/ajaxquery.php";
        a.setVar("SQL", value);
        a.setVar("type", "RAW");
        a.onCompletion = function(){
            var data = a.response;
            if(data.substring(0, 5) === "Error" || data == "-1"){
                alert('Error Updating data:' + a.response);
            } else {
                element.className = "Updated";
            }
        };
        a.runAJAX();
    },

    formHide: function(element) {
        element.disable();
        element.className = "formHide";
    },

    validation:function(element) {
        return true;
    },

    selectValue: function(element, value){
        var found = false;
        for(j=element.options.length-1; j>=0; j--)
        {
            selectedValue = element.options[j].value;
            if(element.options[j].value.toLowerCase() == value.toLowerCase() || element.options[j].text.toLowerCase() == value.toLowerCase()){
                element.options[j].selected = true;
                found = true;
            }
        }
        if(!found)
        {
            var elOptNew = document.createElement('option');
            elOptNew.text = value;
            elOptNew.value =value;
            try {
                element.add(elOptNew, null); // standards compliant; doesn't work in IE
            }
            catch(ex) {
                element.add(elOptNew); // IE only
            }
            element.options[element.options.length-1].selected = true;
        }
    },

    getCheckedValue: function(radioObj) {
            if(!radioObj)
                    return "";
            var radioLength = radioObj.length;
            if(radioLength == undefined)
                    if(radioObj.checked)
                            return radioObj.value;
                    else
                            return "";
            for(var i = 0; i < radioLength; i++) {
                    if(radioObj[i].checked) {
                            return radioObj[i].value;
                    }
            }
            return "";
    }

};

var TableFunctions = {
    addRow: function(element, tBodyIndex) {
        tBodyIndex = tBodyIndex || 0;
        if(!element.rows){exit;}

        tr = document.createElement('tr');
        Element.extend(tr);
        element.getElementsByTagName('tbody')[tBodyIndex].appendChild(tr);

        return tr;
    },

    addCell: function(element, value) {
        if(!element.cells){exit;}
        value = value || ""
        td = document.createElement('td');
        element.appendChild(td);
        td.innerHTML = value;
        Element.extend(td);
        return td;
    },

    addHeader: function(element, value) {
        value = value || "";
        if(!element.cells){exit;}

        td = document.createElement('th');
        element.appendChild(td);
        Element.extend(td);
        td.innerHTML = value;
        return td;
    },

    addBody: function(element) {
        if(!element.rows){exit;}
        tBodyIndex = element.getElementsByTagName('tbody').length;

        tb = document.createElement('tbody');
        Element.extend(tb);
        element.appendChild(tb);

        return true;
    }
};

var ElementFunctions = {
    deleteChildren: function(element){
        var el = element.children;
        for(var i = 0; i < el.length; i++)
        {
            element.removeChild(el[i]);
        }
    },

    findLayer: function(element){
        if(element.style[zIndex]) return element.style[zIndex]
        else {
            var el = element.getOffsetParent();
            return el.findLayer();
        }
    }
};


Element.addMethods(FormAjax);
Element.addMethods(ElementFunctions);
Element.addMethods(TableFunctions);


