/* Code nodig om indexof aan de praat te krijgen in IE */

if (!Array.prototype.indexOf) {
    Array.prototype.indexOf = function(elt /*, from*/) {
        var len = this.length;
        var from = Number(arguments[1]) || 0;
        from = (from < 0)
          ? Math.ceil(from)
          : Math.floor(from);
        if (from < 0)
            from += len;
        for (; from < len; from++) {
            if (from in this &&
           this[from] === elt)

                return from;
        }
        return -1;
    };
}

/* General functions */

function GetBaseUrl() {
    return $("#BaseUrlHiddenField").val();
}

function MaskElement(elementId, format) {
    $("#" + elementId).mask(format);
}

function GetClueTipClass() {
    return $(".ClueTipClassHiddenField").val();
}

function GetLanguage() {
    return $(".LanguageHiddenField").val();
}

function ShowLoadingImage(loadingElementID) {
    $("div#" + loadingElementID).html("<img class=\"loadingImage\" src=\"/" + GetBaseUrl() + "/Infomat/Images/progressbar.gif\" alt=\"Loading...\" />").show();
}

function StripResponse(response) {
    response = response.substring(response.indexOf('<div id="JQueryPage"'));
    response = response.replace('</form>', '');
    response = response.replace('</body>', '');
    response = response.replace('</html>', '');
    return response;
}

function Right(str, n) {
    if (n <= 0)
        return "";
    else if (n > String(str).length)
        return str;
    else {
        var iLen = String(str).length;
        return String(str).substring(iLen, iLen - n);
    }
}

/**
* YOU ARE FREE TO USE THIS CODE IF YOU HOLD THE REFERENCE TO THE AUTHOR
* Plugin for jQuery that delimites the maximum of characteres in inputs and textareas
* @author: Iván Guardado Castro
* @email: dev.ivangc@gmail.com
* @website: http://yensdesign.com/
*/
jQuery.fn.maxLength = function(max) {
    this.each(function() {
        //Get the type of the matched element
        var type = this.tagName.toLowerCase();
        //If the type property exists, save it in lower case
        var inputType = this.type ? this.type.toLowerCase() : null;
        //Check if is a input type=text OR type=password
        if (type == "input" && inputType == "text" || inputType == "password") {
            //Apply the standard maxLength
            this.maxLength = max;
        }
        //Check if the element is a textarea
        else if (type == "textarea") {
            //Add the key press event
            this.onkeypress = function(e) {
                //Get the event object (for IE)
                var ob = e || event;
                //Get the code of key pressed
                var keyCode = ob.keyCode;
                //Check if it has a selected text
                var hasSelection = document.selection ? document.selection.createRange().text.length > 0 : this.selectionStart != this.selectionEnd;
                //return false if can't write more
                return !(this.value.length >= max && (keyCode > 50 || keyCode == 32 || keyCode == 0 || keyCode == 13) && !ob.ctrlKey && !ob.altKey && !hasSelection);
            };
            //Add the key up event
            this.onkeyup = function() {
                //If the keypress fail and allow write more text that required, this event will remove it 
                if (this.value.length > max) {
                    this.value = this.value.substring(0, max);
                }
            };
        }
    });
};

/* Article groups */

function ShowFilteredArticleGroups(language) {
    var currentDate = new Date();
    var dummy = currentDate.getTime();

    $("div.ArticleGroupFilter").html("<img class=\"smallLoadingImage\" src=\"" + GetBaseUrl() + "/Infomat/Images/ajax-loader.gif\" alt=\"...\" />").show();

    $.get(GetBaseUrl() + "/Infomat/Modules/Catalog/ArticleGroupFilter.aspx?language=" + language + "&dummy=" + dummy, function(response) {
        $("div.ArticleGroupFilter").html(StripResponse(response)).show();
    });
}

/* Catalogue menu */

function ShowMenu(module, language) {
    var currentDate = new Date();
    var dummy = currentDate.getTime();

    $("div.menu-content").html("<img class=\"smallLoadingImage\" src=\"" + GetBaseUrl() + "/Infomat/Images/ajax-loader.gif\" alt=\"...\" />").show();

    //no dummy because of performance !
    var url = GetBaseUrl() + "/Infomat/Modules/Catalog/Catalog.aspx?language=" + language;
    if (module + "" == "Contracts") {
        url = url + "&contractdummy=" + dummy;
    }

    $.get(url, function(response) {
        $("div.menu-content").html(StripResponse(response)).show();
        SetupTreeView("ArticleGroupTreeView");
    });
}

function fireAnEvent(obj, evt) {
    var fireOnThis = obj;
    if (document.createEvent) {
        var evObj = document.createEvent('MouseEvents');
        evObj.initEvent(evt, true, false);
        fireOnThis.dispatchEvent(evObj);
    } else if (document.createEventObject) {
        fireOnThis.fireEvent('on' + evt);
    }
}

function ClickMenuItem(groupId) {
    var link = document.getElementById("menuItem" + groupId);

    if (link != null) {
        if (link.parentNode.className == 'Collapsed') {
            fireAnEvent(link, 'click');
        }
    }

    // Click menu item of group, but also his parent (if still necessary)
    var menuItemID = "menuItem" + groupId;
    var mainMenuItem = document.getElementById(menuItemID);

    var menuItemParents = $(mainMenuItem).parents().map(function() {
        if (this.className == 'Collapsed') {
            return this;
        }
    })

    var menuItemParentsArray = jQuery.makeArray(menuItemParents);
    menuItemParentsArray.reverse();

    $.each(menuItemParentsArray, function(index, value) {
        var link = document.getElementById($(value).children()[0].id);

        if (link.id != mainMenuItem.id) {
            var groupId = link.id.replace('menuItem', '');

            ToggleClass(link, "Collapsed", "Expanded", null);

            if ($(link) != null && $(link).parent() != null) {
                $(link).parent().attr("class", "Expanded");
            }
        }
    });
}

function SetActiveMenuItem(groupId) {
    var menuItemID = "menuItem" + groupId;

    var valueOfElement;
    $(".menuItem").each(function(i, valueOfElement) {
        valueOfElement.setAttribute("class", "menuItem");
        valueOfElement.setAttribute("className", "menuItem");
    });

    var element = document.getElementById(menuItemID);
    if (element != null) {
        element.setAttribute("class", "menuItem Active")
        element.setAttribute("className", "menuItem Active");
    }
}

//Array.prototype.indexOf = IndexOf;
function ToggleClass(element, firstClass, secondClass, event) {
    if (event != null) {
        event.cancelBubble = true;
    }

    var classes = element.className.split(" ");
    var firstClassIndex = classes.indexOf(firstClass);
    var secondClassIndex = classes.indexOf(secondClass);

    if (firstClassIndex == -1 && secondClassIndex == -1) {
        classes[classes.length] = firstClass;
    }
    else if (firstClassIndex != -1) {
        classes[firstClassIndex] = secondClass;
    }
    else {
        classes[secondClassIndex] = firstClass;
    }

    element.className = classes.join(" ");
}



function ToggleNodeStateHandler(event) {
    ToggleClass(this, "Collapsed", "Expanded", (event == null) ? window.event : event);
}

function PreventBubbleHandler(event) {
    if (!event) event = window.event;
    event.cancelBubble = true;
}

function SetupTreeView(elementId) {
    var tree = document.getElementById(elementId);

    if (tree != null) {
        var treeElements = tree.getElementsByTagName("li");

        for (var i = 0; i < treeElements.length; i++) {
            if (treeElements[i].getElementsByTagName("ul").length > 0) {
                treeElements[i].onclick = ToggleNodeStateHandler;
            }
            else {
                treeElements[i].onclick = PreventBubbleHandler;
            }
        }
    }
}

/* Catalogue pager */

function ShowNextChapter() {
    var currentChapter;
    currentChapter = parseFloat($("#CurrentChapterHiddenField").val());

    var nextChapter;
    nextChapter = currentChapter + 1;

    $("table.Chapter").each(function() {
        if ($(this).attr("id") + "" == "Chapter" + currentChapter) {
            $(this).addClass('Hide');
        }
    });

    $("table.Chapter").each(function() {
        if ($(this).attr("id") + "" == "Chapter" + nextChapter) {
            $(this).removeClass('Hide');
        }
    });

    $("#CurrentChapterHiddenField").val(nextChapter);
}

function ShowPreviousChapter() {
    var currentChapter;
    currentChapter = parseFloat($("#CurrentChapterHiddenField").val());

    var nextChapter;
    nextChapter = currentChapter - 1;

    $("table.Chapter").each(function() {
        if ($(this).attr("id") + "" == "Chapter" + currentChapter) {
            $(this).addClass('Hide');
        }
    });

    $("table.Chapter").each(function() {
        if ($(this).attr("id") + "" == "Chapter" + nextChapter) {
            $(this).removeClass('Hide');
        }
    });

    $("#CurrentChapterHiddenField").val(nextChapter);
}

/* Catalogue article */

function getParameterByName(name) {
    name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");

    var regexS = "[\\?&#]" + name + "=([^&#]*)";
    var regex = new RegExp(regexS);
    var results = regex.exec(window.location.href);

    if (results == null) {
        return "";
    }
    else {
        return decodeURIComponent(results[1].replace(/\+/g, " "));
    }
}

function LoadCatalogue() {
    setInterval("CheckURL()", 250);

    var groupId = getParameterByName("!groupId");
    var articleId = getParameterByName("!articleId");

    if (groupId + '' == '' && articleId + '' == '') {
        ShowArticles(0, 1);
    }
}

function LoadCatalogueByGroup(groupId) {
    setInterval("CheckURL()", 250);

    ShowArticles(groupId, 1);
}

var lasturl = "";
function CheckURL(hash) {
    if (!hash) hash = window.location.hash;    // if no parameter is provided, use the hash value from the current address

    if (hash != lasturl) // if the hash value has changed
    {
        lasturl = hash;   // update the current hash

        var groupId = getParameterByName("!groupId");
        var page = getParameterByName("!page");
        var articleId = getParameterByName("!articleId");
        var quantityControlName = getParameterByName("!quantityControlName");

        if (document.getElementById(quantityControlName) != null) {
            var currentQuantity = document.getElementById(quantityControlName).value;
        }

        if (page + '' == '') { page = 1; }

        if (articleId + '' != '') {
            ShowArticleDetail(articleId, page, currentQuantity);
        }
        else {
            if (groupId + '' != '') {
                ClickMenuItem(groupId);
                SetActiveMenuItem(groupId);
                ShowArticles(groupId, page);
            }
        }
    }
}

function ShowGroupDetail(fullGroupId, language) {
    fullGroupId = escape(fullGroupId);

    var currentDate = new Date();
    var dummy = currentDate.getTime();

    $(".article-content").html("<img class=\"loadingImage\" src=\"" + GetBaseUrl() + "/Infomat/Images/progressbar.gif\" alt=\"Loading...\" />").show();
    $.get(GetBaseUrl() + "/Infomat/Modules/Catalog/CatalogGroupDetail.aspx?dummy=" + dummy + "&fullGroupId=" + fullGroupId + "&language=" + language, function(response) {
        $(".article-content").html(StripResponse(response)).show();
    });
}

function ShowArticles(groupId, page) {
    groupId = escape(groupId);

    var clueTipClass = GetClueTipClass();
    var currentDate = new Date();
    var dummy = currentDate.getTime();
    var language = GetLanguage();
    var JQueryUrl = GetBaseUrl() + "/Infomat/Modules/Catalog/CatalogDetail_base.aspx" + "?dummy=" + dummy + "&groupId=" + groupId + "&page=" + page + "&language=" + language;

    // Show loading image
    $(".article-content").html("<img class=\"smallLoadingImage\" src=\"" + GetBaseUrl() + "/Infomat/Images/ajax-loader.gif\" alt=\"...\" />").show();

    // Only serve last requested page
    $("#RequestedJQueryPage").val(JQueryUrl);

    $.get(JQueryUrl, function(response) {
        if ($("#RequestedJQueryPage").val() == JQueryUrl) {
            $(".article-content").html(StripResponse(response)).show();

            scrollTo(0, 0);

            /* Set loading images */
            var stockInfoElement;

            $("div.StockInfoElement").each(function(i, stockInfoElement) {
                $(stockInfoElement).html("<img class=\"smallLoadingImage\" src=\"" + GetBaseUrl() + "/Infomat/Images/ajax-loader.gif\" alt=\"...\" />").show();
            });

            /* Hide price quantity popup */
            $("div.ArticlePriceQuantities").each(function(i, valueOfElement) {
                $(valueOfElement).hide();
            });

            /* Set popups */
            switch (clueTipClass) {
                case "jtip": //rounded
                    $('a.ToolTip').cluetip({
                        positionBy: 'bottomTop',
                        cluetipClass: 'jtip',
                        sticky: true,
                        width: 475, //we kunnen de width niet op "auto" zetten. Cluetip heeft deze optie niet voor width                        
                        splitTitle: '|',
                        showTitle: false,
                        mouseOutClose: true,
                        arrows: true,
                        dropShadow: true,
                        dropShadowSteps: 5,
                        closePosition: 'title'
                    });
                    break;
                default:
                    $('a.ToolTip').cluetip({
                        dropShadowSteps: 1,
                        positionBy: 'fixed',
                        topOffset: 20,
                        leftOffset: -90,
                        sticky: true,
                        width: 475, //we kunnen de width niet op "auto" zetten. Cluetip heeft deze optie niet voor width
                        closePosition: 'title',
                        mouseOutClose: true,
                        splitTitle: '|'
                    });

                    $('a.ToolTipRight').cluetip({
                        dropShadowSteps: 1,
                        positionBy: 'fixed',
                        topOffset: 20,
                        leftOffset: -350,
                        sticky: true,
                        width: 475, //we kunnen de width niet op "auto" zetten. Cluetip heeft deze optie niet voor width
                        closePosition: 'title',
                        mouseOutClose: true,
                        splitTitle: '|'
                    });
                    break;
            }

            /* Load price quantity information */
            $.get(GetBaseUrl() + "/Infomat/Modules/Catalog/Controllers/CatalogPriceQuantityController.aspx?dummy=" + dummy + "&language=" + language, function(response) {
                /* Show prices */
                var valueOfElement;
                $("div.ArticlePriceQuantities").each(function(i, valueOfElement) {
                    var articleId = valueOfElement.getAttribute('tag');
                    var priceQuantityLink = $(".ArticlePriceQuantitiesLink", this);

                    $.get(GetBaseUrl() + "/Infomat/Modules/Catalog/PriceQuantityDetail.aspx?dummy=" + dummy + "&articleId=" + articleId + "&language=" + language, function(response) {
                        var content = StripResponse(response);

                        if (content.indexOf('<div') != -1) {
                            $(priceQuantityLink).attr("title", $(priceQuantityLink).attr("title") + content);

                            switch (clueTipClass) {
                                case "jtip": //rounded
                                    $(priceQuantityLink).cluetip({
                                        positionBy: 'bottomTop',
                                        cluetipClass: 'jtip',
                                        sticky: true,
                                        width: 750, //we kunnen de width niet op "auto" zetten. Cluetip heeft deze optie niet voor width                        
                                        splitTitle: '|',
                                        showTitle: false,
                                        mouseOutClose: true,
                                        arrows: true,
                                        dropShadow: true,
                                        dropShadowSteps: 5,
                                        closePosition: 'title'
                                    });
                                    break;
                                default:
                                    $(priceQuantityLink).cluetip({
                                        dropShadowSteps: 1,
                                        positionBy: 'bottomTop',
                                        sticky: true,
                                        closePosition: 'title',
                                        mouseOutClose: true,
                                        splitTitle: '|',
                                        width: 750
                                    });
                                    break;
                            }


                            $(valueOfElement).fadeIn('slow');
                        }
                        else {
                            //$(valueOfElement).hide();
                        }
                    });
                });
            });

            /* Set note textboxes */
            $("div.NoteElement").each(function(i, noteElement) {
                var noteElement = $("#NoteTextBoxElement", this);
                var noteIcon = $(".NoteIcon", this);
                var noteLabel = $(".NoteLabel", this);
                var noteTextArea = $(".NoteTextArea", this);
                var SaveNoteLink = $(".SaveNoteLink", this);

                if (noteTextArea.html() + '' == '') {
                    noteElement.hide();
                }

                if (noteTextArea != null && noteTextArea.length > 0) {
                    noteTextArea.maxLength(240);
                }

                noteIcon.click(function() {
                    noteElement.toggle();
                });
                noteLabel.click(function() {
                    noteElement.toggle();
                });


                SaveNoteLink.hide()

                $(noteTextArea).one("keypress", function() {
                    SaveNoteLink.show();
                });

            });

            /* Set objects explorer */
            var objectExplorerElement;
            $("div.ObjectsExplorer").each(function(i, objectExplorerElement) {
                $(objectExplorerElement).easySlider({
                    prevId: 'PreviousObjectSpan' + objectExplorerElement.getAttribute('tag'),
                    nextId: 'NextObjectSpan' + objectExplorerElement.getAttribute('tag'),
                    prevText: '<',
                    nextText: '>'
                });

                var previousSpan = document.getElementById('PreviousObjectSpan' + objectExplorerElement.getAttribute('tag'));
                $(previousSpan).addClass('PreviousObject');

                var nextSpan = document.getElementById('NextObjectSpan' + objectExplorerElement.getAttribute('tag'));
                $(nextSpan).addClass('NextObject');
            });

            /* Load stock info */
            $.get(GetBaseUrl() + "/Infomat/Modules/Catalog/Controllers/StockController.aspx?dummy=" + dummy + "&language=" + language, function(response) {
                $("div.StockInfoElement").each(function(i, stockInfoElement) {
                    var articleId = stockInfoElement.getAttribute('tag');

                    $.get(GetBaseUrl() + "/Infomat/Modules/Catalog/StockInformation.aspx?dummy=" + dummy + "&display=overview" + "&articleId=" + articleId + "&language=" + language + "&forceCheckStock=false", function(response) {
                        $(stockInfoElement).html(StripResponse(response));

                        //elke 'artikelblok' in de catalogus heeft een class die bestaat uit de article cache id. Op die manier kunnen
                        //we loopen door de artikels en zoeken in het blok naar de class 'AvailableStockToolTip'.
                        $("." + articleId + " .AvailableStockToolTip").each(function(i, tooltipElement) {
                            $(tooltipElement).cluetip({
                                dropShadowSteps: 1,
                                positionBy: 'auto',
                                sticky: true,
                                closePosition: 'title',
                                mouseOutClose: true,
                                splitTitle: '|'
                            });
                        });
                    });
                });
            });

            /* Load all needed prices */
            $.get(GetBaseUrl() + "/Infomat/Modules/Catalog/Controllers/CatalogPriceController.aspx?dummy=" + dummy + "&language=" + language, function(response) {

                /* Show prices */
                var valueOfElement;

                $("div.ArticlePriceElement").each(function(i, valueOfElement) {

                    var classes = valueOfElement.getAttribute('tag').split("|");
                    var articleId = classes[0];
                    var isArticleModel = classes[1];

                    $(valueOfElement).hide();

                    $.get(GetBaseUrl() + "/Infomat/Modules/Catalog/price_pages/PriceDetail.aspx?dummy=" + dummy + "&articleId=" + articleId + "&language=" + language + "&currentpage=" + page + "&groupId=" + groupId + "&isArticleModel=" + isArticleModel, function(response) {
                        $(valueOfElement).html(StripResponse(response)).fadeIn('slow');
                    });
                });
            });
        }
    });
}



function ShowArticlePrice(articleId, language, currentPage, quantityTextBoxName, ArticlePriceElementDivName) {
    var quantity = $("#" + quantityTextBoxName).val();
    var currentDate = new Date();
    var dummy = currentDate.getTime();

    if (ArticlePriceElementDivName != null) {
        $("div#" + ArticlePriceElementDivName).html("<img class=\"loadingImage\" src=\"" + GetBaseUrl() + "/Infomat/Images/progressbar.gif\" alt=\"Loading...\" />").show();

        var classes = $("div#" + ArticlePriceElementDivName).attr("tag").split("|");
        var isArticleModel = classes[1];

        $.get(GetBaseUrl() + "/Infomat/Modules/Catalog/price_pages/PriceDetail.aspx?dummy=" + dummy + "&articleId=" + articleId + "&language=" + language + "&currentPage=" + currentPage + "&isArticleModel=" + isArticleModel + "&quantity=" + quantity, function(response) {
            $("div#" + ArticlePriceElementDivName).html(StripResponse(response)).show();
        });
    }
}

function ShowRecalculatePriceButton(articleId, setVisible) {
    if (setVisible + "" == "1") {
        $(".RecalculatePriceButton_" + articleId).show();
    }
    else {
        $(".RecalculatePriceButton_" + articleId).hide();
    }
}

function ShowContractImage(articleCode, contractNumber) {
    if (contractNumber != "0") {
        $(".ContractImageElement_" + articleCode.replace(" ", "")).html("<a href=\"" + GetBaseUrl() + "/Contract/Default.aspx?contract=" + contractNumber + "\"><img id=\"ContractImage\" class=\"ContractImage\" src=\"" + GetBaseUrl() + "/images/icons/catalogue/adv_icon_handshake.gif\" alt=\"Contract\" /></a>").show();
    }
    else {
        $(".ContractImageElement_" + articleCode.replace(" ", "")).hide();
    }
}

function ShowHtmlObject(url, resultElementId) {
    var resultElement = document.getElementById(resultElementId);

    if (resultElement != null) {
        var fullUrl = GetBaseUrl() + "/" + url;

        $.get(fullUrl, function(response) {
            $(resultElement).html(response);
        });
    }
}

function ShowArticleDetailFromWithinArticleDetail(groupId, currentArticleId, requestedArticleId, page, language, quantityControlName) {

    var currentDate = new Date();
    var dummy = currentDate.getTime();

    if (document.getElementById(quantityControlName) != null) {
        var currentQuantity = document.getElementById(quantityControlName).value;
    }

    $.get(GetBaseUrl() + "/Infomat/Modules/Common/Session.aspx?dummy=" + dummy + "&name=PreviousArticleId" + "&value=" + currentArticleId, function(response) {
        ShowArticleDetail(requestedArticleId, page, currentQuantity);
    });
}

function ShowArticleDetail(articleId, page, quantity) {
    var currentDate = new Date();
    var dummy = currentDate.getTime();
    var language = GetLanguage();

    $(".article-content").html("<img class=\"smallLoadingImage\" src=\"" + GetBaseUrl() + "/Infomat/Images/ajax-loader.gif\" alt=\"...\" />").show();

    $.get(GetBaseUrl() + "/Infomat/Modules/Catalog/CatalogArticleDetail_base.aspx?dummy=" + dummy + "&articleId=" + articleId + "&page=" + page + "&language=" + language + "&quantity=" + quantity, function(response) {
        $(".article-content").html(StripResponse(response)).show();

        scrollTo(0, 0);

        /* Show loading images */
        $("div.StockInfoElement").each(function(i, stockInfoElement) {
            $(stockInfoElement).html("<img class=\"smallLoadingImage\" src=\"" + GetBaseUrl() + "/Infomat/Images/ajax-loader.gif\" alt=\"...\" />").show();
        });
        $("div.WarehouseStockInfoElement").each(function(i, warehouseStockInfoElement) {
            $(warehouseStockInfoElement).html("<img class=\"smallLoadingImage\" src=\"" + GetBaseUrl() + "/Infomat/Images/ajax-loader.gif\" alt=\"...\" />").show();
        });
        $("div.PriceQuantityElement").each(function(i, priceQuantityElement) {
            $(priceQuantityElement).html("<img class=\"smallLoadingImage\" src=\"" + GetBaseUrl() + "/Infomat/Images/ajax-loader.gif\" alt=\"...\" />").show();
        });
        $("div.SubArticleStockInfoElement").each(function(i, subArticleStockInfoElement) {
            $(subArticleStockInfoElement).html("<img class=\"smallLoadingImage\" src=\"" + GetBaseUrl() + "/Infomat/Images/ajax-loader.gif\" alt=\"...\" />").show();
        });

        /* Hide price quantities */
        $(".PriceQuantityRow").each(function(i, priceQuantityRow) {
            $(priceQuantityRow).hide();
        });

        /* Show prices */
        var valueOfElement;
        $("div.ArticlePriceElement").each(function(i, valueOfElement) {
            var classes = valueOfElement.getAttribute('tag').split("|");
            var articleId = classes[0];
            var isArticleModel = classes[1];

            $.get(GetBaseUrl() + "/Infomat/Modules/Catalog/price_pages/PriceDetail.aspx?dummy=" + dummy + "&articleId=" + articleId + '&language=' + language + "&isArticleModel=" + isArticleModel, function(response) {
                $(valueOfElement).html(StripResponse(response));
            });
        });

        /* Set objects explorer */
        var objectExplorerElement;
        $("div.ObjectsExplorer").each(function(i, objectExplorerElement) {
            $(objectExplorerElement).easySlider({
                prevId: 'PreviousObjectSpan' + objectExplorerElement.getAttribute('tag'),
                nextId: 'NextObjectSpan' + objectExplorerElement.getAttribute('tag'),
                prevText: '<',
                nextText: '>'
            });

            var previousSpan = document.getElementById('PreviousObjectSpan' + objectExplorerElement.getAttribute('tag'));
            $(previousSpan).addClass('PreviousObject');

            var nextSpan = document.getElementById('NextObjectSpan' + objectExplorerElement.getAttribute('tag'));
            $(nextSpan).addClass('NextObject');
        });

        /* Show html objects */
        var htmlObjectElement = document.getElementById('HtmlObjectElement');
        var htmlUrlHiddenField = document.getElementById('HtmlUrlHiddenField');

        if (htmlObjectElement != null && htmlUrlHiddenField != null) {
            if (Right(htmlUrlHiddenField.value, 3) == 'mht') {
                $(htmlObjectElement).html('<iframe class="iframe" src="' + htmlUrlHiddenField.value + '" width="100%"></iframe>');
            }
        }

        /* Load stock info */
        $.get(GetBaseUrl() + "/Infomat/Modules/Catalog/Controllers/StockController.aspx?dummy=" + dummy + "&language=" + language, function(response) {
            /* Stock info */
            $("div.StockInfoElement").each(function(i, stockInfoElement) {
                var articleId = stockInfoElement.getAttribute('tag');

                $.get(GetBaseUrl() + "/Infomat/Modules/Catalog/StockInformation.aspx?dummy=" + dummy + "&display=detailStockQuantity" + "&articleId=" + articleId + "&language=" + language + "&forceCheckStock=false", function(response) {
                    $(stockInfoElement).html(StripResponse(response));
                });
            });

            /* Stock for sub articles */
            $("div.SubArticleStockInfoElement").each(function(i, subArticleStockInfoElement) {
                var articleId = subArticleStockInfoElement.getAttribute('tag');

                $.get(GetBaseUrl() + "/Infomat/Modules/Catalog/StockInformation.aspx?dummy=" + dummy + "&display=detailSubArticleStockQuantity" + "&articleId=" + articleId + "&language=" + language + "&forceCheckStock=false", function(response) {
                    $(subArticleStockInfoElement).html(StripResponse(response));
                });
            });

            /* Stock per warehouse */
            $("div.WarehouseStockInfoElement").each(function(i, warehouseStockInfoElement) {
                var articleId = warehouseStockInfoElement.getAttribute('tag');

                $.get(GetBaseUrl() + "/Infomat/Modules/Catalog/StockInformation.aspx?dummy=" + dummy + "&display=detailWarehouseStock" + "&articleId=" + articleId + "&language=" + language + "&forceCheckStock=false", function(response) {
                    $(warehouseStockInfoElement).html(StripResponse(response));
                });
            });
        });

        /* Load price quantity information */
        $.get(GetBaseUrl() + "/Infomat/Modules/Catalog/Controllers/CatalogPriceQuantityController.aspx?dummy=" + dummy + "&language=" + language, function(response) {
            /* Show prices */
            $(".PriceQuantityRow").each(function(i, priceQuantityRow) {
                var valueOfElement = $(".PriceQuantityElement", this);
                var articleId = $(valueOfElement).attr('tag');

                $.get(GetBaseUrl() + "/Infomat/Modules/Catalog/PriceQuantityDetail.aspx?dummy=" + dummy + "&articleId=" + articleId + "&language=" + language, function(response) {
                    var content = StripResponse(response);

                    if (content.indexOf('<div') != -1) {
                        $(valueOfElement).html(StripResponse(response)).fadeIn('slow');
                        $(priceQuantityRow).fadeIn('slow');
                    }
                });
            });
        });

        /* Load all needed prices */
        $.get(GetBaseUrl() + "/Infomat/Modules/Catalog/Controllers/CatalogPriceController.aspx?dummy=" + dummy + "&language=" + language, function(response) {
            /* Show prices */
            var valueOfElement;
            $("div.PriceExclVatElement").each(function(i, valueOfElement) {
                $.get(GetBaseUrl() + "/Infomat/Modules/Catalog/price_pages/PriceDetail.aspx?dummy=" + dummy + "&displaymode=exclvat&articleId=" + valueOfElement.getAttribute('tag') + "&language=" + language, function(response) {
                    $(valueOfElement).html(StripResponse(response));
                });
            });
            $("div.PriceInclVatElement").each(function(i, valueOfElement) {
                $.get(GetBaseUrl() + "/Infomat/Modules/Catalog/price_pages/PriceDetail.aspx?dummy=" + dummy + "&displaymode=inclvat&articleId=" + valueOfElement.getAttribute('tag') + "&language=" + language, function(response) {
                    $(valueOfElement).html(StripResponse(response));
                });
            });
        });

        /* Sub article actions */
        $("td.SubArticleActionCell").each(function(i, subArticleActionCell) {
            var quantityTextBox = $(".QuantityTextBox", this);
            var articleActionElement = $(".ArticleActionElement", this);
            var articleActionResultElement = $(".ArticleActionResultElement", this);

            $(articleActionResultElement).hide();

            quantityTextBox.keydown(function() {
                $(articleActionElement).show();
                $(articleActionResultElement).hide();
            });
        });

        //apply the lightbox to the zoomimage for a nice popup
        $("a.ArticleImageDetailZoomed").lightBox({
            imageLoading: GetBaseUrl() + '/Infomat/Images/lightbox/lightbox-ico-loading.gif',
            imageBtnClose: GetBaseUrl() + '/Infomat/Images/lightbox/lightbox-btn-close.gif',
            imageBtnPrev: GetBaseUrl() + '/Infomat/Images/lightbox/lightbox-btn-prev.gif',
            imageBtnNext: GetBaseUrl() + '/Infomat/Images/lightbox/lightbox-btn-next.gif',
            fixedNavigation: true
        });
    });
}

function AddToFavorites(moduleName, lstFavoriteListControlName, articlecode, language, baseUrl, controlName) {
    var currentDate = new Date();
    var dummy = currentDate.getTime();
    var selectedIndex = document.getElementById(lstFavoriteListControlName).selectedIndex;
    var listId = document.getElementById(lstFavoriteListControlName)[selectedIndex].value;

    $("div#" + controlName).html("<img class=\"smallLoadingImage\" src=\"" + GetBaseUrl() + "/Infomat/Images/ajax-loader.gif\" alt=\"...\" />").show();

    $.get(GetBaseUrl() + "/Infomat/Modules/Catalog/AddToFavorites.aspx?dummy=" + dummy + "&listid=" + listId + "&modulename=" + moduleName + "&articlecode=" + articlecode + "&language=" + language + "&baseurl=" + baseUrl, function(response) {
        $("div#" + controlName).html(StripResponse(response)).show();
    })
}

function DeleteFromFavorites(moduleName, listid, articlecode, language, baseUrl, tableControlName, controlName) {

    var currentDate = new Date();
    var dummy = currentDate.getTime();

    $("div#" + controlName).html("<img class=\"smallLoadingImage\" src=\"" + GetBaseUrl() + "/Infomat/Images/ajax-loader.gif\" alt=\"...\" />").show();

    $.get(GetBaseUrl() + "/Infomat/Modules/Catalog/DeleteFromFavorites.aspx?dummy=" + dummy + "&listid=" + listid + "&modulename=" + moduleName + "&articlecode=" + articlecode + "&language=" + language + "&baseurl=" + baseUrl, function(response) {
        var tablename = document.getElementById(tableControlName);
        tablename.style.display = "none";
    })


}

function ShowSaveImage(showSaveImage, saveControl, actionActionsElement, resultControl) {
    $("div#" + resultControl).html("").show();

    $("#" + actionActionsElement + " img").each(function(i) {
        if ($(this).attr("id").indexOf("RemoveFromShoppingImage") == -1) {
            if (showSaveImage + "" == "1") {
                $(this).hide();
            }
        }
    });
    if (showSaveImage + "" == "1") {
        var saveLinkElement = document.getElementById(saveControl);
        $("#" + saveControl).show();

        saveLinkElement.style.display = "block";
    }
}

function SaveShoppingCartArticleWithNote(groupId, page, articleId, quantity, language, baseUrl, loadingControl, resultControl, customerNumber, remove, noteElementId, saveNoteLinkId, shoppingcartArticleId, modulename) {
    fullGroupId = escape(groupId); // To handle special characters

    var noteElement = document.getElementById(noteElementId);
    var saveNoteLinkId = document.getElementById(saveNoteLinkId);

    var currentNote = "";
    if (noteElement != null) {
        currentNote = escape(noteElement.value);
    }

    var currentDate = new Date();
    var dummy = currentDate.getTime();
    var currentQuantity = document.getElementById(quantity).value;


    $.get(GetBaseUrl() + "/Infomat/Modules/misc/GetCatalogueTranslation.aspx?key=SavingNote&language=" + language, function(response) {
        $(saveNoteLinkId).html(StripResponse(response));
    });

    $("#" + loadingControl).show();
    $.get(GetBaseUrl() + "/Infomat/Modules/Catalog/SaveShoppingCartArticle.aspx?shoppingcartarticleid=" + shoppingcartArticleId + "&action=save&remove=" + remove + "&fullGroupId=" + groupId + "&articleId=" + articleId + "&quantity=" + currentQuantity + "&language=" + language + "&customerNumber=" + customerNumber + "&dummy=" + dummy + "&note=" + currentNote + "&addNote=1", function(response) {
        ShowShopHeader(GetBaseUrl(), customerNumber, language);
        if (modulename == 'Catalogue') {
            $.get(GetBaseUrl() + "/Infomat/Modules/misc/GetCatalogueTranslation.aspx?key=ArticleAddedAndNoteSaved&language=" + language, function(response) {
                $(saveNoteLinkId).html(StripResponse(response));
            });
        }
        else {
            $.get(GetBaseUrl() + "/Infomat/Modules/misc/GetCatalogueTranslation.aspx?key=NoteIsSaved&language=" + language, function(response) {
                $(saveNoteLinkId).html(StripResponse(response));
            });
        }
        $("#" + loadingControl).hide();
        //$("div#" + resultControl).html("<img height=\"18px\" src=\"" + GetBaseUrl() + "/images/icons/catalogue/cart_added.png\" alt=\"...\" />").show();
        $("div#" + resultControl).html(response).show();

    });
}

function SaveShoppingCartArticle(
    shoppingCartArticleId,
    articleId,
    groupId,
    page,
    quantity,
    language,
    loadingControl,
    resultControl,
    customerNumber,
    remove,
    addNote,
    noteElementId,
    stockInfoElement,
    articlePriceElementId,
    skinpath) {
    var currentDate = new Date();
    var dummy = currentDate.getTime();
    var currentQuantity = document.getElementById(quantity).value;

    if (remove == "1")  //1 = remove the item
    {
        $(".article-content").html("<img class=\"loadingImage\" src=\"" + GetBaseUrl() + "/Infomat/Images/progressbar.gif\" alt=\"Loading...\" />").show();
    }
    else {
        $("#" + loadingControl).show();
    }

    var action = "save";
    if (remove == "1") //1 = remove the item
    {
        action = "delete";
    }

    $.get(GetBaseUrl() + "/Infomat/Modules/Catalog/SaveShoppingCartArticle.aspx?shoppingcartArticleId=" + shoppingCartArticleId + "&action=" + action + "&remove=" + remove + "&articleId=" + articleId + "&quantity=" + currentQuantity + "&language=" + language + "&customerNumber=" + customerNumber + "&dummy=" + dummy + "&addNote=0", function(response) {
        if (remove == "1") {
            ShowArticles(groupId, page);
        }
        else {

            $("#" + loadingControl).hide();
            $("div#" + resultControl).html(StripResponse(response)).show();
        }
        ShowShopHeader(GetBaseUrl(), customerNumber, language);

        // Refresh total price
        RecalculateTotalPrice('TotalPriceRefreshImageHolder', 'TotalPriceValueLabel', customerNumber, skinpath, language)

        // Show price for new quantity
        if (remove != "1") {
            ShowArticlePrice(articleId, language, page, quantity, articlePriceElementId);
        }

        // Reset buttons
        if (remove == "1") // 1=delete an item
        {
            $(".SetEmptyCartButtonsButton").click(); //opgelet : causes a postback !
        }

        $.get(GetBaseUrl() + "/Infomat/Modules/Catalog/StockInformation.aspx?dummy=" + dummy + "&display=overview&articleId=" + articleId + "&language=" + language + "&forceCheckStock=true", function(response) {
            $("div#" + stockInfoElement).html(StripResponse(response)).show();
        });
    });
}

function IncrementQuantity(textBoxId, quantity) {
    var currentQuantity = document.getElementById(textBoxId).value;
    currentQuantity = currentQuantity.replace(',', '.');
    var newQuantity = eval(currentQuantity) + eval(quantity);

    document.getElementById(textBoxId).value = newQuantity;
}

function DecrementQuantity(textBoxId, minimumQuantity, quantity) {
    var currentQuantity = document.getElementById(textBoxId).value;
    currentQuantity = currentQuantity.replace(',', '.');
    var newQuantity = eval(currentQuantity) - eval(quantity);

    if (newQuantity > minimumQuantity) {
        document.getElementById(textBoxId).value = newQuantity;
    }
    else {
        document.getElementById(textBoxId).value = minimumQuantity;
    }
}

/* Catalog total price */
function RecalculateTotalPrice(imageElementID, resultElementId, customerNumber, skinpath, language) {
    var resultElement = document.getElementById(resultElementId);


    if (resultElement != null) {

        $("div#" + imageElementID).html("<img src=\"" + GetBaseUrl() + "/Infomat/Images/loading_circle.gif\" alt=\"...\" />").show();

        var currentDate = new Date();
        var dummy = currentDate.getTime();


        $.get(GetBaseUrl() + "/Infomat/Modules/Catalog/RecalculateShoppingCart.aspx?dummy=" + dummy + "&language=" + language, function(response) {
            response = response.replace('<div id="JQueryPage">', '');
            response = response.replace('</div>', '');

            $(resultElement).html(StripResponse(response));

            $("div#" + imageElementID).html("<img id=\"TotalPriceRefreshImage\" class=\"MousePointer\" src=\"" + skinpath + "/infomat/images/icons/catalogue/refresh.png \" alt=\"Rfr\" onclick=\"javascript:RecalculateTotalPrice('TotalPriceRefreshImageHolder','TotalPriceValueLabel','" + customerNumber + "','" + skinpath + "','" + language + "')\" />").show();
            ShowShopHeader(GetBaseUrl(), customerNumber, language);
        });
    }
}

/* Request price */
function RequestPrice(Language, ArticleCode, QuantityTextBoxId, CommentsTextBoxId, EmailTextBoxId) {
    $("div#RequestPriceResultElement").html("<img class=\"smallLoadingImage\" src=\"" + GetBaseUrl() + "/Infomat/Images/ajax-loader.gif\" alt=\"...\" />").show();

    var quantityTextBox = document.getElementById(QuantityTextBoxId);
    var commentsTextBox = document.getElementById(CommentsTextBoxId);
    var emailTextBox = document.getElementById(EmailTextBoxId);

    $.post(GetBaseUrl() + "/Infomat/Modules/Catalog/RequestPrice.aspx", {
        Quantity: quantityTextBox.value,
        Comments: commentsTextBox.value,
        Email: emailTextBox.value,
        Language: Language,
        ArticleCode: ArticleCode
    },
    function(data) {
        $("div#RequestPriceResultElement").html("<img height=\"18px\" src=\"" + GetBaseUrl() + "/images/icons/catalogue/cart_added.png\" alt=\"...\" />").show();
    }
    );
}

function ShowPriceTabContent(divToShow, divToHide, activeTab, inactiveTab) {
    var elementToShow = document.getElementById(divToShow);
    var elementToHide = document.getElementById(divToHide);
    var activeTabElement = document.getElementById(activeTab);
    var inactiveTabElement = document.getElementById(inactiveTab);

    //$(this).addClass("active"); 
    $(elementToShow).show();
    $(activeTabElement).addClass("active");
    $(elementToHide).hide();
    $(inactiveTabElement).removeClass("active");
}

function ShowArticleDetailsInTabContent(divToShow, divToHide, activeTab, inactiveTab) {
    var elementToShow = document.getElementById(divToShow);
    var elementToHide = document.getElementById(divToHide);
    var activeTabElement = document.getElementById(activeTab);
    var inactiveTabElement = document.getElementById(inactiveTab);

    $(elementToShow).show();
    $(activeTabElement).addClass("active");
    $(elementToHide).hide();
    $(inactiveTabElement).removeClass("active");
}

function ClickCheckOutNavigationButton(button) {
    var validationGroupName = "";
    if (typeof (Page_ClientValidate) == 'function') {
        var validationResult = Page_ClientValidate(validationGroupName);

        if (validationResult == true) {
            __doPostBack(button + '_Click', '');
        }
    }
    else {
        __doPostBack(button + '_Click', '');
    }

    return false;
}

function ShowPricesInTabs(divname) {
    $(document).ready(function() {
        $('#' + divname + ' > ul').tabs({ fx: { height: 'toggle', opacity: 'toggle'} });
    });
}

function ShowArticleDetailsInTabs(divname) {
    $(document).ready(function() {
        $('#' + divname + ' > ul').tabs();
    });
}

function ShowShoppingCartComment(resultElement, language, userid) {
    $(resultElement).html("<img class=\"smallLoadingImage\" src=\"" + GetBaseUrl() + "/Infomat/Images/ajax-loader.gif\" alt=\"...\" /> validating basket").show();

    var currentDate = new Date();
    var dummy = currentDate.getTime();

    $.get(GetBaseUrl() + "/Infomat/Modules/Catalog/ShoppingCartComment.aspx?dummy=" + dummy + "&lang=" + language + "&userid=" + userid, function(response) {
        response = response.replace('<div id="JQueryPage">', '');
        response = response.replace('</div>', '');

        $(resultElement).html(StripResponse(response));
    });
}

function ChangeArticleForCheckout(checkboxcontrolId, articlecode, userid, resultElement, language) {
    $("div#" + resultElement).html("<img class=\"smallLoadingImage\" src=\"" + GetBaseUrl() + "/Infomat/Images/ajax-loader.gif\" alt=\"...\" />").show();
    var currentDate = new Date();
    var dummy = currentDate.getTime();

    var includeInCheckout = true;

    if ($("#" + checkboxcontrolId + ":checked").val() == "on")
        includeInCheckout = true;
    else
        includeInCheckout = false;

    $.get(GetBaseUrl() + "/Infomat/Modules/misc/ChangeArticleMode.aspx?dummy=" + dummy + "&userid=" + userid + "&articlecode=" + articlecode + "&includeInCheckout=" + includeInCheckout, function(response) {

    });
    $("div#" + resultElement).html("").show();

    /*
    if (!includeInCheckout) {
    $.get(GetBaseUrl() + "/Infomat/Modules/misc/GetCatalogueTranslation.aspx?key=SavingNote&ArticleIsExcludedFromCheckout&language=" + language, function(response) {
    //$(saveNoteLinkId).html(StripResponse(response));
    $("div#" + resultElement).html("<img src=\"" + GetBaseUrl() + "/Infomat/Images/cross.png\" alt=\"deleted\" /> " + response).show();
    });

    }
    
    else
    $("div#" + resultElement).html("").show();
    */
}

function AddShowHide(divname, linkname) {
    $(document).ready(function() {
        $("#" + divname).hide();
        $("#" + linkname).show();

        $("#" + linkname).click(function() {
            $("#" + divname).slideToggle();
        });
    });
}

function CatchEnterKeyForQuantityTextBox(TextboxId, ButtonId) {
    $("#" + TextboxId).keyup(function(event) {
        if (event.keyCode == 13) {
            $("#" + ButtonId).click();
        }
    });
}





