/* copyright (c) 2005 Eric W. Yee
 *
 *
 */

function DistanceUnit() {}
DistanceUnit.Kilometer = 0;
DistanceUnit.Mile = 1;
DistanceUnit.Meter = 2;
DistanceUnit.Yard = 3;
function WeightUnit() {}
WeightUnit.Kilogram = 0;
WeightUnit.Pound = 1;
var g_mi2km = 1.609344;
var g_vecDistUnits = [ "Kilometer", "Mile", "Meter", "Yard" ];
var g_vecDistUnitsAbbr = [ "km", "mi", "m", "yd" ];
var g_vecWeightUnits = [ "Kilogram", "Pound" ];

function GetElement(id)
{
	return (document.getElementById)
        ? document.getElementById(id)
        : eval("document.all['" + id + "']");
}

function IsIE()
{
    return !(navigator
             && navigator.userAgent.toLowerCase().indexOf("msie") == -1);
}
function GetControlValue(pCell, strCtrlName)
{
    var pCtrl = GetChildNodeByID(pCell, strCtrlName);
    if (pCtrl == null)
        return "";
    return UnquoteString(pCtrl.value);
}
function GetChildNodeByID(pParent, strName)
{
    if (pParent == null)
        return null;

    if (pParent.hasChildNodes == false)
        return null;

    for (var pChild = GetFirstNonTextSiblingNode(pParent.firstChild);
         pChild != null;
         pChild = GetNextNonTextSiblingNode(pChild))
    {
        if (pChild.id == strName)
            return pChild;
    }
    return null;
}
function IsTextNode(pElem)
{
    return pElem.nodeType == 3;
}
function GetFirstNonTextSiblingNode(pElem)
{
	for (var pSibling = pElem; pSibling != null && IsTextNode(pSibling);
         pSibling = pSibling.nextSibling);
    return pSibling;
}
function GetLastNonTextSiblingNode(pElem)
{
    pElem = pElem.parentNode.lastChild;
    while (pElem != null && IsTextNode(pElem))
        pElem = pElem.previousSibling;
    return pElem;
}
function GetPrevNonTextSiblingNode(pElem)
{
    for (var pSibling = pElem.previousSibling;
         pSibling != null && IsTextNode(pSibling);
         pSibling = pSibling.previousSibling);
    return pSibling;
}
function GetNextNonTextSiblingNode(pElem)
{
	for (var pSibling = pElem.nextSibling;
         pSibling != null && IsTextNode(pSibling);
         pSibling = pSibling.nextSibling);
    return pSibling;
}
function GetOffsetLeft(pObj)
{
    return GetOffset(pObj, "offsetLeft");
}

function GetOffsetTop(pObj)
{
    return GetOffset(pObj, "offsetTop");
}

function GetOffset(pObj, strAttr)
{
    var nOffset = 0;
    while(pObj != null)
    {
        nOffset += pObj[strAttr]; 
        pObj = pObj.offsetParent;
    }
    return nOffset;
}
function GetWidth(pObj)
{
    if (IsIE())
        return pObj.offsetWidth;
    return pObj.offsetWidth - 2;
}
function GetHeight(pObj)
{
    return pObj.offsetHeight;
}
function ToggleCtrl(idCtrl, bVis)
{
    var pCtrl = GetElement(idCtrl);
    if (pCtrl != null)
        pCtrl.style.visibility = bVis > 0 ? "visible" : "hidden";
}
function UnquoteString(strQuotedText)
{
    if (strQuotedText.length >= 2 && strQuotedText.substr(0, 1) == '"'
        && strQuotedText.substr(strQuotedText.length - 1, 1) == '"')
    {
        var strUnquoted = strQuotedText.substr(1, strQuotedText.length - 2);
        return decodeURIComponent(strUnquoted);
    }
    return strQuotedText;
}
function EscapeHTML(strHtml)
{
    return strHtml.replace(RegExp('>', 'g'), '&gt;')
        .replace(RegExp('<', 'g'), '&lt;');
}
function UnescapeHTML(strHtml)
{
    return strHtml.replace(RegExp('&gt;', 'g'), '>')
        .replace(RegExp('&lt;', 'g'), '<');
}
function StoreHiddenData(parentNode, strKey, strValue)
{
    var oTextBox = GetChildNodeByID(parentNode, strKey);
    if (oTextBox == null)
    {
        oTextBox = document.createElement("INPUT");
        oTextBox.type = "hidden";
        parentNode.appendChild(oTextBox);
    }
    oTextBox.id = strKey;
    oTextBox.setAttribute("name", strKey);
    oTextBox.setAttribute("value", "\"" + encodeURIComponent(strValue) + "\"");
}
function CreateTextBox(strID, strContents, strWidth, nMaxLength)
{
    var pTextBox = document.createElement("INPUT");
    pTextBox.type = "text";
    pTextBox.id = strID;
    pTextBox.value = strContents;

    if (strWidth.length > 0)
        pTextBox.style.width = strWidth;
    if (nMaxLength)
        pTextBox.maxLength = nMaxLength;
    return pTextBox;
}
function GetElementWidthInPixels(pElem)
{
    var nWidth = 0;
    if (IsIE())
        nWidth = pElem.style.pixelWidth;
    else
        nWidth = document.defaultView.getComputedStyle(pElem, null)
            .getPropertyValue('width');
    return nWidth;
}
function AddSelectOption(pSelect, strKey, strValue, strDefaultKey)
{
    var pOption = document.createElement("OPTION");
    pOption.value = strKey;
    pOption.innerHTML = strValue;

    if (strDefaultKey == strKey)
        pOption.selected = "selected";
    pSelect.appendChild(pOption);
}
function GetKeyCode(evt)
{
    return evt.keyCode > 0 ? evt.keyCode
        : (evt.which > 0 ? evt.which : evt.charCode);
}
function RestrictWholeNumbers(evt, pEdit)
{
    if (evt == null)
        evt = window.event;
    var keyCode = GetKeyCode(evt);
    var bAllow = IsControlKey(keyCode) || (keyCode >= 48 && keyCode <= 57);
    if (evt.preventDefault && !bAllow)
        evt.preventDefault();
    evt.returnValue = bAllow;
}
function RestrictAlphaNumeric(evt)
{
    if (evt == null)
        evt = window.event;
    var keyCode = GetKeyCode(evt);
    var bAllow = IsControlKey(keyCode) || (keyCode >= 48 && keyCode <= 57)
        || (keyCode >= 65 && keyCode <= 90)
        || (keyCode >= 97 && keyCode <= 122)
        || keyCode == 95;
    if (evt.preventDefault && !bAllow)
        evt.preventDefault();
    evt.returnValue = bAllow;
}

function LimitChars(evt, limit, tb, id)
{
    if (evt == null)
        evt = window.event;
    var count = limit - tb.value.length;
    if (count < 0)
    {
        tb.value = tb.value.substr(0, limit);
        count = 0;
    }
    var txt = document.getElementById(id);
    txt.innerHTML = count + " characters remaining";

    var keyCode = GetKeyCode(evt);
    if (count == 0 && !IsControlKey(keyCode))
    {
        evt.returnValue = false;
        return;
    }
}

KeyTab = 9;
KeyBackSpace = 8;
var g_vecControlKeys = [ KeyBackSpace,
                         46, //delete
                         38, //up arrow
                         40, //down arrow
                         37, //left arrow
                         39, //right arrow
                         27, //esc
                         13, //enter
                         33, //page up
                         34, //page down
                         36, //home
                         35, //end
                         KeyTab,
                         16, //shift
                         17, //ctrl
                         18, //alt
                         20  //caps lock
                       ];
function IsControlKey(cKey)
{
    for (var i = 0; i < g_vecControlKeys.length; ++i)
    {
        if (g_vecControlKeys[i] == cKey)
            return true;
    }
    return false;
}

function GetXMLHttpObject()
{
    var pXml = null;
    try
    {
        pXml = new ActiveXObject("Msxml2.XMLHTTP");
    }
    catch(e)
    {
        try
        {
            pXml = new ActiveXObject("Microsoft.XMLHTTP");
        }
        catch(oc)
        {
            pXml = null;
        }
    }
    if(!pXml && typeof XMLHttpRequest != "undefined")
    {
        pXml = new XMLHttpRequest();
    }
    return pXml;
}

function AjaxGetData(strUrl, callback)
{
    var ajax = GetXMLHttpObject();
    if (ajax == null)
        return;
    if (callback != null)
    {
        ajax.onreadystatechange = function()
        {
            if (ajax.readyState == 4)
                callback(ajax.responseText);
        };
    }

    ajax.open("GET", strUrl, callback != null);
    ajax.send(null);

    if (callback == null)
        return ajax.responseText;
}
function AjaxPostData(strUrl, strData, callback)
{
    var ajax = GetXMLHttpObject();
    if (ajax == null)
        return;

    if (typeof(callback) != 'undefined' && callback != null)
    {
        ajax.onreadystatechange = function()
        {
            if (ajax.readyState == 4)
                callback(ajax.responseText);
        }
    }

    ajax.open("POST", strUrl, callback != null);
    ajax.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
    ajax.send(strData);

    if (callback == null)
        return ajax.responseText;
}

function GetPageWidth()
{
    return window.innerWidth != null? window.innerWidth
        : (document.documentElement && document.documentElement.clientWidth
           ? document.documentElement.clientWidth
           : (document.body != null
              ? document.body.clientWidth : null));
}

function GetPageHeight()
{
    return window.innerHeight != null ? window.innerHeight
        : (document.documentElement && document.documentElement.clientHeight
           ?  document.documentElement.clientHeight
           : (document.body != null ? document.body.clientHeight : null));
}

function ConvertWeight(weight, srcUnit, destUnit)
{
    var lb2kg = 0.45359237;
    if (srcUnit == WeightUnit.Pound && destUnit == WeightUnit.Kilogram)
        weight *= lb2kg;
    else if (srcUnit == WeightUnit.Kilogram && destUnit == WeightUnit.Pound)
        weight /= lb2kg;
    return weight;
}
function ConvertDistance(dist, srcUnit, destUnit)
{
    // convert srcUnit to meters
    switch (srcUnit)
    {
        case DistanceUnit.Yard:
            dist /= 1760;
        case DistanceUnit.Mile:
            dist *= g_mi2km;
        case DistanceUnit.Kilometer:
            dist *= 1000;
        case DistanceUnit.Meter:
            break;
    }

    // convert meters to destUnit
    srcUnit = DistanceUnit.Meter;
    while (srcUnit != destUnit)
    {
        switch (srcUnit)
        {
            case DistanceUnit.Meter:
                dist /= 1000;
                srcUnit = DistanceUnit.Kilometer;
                break;
            case DistanceUnit.Kilometer:
                dist /= g_mi2km;
                srcUnit = DistanceUnit.Mile;
                break;
            case DistanceUnit.Mile:
                dist *= 1760;
                srcUnit = DistanceUnit.Yard;
                break;
            case DistanceUnit.Yard:
                srcUnit = destUnit;
                break;
        }
    }
    return dist;
}
function SetDocumentCookie(id, value, days)
{
    var cookie = id + "=" + escape(value);
    var expires = "";
    if (days != null)
    {
        var date = new Date();
        date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
        cookie += "; expires=" + date.toGMTString();
    }
    document.cookie = cookie;
}
function GetDocumentCookie(id)
{
    var vecCookies = document.cookie.split(";");
    id += "=";
    var value = "";
    for (var i = 0; i < vecCookies.length; ++i)
    {
        var cookie = vecCookies[i];
        if (cookie.indexOf(id) == 0)
        {
            value = cookie.substr(id.length);
            break;
        }
    }
    return unescape(value);
}
function ValidateDecimal(val)
{
    var vecResults = val.match(/^\d+(\.)?(\d+)?$/);
    return vecResults != null && vecResults.length > 0;
}
function ValidateTime(val)
{
    var vecResults = val.match(/^((\d+:)?[0-5]?\d:)[0-5]?\d$/);
    return vecResults != null && vecResults.length > 0;
}
function RoundDecimal(val, places)
{
    places = Math.pow(10, places);
    val = Math.round(val * places) / places;
    return val;
}
function TimeStringToSeconds(strTime)
{
    var vecResults = strTime.match(/^((\d+):)?([0-5]?\d):([0-5]?\d)$/);
    
    var nSeconds = 0;

    if (vecResults != null && vecResults.length >= 3)
    {
        var tmp = parseInt(vecResults[2], 10);
        if (!isNaN(tmp))
            nSeconds += tmp;
        nSeconds *= 60;

        var tmp = parseInt(vecResults[3], 10);
        if (!isNaN(tmp))
            nSeconds += tmp;
        nSeconds *= 60;

        var tmp = parseInt(vecResults[4], 10);
        if (!isNaN(tmp))
            nSeconds += tmp;
    } 
    return nSeconds;
}
function SecondsToTimeString(nSeconds)
{
    var strTime = "";
    var nMinutes = Math.floor(nSeconds / 60);
    nSeconds -= nMinutes * 60;
    var nHours = Math.floor(nMinutes / 60);
    nMinutes -= nHours * 60;

    if (nHours > 0)
        strTime = nHours.toString() + ":";

    if (nMinutes < 10 && nHours > 0)
        strTime += "0";
    strTime += nMinutes.toString() + ":";

    if (nSeconds < 10)
        strTime += "0";
    strTime += nSeconds.toString();

    return strTime;
}

function PopulateSelect(id, vecValues, defaultUnit)
{
    var ctlUnits = document.getElementById(id);
    if (ctlUnits != null)
    {
        for (var i = 0; i < vecValues.length; ++i)
        {
            var ctlOption = new Option(vecValues[i], i);
            ctlUnits.options[ctlUnits.length] = ctlOption;

            if (i == defaultUnit)
                ctlUnits.selectedIndex = i;
        }
    }
}


function Expand(idLabel, idTbl)
{  
    var objTbl = GetElement(idTbl);
    var objLabel = GetElement(idLabel);

    if (objTbl != null && objLabel)
    {
        if (objTbl.style.display == "none")
        {
            objTbl.style.display = "";
           
        }
        else
        {
            objTbl.style.display = "none";
            
        }
    }

    return true;
}
