/*   3/27/2008 - ALIWEB's Basic JavaScript                              */

//      AJAX Functions
// createRequestObject() - Create our AJAX request object

//      Window Functions
// gotoNewLocation() - Go to a new location; open a new window if desired

//      Object Functions
// idObj() - Return the object having the passed id
// getTagElementsWithClass() - Return all elements with tag and class
// getLeftPosn() - Return the Left window position of the passed object

//      Page Functions
// setCursor() - Set the cursor to the desired pointer
// setNotice() - Write our copyright notice to the page

//      Event Functions
// getEventObject() - Return the object associated with an event
// stopDefaultAction() - Stop the default action for an event
// addLoadListener() - Add an onLoad function to call
// addListener() - Add an event function to call
// removeListener() - Remove an event listener function

//      Node Functions
// insertAfter() - Insert one node after another (no DOM method)

//      Class Functions
// hasClass() - Return true if the object has the passed class name
// addClass() - Add a class name to an object's classes
// removeClass() - Toss a class name from an object's classes

//      Formatting functions
// formatPhone() - Return a phone string (aaaeeennnn) as (aaa) eee-nnnn

//      Array functions
// sortArray() - Return the passed array sorted by the passed FldX property

//      General functions
// decToHex() - Convert a decimal number to a hex number
// hexToDec() - Convert a hex number to a decimal number

//      Load Listeners

/************************************************************************/

/************************************************************************/

//      AJAX Functions

var requestObj = createRequestObject();

// createRequestObject() - Create our AJAX request object
function createRequestObject() {
    var request;
    try {
        request = new XMLHttpRequest();  // Opera, Mozilla, etc.
    } catch (trymicrosoft) {
        try {
            request = new ActiveXObject("Msxml2.XMLHTTP");
        } catch (othermicrosoft) {
            try {
                request = new ActiveXObject("Microsoft.XMLHTTP");
            } catch (failed) {
                request = null;
            }
        }
    }
    return request;
}


//      Window Functions

// gotoNewLocation() - Go to a new location; open a new window if desired
function gotoNewLocation(newUrl, bNewWindow) {
    var retVal, win;
    if (bNewWindow) {
        win = window.open(newUrl);
        retVal = win;
    } else {
        window.location.href =  newUrl;
        retVal = true;
    }
    return retVal;
}


//      Object Functions

// idObj() - Return the object having the passed id
function idObj(strID) {
    return document.getElementById(strID);
}

// getTagElementsWithClass() - Return all elements with tag and class
function getTagElementsWithClass(tagName, className, obj2Check)    {
    var retArray, elems, thisElem;
    retArray = [];
    if (obj2Check)  {
        elems = obj2Check.getElementsByTagName(tagName);
    } else {
        elems = document.getElementsByTagName(tagName);
    }
    for (var x=0; x < elems.length; x++)  {
        thisElem = elems[x];
        if (hasClass(thisElem, className))  {
            retArray[retArray.length] = thisElem;
        }
    }
    return retArray;
}

// getLeftPosn() - Return the Left window position of the passed object
function getLeftPosn(oObj)  {
    var nLeft = oObj.offsetLeft;
    var keyObj = oObj;
    while (!(keyObj.parentNode.tagName=="HTML")) {
        keyObj = keyObj.parentNode;
        nLeft = nLeft + keyObj.offsetLeft;
    }
    return nLeft;
}

function getXYPosition(theElement)
{
    var positionX = 0;
    var positionY = 0;
    while (theElement != null)
    {
        positionX += theElement.offsetLeft;
        positionY += theElement.offsetTop;
        theElement = theElement.offsetParent;
    }
    var retObj = new Object;
    retObj.PosnX = positionX;
    retObj.PosnY = positionY;
    return retObj;
}


//      Page Functions

// setCursor() - Set the cursor to the desired pointer
function setCursor(style)   {

    // style: std (default), hand (clickability), help, wait
    if (!style) {
        style = "std";
    }

    // clear all cursor styles from the body
    var oBody = document.body;
    removeClass(oBody, "cursorstd");
    removeClass(oBody, "cursorhand");
    removeClass(oBody, "cursorhelp");
    removeClass(oBody, "waiting");

    // set the desired cursor
    if (style == "wait")    {
        addClass(oBody, "waiting");
    } else if (style == "help")    {
        addClass(oBody, "cursorhelp");
    } else if (style == "hand")    {
        addClass(oBody, "cursorhand");
    } else {
        addClass(oBody, "cursorstd");
    }
}

// setNotice() - Write our copyright notice to the page
function setNotice() {
    var obj = document.getElementById("CRNotice");
    if (obj)    {

        // Get our build year
        var oPgYear = document.getElementById("pageYear");
        var buildYear = oPgYear.innerHTML;

        // Get today's year and generate our copyright message
        var nowYear = new Date().getFullYear();
        var cMsg = "Copyright " + buildYear;
        if (nowYear > buildYear)  {
            cMsg = cMsg + "-" + nowYear;
        }
        cMsg = cMsg + '&nbsp;<a class="white" href="mailto:sams@alicorp.com">' +
          "ALI Corporation</a>";
        obj.innerHTML = cMsg;
    }
}


//      Event Functions

// getEventObject() - Return the object associated with an event
function getEventObject(evnt)   {
    var retObj = null;
    if (!evnt)  {
        evnt = window.event;
    }
    if (evnt.target)    {
        retObj = evnt.target;
    } else {
        retObj = evnt.srcElement;
    }
    return retObj;
}

// stopDefaultAction() - Stop the default action for an event
function stopDefaultAction(event) {
    event.returnValue = false;
    if (typeof event.preventDefault != "undefined") {
        event.preventDefault();
    }
    return true;
}

// addLoadListener() - Add an onLoad function to call
function addLoadListener(fn)    {
    if (typeof window.addEventListener != 'undefined') {
        window.addEventListener('load', fn, false);         // W3C Std.
    } else if (typeof document.addEventListener != 'undefined') {
        document.addEventListener('load', fn, false);       // Opera
    } else if (typeof window.attachEvent != 'undefined') {
        window.attachEvent('onload', fn);                   // IE
    } else {
        var oldfn = window.onload;              // Chain all others
        if (typeof window.onload != 'function') {
            window.onload = fn;
        } else {
            window.onload = function()  {
                oldfn();
                fn();
            };
        }
    }                }

// addListener() - Add an event function to call
function addListener(obj, evName, fn) {
    var eventType, oldListener;

    // This code is stolen from Edwards & Adams in "The JavaScript
    //  Anthology" and John Resig's winning entry at
    //  http://ejohn.org/projects/flexible-javascript-events/
    // Changes, adaptions and errors are, alas, all mine!

    // Strip the "on" from the event name if it's there
    if (evName.indexOf('on') == 0) {
        evName = evName.substr(2, evName.length - 2);
    }

    // Now, add this to the object's events
    if (obj.addEventListener) {
        obj.addEventListener(evName, fn, false);    // W3C
    } else if (obj.attachEvent)    {

        // IE: We have to add a special function to make "this" work
        obj['e'+evName+fn] = fn;
        obj[evName+fn] = function()   {
            obj['e'+evName+fn]( window.event );
        };
        obj.attachEvent( 'on' + evName, obj[evName+fn] );
    } else  {

        // Do it the hard way and daisy-chain events
        eventType = "on" + eventType;
        if (typeof target[eventType] == "function") {
            oldListener = target[eventType];
            target[eventType] = function()    {
                oldListener();
                return functionRef();
            };
        } else {
          target[eventType] = functionRef;
        }
    }
}

// removeListener() - Remove an event listener function
function removeListener( obj, evName, fn ) {
    if (obj.detachEvent) {                          // IE

        // Remove the special function
        obj.detachEvent('on' + evName, obj[evName+fn] );
        obj[evName+fn] = null;
    } else if (obj.removeEventListener) {           // W3C
        obj.removeEventListener( evName, fn, false );
    } else  {
        target["on" + eventType] = null;
    }
}

//      Node Functions

// insertAfter() - Insert one node after another (no DOM method)
function insertAfter(newElement, targetElement) {
    var parent = targetElement.parentNode;
    if (parent.lastChild == targetElement)  {
        parent.appendChild(newElement);
    } else {
        parent.insertBefore(newElement, targetElement.nextSibling);
    }
}

//      Class Functions

// hasClass() - Return true if the object has the passed class name
function hasClass(target, classValue)   {
    var pattern = new RegExp("(^| )" + classValue + "( |$)");
    if (pattern.test(target.className)) {
        return true;
    }
    return false;
}

// addClass() - Add a class name to an object's classes
function addClass(target, classValue)   {
    var pattern = new RegExp("(^| )" + classValue + "( |$)");
    if (!pattern.test(target.className))  {
        if (target.className == "") {
            target.className = classValue;
        } else {
            target.className += " " + classValue;
        }
    }
    return true;
}

// removeClass() - Toss a class name from an object's classes
function removeClass(target, classValue)    {
    var removedClass = target.className;
    var pattern = new RegExp("(^| )" + classValue + "( |$)");
    removedClass = removedClass.replace(pattern, "$1");
    removedClass = removedClass.replace(/ $/, "");
    target.className = removedClass;
    return true;
}


//      Formatting functions

// formatPhone() - Return a phone string (aaaeeennnn) as (aaa) eee-nnnn
function formatPhone(cStrIn)    {
    var cRet = "";
    if (cStrIn) {
        cRet = "(" + cStrIn.Left(3) + ") " + cStrIn.Substr(4,3) + "-" +
          cStrIn.Substr(7);
    }
    return cRet;
}


//      Array functions

// sortArray() - Return the passed array sorted by the passed FldX property
function sortArray(ra2Sort, fldName)    {
    var begRow, endRow, retArray, row, moreToDo, thisObj, nextObj;

    // Create our return array and copy all values
    begRow = 1;
    if (ra2Sort[0])    {
        begRow = 0;
    }
    endRow = ra2Sort.length - 1;
    if (ra2Sort[ra2Sort.length])    {
        endRow = ra2Sort.length;
    }
    retArray = [];
    for (row=begRow; row <= endRow; row++)    {
        retArray[row] = ra2Sort[row];
    }

    // We'll almost certainly have to do multiple passes until the array is
    //  fully sorted.
    moreToDo = true;
    while (moreToDo)    {
        moreToDo = false;

        // Go thru all rows in the array
        for (row=begRow; row < endRow; row++)    {
            thisObj = retArray[row];
            if (thisObj)    {
                nextObj = retArray[row+1];
                if (thisObj[fldName] > nextObj[fldName])    {

                    // Swap the 2 values:
                    retArray[row] = nextObj;
                    retArray[row+1] = thisObj;
                    moreToDo = true;
                }
            }
        }
    }
    return retArray;
}


//      General functions

// decToHex() - Convert a decimal number to a hex number
function decToHex(d) {
    return d.toString(16);
}

// hexToDec() - Convert a hex number to a decimal number
function hexToDec(h) {
    return parseInt(h,16);
}


//      Load Listeners
addLoadListener(setNotice);
