/* Reference Article:
Dustin Diaz:
http://www.dustindiaz.com/top-ten-javascript/
*/

/* addEvent: simplified event attachment */
function addEvent(obj, type, fn) {
    if (obj.addEventListener) {
        obj.addEventListener(type, fn, false);
        EventCache.add(obj, type, fn);
    }
    else if (obj.attachEvent) {
        obj["e" + type + fn] = fn;
        obj[type + fn] = function() { obj["e" + type + fn](window.event); }
        obj.attachEvent("on" + type, obj[type + fn]);
        EventCache.add(obj, type, fn);
    }
    else {
        obj["on" + type] = obj["e" + type + fn];
    }
}

var EventCache = function() {
    var listEvents = [];
    return {
        listEvents: listEvents,
        add: function(node, sEventName, fHandler) {
            listEvents.push(arguments);
        },
        flush: function() {
            var i, item;
            for (i = listEvents.length - 1; i >= 0; i = i - 1) {
                item = listEvents[i];
                if (item[0].removeEventListener) {
                    item[0].removeEventListener(item[1], item[2], item[3]);
                };
                if (item[1].substring(0, 2) != "on") {
                    item[1] = "on" + item[1];
                };
                if (item[0].detachEvent) {
                    item[0].detachEvent(item[1], item[2]);
                };
                item[0][item[1]] = null;
            };
        }
    };
} ();
addEvent(window, 'unload', EventCache.flush);

/* window 'load' attachment */
function addLoadEvent(func) {
    var oldonload = window.onload;
    if (typeof window.onload != 'function') {
        window.onload = func;
    }
    else {
        window.onload = function() {
            oldonload();
            func();
        }
    }
}

/* grab Elements from the DOM by className */
function getElementsByClass(searchClass, node, tag) {
    var classElements = new Array();
    if (node == null)
        node = document;
    if (tag == null)
        tag = '*';
    var els = node.getElementsByTagName(tag);
    var elsLen = els.length;
    var pattern = new RegExp("(^|\\s)" + searchClass + "(\\s|$)");
    for (i = 0, j = 0; i < elsLen; i++) {
        if (pattern.test(els[i].className)) {
            classElements[j] = els[i];
            j++;
        }
    }
    return classElements;
}

/* toggle an element's display */
function toggle(obj) {
    var el = document.getElementById(obj);
    if (el.style.display != 'none') {
        el.style.display = 'none';
    }
    else {
        el.style.display = '';
    }
}

/* insert an element after a particular node */
function insertAfter(parent, node, referenceNode) {
    parent.insertBefore(node, referenceNode.nextSibling);
}

/* Array prototype, matches value in array: returns bool */
Array.prototype.inArray = function(value) {
    var i;
    for (i = 0; i < this.length; i++) {
        if (this[i] === value) {
            return true;
        }
    }
    return false;
};

/* get, set, and delete cookies */
function getCookie(name) {
    var start = document.cookie.indexOf(name + "=");
    var len = start + name.length + 1;
    if ((!start) && (name != document.cookie.substring(0, name.length))) {
        return null;
    }
    if (start == -1) return null;
    var end = document.cookie.indexOf(";", len);
    if (end == -1) end = document.cookie.length;
    return unescape(document.cookie.substring(len, end));
}

function setCookie(name, value, expires, path, domain, secure) {
    var today = new Date();
    today.setTime(today.getTime());
    if (expires) {
        expires = expires * 1000 * 60 * 60 * 24;
    }
    var expires_date = new Date(today.getTime() + (expires));
    document.cookie = name + "=" + escape(value) +
		((expires) ? ";expires=" + expires_date.toGMTString() : "") + //expires.toGMTString()
		((path) ? ";path=" + path : "") +
		((domain) ? ";domain=" + domain : "") +
		((secure) ? ";secure" : "");
}

function deleteCookie(name, path, domain) {
    if (getCookie(name)) document.cookie = name + "=" +
			((path) ? ";path=" + path : "") +
			((domain) ? ";domain=" + domain : "") +
			";expires=Thu, 01-Jan-1970 00:00:01 GMT";
}

/* quick getElement reference */
function $() {
    var elements = new Array();
    for (var i = 0; i < arguments.length; i++) {
        var element = arguments[i];
        if (typeof element == 'string')
            element = document.getElementById(element);
        if (arguments.length == 1)
            return element;
        elements.push(element);
    }
    return elements;
}


function CheckContactForm() {
}


function trim(inputString) {
    if (typeof inputString != "string") { return inputString; }
    if (inputString == "") { return inputString; }

    var retValue = inputString;
    var ch = retValue.substring(0, 1);
    while (ch == " ") {
        retValue = retValue.substring(1, retValue.length);
        ch = retValue.substring(0, 1);
    }
    ch = retValue.substring(retValue.length - 1, retValue.length);
    while (ch == " ") { // Check for spaces at the end of the string
        retValue = retValue.substring(0, retValue.length - 1);
        ch = retValue.substring(retValue.length - 1, retValue.length);
    }
    while (retValue.indexOf("  ") != -1) {
        // Note that there are two spaces in the string - look for multiple spaces within the string
        retValue = retValue.substring(0, retValue.indexOf("  ")) + retValue.substring(retValue.indexOf("  ") + 1, retValue.length); // Again, there are two spaces in each of the strings
    }
    return retValue;
}


function IsNumeric(intStr) {
    if (intStr == null || intStr == 'undefined')
        return false;

    if (intStr.match(/^[-+]?[0-9]*\.?[0-9]+(?:[eE][-+]?[0-9]+)?$/))
        return true;
    else
        return false;
}

function IsEmail(emailStr) {
    var objRegExp = /^[a-z]\w*([.\-]\w+)*@[a-z]\w*([.\-]\w+)*\.[a-z]{2,3}$/i;
    return objRegExp.test(emailStr);
}

function DateInFuture(inDate) {
    var now = new Date();
    now = now.getTime(); //NN3
    return (now < inDate);
}

/// resizes the container divs to fit the page, OR the content of the content div
/// if the content div's height (plus header size) is smaller than the 100% height of the body,
/// it is stretched to fit the window
function resizer() {
    if (!orderIsFromAffiliate) {
        var x, y;

        var atmosphereHeight;
        var contextMenuHeight;
        var contentOffsetHeight;
        var footerOffsetHeight = 0;

        var test1 = document.body.scrollHeight;
        var test2 = document.body.offsetHeight;

        if (test1 > test2) // all but Explorer Mac
        {
            x = document.body.scrollWidth;
            y = document.body.scrollHeight;

            atmosphereHeight = document.getElementById("atmosphere").scrollHeight;
            contextMenuHeight = document.getElementById("contextmenu").scrollHeight;
            contentOffsetHeight = document.getElementById("centerContent").scrollHeight;
            if (document.getElementById("footer") != null)
                footerOffsetHeight = document.getElementById("footer").scrollHeight;
        }
        else // Explorer Mac, would also work in Explorer 6 Strict, Mozilla and Safari
        {
            x = document.body.offsetWidth;
            y = document.body.offsetHeight;

            atmosphereHeight = document.getElementById("atmosphere").offsetHeight;
            contextMenuHeight = document.getElementById("contextmenu").offsetHeight;
            contentOffsetHeight = document.getElementById("centerContent").offsetHeight;
            if (document.getElementById("footer") != null)
                footerOffsetHeight = document.getElementById("footer").offsetHeight;

            //alert(contentOffsetHeight);
        }

        var bodyHeight = y;

        var contentHeight = atmosphereHeight + contextMenuHeight + contentOffsetHeight + footerOffsetHeight + 10;
        //alert(contentHeight);
        if (contentHeight < bodyHeight) {
            document.getElementById("containercontainer").style.height = "100%";
            document.getElementById("container").style.height = "100%";
            document.getElementById("innercontainer").style.height = "100%";
            document.getElementById("content").style.height = "100%";
        }
        else {
            document.getElementById("containercontainer").style.height = (atmosphereHeight + contentHeight + footerOffsetHeight) + "px";
            document.getElementById("container").style.height = (atmosphereHeight + contentHeight + footerOffsetHeight) + "px";
            document.getElementById("innercontainer").style.height = (atmosphereHeight + contentHeight + footerOffsetHeight) + "px";
            document.getElementById("content").style.height = (contentHeight - atmosphereHeight - contextMenuHeight - footerOffsetHeight) + "px";
        }

        //document.getElementById("footer").style.position = "absolute";
        //document.getElementById("footer").style.bottom = contentHeight + "px";
    }
}

/////////////////////////////// LOGIN ///////////////////////////////
function CheckLoginForm(objLoginButton, userNameFieldId, passwordFieldId, strDefaultUserNameTxt, strDefaultPasswordTxt) {
    var userName = trim(document.getElementById(userNameFieldId).value);
    var password = trim(document.getElementById(passwordFieldId).value);

    var alertTxt = "";

    if (userName == strDefaultUserNameTxt || userName == "")
        alertTxt += "U dient uw gebruikersnaam in te vullen\n";

    if (password == strDefaultPasswordTxt || password == "")
        alertTxt += "U dient uw wachtwoord in te vullen\n";

    if (alertTxt == "") {
        __doPostBack(objLoginButton, "");
        return true;
    }
    else {
        alert(alertTxt);
        return false;
    }
}

function SetDefaultPassWordText(objPasswordField, strDefaultPasswordText) {
    document.getElementById(objPasswordField).value = strDefaultPasswordText;
}

function clearField(objTextBox, strDefaultText) {
    if (objTextBox.value == strDefaultText)
        objTextBox.value = "";
}

function checkFieldCleared(objTextBox, strDefaultText) {
    if (trim(objTextBox.value) == "")
        objTextBox.value = strDefaultText;
}

addEvent(window, 'load', resizer);
addEvent(window, 'resize', resizer);


var parentId = -1;
function FillChildDdl(objParent, objChildId) {
    parentId = objParent.value;

    var objChild = document.getElementById(objChildId);
    objChild.options.length = 0;

    var opt;

    opt = document.createElement('OPTION');
    opt.value = "";
    opt.text = "";
    objChild.options.add(opt);

    for (var j = 0; j < faqs[parentId].Parts.length; j++) {
        opt = document.createElement('OPTION');
        opt.value = faqs[parentId].Parts[j].Id;
        opt.text = faqs[parentId].Parts[j].Name;
        objChild.options.add(opt);
    }
}

function ShowFaq(objFaqSelect, objDisplayId) {
    var objDisplay = document.getElementById(objDisplayId);
    if (objFaqSelect.value == "") {
        objDisplay.innerHTML = "";
    }
    else {
        for (var j = 0; j < faqs[parentId].Parts.length; j++) {
            if (faqs[parentId].Parts[j].Id == parseInt(objFaqSelect.value)) {
                objDisplay.innerHTML = faqs[parentId].Parts[j].Description;
            }
        }
    }
}


function GotoUrl(objRadio, strUrl) {
    var radios = $('.actSelect');

    for (i = 0; i < radios.length; i++) {
        if (radios[i] != objRadio)
            radios[i].checked = false;
    }
    location.href = strUrl;
}

function SelectProvince(objRadio, strUrl) {
    var radios = $('.provinceSelect');

    for (i = 0; i < radios.length; i++) {
        if (radios[i] != objRadio)
            radios[i].checked = false;
    }
    location.href = strUrl;
}

function doUrchin(urchinUrl) {
    if (typeof urchinTracker == 'function') {
        urchinTracker(urchinUrl);
    }
}

function CheckAvailability(objStripper, objDate, objTime) {
    var pl = new SOAPClientParameters();

    pl.add("stripperId", parseInt(document.getElementById(objStripper).value));
    pl.add("date", document.getElementById(objDate).value);
    pl.add("time", document.getElementById(objTime).value);

    SOAPClient.invoke("/Services/Order.asmx", "CheckAvailability", pl, true, CheckAvailability_CallBack);
}

function CheckAvailability_CallBack(r) {
    var trs = $('.availability');

    trs[0].innerHTML = r;
    trs[0].style.display = "block";
}