/*
 * Project: Priva
 * Agency:  Tamtam 
 * Author:  dirkjan@degroot.in
 * Date:  03-03-2011

 */


var twtBtn = {
    init: function() {
        try {
            var twtBtn,
            insetWidth;

            twtBtn = $('.twt-btn');

            // (padding-right - total width)
            // so only the Twitter icon is visible,
            // when the button is inset
            insetWidth = parseInt(twtBtn.css('padding-right').replace('px', '')) - twtBtn.outerWidth();

            // Calculate and set the inset width first, 
            // then make it visible again
            twtBtn.css('left', insetWidth);
            twtBtn.css('visibility', 'visible');

            twtBtn.hover(
                function () {
                    $(this).animate({
                        left: 0
                    });
                },
                function () {
                    $(this).animate({
                        left: insetWidth
                    });
                }
            );
        }
        catch (e) {
            // So there is no Twitter follow us button.
        }
    }
}

var player = {
    interval: 5000,
    duration: 1000,
    slideSize: 940,
    easing: 'swing',
    mySlider: function (selector, marginLeftPx, newslide, play) {
        player.ablePager("off");
        selector.animate({
            marginLeft: marginLeftPx
        }, {
            duration: this.duration,
            specialEasing: {
                width: player.easing
            },
            complete: function () {
                player.ablePager("on");
                player.updateActive(newslide);
                if (play != 'manual') {
                    setTimeout(player.slideAuto, player.interval);
                } else {
                    selector.stop();
                }
            }
        });
    },
  ablePager: function(onoff) {
    if (onoff == 'off') {
      $("div.pager li a").each(function() {
        var contents = $(this).html();
        $(this).replaceWith('<em>' + contents + '</em>');
      });
    } 

    if(onoff=='on') {
      $("div.pager li > em").each(function() {
        var contents = $(this).html();
        $(this).replaceWith('<a>' + contents + '</a>');
      });
    }
    },
    slideAuto: function () {
        var currentslide = $("div.carousel > ul > li.active").attr("rel");
        var totalsize = $("div.carousel > ul > li").length;
        var maxsize = parseInt(totalsize) - 1;
        var newslide = (currentslide == maxsize) ? 0 : parseInt(currentslide) + 1;
        player.mySlider($("div.carousel > ul"), player.offSet(newslide), newslide, 'auto');
    },
    updateActive: function (newslide, currentslide) {
        if (!currentslide) {
            var currentslide = (newslide == 0) ? parseInt($("div.carousel > ul > li").length) - 1 : newslide - 1;
        }
        $("div.carousel > ul > li[rel='" + newslide + "']").addClass("active");
        $("div.carousel > ul > li[rel='" + currentslide + "']").removeClass("active");
        $("div.pager ul li[rel='" + currentslide + "']").removeClass("active");
        $("div.pager ul li[rel='" + newslide + "']").addClass("active");
    },
    slideManual: function (newslide) {
        var currentslide = $("div.carousel > ul > li.active").attr("rel");
        player.mySlider($("div.carousel > ul"), player.offSet(newslide), newslide, 'manual');
        player.updateActive(newslide, currentslide);

    },
    offSet: function (newslide) {
        var offSet = newslide * player.slideSize;
        var newSet = '-' + offSet + 'px';
        return newSet;
    },
    init: function () {

        /* add rel attributes and hide inactive li's */
        $("div.carousel > ul > li").each(function (index) {
            $(this).attr("rel", index);
        });

        $("div.pager ul li").each(function (index) {
            $(this).attr("rel", index);
        });

        /* add total width to homepage animation */
        var totalWidth = $("div.carousel > ul > li").length * player.slideSize;
        $("div.carousel > ul").css("width", totalWidth);

        if ($("div.autoplay").length != 0) {
            setTimeout(player.slideAuto, player.interval, 0, 'auto');
        }

        /* manual playing */
        $("div.pager li a").live('click', function () {
            player.slideManual($(this).closest("li").attr("rel"));
            return false;
        });

    }
}

var showcase = {
    duration: 1000,
    slideSize: 700,
    easing: 'swing',
    totalLi: $("#showcase ul.slide > li").length * 700,
    mySlider: function (selector, marginLeftPx) {
        selector.animate({
            marginLeft: marginLeftPx
        }, {
            duration: showcase.duration,
            specialEasing: {
                width: showcase.easing
            },
            complete: function () {
                showcase.toggleButtons();
            }
        });
    },
    insertHtml: function () {
        /* add total width to showcase */
        $("#showcase .slide").css("width", showcase.totalLi);

        if (showcase.totalLi > showcase.slideSize) {
            /* insert showcase pager html */
            var html = '<ul class="showcase-pager reset"><li class="left active"><a href="#" class="previous">' + langStr.getString('Previous') + '</a></li><li><ul id="bulls"></ul></li><li class="right"><a href="#" class="next">' + langStr.getString('Next') + '</a></li></ul>';
            $("#showcase").after(html);

            /* now start adding li's into ul class=bulls to show the bullets depending on number of pages */
            $("#showcase .slide > li").each(function (index) {
                $("#bulls").append('<li rel="' + index + '"><a href="#">' + langStr.getString('Page') + ' ' + (parseInt(index) + 1) + '</a></li>');
            });

            /* on first child add active class */
            $("#bulls li:first-child").addClass("active");

            /* add rel attributes */
            $("#showcase ul.slide > li").each(function (index) { $(this).attr("rel", index); });

            /* align ie7 */
            var width = $(".showcase-pager ul").width();
            $(".showcase-pager ul").css("margin-left", -(width / 2) + 'px');
        }
    },
    toggleButtons: function () {
        var slibase = $("#showcase .slide").css('marginLeft');
        var prev = $(".showcase-pager li a.previous");
        var next = $(".showcase-pager li a.next");
        var total = -(showcase.totalLi - showcase.slideSize) + 'px';

        (slibase == '0px') ? prev.before('<div class="nextprev">&nbsp;</div>').fadeOut("fast") : prev.fadeIn("fast");
        (slibase == total) ? next.before('<div class="nextprev">&nbsp;</div>').fadeOut("fast") : next.fadeIn("fast");
        (slibase) ? showcase.cleanNextPrev() : '';
    },
    cleanNextPrev: function () {
        /* garbage collector */
        $("div.nextprev").each(function () { $(this).remove(); });
    },
    updateActive: function (selector, prv) {
        var currentslide = $("#showcase ul.slide li.active").attr("rel");
        if (!prv) {
            var newslide = selector.closest("li").attr("rel");
        } else {
            var newslide = (prv == 'next') ? (parseInt(currentslide) + 1) : (parseInt(currentslide) - 1);
        }
        $(".showcase-pager li[rel='" + newslide + "']").addClass("active");
        $(".showcase-pager li[rel='" + currentslide + "']").removeAttr("class");
        $("#showcase ul.slide li[rel='" + newslide + "']").addClass("active");
        $("#showcase ul.slide li[rel='" + currentslide + "']").removeAttr("class");
    },
    init: function () {
        showcase.insertHtml();
        showcase.toggleButtons();

        $(".showcase-pager .next").live('click', function () {
            showcase.mySlider($("#showcase .slide"), '-=700px');
            showcase.updateActive($(this), 'next');
            return false;
        });

        $(".showcase-pager .previous").live('click', function () {
            showcase.mySlider($("#showcase .slide"), '+=700px');
            showcase.updateActive($(this), 'prev');
            return false;
        });

        $(".showcase-pager ul li a").live('click', function () {
            showcase.updateActive($(this).closest("li"));
            var newslide = $(this).closest("li").attr("rel");
            var offSet = newslide * showcase.slideSize;
            var newSet = '-' + offSet + 'px';
            showcase.mySlider($("#showcase .slide"), newSet);
            return false;
        })
    }
}


var fontset = {
    fontSize: function (size) {
        $("body").removeClass("medium").removeClass("small").removeClass("large").addClass(size);
        $("#settings ul a").each(function () { $(this).parent("li").removeClass("active"); });
        $("a." + size + "").closest("li").addClass("active");
        $.cookie('fontsize', size, { path: '/' });
    },
    blurFocus: function (selector, text) {
        if ($.trim(selector.val()) == '') { selector.attr("value", text).addClass("blur"); }
    },
    focusBlur: function (selector, text) {
        if ($.trim(selector.val()) == text) { selector.attr("value", "").removeClass("blur"); }
    },
    insertHtml: function (small, medium, large) {
        /* append html */
        //SM: Global is also multilingual
        //$("body:not(.global) #settings li:last-child").after('<li><strong class="textbrowse">'+ langStr.getString('Fontsize') +'</strong><ul id="fontsize"><li '+ large +'><a href="/set/font-size/large" class="large" title="'+ langStr.getString('Setlarge') +'"><em>'+ langStr.getString('Large') +'</em></a></li><li '+ medium +'><a href="/set/font-size/medium" class="medium" title="'+ langStr.getString('Setmedium') +'"><em>'+ langStr.getString('Medium') +'</em></a></li><li '+ small +'><a href="/set/font-size/small" class="small" title="'+ langStr.getString('Setdefault') +'"><em>'+ langStr.getString('Default') +'</em></a></li></ul></li>');
        $("#settings li:last-child").after('<li><strong class="textbrowse">' + langStr.getString('Fontsize') + '</strong><ul id="fontsize"><li ' + large + '><a href="/set/font-size/large" class="large" title="' + langStr.getString('Setlarge') + '"><em>' + langStr.getString('Large') + '</em></a></li><li ' + medium + '><a href="/set/font-size/medium" class="medium" title="' + langStr.getString('Setmedium') + '"><em>' + langStr.getString('Medium') + '</em></a></li><li ' + small + '><a href="/set/font-size/small" class="small" title="' + langStr.getString('Setdefault') + '"><em>' + langStr.getString('Default') + '</em></a></li></ul></li>');
        $("#fontsize li a em").addClass("textbrowse");
    },
    init: function () {

        /* log choice of font-size in cookie */
        var fontsize = $.cookie('fontsize');
        if (fontsize) { $("body").addClass(fontsize); } else { fontset.fontSize("small"); }
        var active = "";

        /* set active */
        var large = (fontsize == 'large' || active == 'large') ? 'class="active"' : '';
        var medium = (fontsize == 'medium' || active == 'medium') ? 'class="active"' : '';
        var small = (fontsize == 'small' || active == 'small') ? 'class="active"' : '';

        fontset.insertHtml(small, medium, large);

        $("#settings a.large").live('click', function () { fontset.fontSize("large"); return false });
        $("#settings a.medium").live('click', function () { fontset.fontSize("medium"); return false });
        $("#settings a.small").live('click', function () { fontset.fontSize("small"); return false });
    }
}

var translations = {
    init: function () {
        /* translate some strings */
        $("#str1,#str4").html(langStr.getString('Settings'));
        $("#str2").html(langStr.getString('Skipto'));
        $("#str3").html(langStr.getString('Navigation'));
        $("#str5").html(langStr.getString('Footer'));

        $("#search input").val(langStr.getString('Search'));
        $(".search input#productsearch").val(langStr.getString('Searchproduct'));
        if ($(".newsletter input#subscribe").val() == '')
            $(".newsletter input#subscribe").val(langStr.getString('Youremail'));

        /* handle translations of search boxes */
        $("#search input[type='text']").bind('focus blur', function (e) { (e.type == 'focus') ? fontset.focusBlur($(this), langStr.getString('Search')) : fontset.blurFocus($(this), langStr.getString('Search')); return false; });
        $(".search input[type='text']").bind('focus blur', function (e) { (e.type == 'focus') ? fontset.focusBlur($(this), langStr.getString('Searchproduct')) : fontset.blurFocus($(this), langStr.getString('Searchproduct')); return false; });
        $(".newsletter input#subscribe").bind('focus blur', function (e) { (e.type == 'focus') ? fontset.focusBlur($(this), langStr.getString('Youremail')) : fontset.blurFocus($(this), langStr.getString('Youremail')); return false; });
    }
}

var general = {
    setPrintLink: function () {
        /* add print link and attach print event */
        $("ul.icons li:first-child").after('<li><a href="/print" class="icon print" title="Print">Print</a></li>');
        $(".print").click(function () { window.print(); return false; });
    },
    productFinder: function () {

        $(".productfinder a.close").click(function () {
            $(this).closest("div").removeClass("show");
            var destInput = $(this).closest("div").prev("input");
            destInput.val("");
            fontset.blurFocus(destInput, langStr.getString('Searchproduct'));
            return false;
        });

        $(".productfinder li a").bind('click', function (e) {
            var texty = $(this).html();
            $(this).closest("div").prev("input").attr("value", texty).removeClass("blur");
            $(this).closest("div").removeClass("show");
            return false;
        });

    },
    enlargeClickArea: function (selector, async) {
        /* 
        * @alias   enlargeClickArea
        * @author   d.degroot
        * @classDescription 
        * Enlarges click area of passed selector which contains a <a href> and extracts title. Generally used to improve usability of table rows, table headers or paginators
        * @param   {selector} - regular jquery selector
        */
        $(selector).live('mouseover click mouseout', function (event) {
            var target = $(this).find("a");
            var linkLocation = target.attr('href');
            var external = target.attr('class');
            if (linkLocation !== undefined) {
                if (event.type == 'mouseover') {
                    $(this).addClass("hover");
                } else if (event.type == 'click') {
                    window.location.href = linkLocation;
                } else {
                    if ($(this).attr("class") == 'hover') {
                        $(this).removeAttr("class");
                    } else {
                        $(this).removeClass("hover");
                    }

                }

            }
        });
    },
    overLay: function () {
        /* 
        * 
        * Take action of overlay button and put on overlay div + hide button
        * If the <a> has a class attribute containing a value, the link is not hidden, and the div will not use the href of the link
        * 
        */

        $(".overlay a").hide();

        $('.overlay').addClass("pointer").click(function () {
            var dest = $(this).find("a").attr("href");
            window.location.href = dest;
            return false;
        });


    },
    aligning: function () {

        var width4 = $("#footer .local").width();
        $("#footer ul").css("marginLeft", -(width4 / 2) + 'px');

        //var width5 = $(".main-filter ol").width();
        //$(".main-filter ol").css("marginLeft",-(width5/2) +'px');

        /* gridview */
        if ($(".gridview").length != 0) {
            //  $(".gridview li:last-child").addClass("last");
        }

        /* rounded corners */
        $("div.carousel").append('<em class="corner tleft"/>');
        $("div.carousel").append('<em class="corner tright"/>');
        $("div.carousel").append('<em class="corner bleft"/>');
        $("div.carousel").append('<em class="corner bright"/>');

        $("div.pager").append('<em class="corner bleft"/>');
        $("div.pager").append('<em class="corner bright"/>');

        $("div.carousel:not(.autoplay)").addClass("no-autoplay").after('<div class="clear">&#160;</div>');


    },
    websitePager: function () {
        var html2 = '<ul class="reset"><li class="left"><div class="nextprev">&#160;</div></li><li><ul id="bulls"></ul></li><li class="right"><div class="nextprev">&#160;</div></li></ul>';
        $(".website-pager").prepend(html2);
        $("ul.nav li.active ul li").clone().appendTo($(".website-pager ul#bulls"));
        var totalBulls = $(".website-pager #bulls li").length;

        $(".website-pager #bulls li").each(function (index) {
            if ($(this).hasClass("active")) {
                if (index != 0) {
                    $(this).prev("li").clone().appendTo($(".website-pager li.left"));
                    $(".website-pager li.left a").addClass("previous");
                }
                if (index != totalBulls) {
                    $(this).next("li").clone().appendTo($(".website-pager li.right"));
                    $(".website-pager li.right a").addClass("next");
                }
            }
        });

        var width3 = $(".website-pager ul ul").width();
        $(".website-pager ul ul").css("marginLeft", -(width3 / 2) + 'px');

    },
    ieCorrections: function () {

        if ($.browser.msie) {
            /* we dont do feature detection but old fashioned browser detection */

            var version = parseInt($.browser.version, 10);
            $("html").addClass('ie' + version);

            if (version < 9) {
                /* for ie7 and ie8 add these effects by jquery */
                $(".link-blocks:not(.faq) li:nth-child(2n+1)").addClass("odd");
                $(".link-blocks.faq li:even").addClass("odd");
                $("table:not(.ui) tbody tr:even").addClass("odd");
                $("table.ui tr:nth-child(4n+1)").addClass("pattern");
                $("table.ui tr:last-child").addClass("last");
                //$(".block-listing > ul > li:even").addClass("right");
                $(".block-listing > ul > li:odd").addClass("right");
                $(".nl-issues li:nth-child(2n+1)").addClass("odd");
            }

            if (version == 7) {
                /* detail position on 50% (for ie7) */
                var width2 = $(".main-pager ol").width;
                $(".main-pager ol").css("marginLeft", -(width2 / 2) + 'px!important');
            }
        }


    },
    init: function () {
        general.setPrintLink();

        if ($(".productfinder").length != 0) {
            general.productFinder();
        }

        if ($('.overlay').length != 0 && $(".overlay:has(a)").length != 0 && $.trim($(".overlay a").attr("class")) == "") {
            general.overLay();
        }

        if ($(".overlay:has(a)").length == 0) {
            $(".overlay").addClass("noa");
        }

        general.aligning();

        general.enlargeClickArea($(".main-filter li"));
        $("table.ui tr.details").addClass("textbrowse");
        $(".link-blocks.faq div").addClass("textbrowse");

        /* toggle table ui component */
        $("table.ui tr.base td:nth-child(1), table.ui tr.base td:nth-child(1) a, table.ui tr.base td:nth-child(2), table.ui tr.base td:nth-child(2) a").click(function () {
            $(this).closest("tr.base").next('tr.details').toggleClass('textbrowse');
            return false;
        }).addClass("pointer");

        /* toggle frequently asked questions component */
        $(".link-blocks.faq a").click(function () {
            $(this).next('div').toggleClass('textbrowse');
            return false;
        }).addClass("pointer");

        general.enlargeClickArea($("div.tabs table tr"));

        if ($(".website-pager").length != 0) {
            general.websitePager();
        }

        general.ieCorrections();
    }
}

var formval = {

    /* 
    * Pattern for inline validation in jquery
    * based on eye tracking research by Luke Wreblowski, described here:
    * http://www.alistapart.com/articles/inline-validation-in-web-forms/
    * ported to jQuery by dirkjan@degroot.in
    */

    success_image: '<img src="/images/i_success.png" alt="' + langStr.getString('alt_success_image') + '" />',
    error_image: '<img src="/images/i_error.png" alt="' + langStr.getString('alt_error_image') + '" />',
    loading_image: '<img src="/images/i_ajaxloader.gif" alt="' + langStr.getString('alt_loading_image') + '"/>',
    inlineValidation: function (context) {
        if (context.closest("li").hasClass("required") || context.closest("li").hasClass("mandatory") || context.closest("li").hasClass("captcha")) {
            if ($.trim(context.val()) == "") {
                formval.errorTrue(context, langStr.getString('title_required_field'));
                if (context.attr("name") == "telephone") {
                    formval.grayFields("bytelephone", "on");
                }
            }
            else {
                formval.errorFalse(context);
                if (context.attr("name") == "telephone") {
                    formval.grayFields("bytelephone", "off");
                }
            }
        }
        else {
            if ($.trim(context.val()) != "") {
                formval.errorFalse(context);
            }
            else {
                context.closest("li").removeClass("error").removeAttr("title").removeClass("success").find("img").remove();
            }
        }

    },
    errorTrue: function (selector, error) {
        selector.closest("li").find("img").each(function () { $(this).remove(); });
        selector.closest("li").removeClass("success").addClass("error").attr("title", error);
        selector.closest("li").append(formval.error_image);
    },
    errorFalse: function (selector) {
        selector.closest("li").find("img").each(function () { $(this).remove(); });
        selector.closest("li").removeClass("error").addClass("success").removeAttr("title");
        selector.closest("li").append(formval.success_image);
    },
    errorJsSpecialTrue: function (selector, error) {
        selector.closest("div.js-special").find("img").each(function () { $(this).remove(); });
        selector.closest("div.js-special").removeClass("success").addClass("error").attr("title", error);
        selector.closest("div.js-special").append(formval.error_image);
    },
    errorJsSpecialFalse: function (selector, error) {
        selector.closest("div.js-special").find("img").each(function () { $(this).remove(); });
        selector.closest("div.js-special").removeClass("error").addClass("success").removeAttr("title");
        selector.closest("div.js-special").append(formval.success_image);
    },
    grayFields: function (which, switchit) {
        if (switchit == 'on') {
            $("li." + which + "").addClass("gray").find("input, textarea,select").attr("disabled", "disabled").attr('checked', false);
        }
        if (switchit == 'off') {
            $("ol li ul li." + which + "").removeClass("gray").find("input").removeAttr("disabled");
        }
    },
    validateEmail: function (selector) {
        var email = selector.val();
        if (isValidEmailAddress(email) && !$.trim(email) == '') {
            formval.errorFalse(selector);
            formval.grayFields("byemail", "off");
        } else {
            formval.errorTrue(selector, langStr.getString('email_title_error'));
            formval.grayFields("byemail", "on");
        }

        /*  ------------------ email user feedback function ------------------------*/
        function isValidEmailAddress(email) {
            var pattern = new RegExp(/^([A-Za-z_\.0-9]+@(((([A-Za-z0-9\-])+\.)+[A-Za-z\-]{2,4})))*$/);
            return pattern.test(email);
        }
    },
    validateCombo: function (selector) {
        if (selector.attr('selectedIndex') == 0) {
            formval.errorTrue(selector.closest("li"), "Error");
        } else {
            formval.errorFalse(selector.closest("li"), "Okay");
        }
    },
    manipulateClone: function (chtml) {
        /*
        * Clone participants ol object and manipulate
        * 
        */

        var id = chtml.attr("rel");
        var newid = parseInt(id) + 1;

        /* first get the names of the labels so that we can update the clone */
        var forlabel1 = chtml.find("li:first-child label").attr("for");
        var forlabel2 = chtml.find("li:nth-child(2) label").attr("for");
        var newid1 = forlabel1.substring(0, forlabel1.length - 1) + newid;
        var newid2 = forlabel2.substring(0, forlabel2.length - 1) + newid;

        /* now update the clone */
        chtml.find("li:first-child label").attr("for", newid1)
        chtml.find("li:first-child input").attr("name", newid1)
        chtml.find("li:first-child input").attr("id", newid1)

        chtml.find("li:nth-child(2) label").attr("for", newid2)
        chtml.find("li:nth-child(2) input").attr("name", newid2)
        chtml.find("li:nth-child(2) input").attr("id", newid2)

        /* now make the clone empty in case there is some data inside */
        chtml.find("li input").attr("value", "");

        /* now remove the error image */
        chtml.find("li img").remove();

        /* now remove the error class */
        chtml.find("li").removeClass("error");

        /* now update clone number */
        chtml.attr("rel", newid);

        return chtml;
    },
    //      checkLast: function () {
    //          /* 
    //          * Checks which ordered lists within div.participants is last and puts minus sign 
    //          */
    //          $("div.participants ol").removeClass("last");
    //          $("div.participants ol li span").remove();
    //          /* add minus sign on last participant */
    //          if ($("div.participants ol").length > 1) {
    //              $("div.participants ol:last-child").addClass("last");
    //              $("div.participants ol:last-child li:first-child").append('<span class="remove" title="' + langStr.getString('remove_participant') + '">' + langStr.getString('remove_participant') + '</span>');
    //          }
    //      },
    addRequired: function () {
        $(".myform ol li.required > label span.required").remove();
        $(".myform ol li.required > label").append('<span class="required">*</span>');
    },

    validateAll: function () {
        var emailInput = $(".myform").find("li.email input");
        emailInput.each(function (e) {
            formval.validateEmail($(this));
        });

        var normalInput = $(".myform").find(
            "li.normal input:not(.antispam,.email), li.normal textarea, li.text.mandatory:not(.email) input, li.captcha input"
        );
        normalInput.each(function (e) {
            formval.inlineValidation($(this));
        });

        /* also on combo box */
        var comboInput = $(".myform").find("li select");
        comboInput.each(function (e) { formval.validateCombo($(this)); });
    },

    execute: function () {
        formval.addRequired();

        /* prefill and hide anti-spam questions */
        var prefillAntiSpam = $("body:has(.antispam)");

        var antiSpam = $("li.antispam");
        if (antiSpam.length != 0) {
            var total = parseInt(antiSpam.find("span:first-child").html()) + parseInt(antiSpam.find("span:last-child").html());
            antiSpam.addClass("hide").find("input").attr("value", total);
        }

        /* validate e-mail function */
        var emailInput = $(".myform").find("li.email input");
        emailInput.live('keyup blur', function (e) {
            formval.validateEmail($(this));
        });

        /* end validate e-mail function */

        /*
        * 
        * Initialize inline validation
        * 
        */

        /* execute inline validation */
        var normalInput = $(".myform").find(
                "li.normal input:not(.antispam,.email), li.normal textarea, li.text.mandatory:not(.email) input, li.captcha input"
            );
        normalInput.live('keyup blur', function () { formval.inlineValidation($(this)); });

        /* also on combo box */
        var comboInput = $(".myform").find("li select");
        comboInput.live('change', function () { formval.validateCombo($(this)); });

        /* also on checkboxes in cf-overlay and nl-overlay */
        var cf_checkboxes = $(":checkbox").change(function () {
            var x = $(":checkbox:checked").length;
            x > 0 ? formval.errorFalse($(this).closest("li.checkboxes"), "Okay") : formval.errorTrue($(this).closest("li.checkboxes"), "Error");
            x > 0 ? formval.errorJsSpecialFalse($("h2.required")) : formval.errorJsSpecialTrue($("h2.required"), langStr.getString('title_checkboxes'));
        });
        var cf_checkboxes = $("li.checkboxlist.mandatory :checkbox").blur(function () {
            var x = $(":checkbox:checked").length;
            x > 0 ? formval.errorFalse($(this).closest("li.checkboxlist")) : formval.errorTrue($(this).closest("li.checkboxlist"), "Error");
            x > 0 ? formval.errorJsSpecialFalse($("h2.required")) : formval.errorJsSpecialTrue($("h2.required"), langStr.getString('title_checkboxes'));
        });


        $("ol ul li input:checked").closest("li").removeClass("gray");

        /*
        * 
        * Training form
        * 
        */

        //          $("div.participants ol").attr("rel", 0);

        //          $("div.participants").after('<a href="#" class="add-participant">Deelnemer toevoegen</a>');

        //          $(".myform a.add-participant").click(function () {
        //              var x = $("div.participants ol:last-child").clone();
        //              formval.manipulateClone(x).appendTo("div.participants");
        //              formval.checkLast();
        //              formval.addRequired();
        //              return false;
        //          });

        //          $("div.participants ol li span.remove").live('click', function () {
        //              $(this).closest("ol").remove();
        //              formval.checkLast();
        //              formval.addRequired();
        //          });

        /*
        * Submit function for forms, revalidates all fields
        * 
        */

        $(".myform form, form.allform").submit(function () {

            var which_form = $(this).closest("div.myform").attr("id");

            var requiredInput = $("#" + which_form + " ol li.required > input, #" + which_form + " ol li.required > textarea");
            requiredInput.each(function () {
                formval.inlineValidation($(this));
            });

            formval.validateEmail($("#" + which_form + " li.email:last > input"));

            var are_checkboxes = $("#" + which_form + " ol ul > li input[type=checkbox]").length;

            var are_radiobuttons = $("#" + which_form + " li input[type=radio]").length;

            if (are_checkboxes > 0) {
                var checkboxes = $("#" + which_form + " ol ul li > input:checked").length;

                if (checkboxes < 1) {
                    formval.errorTrue($("ol ul"), langStr.getString('title_checkboxes'));
                }
                else {
                    formval.errorFalse($("ol ul"));
                }
            }

            nl_checkboxes = 1;

            if ($("#nl-overlay:visible ul.nl-issues").length != 0) {
                var nl_checkboxes = $("ul.nl-issues input:checked").length;
                if (nl_checkboxes < 1) {
                    formval.errorJsSpecialTrue($("h2.required"), langStr.getString('title_checkboxes'));
                }
                else {
                    formval.errorJsSpecialFalse($("h2.required"));
                }
                checkboxes = 1;
            }

            var requiredInputError = $("#" + which_form + " ol li.error");

            //alert(are_checkboxes + ' ' + checkboxes);

            if (requiredInputError.length > 0 || checkboxes < 1 || nl_checkboxes < 1) {
                return false;
            }

        });

    },
    init: function () {
        formval.execute();
    }
}

var initialisor = {
  init: function() {
    fontset.init();  
    translations.init();
    general.init();    
                twtBtn.init();
    /* lazyloader */
    if ($(".myform").length != 0) {
      formval.init();
    }
    if ($("div#showcase").length != 0) {
      showcase.init();
    }
    if ($("div.carousel").length != 0) {
      player.init();
    }      
  }
}


var SetRefinePanel = function () {
    if ($(".search-panel").hasClass("show")) {
        $(".search-panel").before('<a class="icon-3 refine open top-3" href="">' + langStr.getString('RefineThisSearch') + '</a>');
    }
    else {
        $(".search-panel").before('<a class="icon-3 refine close top-3" href="">' + langStr.getString('RefineThisSearch') + '</a>');
        $(".search-panel").addClass("textbrowse");
    }

    $("a.refine").click(function () {
        $(this).toggleClass("open", 0);
        $(this).next('div.search-panel').toggleClass('textbrowse');
        return false;
    }).addClass("pointer");
}

/* -------------------------  dom manipulations on document ready  -----------------------------*/

$(function () {

    /* set js on html element */
    $("html").addClass("js");
    try {
        $.preloadCssImages();
        $.preLoadImages("/images/i_success.png", "/images/i_success.png");
        $.preLoadImages("/images/i_error.png", "/images/i_success.png");
    }
    catch (e) { }

    if ($("a.contact-form").length != 0) { $("a.contact-form").fancybox(); }
    if ($("a.subscribe").length != 0) { $("a.subscribe").fancybox(); }
    if ($("a.contact-expert").length != 0) { $("a.contact-expert").fancybox(); }

    /* initialize all javascript, lazy load where necessary */
    initialisor.init();

    if ($("a.contact-form-priva").length != 0) {
        $("a.contact-form-priva").fancybox(
            {
                type: 'iframe',
                centerOnScroll: true,
                width: 460,
                height: 540
            });
    }

    if ($("a.showinoverlay").length != 0) {
        $("a.showinoverlay").fancybox(
        {
            type: 'iframe',
            centerOnScroll: true,
            width: 460,
            height: 540
        });
    }

    $("#sendingcoursesubscription").html(langStr.getString('SendingCourseSubscription'));

    /* open in new window if the link is of the type .pdf, .doc or .docx */
    $('a[href$=".pdf"], a[href$=".doc"], a[href$=".docx"]').attr("target", "_blank");
    $('.twt-btn a').attr("target", "_blank");

    SetRefinePanel();

    try {
        var prm = Sys.WebForms.PageRequestManager.getInstance();
        prm.add_endRequest(function () {
            SetRefinePanel();
            formval.init();
            formval.validateAll();
        });
    } catch (e) {
        // Do nothing
    }

    $('#search').submit(function () {
        return ($.trim($('#search input[type=text]').val()) != "");
    });


    $('#pvform').submit(function () {
        if ($('#pvform #productsearch').size() > 0)
            return ($.trim($('#pvform #productsearch').val()) != "");


        return true;
    });


});

/*******************************************************************************
Google Analytics tracking codes
*******************************************************************************/
$(document).ready(function () {
    //Contactformbutton van een container & Contactformverzendbutton (1)
    $(".contact-form-priva").click(function () {
        //alert('Google Analytics Contact button');
        //alert($(this).parent().find('h2').html());
        //alert(window.location.pathname + 'button.aspx');
        _gaq.push(['_trackPageview', window.location.pathname + 'button.aspx']);
    });

    //CTA van story/product (4)
    $(".googleanalytics4").click(function () {
        //alert('Google Analytics CTA');
        //alert(window.location.pathname);
        _gaq.push(['_trackPageview', window.location.pathname + '/contactbutton.aspx']);
    });

    //Dealer/Partnerfinder (8)
    $(".dealerpartnerfinder #find").click(function () {
        //alert('Google Analytics Dealerfinder Findbutton');
        _gaq.push(['_trackEvent', 'Dealerfinder', $('#segment').val()]); //Findbutton
    });
    // "#partnersearchresults li.partner" is tracked in partnerfinder.js - function initCompanyboxClick()

    //Printknop (9)
    $("#content .icons a.print").click(function () {
        //alert('Google Analytics Print');
        _gaq.push(['_trackEvent', 'Printknop', 'print']);
    });
    $("#content .icons a.rss").click(function () {
        //alert('Google Analytics RSS');
        _gaq.push(['_trackEvent', 'RSS', window.location.pathname]);
    });
    //Productfinder
    $("#searchproduct").click(function () {
        //alert('Google Analytics Productfinder');
        _gaq.push(['_trackEvent', 'Productfinder', $('#productsearch').val()]); //Findbutton
    });
    
});

function HandleGoogleAnalytics(what) {
    switch (what) {
        case "1":
            // The result of a filled out contactform is handled in PrivaAjaxcontactForm
            //alert(window.location.pathname + 'bedankt.aspx');
            _gaq.push(['_trackPageview', window.location.pathname + 'bedankt.aspx']);
            break;
        case "3":
            // The result of a filled out contactform is handled in SiteCourseSubscribeForm
            //alert(window.location.pathname + 'send.aspx');
            _gaq.push(['_trackPageview', window.location.pathname + 'send.aspx']);
            //});
            break;
        default:
            // Do nothing
    }
}

function redirecthostname() {
    var loc = location.hostname;
    //alert(loc);
    if (loc == 'privamx.test.tamtam.nl' || loc == 'www.privamx.test.tamtam.nl') {
        window.location.replace("http://priva.test.tamtam.nl/nl/products/energymirror");
    }
}

