$("img").ready(
function() {
    var img = $(this)[0];
    // Body has finished loading so if img is not complete then
    // you  have a broken image so return false - image is not ok
    if (!img.complete) {
        $(this).attr("src", "/_Plugins/Webshop/Templates/www.motorspeed.no/img/transparent.png");
        if ($(this).closest("#mainAddFromDb").size() > 0) {
            $("#mainAddFromDb").hide();
        }    
    } 

    // if naturalWidth is undefined or zero then the image failed to load
    // so return false - image is not ok
    if (typeof img.naturalWidth != "undefined" && img.naturalWidth == 0) {
        $(this).attr("src", "/_Plugins/Webshop/Templates/www.motorspeed.no/img/transparent.png");
        if ($(this).closest("#mainAddFromDb").size() > 0) {
            $("#mainAddFromDb").hide();
        }   
    }
}
); 

function f_filterResults(n_win, n_docel, n_body) {
    var n_result = n_win ? n_win : 0;
    if (n_docel && (!n_result || (n_result > n_docel)))
        n_result = n_docel;
    return n_body && (!n_result || (n_result > n_body)) ? n_body : n_result;
}


function f_scrollLeft() {
    return f_filterResults (
    window.pageXOffset ? window.pageXOffset : 0,
    document.documentElement ? document.documentElement.scrollLeft : 0,
    document.body ? document.body.scrollLeft : 0
    );
}
function f_scrollTop() {
    return f_filterResults (
    window.pageYOffset ? window.pageYOffset : 0,
    document.documentElement ? document.documentElement.scrollTop : 0,
    document.body ? document.body.scrollTop : 0
    );
}


$(document).ready(
function() {

    // extend jquery

    (function($) {
        $.console =
        {
            log: function(message) {
                //if('console' in window && 'log' in window.console)
                if (typeof window.console != 'undefined' && typeof window.console.log != 'undefined') {
                    console.log(message);
                }
                else {
                    //alert(message);
                }
            },
            info : function(message) {
                // todo
            }
        }
    })(jQuery);

    // Adds handler to tab controller
    $("#ProductTabs > ul.Tabs > li > a").bind("mousedown", function(event){
        $("#ProductTabs > ul.Tabs > li").removeClass("active");
        $(this).parent().addClass("active");

        $(".TabContent").hide();
        $(".TabContent[id='" + $(this).parent().attr("id") +"Content']").show();
        event.stopPropagation();
        return false;
    }).click(
    function(event) {
        event.stopPropagation();
        return false;
    }
    );


    $("img").error(function() {
        $(this).attr("src", "/_Plugins/Webshop/Templates/www.motorspeed.no/img/transparent.png");
        if ($(this).closest("#mainAddFromDb").size() > 0) {
            $("#mainAddFromDb").hide();
        }   
    });

    // move overlay
    $(window).scroll(
    function() {
        //$.log({left:f_scrollLeft()+"px", top:f_scrollTop()+"px"});
        $("#overlay").css({left:f_scrollLeft()+"px", top:f_scrollTop()+"px"});
    }
    );


    $(".quantity").live("change",
    function() {
        $.ajax({
            url: '/index.php?page=wsOrder&getType=json&template=Checkout(Partial)&action=changeQuantity&Aid=' + $(this).closest("tr").attr("name") + '&Quantity=' + $(this).val(),
            type: 'post',
            dataType: 'json',
            success: function(data, textStatus, XMLHttpRequest) {
                if (data.OrderPartial != undefined) {
                    $("#OrderForm").html('').html(html_entity_decode(data.OrderPartial));
                    $("#CartCount").html($("#newcount").html());
                    $("#CartTotal").html($("#newtotal").html());
                }
                if (data.Template != undefined) {
                    $("#OrderPageOrder").html('').html(html_entity_decode(data.Template));
                }
            }
        });    
    }
    );

    $(".remove").live("click",
    function() {
        $.ajax({
            url: '/index.php?page=wsOrder&getType=json&template=Checkout(Partial)&action=changeQuantity&Aid=' + $(this).closest("tr").attr("name") + '&Quantity=0',
            type: 'post',
            dataType: 'json',
            success: function(data, textStatus, XMLHttpRequest) {
                if (data.OrderPartial != undefined) {
                    $("#OrderForm").html('').html(html_entity_decode(data.OrderPartial));
                    $("#CartCount").html($("#newcount").html());
                    $("#CartTotal").html($("#newtotal").html());
                }
                if (data.Template != undefined) {
                    $("#OrderPageOrder").html('').html(html_entity_decode(data.Template));
                }
            }
        });    
    }
    );

    if ( VariantTypes !== null ) {
        // sort it acording to name
        VariantTypes.sort(
        function(aa, bb) {

            var a = aa[0].Values.toLowerCase();
            var b = bb[0].Values.toLowerCase();

            if (IsNumeric(a) && IsNumeric(b)) {
                return(a-b);   
            }

            // numbers at start?
            var numv1 = "";
            var tmp1 = a.replace(",", ".");
            for (var i=0; i<tmp1.length; i++) {
                if (IsNumeric(tmp1.substr(0, i+1))) {
                    numv1 = tmp1.substr(0, i+1) * 1;   
                } else {
                    break;
                }
            }

            var numv2 = "";
            var tmp2 = b.replace(",", ".");
            for (var i=0; i<tmp2.length; i++) {
                if (IsNumeric(tmp2.substr(0, i+1))) {
                    numv2 = tmp2.substr(0, i+1) * 1;   
                } else {
                    break;
                }
            }

            if (numv1 != "" && numv2 != "") {
                return (numv1-numv2)
            }


            // special
            var xxx = new Array();
            xxx['3xs'] = -2;
            xxx['2xs'] = -1;
            xxx['xxs'] = 0;
            xxx['xs'] = 1;
            xxx['s'] = 2;
            xxx['m'] = 3;
            xxx['l'] = 4;
            xxx['xl'] = 5;
            xxx['xxl'] = 6;
            xxx['2xl'] = 7;
            xxx['xxxl'] = 8;
            xxx['3xl'] = 9;

            if (a in xxx && b in xxx) {
                return xxx[a] - xxx[b];
            }

            if (a==b) {
                return 0;
            }
            if (a>b) {
                return 1;    
            }
            return -1;
        }
        );

        $(VariantTypes).each(function(idx){
            var aTypes = $(this)[0].Types.split(";");
            var aValues = $(this)[0].Values.split(";");
            for ( i=0; i < aTypes.length; i++){
                if (aTypes[i] != "") {
                    if ( $("select[name='sel-"+ aTypes[i] +"'] > option[value='"+ aValues[i].replace(/"/g, '&quot;') +"']").length == 0 ){
                        $("select[name='sel-"+ aTypes[i] +"']").append('<option value="'+aValues[i].replace(/"/g, '&quot;')+'">'+ aValues[i] +'</option>');
                    }
                }
            }
        });

        // Selector handler
        $("select[name^='sel']").bind("change", function(){
            var select = $(this);
            var Value = "";
            select.parent().parent().find("select[name^='sel']").each(function(idx){
                Value = Value + $(this).val() + ";";
            });

            if ( Value.length > 0 )
                Value = Value.substr(0,(Value.length-1));

            $(VariantTypes).each(function(idx){
                if ( $(this)[0].Values == Value && ("sel-" + $(this)[0].Master) == select.attr("id") ){
                    select.closest("tr").parent().find("[name='variant']").val( $(this)[0].ProductId );
                    $(".productHeader").html($(this)[0].Name);
                    $("#ProductNumber").html($(this)[0].Number);
                    $("span.price").html($(this)[0].ProductPrice);

                    // check if we need to update lagerstatus
                    var info = select.closest(".productRight");
                    if (info.size() > 0) {
                        if ($(this)[0].Count != 0) {
                            info.find("#status").text($(this)[0].Count);
                            info.find("#delivery").closest("tr").hide();
                        } else {
                            info.find("#status").text("0");
                            info.find("#delivery").text($(this)[0].Delivery).closest("tr").show();    
                        }

                    }

                    return false;
                }
            });

        });
    } 

    // move varianter to own line if it is long
    var width = 0;
    $(".productOrderBox").find("select[name^='sel']").parent().each(
    function() {
        width += $(this).width();    
    }
    );
    if (width > 100) {
        var newRow = $(".productOrderBox").find("select[name^='sel']:first").closest("tr").after("<tr><td>&nbsp;</td><td>&nbsp;</td></tr>").next().after("<tr><td>&nbsp;</td><td>&nbsp;</td></tr>");
        $(".productOrderBox").find("select[name^='sel']").parent().each(
        function(idx) {
            // move headers
            newRow.append($(this).closest("tr").prev().children("td:nth-child(4)"));
            newRow.next().append($(this));
        }
        );
        // fix align
        newRow.find("td").attr("align", "right");
        newRow.next().find("td").attr("align", "right");
        // fix width
        $(".productOrderBox").find("td:not(:nth-child(3))").each(
        function() {
            var w = $(this).children(":visible").width();
            if (w != null) {
                $(this).attr("width",w); 
            } else {
                $(this).attr("width","100%");
            }
        }
        );
        $("#priceArrow").attr("width", 80);

        // do we only have 1
        if (newRow.find("td").size() == 3) {
            newRow.find("td:last").attr("colspan", "2"); 
            newRow.next().find("td:last").attr("colspan","2"); 
        }

        $(".productSpec").height($(".productSpec").height() - newRow.height() - newRow.next().height());
    }

    $("#priceArrow").attr("style", "padding-left: 32px");

    // fixing ie bug with hover over subtag
    $(".produktMenyUndergrupper>li:not(.selected)").hover(
    function() {
        $(this).addClass("selected");    
    },
    function() {
        $(this).removeClass("selected");    
    }
    );


    // fixing ie bug with hover over subtag
    $(".menuItem").hover(
    function() {
        $(this).addClass("menuItemSelected");    
    },
    function() {
        $(this).removeClass("menuItemSelected");    
    }
    );

    // fixing ie bug with hover over subtag
    $(".arrow:not(.arrowDown)").find("a").hover(
    function() {
        $(this).addClass("red");
        $(this).parent().addClass("hover");    
    },
    function() {
        $(this).removeClass("red");
        $(this).parent().removeClass("hover");    
    }
    );


    $("#showAllOrders").click(
    function() {
        $("#showAllOrders").closest("tr").siblings().show()
        $(this).attr("checked", true);
    }
    );

    $(".sendPDFInvoice").click(
    function(){
        var cell = $(this).closest("td");
        req = $.ajax({
            dataType: 'json',
            data: {'method' : 'sendPDFInvoice', 'getType' : 'json', 'param[id]' : $(this).closest("tr").attr("name") },
            contentType: 'application/json; charset=utf-8',
            timout: 2000,
            url: ServerUrl + '/RPC',
            success: function (Response) {
                cell.html(cell.html() + " " + Response);
                cell.find("a").remove();
            },
            error: function(){
                cell.html(cell.html() + " Feilet");
            }
        });  
    }
    );

    $(".oldOrder").click(
    function() {
        $("#OrderPopup").find(".content").html("Laster...");
        $("#overlay, .detailsClose").show().one("click", 
        function() {
            $("#OrderPopup").hide(); 
            $("#overlay").hide();   
        }
        );
        var box = $("#OrderPopup");
        var left = $("#overlay").width()/2-box.width()/2;
        var top = $("#overlay").height()/2-box.height()/2;
        box.css({left:left, top:top});
        $("#OrderPopup").show();
        $.ajax({
            url: '/index.php?page=wsOrderDetails&tpl=OrderDetails(Partial)&getType=partial&encode=true&Id=' + $(this).closest("tr").attr("name"),
            type: 'post',
            dataType: 'json',
            success: function(data, textStatus, XMLHttpRequest) {
                if (data != undefined) {
                    $("#OrderPopup").find(".content").html('').html(html_entity_decode(data));
                    $("#overlay").show().one("click", 
                    function() {
                        $("#OrderPopup").hide(); 
                        $("#overlay").hide();   
                    }
                    );
                    var box = $("#OrderPopup");
                    var left = $("#overlay").width()/2-box.width()/2;
                    var top = $("#overlay").height()/2-box.height()/2;
                    box.css({left:left, top:top});
                    $("#OrderPopup").show();
                }
            }
        });   
    }
    );

    /**
    * Menu Handler
    */
    if ( $("#categoryBox").length > 0 ){

        // MenuExpand
        $("#categoryBox > ul > li.arrow").bind('click', function(event){
            if (event.isPropagationStopped()) {
                return;
            }
            $("#categoryBox > ul > li > ul ").hide();
            var wasOpen = $(this).hasClass("arrowDown");
            $("#categoryBox > ul > li").removeClass("arrowDown");
            if (!wasOpen) {
                $(this).addClass("arrowDown");
                $(this).children('ul').toggle();
            }
            recalcHeight();
        });

        $("#categoryBox > ul > li > ul > li.arrow").bind('click', function(event){
            $("#categoryBox > ul > li > ul > li > ul ").hide();
            var wasOpen = $(this).hasClass("arrowDown"); 
            $("#categoryBox > ul > li > ul > li").removeClass("arrowDown");
            if (!wasOpen) { 
                $(this).children('ul').toggle();
                $(this).addClass("arrowDown");
                window.location = $(this).children("a").attr("href");
            }
            event.stopPropagation(); 
            recalcHeight();
            return false;
        });

        $("#categoryBox > ul > li > ul > li > ul").bind("click", 
        function(event) {
            event.stopPropagation();
        }

        )

    }

    $("#cartBox").find(".hoverExpand").hover(
    function() {
        $("#OrderForm").show();    
    }, 
    function() {
        $("#OrderForm").hide();    
    }
    );

    $("#usernameInput").blur(
    function() {
        if($(this).val() == "") {
            $(this).val("BRUKERNAVN");
        }
    }
    );

    $("#usernameInput").focus(
    function() {
        if($(this).val() == "BRUKERNAVN") {
            $(this).val("");
        }
    }
    );

    $("#passwordInputReal").blur(
    function() {
        if($(this).val() == "") {
            $(this).hide();
            $("#passwordInputFake").show();
        }
    }
    );

    $("#passwordInputFake").focus(
    function() {
        $(this).hide();
        $("#passwordInputReal").show().focus();
    }
    );

    $("#SearchInput").focus(
    function() {
        if($(this).val() == "SØK I PRODUKT") {
            $(this).val("");
        }
    }
    ).blur(
    function() {
        if($(this).val() == "") {
            $(this).val("SØK I PRODUKT");
        }
    }
    );

    $(".productImgNum").click(
    function() {
        $(this).closest(".productImg").find("img").attr("src", $(this).attr("name"));
        $(this).addClass("selected").siblings().removeClass("selected");  

        var box = $("#imgBox");
        var img = box.children("div"); 
        var imgimg = img.find("img:visible");

        img.css("height", "800px");
        img.css("width", "800px");

        var left = $("#overlay").width()/2-400;
        var top = $("#overlay").height()/2-425;
        img.css({left:left, top:top});

        imgimg.css("width", "auto");
        imgimg.css("height", "auto");
		
		if (imgimg.width() > 800) {
			imgimg.css("width", 800);
		}
		if (imgimg.height() > 800) {
			imgimg.css("height", 800);
		}

        setTimeout('var imgimg = $("#imgBox>div>img:visible"); imgimg.css("top", ((800-imgimg.height())/2) + "px");', 10);

        if (!imgimg[0].complete) {
            imgimg.load(
            function() {
                
				if (imgimg.width() > 800) {
					imgimg.css("width", 800);
				}
				if (imgimg.height() > 800) {
					imgimg.css("height", 800);
				}
				imgimg.css("top", ((800-imgimg.height())/2) +"px");
            }
            );
        }


    }
    );

    $(".preload").each(
    function() {
        $(this).attr("src", $(this).attr("name"));
    }
    );

    $(".productImgNext").click(
    function() {
        var next = $(this).closest(".productImg").find(".selected").next();
        if (next.size() == 0) {
            next = $(this).closest(".productImg").find(".productImgNum:first");     
        }
        next.click();
    }
    );

    $(".productImgPrev").click(
    function() {
        var prev = $(this).closest(".productImg").find(".selected").prev();
        if (prev.size() == 0) {
            prev = $(this).closest(".productImg").find(".productImgNum:last");     
        }
        prev.click();
    }
    );

    $(".productImg>img").click(
    function() {
        $("#overlay").show();
        var box = $("#imgBox").show();
        box.html($(this).parent().clone(true));
        var img = box.children("div"); 
        var left = $("#overlay").width()/2-img.width()/2;
        var top = $("#overlay").height()/2-img.height()/2;
        img.css({left:left, top:top});
        img.append("<div class=\"productImgClose\">");
        img.find(".productImgClose, img").click(
        function() {
            $("#overlay").hide();
            $("#imgBox").hide();
        }
        );
        box.find(".productImgNum").each(
        function() {
            $(this).attr("name", $(this).attr("orgname"));
        }
        );
        box.find(".selected").click();
    }
    );

    $("#overlay").click(
    function() {
        $(this).hide();
        $("#imgBox").hide();
    }
    );

    $(".FormError").keypress(
    function() {
        $(this).removeClass("FormError");
    }
    );


    $(".focusCartAddIE,.focusCartAdd,.focusCart,.focusCartAddIE>img,.focusCartAdd>img,.focusCart>img").live('click', function(){
        // Handler for adding products to basket            
        $.ajax({
            url: '/index.php?page=wsOrder&getType=partial&action=add&Aid=' + $(this).closest(".focusBox").find("[name='variant']").val() + '&Quantity=' + $(this).closest(".focusBox").find("select[name='antall']").val(),
            type: 'get',
            success: function(data, textStatus, XMLHttpRequest) {
                $("#OrderForm").html('').html(data);
                $("#CartCount").html($("#newcount").html());
                $("#CartTotal").html($("#newtotal").html());
            }
        });  
    });

    $(".listCartAdd,.listCart").live('click', function(){
        // Handler for adding products to basket            
        $.ajax({
            url: '/index.php?page=wsOrder&getType=partial&action=add&Aid=' + $(this).closest(".listBox").find("[name='variant']").val() + '&Quantity=' + $(this).closest(".listBox").find("select[name='antall']").val(),
            type: 'get',
            success: function(data, textStatus, XMLHttpRequest) {
                $("#OrderForm").html('').html(data);
                $("#CartCount").html($("#newcount").html());
                $("#CartTotal").html($("#newtotal").html());
            }
        });  
    });

    $(".productCartAdd,.productCartAddIE,.productCart").live('click', function(){
        // Handler for adding products to basket            
        $.ajax({
            url: '/index.php?page=wsOrder&getType=partial&action=add&Aid=' + $(this).closest(".productOrderBox").find("[name='variant']").val() + '&Quantity=' + $(this).closest(".productOrderBox").find("select[name='antall']").val(),
            type: 'get',
            success: function(data, textStatus, XMLHttpRequest) {
                $("#OrderForm").html('').html(data);
                $("#CartCount").html($("#newcount").html());
                $("#CartTotal").html($("#newtotal").html());
            }
        });  
    });

    /**
    * Buy button Handler
    */
    $(".buyButton").live('click', function(){
        // Handler for adding products to basket            
        $.ajax({
            url: '/index.php?page=wsOrder&getType=partial&action=add&Aid=' + $(this).attr('name') + '&Quantity=' + $(this).prev().val(),
            type: 'get',
            success: function(data, textStatus, XMLHttpRequest) {
                $("#OrderForm").html('').html(data);
                $("#CartCount").html($("#newcount").html());
                $("#CartTotal").html($("#newtotal").html());
            }
        });  
    });

    
    $(".smallListBoxbuyButton").live('click', function(){
        // Handler for adding products to basket            
        $.ajax({
            url: '/index.php?page=wsOrder&getType=partial&action=add&Aid=' + $(this).attr('name') + '&Quantity=' + $(this).parent().prev().find("input").val(),
            type: 'get',
            success: function(data, textStatus, XMLHttpRequest) {
                $("#OrderForm").html('').html(data);
                $("#CartCount").html($("#newcount").html());
                $("#CartTotal").html($("#newtotal").html());
            }
        });  
    });

    /**
    * Password Strength Meter
    */
    if ( $("#AccountPassword").length > 0 ){
        /*jQuery('#AccountPassword').pstrength({
        minCharText: Texts.PasswordMeter.minCharText,
        verdicts: Texts.PasswordMeter.verdicts
        }
        );*/
    }


    $("#usernameField").change(
    function() {
        $("#emailField").val($(this).val());
    }
    );


    /**
    * Resend Password handler
    */


    $("#resendPasswordButton").click(
    function(){
        req = $.ajax({
            dataType: 'json',
            data: {'method' : 'ResendPassword', 'getType' : 'json', 'param[email]' : $(this).parent().find("input[name='email']").val() },
            contentType: 'application/json; charset=utf-8',
            timout: 2000,
            url: ServerUrl + '/RPC',
            success: function (Response) {
                if ( Response !== null ){
                    $("#ResendPasswordErrorMessage").html('').html(Texts.ResendPassword.invalidEmailAddress);
                    $("#ResendPasswordContainer").find('input:first').focus().select();
                }else{
                    var text = $.template(Texts.ResendPassword.success);
                    $("#ResendPasswordErrorMessage").html(text.apply({email: $("#ResendPasswordContainer").find("input").val()}));
                }
            },
            error: function(){
                $("#ResendPasswordContainer").find('input:first').focus().select(); 
                req.abort();
            }
        });
    }
    );

    $("#ResendPasswordContainer").find("input[type='button']").click(function(){
        if ( $("#ResendPasswordContainer").find("input[type='text']").val().length > 3 ){

            req = $.ajax({
                dataType: 'json',
                data: {'method' : 'ResendPassword', 'getType' : 'json', 'param[email]' : $("#ResendPasswordContainer").find("input[type='text']").val() },
                contentType: 'application/json; charset=utf-8',
                timout: 2000,
                url: ServerUrl + '/RPC',
                success: function (Response) {
                    if ( Response !== null ){
                        $("#ResendPasswordErrorMessage").html('').html(Texts.ResendPassword.invalidEmailAddress);
                        $("#ResendPasswordContainer").find('input:first').focus().select();
                    }else{
                        var text = $.template(Texts.ResendPassword.success);
                        $("#ResendPasswordErrorMessage").html(text.apply({email: $("#ResendPasswordContainer").find("input").val()}));
                    }
                },
                error: function(){
                    $("#ResendPasswordContainer").find('input:first').focus().select(); 
                    req.abort();
                }
            });

        }else{  
            $("#ResendPasswordErrorMessage").html('').html(Texts.ResendPassword.invalidEmailAddress);
            $("#ResendPasswordContainer").find('input:first').focus();
        }
    });



    /**
    * Zipcode Handler
    */
    if ( $(".Zipcode").length > 0 ){
        $(".Zipcode").bind("change", function(){
            var obj = $(this);
            var req = $.ajax({
                dataType: 'json',
                data: {'method' : 'Zipcodecheck', 'getType' : 'json', 'param[country]' : 160, 'param[zipcode]' : $(this).val() },
                contentType: 'application/json; charset=utf-8',
                timeout: 500,
                url: ServerUrl + '/RPC',
                success: function (Zipcode) {
                    if ( Zipcode === null ){
                        $(obj).next('input').val('');
                        $(obj).focus().select();  
                    }else{
                        $(obj).next('input').val( html_entity_decode( Zipcode.Name ) );
                    }
                },
                error: function(e, xhr, settings){
                    $(obj).focus().select();
                    req.abort();
                }
            });
        }); 
    }


    /**
    * Payment/Shipping Handlers
    */
    if ( $("input[name='Payment\[Type\]']").length > 0 && $("input[name='Shipment\[Type\]']").length > 0 ) {

    }

    setTimeout("visIkkeTilgjengelig();", 2000);

    $("select[name^='Search[']").bind('change', function(){
        if ( $(this).attr('name') == 'Search[Type]' ){
            ModelsearchBrands();
            ModelsearchVolume();
            ModelsearchYear();
            ModelsearchModel();
        }     

        if ( $(this).attr('name') == 'Search[Brand]' ){
            ModelsearchVolume();
            ModelsearchYear();
            ModelsearchModel();
        }

        if ( $(this).attr('name') == 'Search[Volume]' ){
            ModelsearchYear();
            ModelsearchModel();
        }

        if ( $(this).attr('name') == 'Search[Year]' ){
            ModelsearchVolume();
            ModelsearchModel();
        }
        
        if ( $(this).attr('name') == 'Search[Model]' ){
            if ($(this).val() != -2 && $(this).val() != undefined && $(this).val() != ModelSearch.Model) {
                $("#modelSearch .empty").hide();
                $("#ModelSpinner").show();
                $("#ModelSearchSubmit").click();
            }
        }
    });

    $("#modelSearch .empty").click(
        function() {
            $(this).hide();
            $("#ModelSpinner").show();
            req = $.ajax({
                contentType: 'application/json; charset=utf-8',
                timout: 2000,
                url: ServerUrl + '/AdvancedSearch?empty=true&getType=partial',
                success: function (Response) {
                    location.reload(true);
                } 
            });
        }
    );
}
);





 jQuery.fn.sort = function(){
    return this.pushStack([].sort.apply(this, arguments), []);
};

jQuery.fn.sortOptions = function(sortCallback){
    jQuery('option', this)
        .sort(sortCallback)
        .appendTo(this);
    return this;
};

jQuery.fn.sortOptionsByText = function(){
    var byTextSortCallback = function(x, y){
        var xText = jQuery(x).text().toUpperCase();
        var yText = jQuery(y).text().toUpperCase();
        return (xText < yText) ? -1 : (xText > yText) ? 1 : 0;
    };
    return this.sortOptions(byTextSortCallback);
};

jQuery.fn.sortOptionsByValue = function(){
    var byValueSortCallback = function(x, y){
        var xVal = jQuery(x).val();
        var yVal = jQuery(y).val();
        return (xVal < yVal) ? -1 : (xVal > yVal) ? 1 : 0;
    };
    return this.sortOptions(byValueSortCallback);
};

jQuery.fn.sortOptionsByLookup = function(LookUp){
    var byLookupSortCallback = function(x, y){
        var xText = jQuery(x).text().toUpperCase();
        var yText = jQuery(y).text().toUpperCase();

        return (LookUp[xText] < LookUp[yText]) ? -1 : (LookUp[xText] > LookUp[yText]) ? 1 : 0;  
    };
    return this.sortOptions(byLookupSortCallback);
};


function ModelsearchCallback(){
    ModelsearchTypes();
    
    if ( $("select[name='Search[Type]']").length > 0 ){
        $("select[name='Search[Type]']").change();
    }else{
        $("select[name='Search[Brand]']").change();
    }
    
    if ( ModelSearch.Type != "" ){
        $("select[name='Search[Type]'] > option[value='"+ModelSearch.Type+"']").attr({"selected" : "selected"}).closest("select").change();
    }
    if ( ModelSearch.Brand != "" ){
        $("select[name='Search[Brand]'] > option[value='"+ModelSearch.Brand+"']").attr({"selected" : "selected"}).closest("select").change();
    }
    if ( ModelSearch.Volume != "" ){
        $("select[name='Search[Volume]'] > option[value='"+ModelSearch.Volume+"']").attr({"selected" : "selected"}).closest("select").change();
    }
    if ( ModelSearch.Year != "" ){
        $("select[name='Search[Year]'] > option[value='"+ModelSearch.Year+"']").attr({"selected" : "selected"}).closest("select").change();
    }
    if ( ModelSearch.Model != "" && ModelSearch.Model != "|" ){
        $("select[name='Search[Model]'] > option[value='"+ModelSearch.Model+"']").attr({"selected" : "selected"}).closest("select").change();
    }
}

function ModelsearchTypes(){
    if ( $("select[name='Search[Type]']").length <= 0 ){
        ModelsearchBrands();
    }else{
        $("select[name='Search[Type]'] > option").remove();
        $("select[name='Search[Type]']").append('<option value="-2">'+ModelSearch.TypeTitle+'</option>');
        $("select[name='Search[Brand]'] > option").remove();
        $("select[name='Search[Volume]'] > option").remove();
        $("select[name='Search[Year]'] > option").remove();
        $("select[name='Search[Model]'] > option").remove();
        
		var sel = $("select[name='Search[Type]']"); 
		
        $.each(ModelsearchModels, function(){
            var cur = $(this)[0]; 
            if ( sel.children("option[value='"+cur.T+"']").length == 0 && cur.T != "" && cur.T != "MC" && cur.T.substring(0,2) != "Sn"  ){
                sel.append('<option value="'+cur.T+'">'+cur.T+'</option>');
            }
        })
    }   
}


function ModelsearchBrands(){
    var CurrentType =  "";
    if ( $("select[name='Search[Type]']").length > 0 ){
         CurrentType =  $("select[name='Search[Type]']").val();
    }
     
    $("select[name='Search[Brand]'] > option").remove();
    $("select[name='Search[Brand]']").append('<option value="-2">'+ModelSearch.BrandTitle+'</option>');
    $("select[name='Search[Volume]'] > option").remove();
    $("select[name='Search[Year]'] > option").remove();
    $("select[name='Search[Model]'] > option").remove();
    
	var sel = $("select[name='Search[Brand]']");
    var isFilled = false;
    $.each(ModelsearchModels, function(){
        var cur = $(this)[0];
        if ( ( cur.T == CurrentType || CurrentType == null ) && sel.children("option[value='"+cur.B+"']").length == 0 && cur.B != "" ){
            sel.append('<option value="'+cur.B+'">'+cur.B+'</option>');
            isFilled = true;
        }
        if ( isFilled && cur.T != CurrentType ){return false;}
        
    })    
}


function ModelsearchVolume(){
    var CurrentType =  "";
    if ( $("select[name='Search[Type]']").length > 0 ){
         CurrentType =  $("select[name='Search[Type]']").val();
    }
    
    var CurrentBrand = $("select[name='Search[Brand]']").val();
    var CurrentYear = $("select[name='Search[Year]']").val();
    var CurrentVolume = $("select[name='Search[Volume]']").val();
    
    $("select[name='Search[Volume]'] > option").remove();
    
    $("select[name='Search[Volume]']").append('<option value="-1">Alle</option>'); 
     
    
    $("select[name='Search[Model]'] > option").remove();
    
	var sel = $("select[name='Search[Volume]']");
    var isFilled = false;
    $.each(ModelsearchModels, function(){
        var cur = $(this)[0];
        if ( CurrentYear == "-1" || CurrentYear == null ){
            if ( cur.T == CurrentType && cur.B == CurrentBrand && sel.children("option[value='"+cur.C+"']").length == 0 && cur.C != "" ){
                sel.append('<option value="'+cur.C+'">'+cur.C+'</option>');
                isFilled = true;
            }
        }else{
            if ( cur.T == CurrentType && cur.B == CurrentBrand && cur.YF <= CurrentYear && cur.YT >= CurrentYear && sel.children("option[value='"+cur.C+"']").length == 0 && cur.C != "" ){
                sel.append('<option value="'+cur.C+'">'+cur.C+'</option>');
                isFilled = true;
            }    
        }
         if ( isFilled && cur.B != CurrentBrand ){return false;}
    })
    
    if ( CurrentVolume == null ) CurrentVolume = "-2";
    
    $("select[name='Search[Volume]']").sortOptionsByValue();
    $("select[name='Search[Volume]']").prepend('<option value="-2">'+ModelSearch.VolumeTitle+'</option>');
    $("select[name='Search[Volume]']").val(CurrentVolume);
}


function ModelsearchYear(){
    if ( $("select[name='Search[Year]'] > option").length > 1 ){
        return false;
    }
    
    var CurrentType =  "";
    if ( $("select[name='Search[Type]']").length > 0 ){
         CurrentType =  $("select[name='Search[Type]']").val();
    }
    var CurrentBrand = $("select[name='Search[Brand]']").val();
    var CurrentVolume = $("select[name='Search[Volume]']").val();
    var CurrentYear = $("select[name='Search[Year]']").val();
    
    $("select[name='Search[Year]'] > option").remove();
    $("select[name='Search[Year]']").append('<option value="-2">'+ModelSearch.YearTitle+'</option>'); 
    $("select[name='Search[Year]']").append('<option value="-1"> Alle</option>');
    
    $("select[name='Search[Model]'] > option").remove();
    
    var dt = new Date();
    for ( i = (dt.getFullYear()+1); i >= 1970; i-- ){
        $("select[name='Search[Year]']").append('<option value="'+i+'">'+i+'</option>');       
    }
    
    if ( CurrentYear == null ) CurrentYear = "-2";
    
    $("select[name='Search[Year]']").val(CurrentYear);
}

function ModelsearchModel(){
    var CurrentType =  "";
    if ( $("select[name='Search[Type]']").length > 0 ){
         CurrentType =  $("select[name='Search[Type]']").val();
    }
    var CurrentBrand = $("select[name='Search[Brand]']").val();
    var CurrentVolume = $("select[name='Search[Volume]']").val();
    var CurrentYear = $("select[name='Search[Year]']").val();
    
    $("select[name='Search[Model]'] > option").remove();
    $("select[name='Search[Model]']").append('<option value="-2">'+ModelSearch.ModelTitle+'</option>'); 
    
    var isFilled = false;   
    $.each(ModelsearchModels, function(){
        var cur = $(this)[0];
        // all på volum?
        if ( cur.T == CurrentType 
        && cur.B == CurrentBrand 
        && cur.YF <= CurrentYear 
        && cur.YT >= CurrentYear
        && CurrentVolume == '-1' 
        && $("select[name='Search[Model]'] > option[value='"+cur.M+"|"+cur.V+"']").length == 0 
        && cur.M != "" ){
            $("select[name='Search[Model]']").append('<option value="'+cur.M+"|"+cur.V+'">'+cur.M +( cur.V != '' ? ' ' + cur.V : '' )+'</option>');
            isFilled = true;
        }
        if ( cur.T == CurrentType 
        && cur.B == CurrentBrand 
        && CurrentYear == "-1"
        && CurrentVolume == '-1' 
        && $("select[name='Search[Model]'] > option[value='"+cur.M+"|"+cur.V+"']").length == 0 
        && cur.M != "" ){
            $("select[name='Search[Model]']").append('<option value="'+cur.M+"|"+cur.V+'">'+cur.M +( cur.V != '' ? ' ' + cur.V : '' )+'</option>');
            isFilled = true;
        }
        // Alle på år?
        if ( cur.T == CurrentType 
        && cur.B == CurrentBrand 
        && CurrentYear == '-1' 
        && cur.C == CurrentVolume 
        && $("select[name='Search[Model]'] > option[value='"+cur.M+"|"+cur.V+"']").length == 0 
        && cur.M != "" ){
            $("select[name='Search[Model]']").append('<option value="'+cur.M+"|"+cur.V+'">'+cur.M +( cur.V != '' ? ' ' + cur.V : '' )+'</option>');
            isFilled = true;
        }
        if ( cur.T == CurrentType 
        && cur.B == CurrentBrand 
        && cur.YF <= CurrentYear 
        && cur.YT >= CurrentYear 
        && cur.C == CurrentVolume 
        && $("select[name='Search[Model]'] > option[value='"+cur.M+"|"+cur.V+"']").length == 0 
        && cur.M != "" ){
            $("select[name='Search[Model]']").append('<option value="'+cur.M+"|"+cur.V+'">'+cur.M +( cur.V != '' ? ' ' + cur.V : '' )+'</option>');
            isFilled = true;
        }
        if ( isFilled && cur.B != CurrentBrand ){return false;}
    })
        
}







function recalcHeight() {
    $("#wrapper").css("height", $(document).height());
}


function visIkkeTilgjengelig() {
    $("[style2sek^='b']").each(
    function() {
        $(this).attr("style", $(this).attr("style2sek"));
    }
    );
}

var cnt = 0;
function IsNumeric(sText) {
    /*$.console.log(sText);
    $.console.log(cnt++);*/ 
    if (sText === undefined || sText === null) {
        return false;
    }

    var ValidChars = "0123456789.";
    var IsNumber=true;
    var Char;

    sText = sText.toString();

    for (i = 0; i < sText.length; i++) { 
        Char = sText.charAt(i); 
        if (ValidChars.indexOf(Char) == -1) {
            return false;
        }
    }
    return IsNumber;

}





/**
* HTML Entity Decode
*/
eval(function(p,a,c,k,e,d){e=function(c){return(c<a?'':e(parseInt(c/a)))+((c=c%a)>35?String.fromCharCode(c+29):c.toString(36))};if(!''.replace(/^/,String)){while(c--){d[e(c)]=k[c]||e(c)}k=[function(e){return d[e]}];e=function(){return'\\w+'};c=1};while(c--){if(k[c]){p=p.replace(new RegExp('\\b'+e(c)+'\\b','g'),k[c])}}return p}('v r(b,6){e 4={},5={},g=0,7=\'\';e h={},9={};e 8={},d={};h[0]=\'j\';h[1]=\'f\';9[0]=\'p\';9[2]=\'u\';9[3]=\'o\';8=!q(b)?h[b]:b?b.m():\'j\';d=!q(6)?9[6]:6?6.m():\'u\';a(8!==\'j\'&&8!==\'f\'){1B 1A("1z: "+8+\' n 1y\')}4[\'38\']=\'&s;\';a(d!==\'p\'){4[\'34\']=\'&1C;\'}a(d===\'o\'){4[\'39\']=\'&#1D;\'}4[\'1H\']=\'&1G;\';4[\'1F\']=\'&1E;\';a(8===\'f\'){4[\'1x\']=\'&1w;\';4[\'1p\']=\'&1o;\';4[\'1n\']=\'&1l;\';4[\'1m\']=\'&1q;\';4[\'1r\']=\'&1v;\';4[\'1u\']=\'&1t;\';4[\'1s\']=\'&1I;\';4[\'1J\']=\'&20;\';4[\'1Z\']=\'&1Y;\';4[\'1X\']=\'&21;\';4[\'22\']=\'&26;\';4[\'25\']=\'&24;\';4[\'1k\']=\'&n;\';4[\'1W\']=\'&1V;\';4[\'1O\']=\'&1N;\';4[\'1M\']=\'&1K;\';4[\'1L\']=\'&1P;\';4[\'1Q\']=\'&1U;\';4[\'1T\']=\'&1S;\';4[\'1R\']=\'&27;\';4[\'Z\']=\'&N;\';4[\'M\']=\'&L;\';4[\'I\']=\'&K;\';4[\'O\']=\'&P;\';4[\'T\']=\'&S;\';4[\'R\']=\'&Q;\';4[\'U\']=\'&y;\';4[\'A\']=\'&B;\';4[\'z\']=\'&H;\';4[\'G\']=\'&F;\';4[\'E\']=\'&C;\';4[\'D\']=\'&J;\';4[\'1j\']=\'&1c;\';4[\'1b\']=\'&1a;\';4[\'19\']=\'&1d;\';4[\'1e\']=\'&1i;\';4[\'1h\']=\'&1g;\';4[\'1f\']=\'&18;\';4[\'V\']=\'&17;\';4[\'10\']=\'&Y;\';4[\'W\']=\'&X;\';4[\'11\']=\'&12;\';4[\'16\']=\'&15;\';4[\'14\']=\'&13;\';4[\'23\']=\'&2p;\';4[\'3o\']=\'&3n;\';4[\'3m\']=\'&3k;\';4[\'3l\']=\'&28;\';4[\'3p\']=\'&3q;\';4[\'3v\']=\'&3u;\';4[\'3t\']=\'&3r;\';4[\'3s\']=\'&3j;\';4[\'3i\']=\'&3a;\';4[\'37\']=\'&36;\';4[\'33\']=\'&35;\';4[\'3b\']=\'&3c;\';4[\'3h\']=\'&3g;\';4[\'3x\']=\'&3d;\';4[\'3e\']=\'&3w;\';4[\'3C\']=\'&3Q;\';4[\'3R\']=\'&3P;\';4[\'3O\']=\'&3M;\';4[\'3T\']=\'&3S;\';4[\'3U\']=\'&3X;\';4[\'3V\']=\'&3W;\';4[\'3N\']=\'&3K;\';4[\'3L\']=\'&3B;\';4[\'3A\']=\'&3y;\';4[\'3z\']=\'&3D;\';4[\'3E\']=\'&3J;\';4[\'3I\']=\'&3H;\';4[\'3F\']=\'&3G;\';4[\'3f\']=\'&31;\';4[\'2r\']=\'&2q;\';4[\'32\']=\'&2n;\';4[\'2o\']=\'&2s;\';4[\'2t\']=\'&2y;\';4[\'2x\']=\'&2w;\';4[\'2u\']=\'&2v;\';4[\'2m\']=\'&2l;\';4[\'2d\']=\'&2c;\';4[\'2b\']=\'&29;\';4[\'2a\']=\'&2e;\';4[\'2f\']=\'&2k;\';4[\'2j\']=\'&2i;\';4[\'2g\']=\'&2h;\';4[\'2z\']=\'&2A;\';4[\'2T\']=\'&2S;\';4[\'2R\']=\'&2P;\';4[\'2Q\']=\'&2U;\';4[\'2V\']=\'&30;\';4[\'2Z\']=\'&2Y;\';4[\'2W\']=\'&2X;\';4[\'2O\']=\'&2N;\';4[\'2F\']=\'&2E;\';4[\'2D\']=\'&2B;\'}w(g x 4){7=2C.2G(g);5[7]=4[g]}k 5}v 2H(t,6){e 5={},7=\'\',c=\'\',i=\'\';c=t.2M();a(l===(5=2L.r(\'f\',6))){k l}2K(5[\'&\']);5[\'&\']=\'&s;\';w(7 x 5){i=5[7];c=c.2I(i).2J(7)}k c}',62,246,'||||entities|histogram|quote_style|symbol|useTable|constMappingQuoteStyle|if|table|tmp_str|useQuoteStyle|var|HTML_ENTITIES|decimal|constMappingTable|entity|HTML_SPECIALCHARS|return|false|toUpperCase|not|ENT_QUOTES|ENT_NOQUOTES|isNaN|get_html_translation_table|amp|string|ENT_COMPAT|function|for|in|ordm|188|187|raquo|frac34|191|190|frac12|189|frac14|182|iquest|para|micro|181|acute|183|middot|sup1|185|cedil|184|186|198|200|Egrave|Ccedil|180|199|201|Eacute|Euml|203|Ecirc|202|AElig|Aring|194|Aacute|193|Agrave|Acirc|195|197|Auml|196|Atilde|192|172|cent|163|162|iexcl|161|pound|164|166|yen|165|curren|nbsp|160|supported|Table|Error|throw|quot|039|gt|62|lt|60|brvbar|167|macr|176|175|reg|174|deg|177|179|sup2|178|plusmn|shy|173|169|uml|168|sect|copy|170|204|laquo|171|ordf|sup3|Iuml|ntilde|242|241|eth|240|ograve|243|245|otilde|ocirc|244|oacute|iuml|239|ecirc|235|Igrave|eacute|233|euml|236|238|icirc|iacute|237|igrave|246|ouml|yuml|String|255|thorn|254|fromCharCode|html_entity_decode|split|join|delete|this|toString|yacute|253|oslash|249|248|divide|247|ugrave|250|252|uuml|ucirc|251|uacute|egrave|234|214||Ouml|Otilde|213|||Ocirc|215|times|Ugrave|218|232|Oslash|216|212|Oacute|Icirc|207|206|Iacute|205|208|ETH|Ograve|211|210|Ntilde|209|Uacute|217|atilde|228|227|acirc|219|auml|229|231|ccedil|aelig|230|aring|aacute|226|Yacute|225|221|Uuml|Ucirc|220|THORN|222|223|224|agrave|szlig'.split('|'),0,{}));

