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).closest("dl").children("dd").slideToggle(100).toggleClass("expanded");
        return false;
    });
    $(".hidBroughtArticleGroupID").val("");
});

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); }
}
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;
    }


    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", "");
}


   

//// Imageslider

$.fn.fortusslider = function(options) {
    // default configuration properties
    var defaults = {
        fadespeed: 1500,
        timeoutspeed: 4500
    };

    var options = $.extend(defaults, options);
    this.each(function() {

        var obj = this;

        var link_target = new Array();
        var link_href = new Array();
        var images_src = new Array();
        var image_count = $(obj).find("li").size();
        var current_array_position = 0;
        var li = "li:first";

        var image_height = 0;
        var highest_image_height = 0;
        $(obj).find("li").each(function(i) {
            images_src[i] = $(this).find("img").attr("src");
            link_target[i] = $(this).find("a").attr("target");
            link_href[i] = $(this).find("a").attr("href");
            image_height = $(this).find("img").height(); if (image_height < highest_image_height) { } else { highest_image_height = image_height; }
        });

        $(obj).find("li").remove();
        $(obj).css("height", highest_image_height + "px");
        
        var i = 0;
        for (i = 0; i < image_count; i++) {
            $(obj).siblings(".click-boxes").append('<div class="clickbox clickbox-inactive clickbox-image' + i + '"></div>');
            $(obj).siblings(".click-boxes").find(".clickbox-image0").removeClass("clickbox-inactive");
        }

        $(obj).siblings(".click-boxes").append('<div style="clear:both;"></div>');
        $(obj).append('<li style="z-index: 2;"><a href="' + link_href[0] + '" target="' + link_target[0] + '"><img src="' + images_src[0] + '" /></a></li>');
        $(obj).append('<li style="z-index: 1;"><a href="' + link_href[1] + '" target="' + link_target[1] + '"><img src="' + images_src[1] + '" /></a></li>');

        animate();

        $(obj).siblings(".click-boxes").find(".clickbox").click(function(e) {
            var new_image = $(this).attr("class");
            $(obj).siblings(".click-boxes").find(".clickbox").addClass("clickbox-inactive");
            $(this).removeClass("clickbox-inactive");
            current_array_position = parseInt(new_image.match(/clickbox-image(\d+)/)[1]);
            var li_inactive = "li:first"; if (li == "li:first") { li_inactive = "li:last"; }
            $(obj).find(li_inactive).find("img").attr("src", images_src[current_array_position]);
            $(obj).find(li_inactive).find("a").attr("href", link_href[current_array_position]);
            $(obj).find(li_inactive).find("a").attr("target", link_target[current_array_position]);
        });

        function animate() {
            if (images_src[current_array_position] == undefined) { current_array_position = 0; }
            $(obj).find(li).find("img").attr("src", images_src[current_array_position]);
            $(obj).find(li).find("a").attr("href", link_href[current_array_position]);
            $(obj).find(li).find("a").attr("target", link_target[current_array_position]);
            if (li == "li:first") { li = "li:last"; } else { li = "li:first"; }
            var li_inactive = "li:first"; if (li == "li:first") { li_inactive = "li:last"; }
            current_array_position += 1;

            setTimeout(function() {
                $(obj).find(li_inactive).find("img").fadeOut(defaults.fadespeed);
                $(obj).find(li).css("z-index", "1");
                $(obj).find(li_inactive).css("z-index", "2");
                $(obj).find(li).find("img").show();
                $(obj).siblings(".click-boxes").find(".clickbox").addClass("clickbox-inactive");
                if (images_src[current_array_position] == undefined) { current_array_position = 0; }
                $(obj).siblings(".click-boxes").find(".clickbox-image" + current_array_position).removeClass("clickbox-inactive");
                animate();
            }, options.timeoutspeed);
        }

    });

}

	$(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 = "";
