var latest;

$(document).ready(function() {

    //Tabs
    $('.DetailTabs a').click(function() {
        //Content
        $('.DetailTab').hide();
        var contentdivname = '#' + $(this).attr('id') + '_content';
        $(contentdivname).show();

        //Tab        
        cleartabs();
        $(this).addClass('selected');
    });

    //Masks
    $('.zip-1').mask('999 99');
    $('.personnummer-1').mask('999999-9999', { placeholder: "_" });
    $('.personnummer-2').mask('999999-9999', { placeholder: "_" });
    $('.personnummer-3').mask('99999999999', { placeholder: "_" });
    $('.personnummer-5').mask('******-****', { placeholder: "-" });
    $(".stars").find("input").attr("title", $("#rating").html());
    $(".stars").find("input").addClass("star");

    //Menu headers
    $("#hozmenu-bottom .mh").mouseenter(function() {
        var id = "#" + $(this).attr("id");
        $(latest + " ul").removeShadow(); latest = id; //fix to remove traceshadows (works?)
        $(id + " ul").dropShadow();
    });

    //Menu headers
    $("#hozmenu-bottom .mh").mouseleave(function() {
        var id = "#" + $(this).attr("id");
        $(id + " ul").removeShadow();
        //$("#hozmenu-bottom .mh ul").removeShadow(); //another way to remove possible traceshadows
        $(id + " ul").hide();
    });


    $(".stars").find("label").css('display', 'none');
    $('input.star').rating();
    $(".stars a").removeAttr("title");
    UpdateForwBack();

    $('div.paging a').click(function(e) {
        e.preventDefault();
        var pageid = $(this).html();
        pageid = parseInt($(this).attr('href').slice(6));

        if (isNaN(pageid)) { pageid = -1; } else { pageid -= 1; }

        $("#plPageID input").val(pageid);
        PlAjax();
    });

    if (/#page-(\d+)/.test(location.href)) {
        pageid = /#page-(\d+)/.exec(location.href)[1];
        if (isNaN(pageid)) { pageid = -1; } else { pageid -= 1; }
        $("#plPageID input").val(pageid);
        PlAjax();
    }
    $('span.payinfo').each(function() {

        if ($(this).text() != "")
            $(this).siblings("a.payinfo").show();
    });
    $('a[rel*=facebox]').facebox();
    $("#login .login-button").live("click", function() {
        $("input.login").val($(this).closest("ul").find('#login').val());
        $("input.password").val($(this).closest("ul").find('#password').val());

        __doPostBack("ctl00$ucPopup$btnDoLogin", "");
    });

    $("h2.eventtitle").each(function() {
        var a = this;
        $("<li><span>" + $(this).text() + "</span></li>").appendTo($("#events")).click(function() {
            //alert($(a).text());
            //alert($(this).html());
            $("#eventswrapper #events li.active").removeClass('active');
            $(this).addClass('active');
            $("#eventscontent > li").hide();
            $(a).parents("li").show();
        });
    });
    $("#eventscontent > li:not(:first)").hide();
    $("#events li:first").addClass('active');

    $(this).find(".tree dl:not(.expanded) > dd").hide();
    $(".tree .expand").click(function(e) {
    e.preventDefault();
        $(this).parent().parent().toggleClass("expanded");
        $(this).closest("dl").children("dd").slideToggle(100).toggleClass("expanded");
        return false;
    });
    $(".hidBroughtArticleGroupID").val("");

    // AjaxSearchField
    $(".search-dummy").click(function(e) {
        var searchButtonId = $(".do-search").attr("id").replace(/_/g, "$");
        e.preventDefault();
        if ($(".AjaxSearchField-Results-").is(":visible")) {

            var doPostBack = true;
            $(".AjaxSearchField-Results-").find(".item").each(function() {
            if ($(this).hasClass("nav")) {
                    document.location = 'http://' + document.location.host + $(this).find('input.url').val();
                    doPostBack = false;
                }

            });

            if (doPostBack) {
                javascript: __doPostBack(searchButtonId, '');
            }
        }
        else {
            javascript: __doPostBack(searchButtonId, '');
        }
    });

  
});

function UpdateForwBack() {
    var pageno = parseInt($("#plPageID input").val());
    var max = $('div.paging a:not(.nav)').length - 1;


    if (pageno > 0) { $('div.paging a.back').addClass('enabled'); $('div.paging a.first').addClass('enabled'); } else { $('div.paging a.back').removeClass('enabled'); $('div.paging a.first').removeClass('enabled'); }
    if (pageno < max) { $('div.paging a.forw').addClass('enabled'); $('div.paging a.last').addClass('enabled'); } else { $('div.paging a.forw').removeClass('enabled'); $('div.paging a.last').removeClass('enabled'); }

    if (pageno < 0) { pageno = 0; }
    if (pageno + 1 > max) {
        $('div.paging a.nav.forw').attr('href', '#page-' + (max + 1));
    } else {
        $('div.paging a.nav.forw').attr('href', '#page-' + (pageno + 2));
    }
    if (pageno <= 0) {
        $('div.paging a.nav.back').attr('href', '#page-1');
        $('div.paging a.nav.back').removeClass('enabled')
    } else {
        $('div.paging a.nav.back').attr('href', '#page-' + (pageno));
    }
}
function cleartabs() {
    $('.DetailTabs a').removeClass('selected');
}

var __defaultFired = false;

function WebForm_FireDefaultButton(event, target) {
    var element = event.target || event.srcElement;

    if (!__defaultFired && event.keyCode == 13 && !(element && (element.tagName.toLowerCase() == "textarea"))) {
        var defaultButton;

        if (__nonMSDOMBrowser)
            defaultButton = document.getElementById(target);
        else
            defaultButton = document.all[target];

        if (defaultButton) {
            if (typeof (defaultButton.click) != "undefined")
                defaultButton.click();
            else
                eval(unescape(defaultButton.href.replace("javascript:", "")));

            event.cancelBubble = true;

            if (event.stopPropagation) event.stopPropagation();
            return false;
        }
    }
    return true;
}
function OrderBy(type) {
     $("#plOrderBy input").val(type);
    if ($("#plPageID input").val() != -1) { $("#plPageID input").val(0); }
}

$('.filters select').live("change", function() {
    var substr = $(this).val().split(',');
    PlFilter(substr[0], substr[1], substr[2], substr[3], substr[4]);
    PlAjax();
});

function PlFilter(type, propvalue, value, orderid, meta) {
    if (type == 1)
    {
        $("#plFilterManu input").val(value);
        if (value == -1) { $("#selections .filterlist-A").hide(); $("#filter .filters .filterlist-A").show(); } else { $("#filter .filters .filterlist-A").hide(); $("#selections .filterlist-A").show(); $("#selections .filterlist-A .value").html(meta); }
    } else if (type == 2) {
        if (value == -1) { $("#plFilterPriceFrom input").val(-1); $("#plFilterPriceTo input").val(-1); }
        if (value == 1) { $("#plFilterPriceFrom input").val(-1); $("#plFilterPriceTo input").val(100); }
        if (value == 2) { $("#plFilterPriceFrom input").val(100); $("#plFilterPriceTo input").val(200); }
        if (value == 3) { $("#plFilterPriceFrom input").val(200); $("#plFilterPriceTo input").val(500); }
        if (value == 4) { $("#plFilterPriceFrom input").val(500); $("#plFilterPriceTo input").val(1000); }
        if (value == 5) { $("#plFilterPriceFrom input").val(1000); $("#plFilterPriceTo input").val(2000); }
        if (value == 6) { $("#plFilterPriceFrom input").val(2000); $("#plFilterPriceTo input").val(5000); }
        if (value == 7) { $("#plFilterPriceFrom input").val(5000); $("#plFilterPriceTo input").val(10000); }
        if (value == 8) { $("#plFilterPriceFrom input").val(10000); $("#plFilterPriceTo input").val(20000); }
        if (value == 9) { $("#plFilterPriceFrom input").val(20000); $("#plFilterPriceTo input").val(50000); }
        if (value == 10) { $("#plFilterPriceFrom input").val(50000); $("#plFilterPriceTo input").val(100000); }
        if (value == 11) { $("#plFilterPriceFrom input").val(100000); $("#plFilterPriceTo input").val(-1); }
        if (value == -1) { $("#selections .filterlist-B").hide(); $("#filter .filters .filterlist-B").show(); } else { $("#filter .filters .filterlist-B").hide(); $("#selections .filterlist-B").show(); $("#selections .filterlist-B .value").html(meta); }

    } else if (type == 3) {
        $("#plFilterProp" + orderid + " input").val(value);
        if (value == -1) { $("#selections .filterlist-" + propvalue).hide(); $("#filter .filters .filterlist-" + propvalue).show(); } else { $("#filter .filters .filterlist-" + propvalue).hide(); $("#selections .filterlist-" + propvalue).show(); $("#selections .filterlist-" + propvalue + " .value").html(meta); }
    }

    if ($("#plPageID input").val() != -1) { $("#plPageID input").val(0); }
}

function PlAjax() {
    var typeid = $("#pltypeid input").val();
    var queryvalue = $("#plQueryValue input").val();
    var pageid = parseInt($("#plPageID input").val());
    var orderby = $("#plOrderBy input").val();
    var FManu = $("#plFilterManu input").val();   
    var FPriceFrom = $("#plFilterPriceFrom input").val();
    var FPriceTo = $("#plFilterPriceTo input").val();
    var FProp1 = $("#plFilterProp1 input").val();
    var FProp2 = $("#plFilterProp2 input").val();
    var FProp3 = $("#plFilterProp3 input").val();
    
    $('div.paging a').removeClass('active');
    if (pageid > -1) { $('div.paging a:not(.nav)').eq(pageid).addClass('active'); window.location.hash = '#page-' + (pageid + 1); }
    if (pageid == -1) { window.location.hash = '#page-all'; }
    
    UpdateForwBack();
    var strtype = "";

    if (typeid == 1) {
        strtype = "TreeID=" + queryvalue + "&typeid=" + typeid;
    } else if (typeid == 2) {
        strtype = "manufacture=" + queryvalue + "&typeid=" + typeid;
    } else if (typeid == 3) {
    strtype = "q=" + queryvalue + "&typeid=" + typeid;
    } else if (typeid == 4) {
    strtype = "tag=" + queryvalue + "&typeid=" + typeid;
    }


    if (FProp1 != -1) {
        strtype += "&prop1=" + FProp1
    }
    if (FProp2 != -1) {
        strtype += "&prop2=" + FProp2
    }
    if (FProp3 != -1) {
        strtype += "&prop3=" + FProp3
    }
    if (FPriceFrom != -1) {
        strtype += "&pricefrom=" + FPriceFrom
    }
    if (FPriceTo != -1) {
        strtype += "&priceto=" + FPriceTo
    }
    if (FManu != -1) {
        strtype += "&manufacture=" + FManu
    }

 
    //alert("/product/listajax.aspx?" + strtype + "&page=" + pageid + "&orderby=" + orderby);
    //$("#productlist").load("/product/listajax.aspx?" + strtype + "&page=" + pageid + "&orderby=" + orderby + " #specialdiv");
    //alert("/product/listajax.aspx?" + strtype + "&page=" + pageid + "&orderby=" + orderby);
    $.get("/product/listajax.aspx?" + encodeURI(strtype) + "&page=" + pageid + "&orderby=" + orderby, function(data) {
    //alert(data);
        $("#productlist").html($(data).find("#specialdiv").html());
        
    });
}
function AddToCart(grpid) {
    $("#Iwbt input").val(grpid);
    //alert($("#Iwbt input").val());
    __doPostBack("ctl00$ContentPlaceHolder1$btnDoBuy", "");
}

function SortProductList(type) {

    var $link = $("div.sorting a[href*='SortProductList(" + type + ")']");
    $link.parent().addClass("active");
    $link.parent().siblings().removeClass("active");

    if (type != 7 && type != 8) {
        if ($link.data("desc") == undefined || !$link.data("desc")) {
            $link.data("desc", true);
        } else {
            $link.data("desc", false);
            type = "-" + type;
        }
    }
    $("#plOrderBy input").val(type);
    if ($("#plPageID input").val() != -1) { $("#plPageID input").val(0); }
}
   

//// Imageslider

function SliderImg(src, alt, target, href) {
    this.src = src;
    this.alt = alt;
    this.target = target;
    this.href = href;
}

$.fn.fortusslider = function(options) {
    // default configuration properties
    var defaults = {
        fadespeed: 1500,
        timeoutspeed: 4500,
        navigationArrows: false,
        images: null
    };

    if (options.images == null) { return; } else { images = options.images; }

    var options = $.extend(defaults, options);
    this.each(function() {
        var $t = $(this);
        var arrPos = 0;
        var liActive = "li:first";

        var imageHeight = 0;
        var img = new Image();

        $(img).load(function() {
            imageHeight = this.height;
            $t.css("height", imageHeight + "px");
            if (options.navigationArrows && images.length != 1) {
                enableNavigationArrows();
            }
        }).attr({ 'src': images[0].src });

        var li1Content = '<li style="z-index:2;cursor:pointer;"><a href="' + images[0].href + '" target="' + images[0].target + '"><img title="' + images[0].alt + '" alt="' + images[0].alt + '" src="' + images[0].src + '" /></a></li>';

        if (images[0].href == '') {
            li1Content = '<li style="z-index:2;cursor:default;"><a href="javascript:;" target="_self"><img title="' + images[0].alt + '" alt="' + images[0].alt + '" src="' + images[0].src + '" /></a></li>';
        }

        $t.append(li1Content);

        if (images.length == 1) {
            $t.siblings("div.click-boxes").remove();
        } else {
            var li2Content = '<li style="z-index:1;cursor:pointer;"><a href="' + images[1].href + '" target="' + images[1].target + '"><img title="' + images[1].alt + '" alt="' + images[1].alt + '" src="' + images[1].src + '" /></a></li>';
            if (images[1].href == '') {
                li2Content = '<li style="z-index:1;cursor:default;"><a href="javascript:;" target="_self"><img title="' + images[1].alt + '" alt="' + images[1].alt + '" src="' + images[1].src + '" /></a></li>';
            }

            $t.append(li2Content);
            for (var i = 0; i < images.length; i++) {
                $t.siblings("div.click-boxes").append('<div class="clickbox clickbox-inactive clickbox-image' + i + '"></div>');
                $t.siblings("div.click-boxes").find(".clickbox-image0").removeClass("clickbox-inactive");
            }
            $t.siblings("div.click-boxes").append('<div style="clear:both;"></div>');

            animate();

            $t.siblings("div.click-boxes").find("div.clickbox").click(function(e) {
                $t.siblings("div.click-boxes").find("div.clickbox").addClass("clickbox-inactive");
                $(this).removeClass("clickbox-inactive");
                arrPos = parseInt($(this).attr("class").match(/clickbox-image(\d+)/)[1]);
                var liInactive = "li:first"; if (liActive == "li:first") { liInactive = "li:last"; }
                $t.find(liInactive).find("img").attr("src", images[arrPos].src);
                $t.find(liInactive).find("img").attr("alt", images[arrPos].alt);
                $t.find(liInactive).find("img").attr("title", images[arrPos].alt);
                if (images[arrPos].href != '') {
                    $t.find(liInactive).find("a").attr("href", images[arrPos].href);
                    $t.find(liInactive).find("a").attr("target", images[arrPos].target);
                    $t.find(liInactive).find("a").css("cursor", "pointer");
                } else {
                    $t.find(liInactive).find("a").attr("href", "javascript:;");
                    $t.find(liInactive).find("a").css("cursor", "default");
                    $t.find(liInactive).find("a").attr("target", "_self");
                }
            });

        }

        function animate() {
            if (images[arrPos] == undefined) { arrPos = 0; }
            $t.find(liActive).find("img").attr("src", images[arrPos].src);
            $t.find(liActive).find("img").attr("alt", images[arrPos].alt);
            $t.find(liActive).find("img").attr("title", images[arrPos].alt);
            if (images[arrPos].href != '') {
                $t.find(liActive).find("a").attr("href", images[arrPos].href);
                $t.find(liActive).find("a").attr("target", images[arrPos].target);
                $t.find(liActive).find("a").css("cursor", "pointer");
            } else {
                $t.find(liActive).find("a").attr("href", "javascript:;");
                $t.find(liActive).find("a").css("cursor", "default");
                $t.find(liActive).find("a").attr("target", "_self");
            }
            if (liActive == "li:first") { liActive = "li:last"; } else { liActive = "li:first"; }
            var liInactive = "li:first"; if (liActive == "li:first") { liInactive = "li:last"; }
            arrPos += 1;

            setTimeout(function() {
                $t.find(liInactive).find("img").fadeOut(defaults.fadespeed);
                $t.find(liActive).css("z-index", "1");
                $t.find(liInactive).css("z-index", "2");
                $t.find(liActive).find("img").show();
                $t.siblings("div.click-boxes").find("div.clickbox").addClass("clickbox-inactive");
                if (images[arrPos] == undefined) { arrPos = 0; }
                $t.siblings("div.click-boxes").find("div.clickbox-image" + arrPos).removeClass("clickbox-inactive");
                animate();
            }, options.timeoutspeed);
        }

        function enableNavigationArrows() {
            var navArrowsStyle = 'style="top:' + Math.round((imageHeight / 2) - 20) + 'px;';
            $t.siblings("div.click-boxes").after('<div ' + navArrowsStyle + 'left:0px;" class="nav-left"></div><div ' + navArrowsStyle + ' right:0px;" class="nav-right"></div>');
            $t.parents("div.spImageSlider-").attr("style", "position:relative");
            $t.siblings("div.nav-right, div.nav-left").click(function() {
                var cbIndex = 0;
                $t.siblings("div.click-boxes").find("div.clickbox").each(function(i) {
                    if (!$(this).hasClass("clickbox-inactive")) {
                        cbIndex = i;
                        return false;
                    }
                });
                if ($(this).hasClass("nav-right")) {
                    cbIndex += 1;
                    if (images.length <= cbIndex) { cbIndex = 0; }
                } else {
                    if (cbIndex == 0) { cbIndex = (images.length - 1); } else { cbIndex -= 1; }
                }
                $t.siblings("div.click-boxes").find("div.clickbox-image" + cbIndex).click();
            });
        }


    });

}

$(function() {
    // CustomMailForm
    $(".divEmailCustom .submit").click(function() {

        $(".EmailCustomValidate").remove();
        var obl = '<span class="EmailCustomValidate" style="color: red;">&nbsp;*</span>';
        var obl2 = '<br><span class="EmailCustomValidate" style="color: red;">&nbsp;* = &auml;r obligatorisk.</span>';
        var subr = true;
        $(".divEmailCustom").children().each(function() {
            if ($(this).attr("required") == "true" && $(this).val() == "") {
                $(this).after(obl);
                subr = false;
            }
        });
        if (subr) { __doPostBack("ctl00$ContentPlaceHolder1$CustomMailForm_doPostForm", ""); } else { $(".divEmailCustom .submit").after(obl2); }
    });

    $(".spPoll span.mode-vote a").live("click", function() {
        var me = $(this).parents(".spPoll");
        var resultsIsVisible = $(this).parents(".spPoll").find("div.results").is(":visible");

        if (resultsIsVisible) {
            $(me).find("div.results").hide();
            $(me).find("div.vote").fadeIn(300);
        } else {
            $(me).find("div.vote").hide();
            $(me).find("div.results").fadeIn(300);
        }

    });

    $(".spPoll a.mode-results").live("click", function() {
        var me = $(this).parents(".spPoll");
        var voteIsVisible = $(this).parents(".spPoll").find("div.vote").is(":visible");

        if (voteIsVisible) {
            $(me).find("div.vote").hide();
            $(me).find("div.results").show();
        } else {
            $(me).find("div.results").hide();
            $(me).find("div.vote").show();
        }
    });

    $('div.spPoll').each(function() {
        var PollID = $(this).attr('pid');
        var VoteMode = $(this).find('input#vote-mode').attr('value');

        if (VoteMode == '12') {
            $(this).find("div.results").hide();
        }
        else if (VoteMode == '1') {
            $(this).find('a.mode-results').remove();
            $(this).find('span.mode-vote').remove();
        }
        else {
            $(this).find('a.mode-results').remove();
            $(this).find('span.mode-vote').remove();
            $(this).find('a.mode-results').remove();
        }
    });

    // MailForm
    $("div.cMailForm a.submit").click(function() {

        var readyToSubmit = MailForm_Validate($(this).parents("div.cMailForm"));

        if (readyToSubmit) {

            var controls = $(this).parents("div.cMailForm").find("*");
            MailForm_Recipient = $(this).parents("div.cMailForm").attr("recipient");
            MailForm_Subject = $(this).parents("div.cMailForm").attr("header");

            $(controls).each(function() {

                if ($(this).get(0).tagName.toLowerCase() == "input") {
                    if ($(this).attr("type") == "text") { MailForm_AddControl("text", $(this)); }
                    if ($(this).attr("type") == "radio") { MailForm_AddControl("radio", $(this)); }
                    if ($(this).attr("type") == "checkbox") { MailForm_AddControl("checkbox", $(this)); }
                }
                else if ($(this).get(0).tagName.toLowerCase() == "textarea") { MailForm_AddControl("textarea", $(this)); }
                else if ($(this).get(0).tagName.toLowerCase() == "select") { MailForm_AddControl("select", $(this)); }

            });

            $("input.hidPostMailForm").val(MailForm_XML + "{/*/items*/}");
            MailForm_XML = "";
            __doPostBack("ctl00$ucMailForm1$btnMailForm", "");

        } else { $(this).after('<span class="cMailFormValidate" style="color: red;"><br>&nbsp;* = &auml;r obligatorisk.</span>'); }

    });

});

	function MailForm_Validate(mailform) {

	    var success = true;

	    $("span.cMailFormValidate").remove();
	    var validationHtml1 = '<span class="cMailFormValidate" style="color: red;">&nbsp;*</span>';

	    $(mailform).find("input[type=text]").each(function() {
	        if ($(this).attr("required") == "true" && $(this).val() == "") {
	            $(this).after(validationHtml1);
	            success = false;
	        }
	        else if ($(this).attr("email") == "true") {
	            var filter = /^([\w-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/;
	            if (filter.test($(this).val())) { } else {
	                $(this).after(validationHtml1);
	                success = false;
	            }
	        }
	        else if ($(this).attr("confirm") != undefined) {
	            var confirmEl = "." + $(this).attr("confirm");
	            if ($(this).val() != $(this).parents("div.cMailForm").find(confirmEl).val()) {
	                $(this).after(validationHtml1);
	                success = false;
	            }
	        }
	    });

	    $(mailform).find("textarea").each(function() {	    
	        if ($(this).attr("required") && $(this).val().replace(/^\s+|\s+$/g, '').length == "0") {
	            $(this).after(validationHtml1);
	            success = false;
	        }
	    });

	    $(mailform).find("select").each(function() {
	        if ($(this).attr("required") && $(this).val() == "0") {
	            $(this).after(validationHtml1);
	            success = false;
	        }
	    });
    
	    return success;
	}

	function MailForm_AddControl(type, control) {

	    var s = "";
	    
	    if (MailForm_XML == "") {
	        s = "{/*?xml version=\"1.0\" encoding=\"utf-8\" ?*/}{/*items*/}";
	        s += "{/*item*/}{/*answer*/}" + MailForm_FixChars(MailForm_Recipient) + "{/*/answer*/}" + "\n";
	        s += "{/*label*/}" + MailForm_FixChars(MailForm_Subject) + "{/*/label*/}{/*/item*/}" + "\n";
	    }

	    if (type == "text" || type == "textarea" || type == "select") {
	        if ($(control).attr("confirm") != undefined) { return; }
	        s += "{/*item*/}" + "\n";
	        s += "{/*label*/}" + MailForm_FixChars($(control).attr("name")) + "{/*/label*/}" + "\n";
	        s += "{/*answer*/}" + MailForm_FixChars($(control).val()) + "{/*/answer*/}" + "\n";
	        if ($(control).attr("required") == "true") { s += "{/*required*/}true{/*/required*/}" + "\n"; } else { s += "{/*required*/}false{/*/required*/}" + "\n"; }
	        if ($(control).attr("email") == "true") { s += "{/*email*/}true{/*/email*/}" + "\n"; } else { s += "{/*email*/}false{/*/email*/}" + "\n"; }
	        s += "{/*/item*/}";
	    }

	    else if (type == "radio" && $(control).is(':checked')) {
	            s += "{/*item*/}" + "\n";
	            s += "{/*label*/}" + MailForm_FixChars($(control).attr("name")) + "{/*/label*/}" + "\n";
	            s += "{/*answer*/}" + MailForm_FixChars($(control).val()) + "{/*/answer*/}" + "\n";
	            s += "{/*required*/}false{/*/required*/}" + "\n"; 
	            s += "{/*email*/}false{/*/email*/}" + "\n";
	            s += "{/*/item*/}";
	    }

        else if (type == "checkbox") {
            s += "{/*item*/}" + "\n";
            s += "{/*label*/}" + $(control).attr("name") + "{/*/label*/}" + "\n";
            if ($(control).is(':checked')) { s += "{/*answer*/}Yes{/*/answer*/}" + "\n"; } else { s += "{/*answer*/}No{/*/answer*/}" + "\n"; }	            
            s += "{/*required*/}false{/*/required*/}" + "\n";
            s += "{/*email*/}false{/*/email*/}" + "\n";
            s += "{/*/item*/}";
        }
   
	    MailForm_XML += s;
	}

	function MailForm_FixChars(value) {
	    value = value.replace(/&/g, "&amp;");
	    value = value.replace(/'/g, "&apos;");
	    value = value.replace(/\\/g, "&quot;");
	    value = value.replace(/>/g, "&gt;");
	    value = value.replace(/</g, "&lt;");
	    return value;        
	}

	var MailForm_Recipient = "";
	var MailForm_Subject = "";
	var MailForm_XML = "";
    
    // AjaxSearchField
	(function($) {

	    $.fn.AjaxSearchField = function(options) {

	        if ($(this).data("AjaxSearchField")) {
	            return;
	        }

	        $(this).data("AjaxSearchField", true);

	        var settings = {
	            'useLoadingAnimation': true,
	            'translation': { 'showAllResults': 'Visa alla resultat' }
	        };

	        return this.each(function() {
	            if (options) {
	                $.extend(settings, options);
	            }
	            var m = $(this);

	            m.attr('autocomplete', 'off');
	            $("body").append('<div class="AjaxSearchField-Cache" style="display:none;"></div>');
	            m.after('<div class="AjaxSearchField-Results-" style="display:none;"><div class="show-all"><a href="javascript:;">' + settings.translation.showAllResults + '</a></div><div class="items"></div></div>');

	            var cacheEl = $('div.AjaxSearchField-Cache');
	            var results = $("div.AjaxSearchField-Results- div.items");

	            var animation = null;
	            if (settings.useLoadingAnimation) {
	                m.before('<style type="text/css">div.asf-animation{display:none;position:relative;}div.asf-animation div {left:' + (m.width() - 16) + 'px;width:16px;height:16px;position:absolute;background-image:url("/_gfx/ajaxloader.gif"); }</style><div class="asf-animation"><div></div></div>');
	                animation = $("div.asf-animation");
	            }

	            var searchString = null;
	            var navigationIndex = 0;
	            var resultsCount = 0;

	            var ignoreKeyCodes = new Array(13, 9, 16, 17, 18, 19, 20, 33, 34, 35, 36, 37, 39, 45, 46, 91, 92, 93, 96, 106, 107, 109, 110, 111, 112, 113, 114,
                            115, 116, 117, 118, 119, 120, 121, 122, 123, 144, 145, 186, 187, 188, 189, 190, 191, 192, 219, 220, 221, 222);

	            m.keyup(function(e) {

	                if ((m.val().length < 3 && e.keyCode == 8) || e.keyCode == 27) {
	                    if (settings.useLoadingAnimation) { animation.hide(); }
	                    results.parent().hide();
	                    navigationIndex = 0;
	                    resultsCount = 0;
	                    return false;
	                } else if (e.keyCode == 40 || e.keyCode == 38) {

	                    if (results.parent().is(":visible")) {

	                        if (resultsCount == 0) {
	                            results.find(".item").each(function(i) {
	                                resultsCount = i;
	                            });
	                            resultsCount += 1;
	                        }

	                        if (e.keyCode == 40) { navigationIndex += 1; } else { navigationIndex -= 1; }

	                        if (navigationIndex <= 0) {
	                            navigationIndex = 0;
	                            results.parent().hide();
	                        }
	                        else if (navigationIndex >= resultsCount) {
	                            navigationIndex = resultsCount;
	                        }

	                        results.find('.item').removeClass("nav");
	                        results.find('.item:nth-child(' + navigationIndex + ')').addClass("nav");

	                    }
	                } else {

	                    for (var i = 0; i <= (ignoreKeyCodes.length - 1); i++) {
	                        if (e.keyCode == ignoreKeyCodes[i]) {
	                            return false;
	                        }
	                    }

	                    searchString = m.val().replace(/^\s+|\s+$/g, '').toLowerCase();
	                    if (searchString.length > 2) {

	                        if (findCacheElement(searchString) == null) {
	                            if (settings.useLoadingAnimation) {
	                                animation.show();
	                            }
	                            $.post("/misc/ajax/AjaxSearch.ashx", { searchstr: searchString }, function(data) {

	                                if (findCacheElement(searchString) == null) {
	                                    data = data.toString().replace("{OP}", "");
	                                    cacheEl.append(data);
	                                }

	                                appendSearchResult(searchString);

	                                if (settings.useLoadingAnimation && $(data).find("div.s").text() == m.val().replace(/^\s+|\s+$/g, '').toLowerCase()) {
	                                    animation.hide();
	                                }

	                            });

	                        } else {
	                            appendSearchResult(searchString);
	                            if (settings.useLoadingAnimation && m.val().replace(/^\s+|\s+$/g, '').toLowerCase() == searchString) {
	                                animation.hide();
	                            }
	                        }

	                    } else {
	                        results.parent().hide();
	                        navigationIndex = 0;
	                        resultsCount = 0;
	                    }
	                }

	            });
	            m.keypress(function(e) {
	                if (e.keyCode == 13 && results.is(":visible")) {
	                    document.location = 'http://' + document.location.host + $(this).find('input.url').val();
	                }
	            });


	            results.find(".item").live("click", function() {
	                document.location = 'http://' + document.location.host + $(this).find('input.url').val();
	            });


	            results.live("mouseover", function() {
	                $(this).find('.item').removeClass("nav");
	                navigationIndex = 0;
	            });

	            results.parent().find("div.show-all a").click(function() {
	                m.siblings(".search-dummy").click();
	            });

	            $("body").click(function() {
	                results.parent().hide();
	            });

	        });

	        function appendSearchResult(searchString) {
	            var resEl = $("div.AjaxSearchField-Results- div.items");
	            resEl.html('');
	            var alt = '';
	            var exists = false;

	            var cacheRes = findCacheElement(searchString);
	            if (cacheRes != null) {
	                cacheRes.find("div.c div").each(function(i) {
	                    if (i = 1) { exists = true; }
	                    resEl.append('<div class="item' + alt + '"><input class="url" type="hidden" value="' + $(this).attr('url') + '" /><img src="' + $(this).attr('img') + '" /><span class="product">' + $(this).text() + '</span> <span class="price">' + $(this).attr('price') + '</span></div>');
	                    if (alt == '') { alt = ' alt'; } else { alt = ''; }
	                });
	            }
	            if (exists) { resEl.parent().show(); } else { resEl.parent().hide(); }
	        }

	        function findCacheElement(searchString) {
	            var ret = null;
	            $('div.AjaxSearchField-Cache').find("div.it div.s").each(function() {
	                if ($(this).text() == searchString) {
	                    ret = $(this).parent();
	                    return false;
	                }
	            });
	            return ret;
	        }

	    };
	})(jQuery);

	(function($) {

	    $.fn.imageDetailZoom = function(options) {
	        var mainImage = $("img[id*='mainImage']");

	        if (mainImage.attr("src").substring(mainImage.attr("src").lastIndexOf('/') + 1) == 'noimage.jpg'
	        || $(this).data("imageDetailZoom")) {
	            return;
	        }

	        $(this).data("imageDetailZoom", true);

	        var settings = $.extend({
	            'imageSizeSmall': { width: 0, height: 0 },
	            'imageSizeLarge': { width: 0, height: 0 },
	            'zoomPercentage': 0,
	            'openInFaceboxOnClick': false
	        }, options);

	        return this.each(function() {
	            var m = $(this);

	            var thumbnails = $("div#productthumbnails");
	            var hasThumbnails = (thumbnails.find("img.thumbnail").length > 0);

	            var multipl = 0;
	            if (settings.zoomPercentage >= 100) {
	                multipl = (settings.zoomPercentage / 100);
	            } else {
	                multipl = (settings.imageSizeLarge.width / settings.imageSizeSmall.width);
	            }

	            var calc = {
	                cursor: { startPosition: { left: 0, top: 0 }, startOffset: { left: 0, top: 0 }, width: Math.round((settings.imageSizeSmall.width / multipl) * Math.pow(10, 2)) / Math.pow(10, 2), height: Math.round((settings.imageSizeSmall.height / multipl) * Math.pow(10, 2)) / Math.pow(10, 2), absPositionSmallImage: { right: 0, bottom: 0} },
	                imageLarge: { width: (multipl * settings.imageSizeSmall.width), height: (multipl * settings.imageSizeSmall.height), absPosition: { right: 0, bottom: 0} }
	            };

	            var isIE8OrOlder = false;
	            if ($.browser.msie) {
	                isIE8OrOlder = (parseFloat($.browser.version) < 9);
	            }

	            var mainImageLink = $(this).find("a[id*='mainImageLink']");
	            var html = '<style type="text/css">';
	            html += 'div.imageDetailZoom {overflow:hidden;}';
	            html += 'div.imageDetailZoom div.idz-cursor{cursor:' + (isIE8OrOlder ? 'crosshair' : 'none') + ';position:absolute;background-color:white;border:1px solid #C4C4C4;width:' + calc.cursor.width + 'px;height:' + calc.cursor.height + 'px;opacity:0.6;filter:alpha(opacity=60);}';
	            html += 'div.imageDetailZoom div.idz-fullsize{display:none;position:absolute;width:' + settings.imageSizeSmall.width + 'px;height:' + settings.imageSizeSmall.height + 'px;z-index: 9999;left:' + (settings.imageSizeSmall.width + 15) + 'px;top:0;overflow:hidden;}';
	            html += 'div.imageDetailZoom div.idz-fullsize img{position:absolute;width:' + calc.imageLarge.width + 'px;height:' + calc.imageLarge.height + 'px}';
	            html += '</style>';
	            html += '<div class="idz-cursor" style="display:none;"></div>';
	            m.prepend(html);
	            m.after('<div class="idz-fullsize"><img src="' + mainImageLink.attr('href') + '" /></div>');
	            m.parents("div#imagewrapper").addClass('imageDetailZoom');
	            m.parents("div.detail-wrapper").css("position", "relative");
	            mainImage.removeAttr("title").attr("style", "width:" + settings.imageSizeSmall.width + "px;height:" + settings.imageSizeSmall.height + "px;");
	            var cursor = $('div.imageDetailZoom div.idz-cursor');
	            var largeImageWrapper = $('div.imageDetailZoom div.idz-fullsize');
	            var largeImage = $('div.imageDetailZoom div.idz-fullsize img');
	            var setValues = true;
	            var inFade = false;
	            m.mousemove(function(e) {
	                if (hasThumbnails) {
	                    largeImage.attr("src", thumbnails.find("img.active").parent().attr("href"));
	                }
	                cursor.show();
	                if (!inFade) {
	                    largeImageWrapper.fadeIn();
	                }
	                if (setValues) {
	                    setValues = false;
	                    var co = cursor.offset();
	                    calc.cursor.startOffset.left = co.left;
	                    calc.cursor.startOffset.top = co.top;
	                    calc.cursor.startPosition.left = (co.left + (calc.cursor.width / 2));
	                    calc.cursor.startPosition.top = (co.top + (calc.cursor.height / 2));
	                    calc.cursor.absPositionSmallImage.right = (settings.imageSizeSmall.width - calc.cursor.width);
	                    calc.cursor.absPositionSmallImage.bottom = (settings.imageSizeSmall.height - calc.cursor.height);
	                    calc.imageLarge.absPosition.bottom = (0 - (calc.cursor.absPositionSmallImage.bottom * multipl));
	                    calc.imageLarge.absPosition.right = (0 - (calc.cursor.absPositionSmallImage.right * multipl));
	                }

	                var currentCursorPosition = {
	                    left: (e.pageX - calc.cursor.startPosition.left),
	                    top: (e.pageY - calc.cursor.startPosition.top)
	                };

	                var zoomPosition = {
	                    left: function() { return Math.round((0 - (multipl * currentCursorPosition.left)) * Math.pow(10, 1)) / Math.pow(10, 1) },
	                    top: function() { return Math.round((0 - (multipl * currentCursorPosition.top)) * Math.pow(10, 1)) / Math.pow(10, 1) }
	                };

	                var cursorEdges = {
	                    withinLeft: (currentCursorPosition.left >= 0),
	                    withinRight: ((currentCursorPosition.left + calc.cursor.width) <= settings.imageSizeSmall.width),
	                    withinTop: (currentCursorPosition.top >= 0),
	                    withinBottom: ((currentCursorPosition.top + calc.cursor.height) <= settings.imageSizeSmall.height)
	                };

	                if (cursorEdges.withinLeft && cursorEdges.withinRight) {
	                    cursor.css("left", currentCursorPosition.left + "px");
	                    largeImage.css("left", zoomPosition.left() + "px");
	                } else if (!cursorEdges.withinLeft) {
	                    cursor.css("left", "0px");
	                    largeImage.css("left", "0px");
	                } else if (!cursorEdges.withinRight) {
	                    cursor.css("left", calc.cursor.absPositionSmallImage.right + "px");
	                    largeImage.css("left", calc.imageLarge.absPosition.right + "px");
	                }


	                if (cursorEdges.withinTop && cursorEdges.withinBottom) {
	                    cursor.css("top", currentCursorPosition.top + "px");
	                    largeImage.css("top", zoomPosition.top() + "px");
	                } else if (!cursorEdges.withinTop) {
	                    cursor.css("top", "0px");
	                    largeImage.css("top", "0px");
	                } else if (!cursorEdges.withinBottom) {
	                    cursor.css("top", calc.cursor.absPositionSmallImage.bottom + "px");
	                    largeImage.css("top", calc.imageLarge.absPosition.bottom + "px");
	                }

	            });


	            m.mouseleave(function() {
	                cursor.hide();

	                if (inFade) { return false; }

	                inFade = true;
	                largeImageWrapper.fadeOut(function() {
	                    inFade = false;
	                });

	            });

	            if (settings.openInFaceboxOnClick) {
	                cursor.click(function() {
	                    mainImageLink.click();
	                });
	            }


	        });

	    };
	})(jQuery);
	
///Clock
	$.fn.retroclock = function(options) {
	    // default configuration properties
	    var defaults = {
	        enddate: '2011-11-02',
	        now: '2011-11-01 15:00',
	        path: '',
	        height: '64px'
	    };

	    var settings = $.extend(defaults, options);
	    var _obj = this;
	    var current = {
	        "h1": -1,
	        "h2": -1,
	        "m1": -1,
	        "m2": -1,
	        "s1": -1,
	        "s2": -1
	    };

	    var flip = function flip(upperId, lowerId, changeNumber, pathUpper, pathLower) {
	        var upperBackId = upperId + "Back";
	        $(_obj).find(upperId).attr('src', $(_obj).find(upperBackId).attr('src')).height(settings.height).css({
	            "visibility": "visible",
	            'display': 'inline-block'
	        });

	        $(_obj).find(upperBackId).attr('src', pathUpper + parseInt(changeNumber) + ".png");

	        $(_obj).find(lowerId).attr('src', pathLower + parseInt(changeNumber) + ".png").height('0px').css({
	            "visibility": "visible",
	            'display': 'inline-block'
	        });

	        $(_obj).find(upperId).animate({
	            'height': 0
	        }, {
	            'duration': 200,
	            defaultEasing: 'easeinoutsine',
	            'complete': function() {
	                $(_obj).find(lowerId).animate({
	                    'height': settings.height
	                }, {
	                    'duration': 200,
	                    defaultEasing: 'easeinoutsine',
	                    'complete': function() {
	                        $(_obj).find(lowerId + "Back").attr('src', $(_obj).find(lowerId).attr('src'));
	                    }
	                });
	            }
	        });
	    };
	    var tick = function tick() {
	        var pathDouble = settings.path;
	        var enddate = settings.enddate;
	        var now = settings.now;
	        var difference = enddate.getTime() - now.getTime(); //calculates difference between dates in ms
	        var hours = 0;
	        var mins = 0;
	        var secs = 0;

	        difference = Math.floor(difference / 1000); //omit the "milliseconds"
	        difference = difference % 86400; //days
	        hours = Math.floor(difference / 3600); //hours
	        difference = difference % 3600;
	        mins = Math.floor(difference / 60); //minutes
	        difference = difference % 60;
	        secs = Math.floor(difference); //seconds

	        if (secs >= 0) { 
	        var h1 = Math.floor(hours / 10);
	        var h2 = hours % 10;
	        var m1 = Math.floor(mins / 10);
	        var m2 = mins % 10;
	        var s1 = Math.floor(secs / 10);
	        var s2 = secs % 10;

	        if (h1 != current.h1) {
	            flip('.hoursUpLeft', '.hoursDownLeft', h1, pathDouble + '/Up/Left/', pathDouble + '/Down/Left/');
	            current.h1 = h1;
	        }
	        if (h2 != current.h2) {
	            flip('.hoursUpRight', '.hoursDownRight', h2, pathDouble + '/Up/Right/', pathDouble + '/Down/Right/');
	            current.h2 = h2;
	        }
	        if (m1 != current.m1) {
	            flip('.minutesUpLeft', '.minutesDownLeft', m1, pathDouble + '/Up/Left/', pathDouble + '/Down/Left/');
	            current.m1 = m1;
	        }
	        if (m2 != current.m2) {
	            flip('.minutesUpRight', '.minutesDownRight', m2, pathDouble + '/Up/Right/', pathDouble + '/Down/Right/');
	            current.m2 = m2;
	        }
	        if (s1 != current.s1) {
	            flip('.secondsUpLeft', '.secondsDownLeft', s1, pathDouble + '/Up/Left/', pathDouble + '/Down/Left/');
	            current.s1 = s1;
	        }
	        if (s2 != current.s2) {
	            flip('.secondsUpRight', '.secondsDownRight', s2, pathDouble + '/Up/Right/', pathDouble + '/Down/Right/');
	            current.s2 = s2;
	        }
	        now.setSeconds(now.getSeconds() + 1); 
	       }
	    };
	    this.each(function() {
	        setInterval(tick, 1000);
	    });
	};
