/* -----------------------------------------------------------------
// One field to search them all.
//
// Generic Search for TNT Post
// Generic scripts with dependency on TNT Post framework/scripts
// Make sure the Page object has loaded first or this will fail.
//
// Build: 20071204
//
// Copyright 2007, TNT Post
----------------------------------------------------------------- */

// Initialize one field form
OneFieldPagesKickStart = function() {
    if (window.page) {
        window.onefieldpage = new OneFieldPages();
//alert("page set");
    }
    else {
        // try again in x milliseconds
        setTimeout("OneFieldPagesKickStart()", 100);
    }
}

OneFieldPagesKickStart();
//setTimeout("OneFieldPagesKickStart()", 2000);


// Set event listeners
addEvent(window, "unload", function() {
if (window.onefieldpage) { window.onefieldpage.destroy(); }
});

window.defaultTab = 0;

//function newPage(tcm){
//    window.onefieldpage = new OneFieldPages();
//    window.onefieldpage.showPageTab(tcm);
//}


function newPage(tcm, tab){
    var onefieldpage = new OneFieldPages();
//alert(tab);
//alert(window.defaultTab);
    window.defaultTab = tab;
//alert("window.defaultTab" + window.defaultTab);
    onefieldpage.showPageTab(tcm);
}

/* -----------------------------------------------------------------
// Main one field form object
----------------------------------------------------------------- */

OneFieldPages = function() {

    if (!window.page.hasSupport()) return;

    this.sForm = "frmOneField"; // The name of the form
    this.sField = "ofq"; // The name of the field
    if (document.getElementById('NavTCM')) {
        this.sNavTCM = document.getElementById('NavTCM').value;
    } else {
        this.sNavTCM = "tcm"
    }
    //loadXMLDoc('/zakelijk/includes/controls/onefield/' + this.sNavTCM + '.xml');
    //this.sSearchUri = "/zakelijk/includes/controls/onefield/OneField_v2.aspx?nav=" + this.sNavTCM;
    this.sSearchUri = "";
    this.searchWidth = 920;

    //this.warning.init(); // Init warning message
    //this.validationInit(); // Init form validation
    //this.fixInfoBoxes(); // Fix infoboxes on IE
    this.ofsearch.init(); // Prepare one field search
    window.arrTabsInfo = new Array();
    this.SearchHandler = null;
}

// Helper function to clean up the onefield object
OneFieldPages.prototype.destroy = function() {

    if (!window.page.hasSupport()) return;

    // Kill objects to prevent memory leaks due to closures. - TODO!

}


// Function to fix the mouseover of the infoboxes in IE
OneFieldPages.prototype.fixInfoBoxes = function() {
    var i, aInfobox = getElementsByClassName("infobox", document);
    if (aInfobox) {
        this.infobox.init(); // Create a separate infobox
        var self = this;
        for (i = 0; i < (aInfobox.length); i++) {
            aInfobox[i].onmouseover = function() {
                addClass(this, "infoboxhover");
                self.infobox.show(this);
                tickle();
            }
            aInfobox[i].onmouseout = function() {
                removeClass(this, "infoboxhover");
                self.infobox.hide();
                tickle();
            }
        }
    }
}
// Infobox div
OneFieldPages.prototype.infobox = {
    init: function() {
        var oBody = document.getElementsByTagName("body")[0];
        var oInfoBox = document.createElement("div");
        oInfoBox.id = "onefield-infobox";
        var oInfoBoxMsg = document.createElement("div");
        oInfoBoxMsg.id = "onefield-infobox-msg";
        oInfoBox.appendChild(oInfoBoxMsg);
        if (document.all) { // IE only iframe
            var oInfoBoxIFrame = document.createElement("iframe");
            oInfoBoxIFrame.id = "onefield-infobox-iframe";
            oInfoBoxIFrame.frameBorder = 0;
            oInfoBoxIFrame.scrolling = "no";
            oInfoBoxIFrame.src = "about:blank";
            oInfoBox.appendChild(oInfoBoxIFrame);
        }
        // Append to body
        oBody.appendChild(oInfoBox);
    },
    show: function(obj) {
        var oInfoBox = document.getElementById("onefield-infobox");
        if (oInfoBox) {
            var oInfoBoxMsg = document.getElementById("onefield-infobox-msg");
            var oObjDD = obj.getElementsByTagName("dd")[0];
            var oInfoBoxX = calculateLeft(oObjDD), oInfoBoxY = calculateTop(oObjDD);
            oInfoBox.style.left = oInfoBoxX + "px";
            oInfoBox.style.top = oInfoBoxY + "px";
            oInfoBoxMsg.innerHTML = oObjDD.innerHTML;
            oInfoBox.style.display = "block";
            oObjDD.style.visibility = "hidden";
        }
    },
    hide: function() {
        var oInfoBox = document.getElementById("onefield-infobox");
        if (oInfoBox) {
            oInfoBox.style.display = "none";
        }
    }
};

// Function to do search
OneFieldPages.prototype.showPage = function(tcm) {
    window.arrTabsInfo = new Array();
//alert(window.defaultTab);
    /*loadXMLDoc('/zakelijk/includes/controls/onefield/' + this.sNavTCM + '.xml');
    this.sSearchUri = "/zakelijk/includes/controls/onefield/OneField_v2.aspx?nav=" + this.sNavTCM;*/
    loadXMLDoc('/zakelijk/includes/controls/onefield/' + tcm + '.xml');
    this.sSearchUri = "/zakelijk/includes/controls/onefield/OneField_v2.aspx?nav=" + tcm;


    this.ofsearch.show();
    var sQuery = '';
    if (arguments.length > 0) {
        sQuery = arguments[0];
    }
    else {
        sQuery = document.getElementById(this.sField).value;
    };
    this.getSearchResults(escape(sQuery));

    AJAXHandler.RenderComponent(this.sHelpTCMUri, this.sPlaceholder, this.sPlaceholder, self.Callback);
    try{
        this.initSidebar(this.sHelpSidebarTCMUri);
    } catch (err) {
    }
};

OneFieldPages.prototype.showPageTab = function(tcm, tab) {
    window.defaultTab = tab;
    this.showPage(tcm);
};
OneFieldPages.prototype.getSearchResults = function(sQuery) {
    var xmlhttp = null;
    if (window.XMLHttpRequest) {
        xmlhttp = new XMLHttpRequest();
    }
    else if (window.ActiveXObject) {
        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
    }
    if (xmlhttp == null) {
        this.ofsearch.hide();
        return;
    }

    if (document.getElementById('NavTCM')) {
        this.sNavTCM = document.getElementById('NavTCM').value;
    } else {
        this.sNavTCM = "tcm"
    }


    // Build link to Search URI.
    var url = this.sSearchUri
		+ "&rnd=" + (new Date().getTime());
    var self = this;
    xmlhttp.open("GET", url, true);
    xmlhttp.onreadystatechange = function() {
        if (xmlhttp.readyState == 4) { // We've got a result back
            if (xmlhttp.status == 200) { // And it's valid
                var oSearch = document.getElementById("onefield-search");
                var oSearchContent = document.getElementById("ofs-content");
                var oLoader = document.getElementById("onefield-loader");
                oSearchContent.innerHTML = xmlhttp.responseText;
                // show the results...
                oSearch.style.display = "block";
                oLoader.style.display = "none";
                oSearch.style.marginLeft = "-" + parseInt((self.searchWidth / 2), 10) + "px";
                oSearch.style.width = self.searchWidth + "px";
                var winHeight = (window.innerHeight || self.innerHeight || (document.documentElement && document.documentElement.clientHeight) || document.body.clientHeight) - 40;
                oSearch.style.height = (winHeight) + "px";
                oSearchContent.style.height = (winHeight - 87) + "px";
                if (!(navigator.userAgent.indexOf("MSIE 6.0") != -1)) {
                    oSearch.style.marginTop = "-" + parseInt((winHeight / 2), 10) + "px";
                };
                self.SearchHandler = new ShowOneFieldPages();
                tickle();
            }
            else {
                // Something went wrong (not found|forbidden|?)
                self.ofsearch.hide();
            };
            xmlhttp = null;
        }
    }
    xmlhttp.send(null);
};
// Search divs (rework of jQuery's Thickbox)
OneFieldPages.prototype.ofsearch = {
    init: function() {
        // preload stuff...
        this.loadimg = new Image(); // preload image
        this.loadimg.src = "/img/onefield/loadingAnimation.gif";
    },
    show: function() {
        var oBody = document.getElementsByTagName("body")[0];
        // create overlay
        var oOverlay = document.createElement("div");
        oOverlay.id = "onefield-overlay";
        oOverlay.className = "onefield-overlayBG";
        oOverlay.onclick = this.hide;
        if (document.all) { // IE only iframe
            var oOverlayIFrame = document.createElement("iframe");
            oOverlayIFrame.id = "onefield-hideSelects";
            oOverlayIFrame.frameBorder = 0;
            oOverlayIFrame.scrolling = "no";
            oOverlayIFrame.src = "about:blank";
            oBody.appendChild(oOverlayIFrame);
            oOverlayIFrame = null;
        }
        // create search
        var oSearch = document.createElement("div");
        oSearch.id = "onefield-search";
        oSearch.innerHTML = "<div id=\"ofs-head\"><div id=\"ofs-close\"><a href='#' onclick=\"onefield.ofsearch.hide();\">Sluit venster</a></div></div><div id=\"ofs-content\"></div><div id=\"ofs-foot\"></div>";
        // create loader
        var oLoader = document.createElement("div");
        oLoader.id = "onefield-loader";
        oLoader.innerHTML = "<img src=\"" + this.loadimg.src + "\" />";
        // Append to body
        oBody.appendChild(oOverlay);
        oBody.appendChild(oSearch);
        oBody.appendChild(oLoader);
        oOverlay = null;
        oSearch = null;
        oLoader = null;
    },
    hide: function() {
        // remove one field layers
        var oBody = document.getElementsByTagName("body")[0];
        var oOverlay = document.getElementById("onefield-overlay");
        oOverlay.onclick = null;
        var oOverlayIFrame = document.getElementById("onefield-hideSelects");
        var oSearch = document.getElementById("onefield-search");
        var oLoader = document.getElementById("onefield-loader");
        oBody.removeChild(oSearch);
        oBody.removeChild(oLoader);
        if (oOverlayIFrame) { oBody.removeChild(oOverlayIFrame); };
        oBody.removeChild(oOverlay);
    }
};

OneFieldPages.prototype.clean = function(sQuery) {
    sQuery = sQuery.replace("<", "");
    sQuery = sQuery.replace(">", "");
    sQuery = sQuery.replace("?", "");
    sQuery = sQuery.replace("&", "");
    return sQuery;
};

var xmlhttp;
function is_ws(nod) {
    return !(/[^\t\n\r ]/.test(nod.data));
}

function findWhiteSpace(node, nodeNo) {
    for (i = 0; i < node.childNodes.length; i++) {
        if (node.childNodes[i].nodeType == 3 && is_ws(node.childNodes[i])) {
            nodesToDelete[nodesToDelete.length] = node.childNodes[i]
        }
        if (node.childNodes[i].hasChildNodes()) {
            findWhiteSpace(node.childNodes[i], i);
        }
    }
    node = node.parentNode;
    i = nodeNo;
}

function stripWhiteSpace(node) {
    nodesToDelete = Array();
    findWhiteSpace(node, 0);
    for (i = nodesToDelete.length - 1; i >= 0; i--) {
        nodeRef = nodesToDelete[i];
        nodeRef.parentNode.removeChild(nodeRef)
    }
}

function loadXMLDoc(url) {
    xmlhttp = null;
    if (window.XMLHttpRequest) {// code for IE7, Firefox, Opera, etc.
        xmlhttp = new XMLHttpRequest();
    }
    else if (window.ActiveXObject) {// code for IE6, IE5
        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
    }
    if (xmlhttp != null) {

        xmlhttp.onreadystatechange = state_Change;
        xmlhttp.open("GET", url, true);
        xmlhttp.send(null);
    }
    else {

    }
}

function state_Change() {
    if (xmlhttp.readyState == 4) {// 4 = "loaded"
        if (xmlhttp.status == 200) {// 200 = "OK"
            var arr = new Array()
            stripWhiteSpace(xmlhttp.responseXML);
            var bFirst = true;
            var xmlDoc = xmlhttp.responseXML;
            var e = xmlDoc.documentElement.getElementsByTagName("tab");
            for (var a = 0; a < e.length; a++) {
                var t = new Array();
                t[0] = e[a].childNodes[1].childNodes[0].nodeValue;
                t[1] = e[a].childNodes[3].childNodes[0].nodeValue;
                if (e[a].childNodes[4].childNodes[0]) {
                    t[2] = e[a].childNodes[4].childNodes[0].nodeValue;
                } else {
                    t[2] = "";
                }

                arr[a] = t;
            }

            window.arrTabsInfo = arr;
            return;
        }
        else {

        }
    }
}


/*********/
/*********/
/*********/
/*********/
/*********/
/*********/
/*********/
/*********/
/*********/


Array.prototype.inArray = function(value)
// Returns true if the passed value is found in the
// array.  Returns false if it is not.
{
    var i;
    for (i = 0; i < this.length; i++) {
        // Matches identical (===), not just similar (==).
        if (this[i] === value) {
            return true;
        }
    }
    return false;
};

ShowOneFieldPages = function() {
    this.arrTabs = new Array();
    this.sForm = "frmOneFieldPopup";
    this.sField = "ofs-ofq";
    this.sQueryPlaceholder = "ofs-ofq-ph";

    this.sQuery = "";

    //Placeholders
    this.sPlaceholder = "ofs-placeholder";
    this.sTabsPlaceholder = "ofs-tabs";
    this.sSidebarPlaceholder = "ofs-sidebar";

    this.arrTab = new Array();

    //TODO Dynamisch laden van de tabjes.
    this.arrTabs = new Array();
    this.arrTabs = window.arrTabsInfo;

    this.sUrl = window.location;

    this.init();
}

ShowOneFieldPages.prototype.init = function() {
    var oForm = document.getElementById(this.sForm);
    var oQuery = document.getElementById(this.sField);
    var oPlaceholder = document.getElementById(this.sPlaceholder);
    var self = this;

    new OFAutoSuggest(this.sField, { className: "autosuggest popup" });

    this.sTab1TCMUri = ""
    this.sTab1SidebarTCMUri = ""

    oPlaceholder.handler = this;
    this.Kickit();
}
ShowOneFieldPages.prototype.onTimeout = function() {
}

ShowOneFieldPages.prototype.Kickit = function() {
    var bLoaded = false;
    if (!this.arrTabs) {
	//alert('Geen tabs');
        setTimeout("window.onefieldpage.SearchHandler.Kickit()", 1000);
    } else {
		//alert('tabs.length ' + this.arrTabs.length + '. window.defaultTab ' + window.defaultTab );
        if (this.arrTabs.length == 0) {

            setTimeout("window.onefieldpage.SearchHandler.Kickit()", 1000);
        } else {
            if (window.defaultTab != "" && window.defaultTab != "undefined") {
                this.getOneFieldContent(this.arrTabs[window.defaultTab][1], this.arrTabs[window.defaultTab][2]);
            } else {
                this.getOneFieldContent(this.arrTabs[0][1], this.arrTabs[0][2]);
            }
            this.initTabs();
            window.defaultTab = "";
        }
    }
}

ShowOneFieldPages.prototype.initTabs = function() {
    var self = this;
    var oTabsPlaceholder = document.getElementById(this.sTabsPlaceholder);
    var arrTabs = oTabsPlaceholder.getElementsByTagName("li");
    for (i = 0; i < arrTabs.length; i++) {
        oTab = arrTabs[i];
        oTab.parent = oTabsPlaceholder;
        oTab.onclick = function() {
            arrTabs = this.parent.getElementsByTagName("li");
            for (i = 0; i < window.arrTabsInfo.length; i++) {
                removeClass(arrTabs[i], "current");
            }
            addClass(this, "current");
            try{
                eval(this.childNodes[0].getAttribute("omniture"))
            } catch (err) {
            }
        }
        if (i == 0) {
            addClass(oTab, "current");
        }
        if (window.defaultTab != "" && window.defaultTab != "undefined") {
            if (window.arrTabsInfo[i][0] == "tab" + window.defaultTab) {
                for (x = 0; x < window.arrTabsInfo.length; x++) {
                    removeClass(arrTabs[x], "current");
                }
                addClass(oTab, "current");
            }
        }



        arrLinks = oTab.getElementsByTagName("a");
        arrLinks[0].onclick = function() {
            for (x = 0; x < window.arrTabsInfo.length; x++) {
                if (this.href.match("#" + window.arrTabsInfo[x][0])) {
                    self.getOneFieldContent(window.arrTabsInfo[x][1], window.arrTabsInfo[x][2]);
                }
            }
        }
    }
}

ShowOneFieldPages.prototype.initSidebar = function(sSidebarTCMUri) {
    var self = this;
    var oSidebar = document.getElementById(this.sSidebarPlaceholder);
    oSidebar.handler = self;
    this.showLoading(oSidebar.id);
    AJAXHandler.RenderComponent(sSidebarTCMUri, this.sSidebarPlaceholder, this.sSidebarPlaceholder, self.SidebarCallBack);
}

ShowOneFieldPages.prototype.goBack = function(self, steps) {
    for (i = 0; i < steps; i++) {
        self.sHyloHistory.pop();
    }
    var oHyloResult = self.sHyloHistory[self.sHyloHistory.length - 1];
    var myPlaceHolder = document.getElementById(oHyloResult.HTML_ID);
    var myLoaderPlaceHolder = document.getElementById(oHyloResult.Loader_ID);
    if (oHyloResult.HTML.match("<redirect>")) {
        window.location = oHyloResult.HTML.replace("<redirect>", "").replace("</redirect>", "")
    } else if (oHyloResult.HTML.match("ofs-hyloresultlinks")) {
        myPlaceHolder = document.getElementById("ofs-placeholder");
        myPlaceHolder.innerHTML = oHyloResult.HTML;
    } else {
        myPlaceHolder.innerHTML = oHyloResult.HTML;
    }
    self.initHylo();
}

ShowOneFieldPages.prototype.getQueryStringFromUrl = function(sUrl) {
    var arrUrl = sUrl.split("?");
    if (arrUrl.length > 1) {
        return arrUrl[1];
    } else {
        return "";
    }
}

ShowOneFieldPages.prototype.getVarsFromQueryString = function(sQueryString) {
    var vars = new Array();
    var tmp = sQueryString.split("&");
    for (i = 0; i < tmp.length; i++) {
        myVar = tmp[i].split("=");
        vars[myVar[0]] = myVar[1];
    }
    return vars;
}


ShowOneFieldPages.prototype.Callback = function(res) {
    var myPlaceholder = null;
    var self = null;
    var result = null;
    if (res.error) {
        myPlaceHolder = document.getElementById("ofs-placeholder");
        self = myPlaceHolder.handler;
        self.hideLoading(result.Loader_ID);
        myPlaceHolder.innerHTML = "Er is een fout opgetreden. Probeer het nog eens.";
    } else {
        result = res.value;
        myPlaceHolder = document.getElementById(result.HTML_ID);
        self = myPlaceHolder.handler;
        self.hideLoading(result.Loader_ID);
        myPlaceHolder.innerHTML = result.HTML;
        //self.initResultForm();
    }
}


ShowOneFieldPages.prototype.SidebarCallBack = function(res) {
    if (res.error) {
        myPlaceHolder = document.getElementById("ofs-sidebar");
        var self = myPlaceHolder.handler;
        self.hideLoading(result.Loader_ID);
        myPlaceHolder.innerHTML = "Er is een fout opgetreden. Probeer het nog eens.";
    } else {
        var result = res.value;
        var myPlaceHolder = document.getElementById(result.HTML_ID);
        var self = myPlaceHolder.handler;
        self.hideLoading(result.Loader_ID);
        myPlaceHolder.innerHTML = result.HTML;
        //self.initResultForm();
    }
}


ShowOneFieldPages.prototype.showLoading = function() {
    if (!this.showLoading.arguments[0] || this.showLoading.arguments[0] == "") {
        id = this.sPlaceholder;
    } else {
        id = this.showLoading.arguments[0];
    }
    var myPlaceHolder = document.getElementById(id);
    myPlaceHolder.innerHTML = "Een moment geduld alstublieft. Uw gegevens worden opgehaald...";
    addClass(myPlaceHolder, "loader");
}

ShowOneFieldPages.prototype.showSmallLoading = function() {
    if (!this.showSmallLoading.arguments[0] || this.showSmallLoading.arguments[0] == "") {
        id = this.sPlaceholder;
    } else {
        id = this.showSmallLoading.arguments[0];
    }
    var myPlaceHolder = document.getElementById(id);
    addClass(myPlaceHolder, "loader");
    myPlaceHolder.innerHTML = "&nbsp;<br>";
}

ShowOneFieldPages.prototype.hideLoading = function() {
    if (!this.hideLoading.arguments[0] || this.hideLoading.arguments[0] == "") {
        id = this.sPlaceholder;
    } else {
        id = this.hideLoading.arguments[0];
    }
    var myPlaceHolder = document.getElementById(id);
    myPlaceHolder.innerHTML = "";
    removeClass(myPlaceHolder, "loader");
}


ShowOneFieldPages.prototype.getHelpResult = function() {
    var self = this;
    this.showLoading();
    AJAXHandler.RenderComponent(this.sHelpTCMUri, this.sPlaceholder, this.sPlaceholder, self.Callback);
    this.initSidebar(this.sHelpSidebarTCMUri);
}

ShowOneFieldPages.prototype.getOneFieldContent = function(sTCMUri, sSidebarTCMUri) {
    var self = this;
    this.showLoading();
    AJAXHandler.RenderComponent(sTCMUri, this.sPlaceholder, this.sPlaceholder, self.Callback);
    this.initSidebar(sSidebarTCMUri);
}

ShowOneFieldPages.prototype.stats = function(sQuery, sApplication) {
    /*if (typeof(s) != "undefined" || typeof(s_account) != "undefined"){ // Omniture present?
    var s = s_gi(s_account);
    s.linkTrackVars = "prop1,eVar1";
    s.linkTrackEvents = "None";
    s.prop1 = s.eVar1 = sQuery;
    s.tl(true,"o","One Field Search : " + sApplication);
    }*/

}

ShowOneFieldPages.prototype.query = function(sInput) {
    this.sQuery = this.clean(sInput);
    var oQueryPlaceholder = document.getElementById(this.sQueryPlaceholder);

    var text = document.createTextNode(sInput); //This will enforce html encoding in javascript.

    oQueryPlaceholder.appendChild(text);

    this.arrTab = new Array();

    this.filter(sInput);

    this.initTabs();

    //Run Template
    if (this.arrTrackTrace.length > 0 || this.arrTab.inArray("tracktrace")) {
        this.stats(this.sQuery, "Track & Trace");
        this.getTrackTraceResult();
    } else if ((this.arrAddress.length > 0 && this.sQuery.split(" ").length <= 3) || (this.arrPostalCode.length > 0 && this.arrHousenumber.length > 0) || (this.arrCity.length > 0 && this.sQuery.split(" ").length <= 3) || this.arrCity.length > 0 || this.arrTab.inArray("postcode")) {
        this.stats(this.sQuery, "Postcode zoeken");
        this.getPostalCodeResult();
    } else if (this.arrPostalCode.length > 0 || this.arrTab.inArray("locatiewijzer")) {
        this.stats(this.sQuery, "Locatiewijzer");
        this.getOfficeResult();
    } else if (this.arrTab.inArray("tarievenwijzer")) {
        this.stats(this.sQuery, "Tarievenwijzer");
        this.getPriceResult();
    } else if (this.arrTab.inArray("help")) {
        this.stats(this.sQuery, "Help");
        this.getHelpResult();
    } else {
        this.stats(this.sQuery, "Hylo");
        DM2.DMStart();
    }

    return false;
}

ShowOneFieldPages.prototype.clean = function(sQuery) {
    sQuery = sQuery.replace("<", "");
    sQuery = sQuery.replace(">", "");
    sQuery = sQuery.replace("?", "");
    sQuery = sQuery.replace("&", "");
    return sQuery;
}
