function whichBrowser() {
    this.agt = navigator.userAgent.toLowerCase();
    this.major = parseInt(navigator.appVersion);
    this.dom = (document.getElementById) ? 1 : 0;
    this.ns = (document.layers) ? 1 : 0;
    this.ns4up = (this.ns && this.major >= 4) ? 1 : 0;
    this.ns6 = (this.dom && navigator.appName == "Netscape") ? 1 : 0;
    this.mozilla = this.agt.indexOf('mozilla') != -1 && parseInt(navigator.appVersion.substring(0, 1)) >= 5;
    this.op = (window.opera) ? 1 : 0;
    this.ie = (document.all) ? 1 : 0;
    this.ie4 = (document.all && !this.dom) ? 1 : 0;
    this.ie4up = (this.ie && this.major >= 4) ? 1 : 0;
    this.ie5 = (document.all && this.dom) ? 1 : 0;
    this.firefox = (this.agt.indexOf("firefox") != -1);
    this.win = ((this.agt.indexOf("win") != -1) || (this.agt.indexOf("16bit") != -1));
    this.mac = (this.agt.indexOf("mac") != -1);
}

var oBw = new whichBrowser();

var showProcessingForm = false;

function formatCurrency(value) {
    valueInString = value.toString();
    if (valueInString.indexOf('.') == -1) { //If zero or an integer
        if (valueInString == '0') {
            valueInString = "0.00"
        } else {
            valueInString = valueInString + '.00'
        }
    } else { // Fraction
        tmp = valueInString.split('.');
        tmp[1] = tmp[1] + '000';
        if (parseInt(tmp[1].slice(0, 3)) > 994) {
            // Do we need to round
            valueInString = (parseInt(tmp[0]) + 1) + '.00';
        } else {
            if (tmp[1].charAt(2) > 4) {
                xtmp = Math.round('1' + tmp[1].slice(0, 2) + '.9');
                xtmp = xtmp.toString() + '0';
                xtmp = xtmp.charAt(1) + xtmp.charAt(2);
            } else {
                xtmp = tmp[1].slice(0, 2);
            }
            valueInString = tmp[0] + '.' + xtmp;
        }
    }
    return valueInString;
}

function mouseIn(obj) {
    mouseInC(obj, '#990000');
}

function mouseOut(obj) {
    mouseOutC(obj, '#000000');
}

function mouseInC(obj, fcolor) {
    $(obj).css("color", fcolor);
}

function mouseOutC(obj, fcolor) {
    $(obj).css("color", fcolor);
}

function mouseInB(obj) {
    mouseInBC(obj, '#ffb6aa');
}

function mouseOutB(obj) {
    mouseOutBC(obj, 'white');
}

function mouseInBC(obj, bcolor) {
    $(obj).css("backgroundColor", bcolor);
}

function mouseOutBC(obj, bcolor) {
    $(obj).css("backgroundColor", bcolor);
}

var lastRow = '0';
var originalColor = '#000';

function M(row) {
    if (originalColor != '#000') $("#R" + lastRow).css("backgroundColor", originalColor);
    lastRow = row;
    originalColor = $("#R" + lastRow).css("backgroundColor");
    $("#R" + lastRow).css("backgroundColor", "#fafad2");
}

function HM(pressedLabel) {
    $("#" + pressedLabel + "style").css("color", "#ff0000");
    if (pressedLabel != orderBy) document.forms[0][pressedLabel + "arrow"].src = "/images/arrow0.gif";
    return false;
}

function HO(pressedLabel) {
    if (pressedLabel != orderBy) {
        $("#" + pressedLabel + "style").css("color", "#990000");
        document.forms[0][pressedLabel + "arrow"].src = "/images/clear.gif";
    }
    return false;
}

function openNew(url, name, width, height) {
    return openNewS(url, name, width, height, 'no');
}

var newFormWindow = null;

function closeForm(e) {
    if (!e) e = window.event;
    if (newFormWindow != null) {
        newFormWindow.close();
        newFormWindow = null;
    }
    return false;
}

function openNewS(url, name, width, height, scrollbars) {
    var xpos;
    var ypos;
    if (width == -1) {
        xpos = 0;
        width = screen.availWidth - 6;
    } else
        xpos = (screen.width) ? (screen.width - width) / 2 : 0;
    if (height == -1) {
        ypos = 0;
        height = screen.availHeight - 35;
    } else
        ypos = (screen.height) ? (screen.height - height) / 2 : 0;
    return openNewP(url, name, width, height, scrollbars, xpos, ypos);
}

function openNewP(url, name, width, height, scrollbars, xpos, ypos) {
    if (newFormWindow != null && !newFormWindow.closed && newFormWindow.location) {
        newFormWindow.location.href = url;
    } else {
        newFormWindow = window.open(
                url,
                name,
                "left=" + xpos + ",top=" + ypos + ",width=" + width + ",height=" + height +
                        ",location=no,navigation=no,resizable=yes,status=no,titlebar=yes,directories=no,toolbar=no,menubar=no,scrollbars=" +
                        scrollbars);
        if (!newFormWindow.opener) newFormWindow.opener = self;
    }
    if (window.focus) newFormWindow.focus();
    return false;
}

var submitFormCount = 0;

function submitFormAlert() {
    alert("You could not submit form twice.");
}

function safeDisableForm(form, action, singleSubmit) {
    if (submitFormCount == 0) {
        displayProcessingForm();
        if (singleSubmit == null || singleSubmit) {
            submitFormCount++;
            $("a.button").button("option", "disabled", true);
        }
    } else {
        if (this.submitFormAlert != null) {
            submitFormAlert();
        }
    }
}

function safeSubmitForm(form, action, singleSubmit) {
    if (submitFormCount == 0) {
        try {
            displayProcessingForm();
            if (singleSubmit == null || singleSubmit) {
                submitFormCount++;
                $("a.button").button("option", "disabled", false);
            }

            if (action != null) {
                form.action = action;
            }
        } finally {
            form.submit();
        }
    } else {
        if (this.submitFormAlert != null) {
            submitFormAlert();
        }
    }
}

function isEmpty(value) {
    return ((value == null) || (value.length == 0))
}

function isWhitespace(value) {
    // 	 Is value empty
    if (isEmpty(value)) return true;

    var i;
    var whitespace = " \t\n\r";
    // 	 Search through string's characters one by one
    //	 until we find a non-whitespace character.
    //	 When we do, return false; if we don't, return true.
    for (i = 0; i < value.length; i++) {
        // Check that current character isn't whitespace.
        var c = value.charAt(i);

        if (whitespace.indexOf(c) == -1) return false;
    }

    //	 All characters are whitespace.
    return true;
}

function isNumber(value) {
    var valid = "0123456789.";
    var each;

    //	 Is value empty
    if (isWhitespace(value)) return false;

    for (var i = 0; i < value.length; i++) {
        each = "" + value.substring(i, i + 1);
        var myindex = valid.indexOf(each);
        if (myindex < 0) return false; // An invalid character was found
    }
    return true;
}

function validateDate(year, month, day) {
    var monthDays = new Array(31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31);
    var yearValue,monthValue,dayValue;

    if (isWhitespace(year)) return false;
    if (isWhitespace(month)) return false;
    if (isWhitespace(day)) return false;

    if (!isNumber(year)) return false;
    if (!isNumber(month)) return false;
    if (!isNumber(day)) return false;

    yearValue = parseInt(year, 10);
    monthValue = parseInt(month, 10);
    dayValue = parseInt(day, 10);

    if (monthValue > 12 || monthValue < 1) return false;
    if (dayValue > monthDays[monthValue - 1]) return false;
    if ((yearValue % 4 != 0) && (monthValue == 2) && (dayValue > 28)) return false;
    return !((yearValue % 4 == 0) && (monthValue == 2) && (dayValue > 29));

}

function displayProcessingForm() {
    progressBar.showBar();
    window.status = "Connecting Xpeedite Server...";
}

function hiddenProcessingForm() {
    progressBar.hideBar();
    window.status = "Done";
}

// return the value of the radio button that is checked
// return an empty string if none are checked, or
// there are no radio buttons
function getCheckedValue(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 "";
}

// set the radio button with the given value as being checked
// do nothing if there are no radio buttons
// if the given value does not exist, all the radio buttons
// are reset to unchecked
function setCheckedValue(radioObj, newValue) {
    if (!radioObj)
        return;
    var radioLength = radioObj.length;
    if (radioLength == undefined) {
        radioObj.checked = (radioObj.value == newValue.toString());
        return;
    }
    for (var i = 0; i < radioLength; i++) {
        radioObj[i].checked = radioObj[i].value == newValue.toString();
    }
}

// var xyz = createBar(
// total_width,
// total_height,
// background_color,
// border_width,
// border_color,
// block_color,
// scroll_speed,
// block_count,
// scroll_count,
// action_to_perform_after_scrolled_n_times
// )

var valueN = -1;

function createBar(w, h, bgc, brdW, brdC, blkC, speed, blocks, count, action) {
    var t = '<div id="_xpbar' + (++valueN) + '" style="text-align:center;vertical-align:middle;visibility:hidden;z-index:99999;display:none;position:absolute;overflow:hidden;width:' + w + 'px; height:' + h + 'px;background-color:' + bgc + ';border-color:' + brdC + ';border-width:' + brdW + 'px; border-style:solid;font-size:xx-small;">';
    t += '<span id="blocks' + valueN + '" style="left:-' + (h * 2 + 1) + 'px;position:absolute;font-size:1px">';
    for (i = 0; i < blocks; i++) {
        t += '<span style="background-color:' + blkC + ';left:-' + ((h * i) + i) + 'px;font-size:1px;position:absolute;width:' + h + 'px;height:' + h + 'px;';
        t += 'filter:alpha(opacity=' + (100 - i * (100 / blocks)) + ')' + ';opacity:' + ((100 - i * (100 / blocks)) / 100) + '"></span>';
    }
    t += '</span>Getting data from Xpeedite...</div><iframe id=_ixpbar' + valueN + ' src="javascript:false;" scrolling=no frameborder=0 style="position:absolute;top:0px;left:0px;display:none;border-width:0;background-color:transparent"></iframe>';
    document.write(t);
    var bA = (oBw.ie) ? document.all['blocks' + valueN] : getElement('blocks' + valueN);
    bA.bar = (oBw.ie) ? document.all['_xpbar' + valueN] : getElement('_xpbar' + valueN);
    bA.ibar = (oBw.ie) ? document.all['_ixpbar' + valueN] : getElement('_ixpbar' + valueN);
    bA.blocks = blocks;
    bA.N = valueN;
    bA.w = w;
    bA.h = h;
    bA.speed = speed;
    bA.ctr = 0;
    bA.count = count;
    bA.action = action;
    bA.togglePause = togglePause;
    bA.showBar = function() {
        var x,            // layer target position on X axis
                y,            // layer target position on Y axis
                docWidth,     // width of current frame
                docHeight,    // height of current frame
                layerWidth,   // width of popup layer
                layerHeight;  // height of popup layer

        showProcessingForm = true;
        // First let's initialize our variables
        if (oBw.ie) {
            docWidth = document.body.offsetWidth;
            docHeight = document.body.offsetHeight;
            layerWidth = this.offsetWidth;
            layerHeight = this.offsetHeight;
            //alert("1:("+docWidth+"+"+docHeight+")"+layerWidth+"+"+layerHeight);
        } else if (oBw.ns) {
            docWidth = document.width;
            docHeight = document.height;
            layerWidth = this.style.clip.width;
            layerHeight = this.style.clip.height;
            //alert("2:("+docWidth+"+"+docHeight+")"+layerWidth+"+"+layerHeight);
        } else {
            docWidth = window.innerWidth ? window.innerWidth : document.body.clientWidth;
            docHeight = window.innerHeight ? window.innerHeight : document.body.clientHeight;
            layerWidth = this.style.width;
            layerHeight = this.style.height;
            //alert("3:("+docWidth+"+"+docHeight+")"+layerWidth+"+"+layerHeight);
            //alert("3:("+document.body.clientWidth+"+"+document.body.clientHeight+")"+window.innerWidth+"+"+window.innerHeight);
        }
        if (layerWidth <= 0) layerWidth = 300;
        if (layerHeight <= 0) layerHeight = 15;
        if (docWidth < layerWidth - 10) layerWidth = docWidth - 10;

        // Then we calculate the processing form's position
        x = Math.floor((docWidth - layerWidth) / 2);
        y = Math.floor((docHeight - layerHeight) / 2);
        if (oBw.ie) {
            x += document.body.scrollLeft;
            y += document.body.scrollTop;
        } else if (oBw.ns) {
        } else {
            x += window.pageXOffset;
            y += window.pageYOffset;
        }
        this.bar.style.left = x;
        this.bar.style.top = y;
        this.bar.style.width = layerWidth;
        this.bar.style.height = layerHeight;
        this.bar.style.visibility = "visible";
        this.bar.style.display = "block";

        this.ibar.style.left = x;
        this.ibar.style.top = y;
        this.ibar.style.width = layerWidth;
        this.ibar.style.height = layerHeight;
        this.ibar.style.visibility = "visible";
        this.ibar.style.display = "block";
    };
    bA.hideBar = function() {
        showProcessingForm = false;
        this.bar.style.visibility = "hidden";
        this.bar.style.display = "none";

        this.ibar.style.visibility = "hidden";
        this.ibar.style.display = "none";
    };
    bA.tid = setInterval('startBar(' + valueN + ')', speed);
    return bA;
}

function startBar(bn) {
    var t = (oBw.ie) ? document.all['blocks' + bn] : getElement('blocks' + bn);
    if (parseInt(t.style.left) + t.h + 1 - (t.blocks * t.h + t.blocks) > t.w) {
        t.style.left = -(t.h * 2 + 1) + 'px';
        t.ctr++;
        if (t.ctr >= t.count) {
            eval(t.action);
            t.ctr = 0;
        }
    } else t.style.left = (parseInt(t.style.left) + t.h + 1) + 'px';
}

function togglePause() {
    if (this.tid == 0) {
        this.tid = setInterval('startBar(' + this.N + ')', this.speed);
    } else {
        clearInterval(this.tid);
        this.tid = 0;
    }
}

var xmlHttp = false;

function initXmlHttp() {
    if (xmlHttp) return;
    xmlHttp = false;
    try {
        xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
    } catch (e) {
        try {
            xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
        } catch (e2) {
            xmlHttp = false;
        }
    }
    if (!xmlHttp && typeof XMLHttpRequest != 'undefined') {
        xmlHttp = new XMLHttpRequest();
    }
    if (!xmlHttp) alert("Your browser doesn't support AJAX");
}

function getWeather(param) {
    sendWeatherAJAXRequest(param, getWeatherCallback);
}

function sendWeatherAJAXRequest(param, callback) {
    initXmlHttp();
    if (xmlHttp) {
        window.status = "Fetching weather data from Xpeedite...";
        var url = "/getWeather";
        xmlHttp.open("POST", url, true);
        xmlHttp.onreadystatechange = callback;
        xmlHttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
        xmlHttp.send(param);
    }
}

function getWeatherCallback() {
    if (xmlHttp.readyState == 4) {
        if (xmlHttp.status == 200) {
            try {
                // Update the HTML DOM based on whether or not message is valid: alert(xmlHttp.responseText);
                var strWeather = getPropertyValue("weatherMsg");
                var weatherIcon = getPropertyValue("weatherIcon");
                $("#spnWeather").html(strWeather);
                $("#spnWeatherIcon").html(weatherIcon);
                $("#messageBar").fadeIn("slow");
            } finally {
                window.status = "Weather data has been updated on " + new Date();
            }
        }
        /*else if (xmlHttp.status == 404) alert("Requested URL is not found");
         else if (xmlHttp.status == 403) alert("Access denied");
         else alert("Status code is " + xmlHttp.status);*/
    }
}

function getPropertyValueFromXML(xml, key) {
    var value = '';
    $(xml).find("property").each(function() {
        if ($(this).find("name:first").text() == key) {
            $(this).find("list").each(function() {
                $("select[name=" + key + "]").html("");
                $(this).find("item").each(function() {
                    $("<option value='" + $(this).find("value").text() + "'>" + $(this).find("name").text() + "</option>").appendTo("select[name=" + key + "]");
                });
                return false;
            });
            value = $(this).find("value").text();
            $("select[name=" + key + "]").val(value);
            return false;
        }
    });
    return value;
}

function getPropertyValue(key) {
    try {
        var properties = xmlHttp.responseXML.getElementsByTagName("property");
        for (i = 0; i < properties.length; i++) {
            var name = "";
            if (properties[i].getElementsByTagName("name")[0].firstChild != null)
                name = properties[i].getElementsByTagName("name")[0].firstChild.nodeValue;
            if (name != "" && name == key) {
                var listElement = properties[i].getElementsByTagName("list");
                var value = "";
                if (properties[i].getElementsByTagName("value")[0].firstChild != null)
                    value = properties[i].getElementsByTagName("value")[0].firstChild.nodeValue;
                if (listElement.length > 0) {
                    var itemElements = listElement[0].childNodes;
                    var keyElement = getElement(key);
                    if (keyElement.type.toLowerCase() == 'select-one') {
                        keyElement.options.length = 0;
                        for (j = 0; j < itemElements.length; j++) {
                            var itemName = "";
                            if (itemElements[j].getElementsByTagName("name")[0].firstChild != null)
                                itemName = itemElements[j].getElementsByTagName("name")[0].firstChild.nodeValue;
                            var itemValue = "";
                            if (itemElements[j].getElementsByTagName("value")[0].firstChild != null)
                                itemValue = itemElements[j].getElementsByTagName("value")[0].firstChild.nodeValue;
                            var selected = (value == itemValue);
                            keyElement.options[j] = new Option(itemName, itemValue, selected, selected);
                        }
                    }
                    keyElement.value = value;
                }
                return value;
            }
        }
    } catch (e) {
        // alert("Invalid key:" + key);
    }
    return '';
}

function setFormPropertyValue(key, value) {
    var keyElement = getElement(key);
    if (keyElement != null)
        keyElement.value = value;
    //else alert("Invalid key/value:" + key + "/" + value);
}

function getElement(key) {
    var element = document.getElementById(key);
    if (element) return element;
    var form = window.document.forms[0];
    if (form) element = form[key];
    if (element) return element;
    return document.embeds[key];
}

function loadApplication(toolbarId) {
    switch (toolbarId) {
        case 1:
            window.parent.topper.click('orders');
            window.parent.topper.menuClick('orders', "Place Order");
            break;
        case 2:
            window.parent.topper.click('orders');
            window.parent.topper.menuClick('orders', "Today\'s Orders");
            break;
        case 3:
            window.parent.topper.click('dispatch');
            window.parent.topper.menuClick('dispatch', "Orders Ready for Dispatch");
            break;
        case 4:
            window.parent.topper.click('dispatch');
            window.parent.topper.menuClick('dispatch', "Enter POD");
            break;
        case 5:
            window.parent.topper.click('invoice');
            window.parent.topper.menuClick('invoice', "Create Invoices");
            break;
        case 6:
            window.parent.topper.click('invoice');
            window.parent.topper.menuClick('invoice', "Today\'s Invoices");
            break;
        case 7:
            window.parent.topper.click('invoice');
            window.parent.topper.menuClick('invoice', "Apply Payments");
            break;
        case 8:
            window.parent.topper.click('administration');
            window.parent.topper.menuClick('administration', "Customer");
            break;
        case 9:
            window.parent.topper.click('help');
            window.parent.topper.menuClick('help', "Online Help");
            break;
        case 10:
            window.parent.topper.click('orders');
            window.parent.topper.menuClick('orders', "Find Orders");
            break;
        case 11:
            window.parent.topper.click('invoice');
            window.parent.topper.menuClick('invoice', "Find Invoices");
            break;
        case 12:
            window.parent.topper.click('myinfo');
            break;
        //default: alert('Unkown icon '+toolbarId+' was clicked');
    }
}

function showOnlineHelp(params) {
    openNewS('/showOnlineHelp.do?url=' + document.location.href + '&' + params, 'onlineHelpWin', -1, -1, 'yes');
}

function getClientWidth() {
    if (document.all) return screen.width;
    return window.innerWidth;
}

function getClientHeight() {
    if (document.all) return screen.height;
    return window.innerHeight;
}

function replaceAll(sourceStr, findStr, replaceStr) {
    if (isEmpty(sourceStr) || isEmpty(findStr) || isEmpty(replaceStr) || findStr == replaceStr) return sourceStr;
    while (sourceStr.indexOf(findStr) >= 0) sourceStr = sourceStr.replace(findStr, replaceStr);
    return sourceStr;
}

function transferValueTo(formName, key, value) {
    document.forms[formName][key].value = value;
}