/// <reference path="jquery-1.4.4-vsdoc.js" />

//wrap the $ in a anonymous function to prevent faults with other libraries an run everything in this scope
var delay, ajaxRequest = null;
var application = (function ($)/// <param name="$" type="jQuery" />
{
    $ = jQuery;
    //this is neccesary for the canceling of the menu ajax request in ie7
    $(function () {
        $.ajaxSetup
        ({
            xhr: function () {
                if ($.browser.msie) {
                    return new ActiveXObject("Microsoft.XMLHTTP");
                }
                else {
                    return new XMLHttpRequest();
                }
            }
        })
    });
    //function object instead of annonymous functions (profilers give you the function names => better to debug )
    var app = {
        //document ready initialisation
        initReady: function () {
            //app.setZindex();
            app.makeEnterClickable();
            app.setDisabledClasses();
            /*app.initCollapsibleStylePanels();*/
            app.initDropdown();
            app.initCollapsibleLists();
            app.initSlider();
            app.initVideo();
            app.initLanguageDropdown();
            app.clearEmptyPageViewDiv();
            app.clearTopBorderProductDetail();
            app.positionWhereToBy();
            app.setBoldTipText();
            app.setCharacterCount();
            app.checkFormTankScreen();
            app.deleteLastCatlagBorder();
            app.positionLegend();
            app.trackSoftWareDownloads();
            app.setMovies();
            app.setTabs();
            app.setChoices();
            app.setTableStripes();
            app.setNewsLetterActive();
            app.initLoginColorBox();
            app.setVideoPopup();


        },
        setVideoPopup: function () {
            $(".videolink").click(function (e) {
                e.preventDefault();
                $.colorbox({ href: "/movie.html", width: 500, height: 500 });
            });
        },
        initLoginColorBox: function () {
            if ($("#lbLogin").exists() && jQuery().colorbox) {
                $("#lbLogin").colorbox({ width: "600px", height: "500px", inline: true, href: "#login" });
                $("#colorbox").appendTo('form');
            }
        },

        //led switcher on sfeer theme
        setChoices: function () {
            $(".switcher img").click(function () {
                $(".switcher img").each(function () {
                    var regularImg = $(this).attr("regularsrc");
                    $(this).attr("src", regularImg);
                });
                var activeImage = $(this).attr("ativesrc");
                var bigImage = $(this).attr("bigsrc");
                $(this).attr("src", activeImage);
                $(this).closest(".switchParent").find(".bigImage").attr("src", bigImage);
            });
        },
        positionLegend: function () {

            $('#legende').stickySidebar();

        },
        setTabs: function () {
            if ($('.smoothTabs').exists()) {
                $('.smoothTabs').smoothTabs(10);
                $(".slider-1").rotator({
                    tranSpeed: 800,
                    delay: 4000,
                    auto: false,
                    loop: true,
                    backwards: false
                });
                $(".slider-2").rotator({
                    tranSpeed: 800,
                    delay: 4000,
                    auto: false,
                    loop: true,
                    backwards: false
                });
                $(".slider-3").rotator({
                    tranSpeed: 800,
                    delay: 4000,
                    auto: false,
                    loop: true,
                    backwards: false
                });
            }

        },
        setMovies: function () {
            $("a.move").click(function (e) {
                e.preventDefault();
                var url = $(this).attr("rel");
                $.colorbox({ href: url, width: "928px", height: "522px;", scrolling: false, iframe: true, returnFocus: true });
            });
        },
        //window load initialisation
        initLoad: function () {
            app.initFacetDropDown();
        },
        showLegend: function () {
            $(window).scroll(function () {
                var objectTop = $('#legende').position().top;
                var objectHeight = $('#object').outerHeight();
                var windowScrollTop = $(window).scrollTop();
                var windowHeight = $(window).height();

                if (windowScrollTop > objectTop)
                    $('#object').css('top', windowScrollTop);
                else if ((windowScrollTop + windowHeight) < (objectTop + objectHeight))
                    $('#object').css('top', (windowScrollTop + windowHeight) - objectHeight);

                $('#object').html('Top: ' + $('#object').position().top + 'px');

            });
        },
        //delete the bottom border on the last catalog on the algemene catalogus page
        deleteLastCatlagBorder: function () {
            $(".catalogue:last-child").addClass("last");
        },
        checkFormTankScreen: function () {
            var thanks = $(".thanks");
            if ($(".thanks").is(":visible")) {
                thanks.parent().prev(".module").hide();
            }
        },
        setCharacterCount: function () {
            $('.form textarea').jqEasyCounter({
                'maxChars': 2000,
                'maxCharsWarning': 1900,
                'msgFontSize': '11px',
                'msgFontColor': '#333',
                'msgFontFamily': 'Arial',
                'msgTextAlign': 'left',
                'msgWarningColor': '#F00',
                'msgAppendMethod': 'insertAfter'
            });
        },
        setBoldTipText: function () {
            /* $(".tipContent").each(function () {
            $(this).html($(this).html().replace(/^(\s*.*!)/i, '<strong style="text-transform:uppercase;">$1</strong><br />')); //begin with optional whitespace (0 or more), any character (0 or more) followed by a !
            });*/

        },
        trackSoftWareDownloads: function () {
            $("#softwareTracking a").click(function () {
                var softwareText = $(this).text(); //the link text for the label
                var softwareValue = $(this).attr("href"); //the link value for the value
                var culture = $("body").attr("class");
                //console.log(softwareValue);
                //console.log(softwareText);
                //track the download action in google analytics
                _gaq.push(['_trackEvent', culture, 'DownloadSoftware', softwareValue]);
                //console.log('_trackEvent '+culture +' DownloadSoftware '+ softwareValue);

            });
        },
        initLanguageDropdown: function () {
            $("#countryLink").die("click");
            $("#countryLink").live("click", function () {
                var that = $(this);
                that.toggleClass("activeTop");
                that.parent().toggleClass("activeTop");
                that.parent().find("#languagesDropDown").toggle();
                $("#languagesDropDown:visible").parent().mouseleave(function () {
                    $("#languagesDropDown").hide();
                    $("#countryLink").removeClass("activeTop").parent().removeClass("activeTop");
                });
            });

        },

        clearEmptyPageViewDiv: function () {
            $(".pageView:not(:has(div))").hide();

        },
        clearTopBorderProductDetail: function () {
            $(".productLeftContent:eq(0),.productRightContent:eq(0)").css({ "background-image": "none" })
        },
        //make each individual slider
        initSlider: function () {

            $('.slider-code').each(function () {
                $(this).tinycarousel({});
            });
        },

        //initiate videos with flow player
        initVideo: function () {
            flowplayer("a.myPlayer", "/sites/main/templates/swf/flowplayer-3.2.5.swf", {

                // this is the player configuration. You'll learn on upcoming demos.
                plugins: {
                    controls: {

                    }
                }
            });
        },

        //set noMargin classes on flyout items that are on the right side
        setNoMargin: function () {
            $("#headerWrapper").find(".themeFlyOut:nth-child(4n)").addClass("noMargin");
        },
        hideElement: function (element) {
            $(element).hide();
        },
        setNewsLetterActive: function () {
            $("#newsletterMenu a.professionalButton").click(function (e) {
                e.preventDefault();
                $("div.newsletter").addClass("faded");
                $("#prof").removeClass("faded");
            });
            $("#prof").click(function (e) {
                $("div.newsletter").addClass("faded");
                $(this).removeClass("faded");
            });
            $("#newsletterMenu a.consumerButton").click(function (e) {
                e.preventDefault();
                $("div.newsletter").addClass("faded");
                $("#cons").removeClass("faded");
            });
            $("#cons").click(function (e) {

                $("div.newsletter").addClass("faded");
                $(this).removeClass("faded");
            });
        },
        //initiate collapsible panels
        initCollapsibleStylePanels: function () {
            //console.log("ok");
            if (getCookie("ctl00_ctl13_ctl00_repPOIPlaceHoldersRight_ctl00_POIarticlePreview1_lbPure")) {
                var that = $("a.pure");
                that.addClass("expanded");
                that.next(".triggerPanel").css({ "display": "block" });

            }
            if (getCookie("ctl00_ctl13_ctl00_repPOIPlaceHoldersRight_ctl00_POIarticlePreview1_lbIntense")) {
                var that = $("a.intense");
                that.addClass("expanded");
                that.next(".triggerPanel").css({ "display": "block" });

            }
            if (getCookie("ctl00_ctl13_ctl00_repPOIPlaceHoldersRight_ctl00_POIarticlePreview1_lbOriginal")) {
                var that = $("a.original");
                that.addClass("expanded");
                that.next(".triggerPanel").css({ "display": "block" });

            }
            $("#container").undelegate("a.trigger", "click.trigger");
            $("#container").delegate("a.trigger", "click.trigger", function (e) {
                e.preventDefault();
                var that = $(this);
                var cookieID = that.attr("id");
                that.toggleClass("expanded");
                that.next(".triggerPanel").stop().slideToggle("fast");
                if (that.hasClass("expanded")) {
                    setCookie(cookieID, cookieID, 365);
                } else {
                    setCookie(cookieID, "", 365);
                }

            });
        },
        positionWhereToBy: function () {
            if (getInternetExplorerVersion() < 8 && getInternetExplorerVersion() > 0) {
                //pas de positie voor het where to by submenu aan enkel voor ie7
                $(".nlbe .whereToBy, .nlnl .whereToBy").css({ "left": "620px", "right": "150px" });
                $(".frbe .whereToBy, .frfr .whereToBy").css({ "left": "588px", "right": "150px" });
                $(".engb .whereToBy, .enus .whereToBy").css({ "left": "601px", "right": "170px" });
            }
            function getInternetExplorerVersion()

            // Returns the version of Internet Explorer or a -1

            // (indicating the use of another browser).
            {

                var rv = -1; // Return value assumes failure.

                if (navigator.appName == 'Microsoft Internet Explorer') {

                    var ua = navigator.userAgent;

                    var re = new RegExp("MSIE ([0-9]{1,}[\.0-9]{0,})");

                    if (re.exec(ua) != null)

                        rv = parseFloat(RegExp.$1);

                }

                return rv;
            }
        },
        initDropdown: function () {
            $(".pageContainer:eq(4)").addClass("whereToBy");
            var menuConfig = {
                over: app.showMenuItem, // function = onMouseOver callback (REQUIRED)    
                timeout: 0, // number = milliseconds delay before onMouseOut    
                out: app.hideMenuItem // function = onMouseOut callback (REQUIRED)    
            };
            $("#mainNav li.dropdown").unbind();
            $("#mainNav li.dropdown").hoverIntent(menuConfig);
            $("#mainNav").undelegate("li.dropdown", "click");
            $("#mainNav").delegate("li.dropdown > a", "click", function (e) {
                e.preventDefault();
            });
        },
        showMenuItem: function (e) {
            $("#dropDownTrigger a").css({ "position": "static" }); //hack for ie7
            //console.log("ok");
            $("#mainNav").find(".pageContainer:visible").clearQueue().hide().empty();
            var that = $(this);
            var url = that.find("a").attr("href"); //the url to load in the dropdown
            var containerDiv = that.find(".pageContainer");
            containerDiv.css({ "z-index": "10000" });
            // load the url in the wrapper .pageContainer
            ajaxRequest = $.ajax({
                url: url,
                cache: false,
                type: "GET",
                dataType: "html",
                success: function (data) {
                    containerDiv.html(data).fadeIn(100);
                    that.addClass("over");


                },
                error: function (XMLHttpRequest, textStatus, errorThrown) {
                    //console.log(textStatus);
                }
            });

            //setTimeout(function () { containerDiv.css({ "z-index": "1000" }) }, 50);
            // console.log("over");
        },
        hideMenuItem: function (element) {
            $("#dropDownTrigger a").css({ "position": "relative" }); //hack for ie7

            var that = $(this);
            ajaxRequest.abort(); //cancel ajax request in the menu that are still active on the element
            $("#mainNav li.dropdown").removeClass("over");
            var containerDiv = that.find(".pageContainer").fadeOut(50).empty(); //hide the dropdown and remove the content
            that.data("busy", "0");

            //console.log("out");
        },
        setTableStripes: function () {
            $(".detailContent table.styledTable tr:nth-child(odd)").addClass("alternate");
        },
        initFacetDropDown: function () {
            //Perform initial logic
            if (getCookie("facetDropdownOpen")) {

                if (getCookie("facetDropdownOpen") == "yes") {//if facetDropdown was open show it 
                    $("#dropDownTrigger").addClass("up");
                    $("#facedTree").css({ "display": "block" });
                }
                else {
                    $("#facedTree").css({ "display": "none" }); // if not hide it
                }

            } else {//if there is no cookie yet (only first time)
                $("#facedTree").css({ "display": "block" });
                $("#dropDownTrigger").removeClass("up");
                $("#facedTree").slideUp(1000, function () { setCookie('facetDropdownOpen', 'no', 365); });

            }
            $("#dropDownTrigger a").click(function (e) {

                if (getCookie("facetDropdownOpen") == "yes") {
                    app.closeFacetDropdown();
                    setCookie('facetDropdownOpen', 'no', 365);
                    //track the collapse action in google analytics
                    _gaq.push(['_trackEvent', 'Faceted search', 'Dropdown', 'Close dropdown']);
                } else {
                    app.openFacetDropdown();
                    setCookie('facetDropdownOpen', 'yes', 365);
                    //track the expand action in google analytics
                    _gaq.push(['_trackEvent', 'Faceted search', 'Dropdown', 'Open dropdown']);

                }
            });
            if ($(".facetItem")[0]) {//if there are no facets hide the menu button and remove the top margin of the #leftbar
            } else {
                $("#dropDownTrigger").css({ "display": "none" })
                $("#leftBar").css({ "margin-top": "0px" })
            };


        },
        openFacetDropdown: function () {
            $("#dropDownTrigger").addClass("up");
            $("#facedTree").slideDown();
            setCookie('facetDropdownOpen', 'yes', 365);
        },
        closeFacetDropdown: function () {
            $("#dropDownTrigger").removeClass("up");
            $("#facedTree").slideUp();
            setCookie('facetDropdownOpen', 'no', 365);
        },
        initCollapsibleLists: function () {
            //2 sub levels
            $("ul.collapsibleList li:has( > ul)").addClass("child");
            $("ul.collapsibleList li:has(ul)").click(function (e) {
                $(this).find("> ul").slideToggle();
                $(this).toggleClass("open");
                e.stopPropagation();
            });
            $("ul.collapsibleList li").click(function (e) {
                e.stopPropagation();
            });
            $("ul.collapsibleList > li > a").click(function () {
                var ulIndexFirst = $(this).parent().index();
                deleteCookie("openFaqFirst");
                deleteCookie("openFaqSecond");
                deleteCookie("openFaqThird");
                setCookie("openFaqFirst", ulIndexFirst, 365);
            });
            $("ul.collapsibleList > li > ul > li > a").click(function () {
                var ulIndexSecond = $(this).parent().index();
                deleteCookie("openFaqSecond");
                deleteCookie("openFaqThird");
                setCookie("openFaqSecond", ulIndexSecond, 365);
            });
            $("ul.collapsibleList > li > ul > li > ul > li > a").click(function () {
                var ulIndexSecond = $(this).parent().index();
                deleteCookie("openFaqThird");
                setCookie("openFaqThird", ulIndexSecond, 365);
            });
            //show the previous chosen faq when you come backt to the page
            if (document.cookie.indexOf('openFaqFirst') != -1) {
                $("ul.collapsibleList > li:eq(" + getCookie('openFaqFirst') + ")").addClass("open").find("> ul").css({ 'display': 'block' });
            }
            if (document.cookie.indexOf('openFaqSecond') != -1) {
                $("ul.collapsibleList > li:eq(" + getCookie('openFaqFirst') + ")").find("> ul").find("> li:eq(" + getCookie('openFaqSecond') + ")").addClass("open").find("> ul").css({ "display": "block" });
            }
            if (document.cookie.indexOf('openFaqThird') != -1) {
                $("ul.collapsibleList > li:eq(" + getCookie('openFaqFirst') + ")").find("> ul").find("> li:eq(" + getCookie('openFaqSecond') + ")").addClass("open").find("> ul").css({ "display": "block" }).find(" > li:eq(" + getCookie('openFaqThird') + ")").addClass("open").find("div.answer").css({ "display": "block" });
            }

            //1 sub level
            $("ul.collapsibleList2 li:has(ul)").addClass("child");
            $("ul.collapsibleList2 li:has(ul)").click(function (e) {
                $(this).find("> ul").slideToggle();
                $(this).toggleClass("open");
                e.stopPropagation();
            });
            $("ul.collapsibleList2 li").click(function (e) {
                e.stopPropagation();
            })
            $("ul.collapsibleList2 li.child:eq(0)").addClass("open").find(">ul").css({ "display": "block" });
            $("ul.collapsibleList li:has(> a[href^='/#']), ul.collapsibleList2 li:has(> a[href^='/#']), ul.collapsibleList3 li:has(> a[href^='/#'])").click(function (e) {
                $(this).toggleClass("open");
                e.preventDefault();
                $(this).find("div.answer").slideToggle();

            });
            $("ul.collapsibleList li a[href^='/#'], ul.collapsibleList2 li a[href^='/#'], ul.collapsibleList3 li a[href^='/#']").click(function (e) {
                e.preventDefault();
            });

        },



        //set disabled classes on links
        setDisabledClasses: function () {
            $("a[disabled=disabled]").addClass("disabled");
        },

        //make input elements fire the submit action on enter click and cancel action on esc click
        makeEnterClickable: function () {
            $(".clicker :text,.clicker :password").die("keydown");
            $(".clicker :text,.clicker :password").live("keydown",
                function (evt) {
                    var evt = (evt) ? evt : ((event) ? event : null);
                    //cache the enter button
                    var $enterButton = $(this).parents(".clicker:eq(0)").find(".enterAction");
                    //cache the cancel button
                    var $cancelButton = $(this).parents(".clicker:eq(0)").find(".cancelAction");
                    if (evt.keyCode == 13) {
                        // enter click action
                        if ($enterButton.attr("href")) {
                            eval($enterButton.attr("href").replace("javascript:", ""));
                        } else if ($enterButton.attr("onclick")) {
                            $enterButton.trigger("click");
                        } else {
                            $enterButton.trigger("click");
                        }
                        return false;
                    } else if ((evt.keyCode == 27) && ($cancelButton.exists())) {
                        //escape click action
                        if ($cancelButton.attr("href")) {
                            eval($cancelButton.attr("href").replace("javascript:", ""));
                        } else if ($cancelButton.attr("onclick")) {
                            $cancelButton.trigger("click");
                        } else {
                            $cancelButton.trigger("click");
                        }
                        return false;
                    }
                });
        }
    };
    // $(document).ready(app.initReady);

    //functionality that needs to run after the page has finished loading
    $(window).load(app.initLoad);

    // return the public methods and variables
    return {
        initReady: app.initReady,
        hideElement: app.hideElement,
        makeEnterClickable: app.makeEnterClickable,
        initDropdown: app.initDropdown,
        initLanguageDropdown: app.initLanguageDropdown,
        positionLegend: app.positionLegend,
        setDisabledClasses: app.setDisabledClasses,
        setNewsLetterActive: app.setNewsLetterActive
    }
})(jQuery);

//function to see if an element exists
jQuery.fn.exists = function () { return jQuery(this).length > 0; }

/* solves the firebug console calls in browsers without firebug */
if (!('console' in window) || !('firebug' in console)) {
    var names = ['log', 'debug', 'info', 'warn', 'error', 'assert', 'dir', 'dirxml', 'group', 'groupEnd', 'time', 'timeEnd', 'count', 'trace', 'profile', 'profileEnd'];
    window.console = {};
    for (var i = 0; i < names.length; ++i) window.console[names[i]] = function () { };
}

/* get cookie */
function getCookie(c_name) {
    if (document.cookie.length > 0) {
        c_start = document.cookie.indexOf(c_name + "=");
        if (c_start != -1) {
            c_start = c_start + c_name.length + 1;
            c_end = document.cookie.indexOf(";", c_start);
            if (c_end == -1) c_end = document.cookie.length;
            return unescape(document.cookie.substring(c_start, c_end));
        }
    }
    return "";
}

/* function set cookie */
function setCookie(c_name, value, expiredays) {
    var exdate = new Date();
    exdate.setDate(exdate.getDate() + expiredays);
    document.cookie = c_name + "=" + escape(value) +
((expiredays == null) ? "" : ";expires=" + exdate.toGMTString() + ";path=/");
}
/* function delete cookie */
function deleteCookie(name) {
    // set the expiry date to the past
    document.cookie = name + "=;expires=Thu, 01-Jan-1970 00:00:01 GMT" + ";path=/"
}
function pageLoad(sender, args) {
    application.initReady();
    application.makeEnterClickable();
}
jQuery.extend(jQuery.expr[':'], {
    inview: function (el) {
        var $e = $(el),
    $w = $(window),
    top = $e.offset().top,
    height = $e.outerHeight(true),
    windowTop = $w.scrollTop(),
    windowScroll = windowTop - height,
    windowHeight = windowTop + height + $w.height();
        return (top > windowScroll && top < windowHeight);
    }
});

//for the scriptmanager, needs to be at the end of the script
if (typeof (Sys) !== 'undefined') Sys.Application.notifyScriptLoaded();

