/*
    template.js
    Author      : Arnaud kleinveld
    Version     : $Revision: 1.39 $
    Copyright   : Your Business Online Pte Ltd, Singapore
*/

/**
 * Generate calendar icon next to give element *
 * @param args inputFieldId, format[%d-%m-%Y %H:%M:%S], showsTime, date
 */
function addCalendar(args) {

    var icon = document.createElement("img");
    icon.src = "/images/calendar.png";
    icon.className = "calendarIcon";
    icon.alt = "Calendar Icon";
    icon.title = "Click to select a date";
    icon.style.marginLeft = "3px";
    if (isIE) icon.style.marginBottom = "0px";

    var inputFieldId = args["inputFieldId"];
    var field = getElement(inputFieldId);
    if (field.nextSibling) field.parentNode.insertBefore(icon, field.nextSibling);
    else field.parentNode.appendChild(icon);
    
    var id = 0;
    var element = getElement("calendarIcon" + id);
    while (element) element = getElement("calendarIcon" + ++id);
    icon.id = "calendarIcon" + id;

    var format = args["format"];
    if (! format || format.length == 0) format = "%d-%m-%Y";

    var showsTime = args["showsTime"];
    if (! showsTime) showsTime = false;

    var date = args["date"];
    Calendar.setup({
        inputField  :   inputFieldId,
        ifFormat    :   format,
        button      :   icon.id,
        showsTime   :   showsTime,
        firstDay    :   1,
        date        :   date
    });
}

function addEventHandler(oTarget, sEventType, fnHandler) {
    if (oTarget.addEventListener) {
        oTarget.addEventListener(sEventType, fnHandler, false);
    } else if (oTarget.attachEvent) {
        oTarget.attachEvent("on" + sEventType, fnHandler);
    } else {
        oTarget["on" + sEventType] = fnHandler;
    }
}

function addPostParam(sParams, sParamName, sParamValue) {
    if (sParams.length > 0) sParams += "&";
    
    return sParams + encodeURIComponent(sParamName) + "="
        + encodeURIComponent(sParamValue);
}

function addToolTip(elementId, tooltip) {
    var element = getElement(elementId);
    if (element == null) return;
    element.setAttribute("title", tooltip);
}

function checkEmail(emailAddress) {
    var valid = true;

    var indx = emailAddress.indexOf("@");
    if (emailAddress == "" || indx == -1) valid = false;

    var part1 = emailAddress.substr(0,indx);
    var part2 = emailAddress.substr(indx + 1);
    if (part1.length < 2 || part2.length < 4 || part2.indexOf(".") == -1) valid = false;

    if (valid) return true;
    return false;
}

function checkDate(value, format, allowZero) {

    // HC requires this. If other customer do not later on, make it optional with allowZero
    if (allowZero && value.length == 1 && value == "0") return true;

    if (value.length != format.length) {
        alert("Date format should be " + format);
        return false;
    }

    if (format.length == 6 && ! /(\d\d)(\d\d)(\d\d)/.test(value)) {
        alert("Date format should be " + format);
        return false;

    } else if (format.length == 8 && ! /(\d\d)(\d\d)(\d{4})/.test(value)) {
        alert("Date format should be " + format);
        return false;

    } else if (format.length != 6 && format.length != 8) {
        alert("Date format should be " + format);
        return false;
    }

    var date = parseInt(RegExp.$1, 10);
    if (date < 1 || date > 31) {
        alert("Date format should be " + format);
        return false;
    }

    var month = parseInt(RegExp.$2, 10);
    if (month < 1 || month > 12) {
        alert("Date format should be " + format);
        return false;
    }
    
    return true;
}

function closePopupBox(elementId) {
    var box = getElement(elementId);
    if (box) box.close();
    removeOverlay();
}

function closePopupFrame(returnValue) {
    if (isIE && ! isMinIE8) parent.unHideSelects();
    
    if (! frameElement) return;
    if (! returnValue) returnValue = false;
    
    if (frameElement.onunload) frameElement.onunload(returnValue);
    parent.removeOverlay();
    parent.document.body.removeChild(frameElement);
}

function disable(controlId) {
    getElement(controlId).setAttribute("disabled", "disabled");
}

function disableAndHide(controlId) {
    disable(controlId);
    hide(controlId);
}

function disableFieldDep(dep, target) {
    var value = document.getElementById(dep).value;
    if (value == "New" || value == "") {
        enableAndUnHide(target);
    } else {
        disableAndHide(target);
    }
}

function emailLink(address, subject, linkClass) {
    if (! address) return;
    document.write("<a href='mailto:" + address);
    if (subject && subject.length > 0) document.write("?subject=" + subject);
    if (linkClass && linkClass.length > 0) document.write("' class='" + linkClass);
    document.write("'>" + address + "</a>");
}

function enable(controlId) {
    getElement(controlId).removeAttribute("disabled");
}

function enableAndUnHide(controlId) {
    enable(controlId);
    unHide(controlId);
}

function focusElement(elementId) {
    var element = document.getElementById(elementId);
    if (! element) return;
    
    element.focus();

    var top = getRealTop(element);
    
    var yScroll = getScroll()[1];
    if (yScroll > top) yScroll = Math.abs(top - 50);

    scrollTo(0, yScroll);
}

/**
 * Flash element using two css classes. The normal element state uses css class
 * "cssClass" and the highlighted state uses the css class "cssClassFlash"
 * 
 * Parameter times and interval are optional
 */
function FlashElement(element, cssClass, times, interval) {
    this.flashTimes = 5;
    this.flashTimesDone = 0;
    this.elementFlash = false;
    this.flashInterval = 600;
    this.element = element;
    this.run = true;
    this.cssClass = cssClass;

    if (times) this.flashTimes = (times * 2) - 1;
    if (interval) this.flashInterval = interval;
}

FlashElement.prototype.flash = function() {

    if (this.elementFlash) {
        this.element.className = this.element.className + " " + this.cssClass + "Flash";
        this.elementFlash = false;
    } else {
        this.element.className = this.element.className.replace(" " + this.cssClass + "Flash", "");
        this.elementFlash = true;
    }

    if (this.flashTimesDone < this.flashTimes) {
        this.flashTimesDone++;
        var ref = this;
        setTimeout(function() {ref.flash(ref);}, ref.flashInterval);
    } else {
        this.element.style.visibility = "hidden";
        this.flashTimesDone = 0;
        this.elementFlash = true;
    }
}

FlashElement.prototype.start = function() {
    this.element.style.visibility = "visible";
    this.flash();
}

FlashElement.prototype.stop = function() {
    this.flashTimesDone = this.flashTimes;
    this.element.style.visibility = "hidden";
}

function getCookie(name) {
    var dc = document.cookie;
    var prefix = name + "=";
    var begin = dc.indexOf("; " + prefix);
    if (begin == -1) {
        begin = dc.indexOf(prefix);
        if (begin != 0) return null;
    } else {
        begin += 2;
    }
    var end = document.cookie.indexOf(";", begin);
    if (end == -1) end = dc.length;
    return unescape(dc.substring(begin + prefix.length, end));
}

function getCursorPos(event) {
    if (window.event) {event = window.event;}
    var x = isIE ? event.x + getScroll()[0] : event.pageX;
    var y = isIE ? event.y + getScroll()[1] : event.pageY;
    return [x, y];
}

function getDataSync(event, state, args) {
    
    var oHttp = zXmlHttp.createRequest();    
    oHttp.open("post", "/data", false);
    
    var sParams = "";
    sParams = addPostParam(sParams, "appEvent", event);
    sParams = addPostParam(sParams, "appState", state);
    
    if (args && args.length > 0) {
        var argString = "";
        for (var i = 0; i < args.length; i++) {
            argString += args[i];
            if (i < (args.length - 1)) argString += "<a|s>";
        }
        sParams = addPostParam(sParams, "args", argString);
    }
    
    oHttp.setRequestHeader("content-type", "application/x-www-form-urlencoded");
    oHttp.send(sParams);

    if (oHttp.status == 401) goHome();

    return oHttp.responseText;
}

function getDataAsync(event, state, args) {
    var oHttp = zXmlHttp.createRequest();
    oHttp.open("post", "/data", true);
    
    var sParams = "";
    sParams = addPostParam(sParams, "appEvent", event);
    sParams = addPostParam(sParams, "appState", state);
    
    if (args && args.length > 0) {
        var argString = "";
        for (var i = 0; i < args.length; i++) {
            argString += args[i];
            if (i < (args.length - 1)) argString += "<a|s>";
        }
        sParams = addPostParam(sParams, "args", argString);
    }
    
    oHttp.setRequestHeader("content-type", "application/x-www-form-urlencoded");
    oHttp.send(sParams);
    
    return oHttp;

    /* Implement this function in the calling function
    oHttp.onreadystatechange = function() {
        if (oHttp.readyState == 4) {
            var text = oHttp.responseText;

            if (oHttp.status == 401) {
                goHome();
                return;
            }
        }
    };
    */
}

function getDocumentSize() {
    var y = (document.height !== undefined) ? document.height : document.body.offsetHeight;
    var x = (document.width !== undefined) ? document.width : document.body.offsetWidth;
    return [x, y];
}

function getElement(elementId) {
    return document.getElementById(elementId);
}

function getHexChars(number) {
    var chars = "";
    for (var i = 0; i < number; i++) {
        if (Math.random() > 0.5) {
            chars += String.fromCharCode(Math.round(Math.random() * 5) + 65);
        } else {
            chars += String.fromCharCode(Math.round(Math.random() * 9) + 48);
        }
    }
    return chars;
}

function getHostName() {
    var url = window.location.toString();
    var regHost = /\/\/(.*)\//;
    regHost.test(url);
    var host = RegExp.$1;
    return host.split(":")[0];
}

function getInnerHtml(elementId) {
    var element = getElement(elementId);
    if (element == null) return null;
    return element.innerHTML;
}

function getMainForm() {
    return getElement("mainForm");
}

function getParamUrl() {
    var url = "";
    var elements = getMainForm().elements;
    var firstElement = true;

    for (var i = 0; i < elements.length; i++) {
        var element = elements[i];
        
        if (! element.name || element.disabled) continue;
            
        if (element.nodeName == "INPUT" || element.nodeName == "SELECT") {
            var name = element.name;

            if (name.substring(0, 2) == "j_") continue;
            if (name.substring(0, 6) == "member") continue;
            if (! element.value || element.value == "") continue;

            url += (firstElement) ? "?" : "&";
            url += name + "=" + element.value;
            firstElement = false;
        }
    }
    return encodeURI(url);
}

function getRealLeft(element) {
    var realLeft = element.offsetLeft;
    var parent = element.offsetParent;
    while (parent != null) {
        realLeft += parent.offsetLeft;
        parent = parent.offsetParent;
    }
    return realLeft;
}

function getRealTop(element) {
    var realTop = element.offsetTop;
    var parent = element.offsetParent;
    while (parent != null) {
        realTop += parent.offsetTop;
        parent = parent.offsetParent;
    }
    return realTop;
}

function getScroll() {
    var x = 0, y = 0;
    if (typeof( window.pageYOffset ) == 'number') {
        // Netscape compliant
        y = window.pageYOffset;
        x = window.pageXOffset;
    } else if (document.body && (document.body.scrollLeft || document.body.scrollTop)) {
        // DOM compliant
        y = document.body.scrollTop;
        x = document.body.scrollLeft;
    } else if (document.documentElement &&
        (document.documentElement.scrollLeft || document.documentElement.scrollTop)) {
        // IE6 standards compliant mode
        y = document.documentElement.scrollTop;
        x = document.documentElement.scrollLeft;
    }
    return [x, y];
}

function getStyle(element, styleProp) {
    var y = null;
    if (window.getComputedStyle) {
        y = window.getComputedStyle(element, null).getPropertyValue(styleProp);
    } else if (element.currentStyle) {
        y = eval('element.currentStyle.' + styleProp);
    } else if (element.runtimeStyle) {
        y = eval('element.runtimeStyle.' + styleProp);
    } else if (element.style) {
        y = eval('element.style.' + styleProp);
    }
    return y;
}

function getTarget(event) {
    if (window.event) {event = window.event;}
    var target;
    if (event.srcElement != null) {
        target = event.srcElement;
    } else if (event.fromElement != null) {
        target = event.fromElement;
    } else if (event.target != null) {
        target = event.target;
    }
    return target;
}

function getUserPref(pref) {
    var value = getDataSync("pref", "getUser", [pref]);
    if (/;;/.test(value)) return value.split(";;");
    else return value;
}

function getValue(elementId) {
    var element = getElement(elementId);
    if (! element) return null;

    if (element.multiple) {
        var values = new Array();
        for (var i = 0; i < element.options.length; i++) {
            if (element.options[i].selected) values.push(element.options[i].value);
        }
        return values;
    } else {
        return element.value;
    }
}

function getViewPort() {
    var x, y;
    if (window.innerHeight) {
        // all except Explorer
        x = window.innerWidth;
        y = window.innerHeight;
    } else if (document.documentElement && document.documentElement.clientHeight) {
        // Explorer 6 Strict Mode
        x = document.documentElement.clientWidth;
        y = document.documentElement.clientHeight;
    } else if (document.body) {
        // other Explorers 
        x = document.body.clientWidth;
        y = document.body.clientHeight;
    }
    return [x, y];
}

function goBack() {
    submitParms({"appEvent" : "goBack"});
}

function goHome() {
    submitParms({});
}

function goPage(page) {
    submitParms({
        "appEvent"  :   "goPage",
        "view"      :   page
    });
}

function hide(elementId, display) {
    var element = getElement(elementId);
    if (! element) return;
    element.style.visibility = "hidden";
    if (display != undefined && ! display) element.style.display = "none";
}

function hideObjects() {
    var selects = document.getElementsByTagName("object");
    for (var i = 0; i < selects.length; i++) {
        selects[i].style.visibility = "hidden";
    }
}

function hideSelects() {
    var selects = document.getElementsByTagName("select");
    for (var i = 0; i < selects.length; i++) {
        selects[i].style.visibility = "hidden";
    }
}

function inputAlert(element, name) {
    
    if (! element) return true;
    focusElement(element.id);
    
    // Get node name for proper message
    var nodeText = "enter";
    var nodeName = element.nodeName;
    if (nodeName == "SELECT") {
        nodeText = "select";
    }
    alert("Please " + nodeText + " a valid '" + name + "' value");
    return false;
}
    
function inputTest(input) {
    if (input.length < 2) {
        alert("Input must have at least 2 characters");
        return false;
    }
    return true;
}

function inputValidate(inputElement) {
    if (inputElement == null) return false;
    var input = inputElement.value;

    if (input.indexOf(" ") == -1) {
        return inputTest(input);
    } else {
        var inputArray = new Array();
        inputArray = input.split(" ");
        for (i = 0;i < inputArray.length; i++) {
            var word = inputArray[i];
            return inputTest(word);
        }
    }
    return false;
}

function itemListDeselectAll() {
    var elements = getMainForm().elements;
    for (var i = 0; i < elements.length; i++) {
        var element = elements[i];
        if (element.name && element.name.substring(0, 10) != "listSelect") continue;
        
        // Both actions are necessary to manipulate with javascript and manual
        element.removeAttribute("checked");
        element.checked = false;
    }
}

function itemListSort(listName, fieldName) {
    submitParms({
        "appEvent"              : "sort",
        "appState"              : "itemListSort",
        "itemListSortListName"  : listName,
        "itemListSortFieldName" : fieldName
    });
}

function loadScroll(pageName) {
    if (! scroll()) return;

    var xy = getCookie(pageName);
    if (! xy) return;

    var ar = xy.split("_");
    if (ar.length == 2) {
        window.scrollTo(parseInt(ar[0]), parseInt(ar[1]));
    }
}

function noSubmitOnEnter(event) {
    if (window.event) event = window.event;
    return event.keyCode != 13;
}
                                                                                                                                                                  
function popup(url, width, height) {
    return popupArgs(url, width, height, "");
}

function popupArgs(url, width, height, arg) {
    return popupNameArgs(url, 'popup', width, height, arg);
}


/**
 * Window popup using a div
 * @param args Map using values:
 *  (Element) element = Element placed inside div using appendChild
 *  (boolean) closeLinkBottom = Print "Close" link at the bottom
 *  (boolean) closeLinkTop = Print "Close" link at the top
 *  (String) className = Style class name. Defaults to popupBox
 *  (String) elementId = Popup box element Id
 *  (String) elementName = Popup box element Name
 *  (boolean) overlay = Popup box background overlay
 */
function popupBox(args) {

    var element = args["element"];
    if (! element) return null;

    var zIndex = (frameElement) ? parseInt(frameElement.style.zIndex) : 100;
    if (isNaN(zIndex)) zIndex = 100;

    var overlay = args["overlay"];
    if (overlay) showOverlay(zIndex - 1);

    var box = document.createElement("div");
    document.body.appendChild(box);

    box.style.position = "fixed";
    box.style.zIndex = zIndex;
    
    box.close = function() {
        document.body.removeChild(box);
        if (isIE && ! isMinIE8) unHideSelects();
        removeOverlay();
    }

    var elementId = args["elementId"];
    if (elementId) box.id = elementId

    var elementName = args["elementName"];
    if (elementName) box.name = elementName
    
    var className = args["className"];
    if (className) box.className = "popupBox " + className;
    else box.className = "popupBox";

    var linkBox = document.createElement("div");
    linkBox.style.paddingTop = "10px";
    linkBox.style.textAlign = "center";

    var link = document.createElement("span");
    link.className = "link";
    link.innerHTML = "Close";
    linkBox.appendChild(link);
    link.onclick = function() {box.close();};

    if (args["closeLinkTop"] == true) box.appendChild(linkBox);
    box.appendChild(element);
    if (args["closeLinkBottom"] == true) box.appendChild(linkBox);

    var boxHeight = element.clientHeight;
    var boxWidth = element.clientWidth;

    var viewPort = getViewPort();
    var viewPortWidth = viewPort[0];
    var viewPortHeight = viewPort[1];

    if (boxHeight > (viewPortHeight - 100)) {
        var factor = (boxHeight / (viewPortHeight - 100));
        boxHeight = viewPortHeight - 100;
        boxWidth = boxWidth / factor;
    }

    if (boxWidth > (viewPortWidth - 200)) {
        var factor = (boxWidth / (viewPortWidth - 200));
        boxWidth = viewPortWidth - 200;
        boxHeight = boxHeight / factor;
    }

    var minWidth = args["minWidth"];
    var minHeight = args["minHeight"];

    if (! isNaN(minWidth) && minWidth > boxWidth) boxWidth = minWidth;
    if (! isNaN(minHeight) && minHeight > boxHeight) boxHeight = minHeight;
    if (args["closeLinkTop"] == true || args["closeLinkBottom"] == true) boxHeight += linkBox.clientHeight;

    box.style.width = boxWidth + "px";
    box.style.height = boxHeight + "px";
    box.style.textAlign = "center";

    var elementMarginTop = (boxHeight / 2) - (element.clientHeight / 2);
    if (args["closeLinkTop"] == true || args["closeLinkBottom"] == true) {
        elementMarginTop -= (linkBox.clientHeight / 2);
    }
    element.style.marginTop = elementMarginTop + "px";

    var linkBoxMarginTop = ((boxHeight - element.clientHeight) / 2) - linkBox.clientHeight;
    if (args["closeLinkTop"] == true || args["closeLinkBottom"] == true) {
        if (linkBoxMarginTop > 0) linkBox.style.marginTop = linkBoxMarginTop + "px";
    }

    var elementHeight = boxHeight - element.clientHeight;
    if (args["closeLinkTop"] == true || args["closeLinkBottom"] == true) {
        elementHeight -= linkBoxMarginTop;
    }
    element.style.maxHeight = elementHeight + "px";
    element.style.maxWidth = "100%";

    var xPos = (viewPortWidth / 2) - (boxWidth / 2) - 8;
    var yPos = (viewPortHeight / 2) - (boxHeight / 2) - 30;
    if (yPos < 5) yPos = 5;
    if (isIE && ! isMinIE8) yPos += getScroll()[1];
    box.style.left = parseInt(xPos) + "px";
    box.style.top = parseInt(yPos) + "px";

    if (isIE && ! isMinIE8) hideSelects();

    return box;
}

/**
 * Window popup using a frame
 * @param args Parameter map using values:
 *  (String) appState = Application State
 *  (String) appEvent = Application Event
 *  (String) view = View to load
 *  (boolean) scrollbars = Show scrollbars
 *  (int) width = Frame pixel width
 *  (int) height =  Frame pixel height
 *  (String[]) parms = Parms to add to request
 *  (boolean) overlay = Popup box background overlay
 */
function popupFrame(args) {

    // Check permission first
    var appState = args["appState"];
    if (! appState) appState = null;
    var appEvent = args["appEvent"];
    if (! appEvent) appEvent = null;

    // Get popup
    var popup = document.createElement("iframe");
    popup.className = "popupFrame";

    var zIndex = (frameElement) ? parseInt(frameElement.style.zIndex) : 100;
    if (isNaN(zIndex)) zIndex = 100;

    // Add id to refer to frameElement by other methods
    var date = new Date();
    var popupId = "popupFrameId" + date.getTime();
    popup.id = popupId;
    
    // Popup.name is set by setWindowId()
    // Set empty to make sure it's available and not prefilled by browser
    popup.name = "";

    var overlay = args["overlay"];
    if (overlay) showOverlay(zIndex - 1);
    
    // Set scroll bars
    if (args["scrollbars"] != null) {
        if (args["scrollbars"]) popup.scrolling = "yes";
        else popup.scrolling = "no";
        
    } else {
        if (isIE) popup.scrolling = "yes";
    }

    // Get position and size
    var viewPort = getViewPort();
    var height = (args["height"]) ? args["height"] : viewPort[1] - 50;
    var width = (args["width"]) ? args["width"] : viewPort[0] - 100;

    // Set horizontal position
    var xPos = parseInt((viewPort[0] / 2) - (width / 2));
    popup.style.width = width + "px";
    popup.style.left = xPos + "px";

    // Set vertical position
    var yPos = (viewPort[1] / 2) - (height / 2);
    if (yPos < 5) yPos = 5;
    if (isIE && ! isMinIE8) yPos += getScroll()[1];
    popup.style.height = height + "px";
    popup.style.top = parseInt(yPos) + "px";

    // Add appState, appEvent and view to url
    var url = "";
    if (args["url"]) {
        url = args["url"];

    } else if (args["view"]) {
        url += "?appEvent=goPage&view=" + args["view"];
        
    } else {
        url += "?appEvent=" + appEvent;
        url += "&appState=" + appState;
    }

    postPopupParms(args["parms"]);
    
    document.body.appendChild(popup);
    popup.src = encodeURI(url);
    
    return popup;
}
                                                                                                                                                                  
function popupName(url, name, width, height) {
    return popupNameArgs(url, name, width, height, "");
}

function popupNameArgs(url, name, width, height, arg) {
    if (arg != "") arg += ",";
    if (self.screen.width < width) width = self.screen.width;
    if (self.screen.height < height) height = self.screen.height - 50;
    
    posLeft = ( self.screen.width - width ) / 2;
    posTop = (( self.screen.height - height ) / 2) - 50;
    if (posTop < 0) posTop = 0;
    
    arg += "height=" + height + ",width=" + width + ",left=" + posLeft + ",top=" + posTop;
    
    postPopupParms();
    
    popupwindow = window.open(url, name, arg);    
    if (window.focus) popupwindow.focus();
    
    return popupwindow;
}

/**
 * Post popup parms. This is needed because using the URL to pass the parms
 * won't work with IE if the URL gets too long because of the amount of parms.
 * 
 * Run this method before loading the popup's url. The parms will be available
 * to the FrontController through the user data.
 * 
 * Before DataFlow was used to synchronise the data availability in user data but
 * the side effect is that 3rd party popups would wait for the timeout on every
 * action because they do not use this function.
 */
function postPopupParms(parms) {
    
    var sParams = "";
    sParams = addPostParam(sParams, "appEvent", "popupParms");
    sParams = addPostParam(sParams, "appState", "set");
    
    var elements = getMainForm().elements;
    for (var i = 0; i < elements.length; i++) {
        var element = elements[i];
        if (! element.name || element.disabled || ! element.value) continue;
        if (element.type && element.type == "checkbox" && ! element.checked) continue;
        sParams = addPostParam(sParams, element.name, element.value);
    }
    
    if (parms) {
        for (var parmName in parms) {
            sParams = addPostParam(sParams, parmName, parms[parmName]);
        }
    }
    
    var oHttp = zXmlHttp.createRequest();
    oHttp.open("post", "/data", false);
    oHttp.setRequestHeader("content-type", "application/x-www-form-urlencoded");
    oHttp.send(sParams);
}

function printFrame() {
    if (frameElement) window.print();
}

function printOnLoad() {
    var body = document.getElementById("templateBody");
    if (isIE && body != null) {
        body.onload = function() {window.setTimeout("window.print()", 300);};
    } else {
        window.setTimeout("window.print()", 300);
    }
}

function productDetail(id, width, height) {
    var viewPort = getViewPort();
    var detailHeight = viewPort[1] - 150;
    var detailWidth = 600;

    popupFrame({
        appState    :   "browse",
        appEvent    :   "enlargeImage",
        width       :   (width) ? width : detailWidth,
        height      :   (height) ? height : detailHeight,
        parms       :   {productId : id}
    });
}

function reloadImage(id) {
    var element = getElement(id);
    if (! element) return;
    var image = element.src.toString();
    var parmIndex = image.indexOf("?");
    if (parmIndex > 0) image = image.substring(0, parmIndex);
    var now = new Date();
    element.src = image + "?foo=" + now.getTime();
}

function removeEventHandler(oTarget, sEventType, fnHandler) {
    if (oTarget.removeEventListener) {
        oTarget.removeEventListener(sEventType, fnHandler, false);
    } else if (oTarget.detachEvent) {
        oTarget.detachEvent("on" + sEventType, fnHandler);
    } else { 
        oTarget["on" + sEventType] = null;
    }
}

function removeToolTip(elementId) {
    var element = getElement(elementId);
    if (element == null) return;
    element.removeAttribute("title");
}

function resetForm() {
    getMainForm().reset();
}

function saveScroll(appState) {
    if (! scroll()) {return;}
    var expire = new Date();
    expire.setTime(expire.getTime() + 2 * 60 * 60 * 1000);
    var xy = getScroll();
    setCookie(appState, xy[0] + "_" + xy[1], "/", expire);
}

function scroll() {
    if (window.scrollTo != null) {
        return true;
    } else {
        return false;
    }
}

function selectStyleSheet(baseName) {
    var styleSheet = baseName + "Ns.css";
    if (isIE) styleSheet = baseName + "Ie.css";
    document.write("<link href='" + styleSheet + "' type='text/css' rel='Stylesheet'>");
}

function setCheckBox(elementId, value) {
    var element = getElement(elementId);
    if (element == null) return;
    
    if (value) {
        element.setAttribute("checked", "checked");
        element.checked = true;
    } else {
        element.removeAttribute("checked");
        element.checked = false;
    }
}

function setRadio(elementId, value) {
    var element = getElement(elementId);
    if (element == null) return;

    if (value) {
        element.setAttribute("checked", "checked");
        element.checked = true;
    } else {
        element.removeAttribute("checked");
        element.checked = false;
    }
}

function setCityNations(countryId, cityId) {
    var country = getValue(countryId);
    var cityElement = getElement(cityId);
    if (country == "Singapore") {
        cityElement.value = "Singapore";
    } else if (country == "Dubai") {
        cityElement.value = "Dubai";
    }
}

function setClass(elementId, className) {
    getElement(elementId).className = className;
}

function setCookie(name, value, path, expires, domain, secure) {
    var curCookie = name + "=" + escape(value) +
        ((path) ? "; path=" + path : "") +
        ((expires) ? "; expires=" + expires.toGMTString() : "") +
        ((domain) ? "; domain=" + domain : "") +
        ((secure) ? "; secure" : "");
    document.cookie = curCookie;
}

function setFocusAndBottomClass(table) {
    var rows = table.getElementsByTagName("tr");
    var firstRow = null;
    var lastRow = rows[rows.length - 1];
    
    for (var i = 0; i < rows.length; i++) {
        if (rows[i].style.display != "none") {
            if (! firstRow) firstRow = rows[i];
            lastRow = rows[i];
        }
    }

    var firstInput = firstRow.getElementsByTagName("input")[0];
    var firstSelect = firstRow.getElementsByTagName("select")[0];
    
    if (firstInput) firstInput.focus()
    else if (firstSelect) firstSelect.focus();

    var cells = lastRow.getElementsByTagName("td");
    for (var i = 0; i < cells.length; i++) {
        cells[i].className = cells[i].className + "Bottom";
    }
}

function setWindowId() {
    
    var newId = getHexChars(8);
    var currentWindowId = (frameElement) ? frameElement.name : window.name;

    if (frameElement && currentWindowId.length == 0) {
        window.name = newId;
        setInput("windowId", newId);
        getDataAsync("windowId", "set", [newId, parent.name]);

    } else if (currentWindowId.length == 0) {
        window.name = newId;
        setInput("windowId", newId);
        getDataAsync("windowId", "set", [newId]);

    } else if (currentWindowId.length > 3 && currentWindowId.substring(0, 3) == "mc_") {
        // TinyMCE window popup
        setInput("windowId", currentWindowId);
        getDataAsync("windowId", "set", [currentWindowId, window.opener.name]);

    } else {
        setInput("windowId", currentWindowId);
    }
}

function setFormMultiPart() {
    getMainForm().setAttribute("enctype", "multipart/form-data");
    // And for IE of course something completely out of the blue
    if (isIE) getMainForm().setAttribute("encoding", "multipart/form-data");
}

// Set mouse events on elements with tagName and tagType to change class to
// className + Hover on mouseover. If tagType == "" tagType is ignored
function setHoverEvents(tagName, tagType, styleName) {
    var elements = document.getElementsByTagName(tagName);
    for (var i = 0; i < elements.length; i++) {
        var element = elements[i];
        
        if (tagType.length > 0 && (! element.type || element.type != tagType)) continue;
        if (element.className != styleName) continue;
        
        addEventHandler(element, "mouseout", function() {
            var cn = this.className.toString();
            if (/Hover/.test(this.className)) {
                this.className = cn.substring(0, cn.length - 5);
            }
        });
        
        addEventHandler(element, "mouseover", function() {
            if (! /Hover/.test(this.className)) this.className += "Hover";
        });
    }
}

function setInput(elementId, value) {
    var element = getElement(elementId);
    if (element == null) return;
    if (value == null || value == "null") value = "";
    element.value = value;
}

function setInnerHtml(elementId, html) {
    var element = getElement(elementId);
    if (element == null) return;
    if (html == null || html == "null") html = "";
    element.innerHTML = html;
}

function setSelect(elementId, value) {
    var element = getElement(elementId);
    if (element == null) return false;
    
    var optionSet = false;

    if (element.multiple) {
        for (var i = 0; i < element.options.length; i++) {
            var option = element.options[i];
            optionSet = false; // Have to do this here again
            
            for (var j = 0; j < value.length; j++) {
                if (option.value == value[j]) {
                    option.setAttribute("selected", "selected");
                    optionSet = true;
                }
            }
            if (! optionSet) {
                option.selected = false;
                option.removeAttribute("selected");
            }
        }
    } else {
        for (i = 0; i < element.options.length; i++) {
            option = element.options[i];
            if (option.value == value) {
                element.selectedIndex = i;
                option.setAttribute("selected", "selected");
                optionSet = true;
            } else if (option.selected) {
                option.removeAttribute("selected");
            }
        }
    }
    return optionSet;
}

/**
 * With arrayValues = true the values should be of type array with [0] = value
 * and [1] = option content.
 */
function setSelectOptionList(sSelectId, aOptionList, sSelectedOption, arrayValues) {
    
    if (! sSelectId || ! aOptionList) return;
    
    var select = getElement(sSelectId);
    // select.innerHTML = optionList doesn't work on IE
    var aCurrentOptions = select.getElementsByTagName("option");
    while (aCurrentOptions.length > 0) select.removeChild(aCurrentOptions[0]);
    
    if (aOptionList.length == 1 && aOptionList[0].length == 0) return;
    
    for (var i = 0; i < aOptionList.length; i++) {
        var option = document.createElement("option");
        var value = aOptionList[i];
        if (arrayValues) {
            option.value = value[0];
            option.innerHTML = (value[1] == "") ? "&nbsp;" : value[1];
        } else {
            option.value = value;
            option.innerHTML = (value == "") ? "&nbsp;" : value;
        }
        select.appendChild(option);
    }
    
    // Run setSelect afterwards works better on IE on some cases
    if (sSelectedOption) setSelect(sSelectId, sSelectedOption);
}

function setStateEnable(countryId, stateRowId) {
    var element = getElement(countryId);
    if (element == null) return;
    
    var country = element.value;
    if (country == "United States") {
        unHide(stateRowId, "table-row");
    } else {
        hide(stateRowId, false);
        var row = document.getElementById(stateRowId);
        var stateInput = row.getElementsByTagName("input");
        if (stateInput && stateInput.length > 0) stateInput[0].value = "";
    }
}

function setTextarea(elementId, value) {
    var element = getElement(elementId);
    if (element == null) return;
    if (value == null || value == "null") value = "";

    if (element.firstChild) {
        element.firstChild.nodeValue = value;
    } else {
        element.appendChild(document.createTextNode(value));
    }
}

function setUserPref(pref, value) {
    if (typeof(value) == "object") {
        var stringValue = "";
        for (var j = 0; j < value.length; j++) {
            stringValue += value[j] + ";;";
        }
        return getDataSync("pref", "setUser", [pref, stringValue]);
    } else {
        return getDataSync("pref", "setUser", [pref, value]);
    }
    
}

function showMessage(message, type) {

    if (isIE && ! isMinIE8) {
        alert(message);
        return;
    }

    var element = document.createElement("div");
    element.style.padding = "2px";

    var clickToHide = document.createElement("div");
    clickToHide.className ="clickToHide";
    clickToHide.innerHTML = "X";

    var messageBlock = document.createElement("p");
    messageBlock.style.paddingBottom = "0";
    messageBlock.innerHTML = message;

    var okButton = document.createElement("input");
    var overlay = false;

    // Set type and text
    var messageType = parseInt(type);
    if (isNaN(messageType) || messageType == 0) {
        
        var buttonBlock = document.createElement("div");
        buttonBlock.style.textAlign = "center";
        
        okButton.type = "button";
        okButton.value = "Ok";
        okButton.className = "button";
        okButton.style.paddingLeft = "15px";
        okButton.style.paddingRight = "15px";
        okButton.style.margin = "0 auto";
        
        element.appendChild(messageBlock);
        element.appendChild(buttonBlock);
        buttonBlock.appendChild(okButton);
        overlay = true;

    } else if (messageType == 1) {
        element.appendChild(clickToHide);
        element.appendChild(messageBlock);

    } else if (messageType == 2) {
        element.appendChild(clickToHide);
        element.appendChild(messageBlock);
        setTimeout("closePopupBox('messageBox')", 2500);
    }

    var messageBox = popupBox({
        element     : element,
        className   : "message",
        elementId   : "messageBox",
        overlay     : overlay
    });

    if (messageType == 0) {
        okButton.onclick = function() {messageBox.close();}

    } else if (messageType == 1) {
        messageBox.flashElement = new FlashElement(messageBox, "message");
        messageBox.flashElement.start();
        messageBox.onclick = function() {
            messageBox.flashElement.stop();
            messageBox.close();
        }

    } else if (messageType == 2) {
        messageBox.onclick = function() {messageBox.close();};
    }
}

function showOverlay(zIndex) {
    var overlayDiv = document.createElement("div");
    overlayDiv.id = "popupBoxOverLay";
    overlayDiv.style.position = "absolute";
    overlayDiv.className = "overlay";
    overlayDiv.style.zIndex = zIndex;
    document.body.appendChild(overlayDiv);
    overlayDiv.style.top = "0px";
    overlayDiv.style.left = "0px";
    var viewPortHeight = getViewPort()[1];
    var docHeight = getDocumentSize()[1];
    docHeight = (docHeight > viewPortHeight) ? docHeight : viewPortHeight;
    overlayDiv.style.height = docHeight + "px";
    overlayDiv.style.width = "100%";
}

function submitAppEvent(appEvent, appState) {
    submitParms({
        "appEvent"    :   appEvent,
        "appState"    :   appState
    });
}

function submitLogin() {
    getMainForm().action = "/j_security_check";
    submitMainForm();
}

function submitMainForm() {
    getElement("hiddenSubmitButton").click();
}

function submitNotSecure() {
    /* Get url with parameters from controls to send to the application
       instead of a POST. This way the change from secure to non secure does
       not post any user information and so the browser will not warn the 
       user about the redirection. */
    return switchNotSecure(getParamUrl());
}

/**
 * Use this function with return.
 * For example onkeypress="return submitOnEnter(event, submitHandler);"
 */
function submitOnEnter(event, submitHandler) {
    if (window.event) event = window.event;
    if (event.keyCode != 13) return true;
    submitHandler();
    return false;
}

function submitOnKeypress(event, appEvent, appState) {
    if (window.event) event = window.event;
    if (event.keyCode != 13) return true;
    submitAppEvent(appEvent, appState);
    return false;
}

function submitParm(appEvent, appState, submittedParm) {
    submitParms({
        "appEvent"      : appEvent,
        "appState"      : appState,
        "submittedParm" : submittedParm
    });
}

function submitParms(parms) {
    var mainForm = getMainForm();
    for (var parmName in parms) {

        var oldElement = document.getElementById(parmName);
        if (oldElement) mainForm.removeChild(oldElement);

        var element = document.createElement("input");
        element.type = "hidden";

        element.name = parmName;
        element.id = parmName;
        element.value = parms[parmName];
        mainForm.appendChild(element);
    }
    submitMainForm();
}

function submitParentParms(parms, includePopupElements) {
    for (var parmName in parms) {
        var element = parent.document.createElement("input");
        element.type = "hidden";
        element.name = parmName;
        element.value = parms[parmName];
        parent.getMainForm().appendChild(element);
    }
    
    if (includePopupElements)  {
        var elements = getMainForm().elements;

        for (var i = 0; i < elements.length; i++) {
            element = elements[i];

            if (! element.name || element.disabled || ! element.value) continue;
            if (element.nodeName != "INPUT" && element.nodeName != "SELECT") continue;

            // Adding a cloned node from current document to parent form does not
            // work on IE so we create a new node here
            var newElement = parent.document.createElement("input");
            newElement.type = "hidden";
            newElement.name = element.name;
            newElement.id = element.id;
            newElement.value = element.value;

            // Skip with the same id (and name), such as window id
            var parentElement = parent.getElement(element.id);
            if (parentElement) continue;

            parent.getMainForm().appendChild(newElement);
        }
    }
    parent.submitMainForm();
}

function submitSecure() {
    /* see submitNotSecure() */
    return switchSecure(getParamUrl());
}

/**
 * SuggestionProvider used by AutoSuggestControl
 * 
 * @param appState Application state
 * @param appEvent Application event
 * @param args Array of extra args to pass to DataServer method
 */
function SuggestionProvider(appState, appEvent, args) {
    this.http = zXmlHttp.createRequest();
    this.appState = appState;
    this.appEvent = appEvent;
    this.args = args;
}
    
SuggestionProvider.prototype.requestSuggestions = function (oAutoSuggestControl) {

    var oHttp = this.http;

    // Cancel any active requests                          
    if (oHttp.readyState != 0) oHttp.abort();
    
    var userText = oAutoSuggestControl.userText;
    if (userText.length < 1) {
        oAutoSuggestControl.hideSuggestions();
        return;
    }
    
    oHttp.open("post", "/data", true);
    
    oHttp.onreadystatechange = function () {
        if (oHttp.readyState == 4) {

            if (oHttp.status == 401) {
                goHome();
                return;
            }
    
            var aSuggestions = oHttp.responseText.toString().split(";");
            if (aSuggestions.length == 1 && aSuggestions[0].length == 0) aSuggestions.pop();
            oAutoSuggestControl.autosuggest(aSuggestions);
        }    
    }
    
    var sParams = "";
    sParams = addPostParam(sParams, "appEvent", this.appEvent);
    sParams = addPostParam(sParams, "appState", this.appState);
    if (this.args && this.args.length > 0) {
        for (var i = 0; i < this.args.length; i++) {
            userText += "<a|s>" + this.args[i];
        }
    }
    sParams = addPostParam(sParams, "args", userText);
    
    oHttp.setRequestHeader("content-type", "application/x-www-form-urlencoded");
    oHttp.send(sParams);
}

function switchNotSecure(path) {
    // Get hostname
    var host = getHostName();
    
    // Test if port in included in url and use for standard http port
    var url = window.location.toString();
    var regHighPort = /:(\d{1,3})443/;
    if (regHighPort.test(url)) { 
        var highPort = RegExp.$1;
        highPort += "0";
        host += ":" + highPort + "80";
    } else {
        regHighPort = /:(\d{1,5})/;
        if (regHighPort.test(url)) {
            highPort = RegExp.$1;
            host += ":" + highPort;
        }
    }
       
    window.location = "http://" + host + "/" + path;
    // Return false so that it can be used on a form onsubmit without posting the form
    return false;
}

function switchSecure(path) {
    // Get hostname
    var host = getHostName();
    
    // Test if port in included in url and use for standard http port
    var url = window.location.toString();
    var regHighPort = /:(\d)080/;
    if (regHighPort.test(url)) { 
        var highPort = RegExp.$1;
        host += ":" + highPort + "443";
    }
    
    window.location = "https://" + host + "/" + path;
    // Return false so that it can be used on a form onsubmit without posting the form
    return false;
}

function removeOverlay() {
    var overLay = getElement("popupBoxOverLay");
    if (overLay) document.body.removeChild(overLay);
}

function showTerms() {
    var url = "/index?appEvent=goPage&view=Terms";
    popupNameArgs(encodeURI(url), "Terms", 800, 640, "scrollbars,dialog");
}

function unHide(elementId, display) {
    var element = document.getElementById(elementId);
    if (! element) return;
    element.style.visibility = "visible";
    if (isIE && display && display == "table-row") display = "block";
    if (display != undefined && display) element.style.display = display;
}

function unHideObjects() {
    var selects = document.getElementsByTagName("object");
    for (var i = 0; i < selects.length; i++) {
        selects[i].style.visibility = "visible";
    }
}

function unHideSelects() {
    var selects = document.getElementsByTagName("select");
    for (var i = 0; i < selects.length; i++) {
        selects[i].style.visibility = "visible";
    }
}
