/* JavaScript for the common functions
 */

// See the discussion at http://www.regular-expressions.info/email.html
// for details on making a regular expression for email addresses.
var emailRegExp = new RegExp("^[a-zA-Z0-9!#$%&'*+/=?^_`{|}~-]+(?:\\.[a-zA-Z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?\\.)+(?:[a-zA-Z]{2}|com|org|net|gov|mil|biz|info|mobi|name|aero|jobs|museum|edu)$");
var passwordRegExp = new RegExp("[a-zA-Z0-9_!@]*");
var XML_REQUEST_NOT_INITIALIZED = 0;
var XML_REQUEST_SET_UP = 1;
var XML_REQUEST_SENT = 2;
var XML_REQUEST_IN_PROCESS = 3;
var XML_REQUEST_COMPLETE = 4;
var panes = new Array();
var PUBLISHER_MAIN_FRAME = 0;

var host = "";

function addOption(selectionObj, text, value) {
    var newOption = document.createElement("option");
    newOption.text = text;
    newOption.value = value;
    try {
        selectionObj.add(newOption,null); // Standards based
    } catch (ex) {
        selectionObj.add(newOption); // IE Based
    }
}

// Return the string with a message added to a new line.
function appendErrorString(errorString, message) {
    errorString = nvl(errorString, "");
    
    if (errorString.length > 0) {
        errorString += "<br/>";
    }
    
    errorString += message;
    
    return errorString;
}

function cancelForm(location) {
    document.location = location;
    return false;
}

function createJSImage(path) {
    var newImage = new Image();
    newImage.src = path;
    return newImage;
}

// this fixes an issue with the old method, ambiguous values
// with this test document.cookie.indexOf( name + "=" );
// See http://techpatterns.com/downloads/javascript_cookies.php
function getCookie(checkName) {
    // first we'll split this cookie up into name/value pairs
    // note: document.cookie only returns name=value, not the other components
    var allCookies = document.cookie.split(';');
    var tempCookie = '';
    var cookieName = '';
    var cookieValue = null;

    for (i = 0; i < allCookies.length; i++) {
        // now we'll split apart each name=value pair
	tempCookie = allCookies[i].split('=');

        // and trim left/right whitespace while we're at it
	cookieName = tempCookie[0].replace(/^\s+|\s+$/g, '');

        // if the extracted name matches passed check_name
	if (cookieName == checkName) {
            // we need to handle case where cookie has no value but exists (no = sign, that is):
            if (tempCookie.length > 1) {
                cookieValue = unescape(tempCookie[1].replace(/^\s+|\s+$/g, ''));
            }
            
            // note that in cases where cookie is initialized but no value, null is returned
            break;
        }
    }
    
    return cookieValue;
}

function getXmlHttpObject() {
    var xmlHttp = null;
    var browser = navigator.appName;
    var version = parseFloat(navigator.appVersion);
    
    try {
        if (browser == "Microsoft Internet Explorer" && version >= 5) {
            try {
                xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
            } catch (e) {
                xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
            }            
        } else {
            // Firefox, Opera 8.0+, Safari
            xmlHttp = new XMLHttpRequest();
        }
    } catch (e) {
        // The browser doesn't support AJAX
    }
    
    return xmlHttp;
}

function isCookieEnabled() {
    var cookieEnabled = (navigator.cookieEnabled) ? true : false;

    //if not IE4+ nor NS6+
    if (typeof navigator.cookieEnabled == "undefined" 
                && !cookieEnabled) { 
        document.cookie = "testcookie";
        cookieEnabled = (document.cookie.indexOf("testcookie") != -1) ? true : false;
    }
    
    return cookieEnabled;
}

function isNumberKey(evt) {
    var charCode = (evt.which) ? evt.which : event.keyCode
    if (charCode > 31 && (charCode < 48 || charCode > 57)) {
        return false;
    } else {
        return true;
    }
}

function isCurrencyKey(evt) {
    var charCode = (evt.which) ? evt.which : event.keyCode
    if (charCode > 31 && (charCode < 46 || charCode > 57 || charCode == 47)) {
        return false;
    } else {
        return true;
    }
}

function limitTextAreaSize(fieldId, maxLen) {
    var field = document.getElementById(fieldId);
    if (field != null
            && field != undefined
            && field.value.length > maxLen + 1) {
        if (field.value.length > maxLen) {
            field.value = field.value.substring(0, maxLen);
        }
    }
}

function mailingListEmailChange() {
    var mlEmailInput = document.getElementById("mlEmail").value;
    var mlEmailBtn = document.getElementById("mlEmailBtn");

    if (isValidEmail(mlEmailInput)) {
        mlEmailBtn.disabled = false;
    } else {
        mlEmailBtn.disabled = true;
    }
}

// See http://techpatterns.com/downloads/javascript_cookies.php
function setCookie(name, value, expires, path, domain, secure) {
    if (name == null || name == "" || name == undefined
            || value == null || value == "" || value == undefined) {
        return;
    }
    
    var cookieValue = name + "=" + escape(value);

    /*
     if the expires variable is set, make the correct
     expires time, the current script below will set
     it for x number of days, to make it for hours,
     delete * 24, for minutes, delete * 60 * 24
     */
    if (expires != null && expires != undefined && expires != "") {
        var today = new Date();
        today.setTime(today.getTime());
        expires = expires * 1000 * 60 * 60 * 24;
        
        var expiresDate = new Date(today.getTime() + expires);
        cookieValue += ";expires=" + expiresDate.toGMTString();
    }
    
    if (path != null && path != undefined && path != "") {
        cookieValue += ";path=" + path;
    }
    
    if (domain != null && domain != undefined && domain != "") {
        cookieValue += ";domain=" + domain;
    }
    
    if (secure != null && secure != undefined && secure != "") {
        cookieValue += ";secure" + secure;
    }
    
    document.cookie = cookieValue;
}

function setHost(newHost) {
    host = newHost;
}

// See http://esdi.excelsystems.com/wsexmp/DIVTAB.pgm?task=showinst&wsnum=00096
function setupPanes(containerId, defaultTabId, frames) {
    var mainFrameDocument = document;

    if (frames) {
        mainFrameDocument = top.frames[PUBLISHER_MAIN_FRAME].document;
    }

    // go through the DOM, find each tab-container
    // set up the panes array with named panes
    panes[containerId] = new Array();
    var container = mainFrameDocument.getElementById(containerId);
    var paneContainer = container.getElementsByTagName("div")[0];
    var paneList = paneContainer.childNodes;
    for (var i = 0; i < paneList.length; i++) {
        var pane = paneList[i];
        if (pane.nodeType != 1) {
            continue;
        }
        panes[containerId][pane.id] = pane;
        pane.style.display = "none";
    }
    mainFrameDocument.getElementById(defaultTabId).onclick();
}

// See http://esdi.excelsystems.com/wsexmp/DIVTAB.pgm?task=showinst&wsnum=00096
function showPane(paneId, activeTab, frames) {
    var mainFrameDocument = document;

    if (frames) {
        mainFrameDocument = top.frames[PUBLISHER_MAIN_FRAME].document;
    }
    // make tab active class
    // hide other panes (siblings)
    // make pane visible

    for (var con in panes) {
        activeTab.blur();
        activeTab.className = "tab-active";
        if (panes[con][paneId] != null) { // tab and pane are members of this container
            var pane = mainFrameDocument.getElementById(paneId);
            pane.style.display = "block";
            var container = mainFrameDocument.getElementById(con);
            var tabs = container.getElementsByTagName("ul")[0];
            var tabList = tabs.getElementsByTagName("a")
            for (var i = 0; i < tabList.length; i++) {
                var tab = tabList[i];
                if (tab != activeTab) {
                    tab.className = "tab-disabled";
                }
            }
            for (var i in panes[con]) {
                var pane2 = panes[con][i];
                if (pane2 == undefined) {
                    continue;
                }
                if (pane2.id == paneId) {
                    continue;
                }
                pane2.style.display = "none"
            }
        }
    }

    return false;
}

function isValidEmail(emailAddress) {
    var isValid = false;
    if (emailAddress.match(emailRegExp) != null
            && emailAddress.match(emailRegExp) == emailAddress) {
        isValid = true;
    }
    
    return isValid;
}

// If the value is null, set it to the default value
function nvl(value, defaultValue) {
    if (value == null || value == undefined) {
        return defaultValue;
    } else {
        return value;
    }
}

function openWindow(url, name, height, width) {
    openWindow(url,name,height,width,100,"no","no","no","no","no","no",100);
}

function openWindow(url, name, height, width, left, location, menubar,
        resizable, scrollbars, status, toolbar, top) {
    var specs = "";
    if (height != null && !isNaN(height)) {
        height += 40;
        specs += "height=" + height;
    }

    if (width != null && !isNaN(width)) {
        if (specs.length > 0) {
            specs += ",";
        }
        specs += "width=" + width;
    }

    if (specs.length > 0) {
        specs += ",";
    }

    specs += "channelmode=no,directories=no,fullscreen=no,";
    specs += "left=" + left + ",location=" + location + ",";
    specs += "menubar=" + menubar + ",resizable=" + resizable + ",";
    specs += "scrollbars=" + scrollbars + ",status=" + status + ",";
    specs += "toolbar=" + toolbar + ",top=" + top;

    window.open(url, name, specs, true);

    return false;
}

function updateDayDropdown(monthDropdown, dayDropdown, yearDropdown) {
    if (monthDropdown == null
            || monthDropdown == undefined
            || dayDropdown == null
            || dayDropdown == undefined
            || yearDropdown == null
            || yearDropdown == undefined) {
        return;
    }
    
    var selectedMonth = monthDropdown.selectedIndex;
    var selectedDay = dayDropdown.selectedIndex;
    var selectedYear = yearDropdown.options[yearDropdown.selectedIndex].value;
    var dayDropdownLen = dayDropdown.length;
    
    // Remove all days past 28
    for (var i = dayDropdownLen - 1; i > 27; i--) {
        dayDropdown.remove(i);
    }
    
    if (selectedMonth == 3 // April
                || selectedMonth == 5 // June
                || selectedMonth == 8 // Sept
                || selectedMonth == 10) { // Nov
        addOption(dayDropdown, "29", "29");
        addOption(dayDropdown, "30", "30");
    } else if (selectedMonth == 0 // Jan
                || selectedMonth == 2 // March
                || selectedMonth == 4 // May
                || selectedMonth == 6 // July
                || selectedMonth == 7 // Aug
                || selectedMonth == 9 // Oct
                || selectedMonth == 11) { // Dec
        addOption(dayDropdown, "29", "29");
        addOption(dayDropdown, "30", "30");
        addOption(dayDropdown, "31", "31");
    } else if (selectedMonth == 1
            && Math.floor(selectedYear/4) == selectedYear/4) { // Leap year
        addOption(dayDropdown, "29", "29");
    }
    
    if (selectedDay < dayDropdown.length) {
        dayDropdown.selectedIndex = selectedDay;
    } else {
        dayDropdown.selectedIndex = 0;
    }
}

function updateWindowStatus(newStatus) {
    // TODO Any special browser checks??
    if (newStatus != null) {
        window.status = newStatus;
    } else {
        window.status = "";
    }
    
    return true;
}