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");

    $('div.paging a').each(function() {
        $(this).attr("href", "#page-" + $(this).html());

    });
    $('div.paging a').click(function(e) {
        //e.stopPropagation();
        var pageid = $(this).html();
        if (isNaN(pageid)) { pageid = -1 } else { pageid -= 1 }
        $("#plPageID input").val(pageid);
        PlAjax();
        //var baseURL = location.href.slice(0, location.href.indexOf('#'));
        //location.href = baseURL + '#page-' + pageid;

    });

    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 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 = $("#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();
    
    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 model = [];
//			$(obj).find("li").each(function(){
//				model.push(this);
//			});
//			model.forEach(function(x){alert($(x).html()); });
			
			$(obj).find("li").hide();
			$(obj).find("li:first").show();	
							
			setTimeout(function() {
				animate("next");
			}, options.timeoutspeed);
			
			var highest_height = 0;
            var this_height = 0;						
			var li_count = 0;
			var doAnimate = true;
			
         	$(obj).find("li").each(function(i) {
                 li_count = (i + 1);
                      if (li_count != 0) {
                         $(obj).siblings(".click-boxes").append('<div class="clickbox clickbox-inactive clickbox-image' + li_count + '"></div>');
                         $(this).addClass("image" + li_count); 
                         $(obj).siblings(".click-boxes").find(".clickbox-image1").removeClass("clickbox-inactive");
                      }   
                      
                     
                      
			     this_height = $(this).height(); if (this_height < highest_height) { } else { highest_height = this_height; }     
             });
            
            $(obj).siblings(".click-boxes").append('<div style="clear:both;"></div>');
			if ( $(obj).attr('style') == undefined ) { $(obj).attr('style', "height: " + highest_height + "px") ;}	                    
		                	
			$(obj).siblings(".click-boxes").find(".clickbox").click(function(e) {
                var new_image = $(this).attr("class");
                 doAnimate = false;
                $(obj).find("li").hide();
                $(obj).find("li.image" +  new_image.match(/clickbox-image(\d+)/)[1]).show();
                var id = $(this).attr("class");
         
            $(obj).siblings(".click-boxes").find(".clickbox").each(function(i) {
                $(this).addClass("clickbox-inactive");            
             });
        
            $(this).removeClass("clickbox-inactive");  
            
            
    });			
    
			function animate() {
			   	if(doAnimate) {  		   
				    var li =  $(obj).find("li:visible");
				    li.hide();
				    if (li.next().html() == undefined) 
					    $(obj).find("li:first").fadeIn(options.fadespeed);
				    else  
					    li.next().fadeIn(options.fadespeed);
				} else {
				    doAnimate = true;
				}
				setTimeout(function(){
					animate("next");			    
				}, options.timeoutspeed);
							
                $(obj).siblings(".click-boxes").find(".clickbox").addClass("clickbox-inactive");	           	     
	            var current_image = $(obj).find("li:visible").attr("class");	           	            
	            $(obj).siblings(".click-boxes").find(".clickbox-" + current_image).removeClass("clickbox-inactive");
                  	
			}
		});
	}

	$(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").children();
	            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;
	            }
	        }
	    });

	    $(mailform).find("textarea").each(function() {
	        if ($(this).attr("required") == "true" && $(this).val() == "") {
	            $(this).after(validationHtml1);
	            success = false;
	        }
	    });

	    $(mailform).find("select").each(function() {
	        if ($(this).attr("required") == "true" && $(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") {
	        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 = "";

