var aVariants = new Array();
var aSortArray = { 'XXS' : 10, 'XS' : 20, 'S' : 30, 'M' : 40, 'L': 45, 'XL': 50, 'XXL': 60, '3XL' : 70, '4XL':80 };

function getOffset( el ) {
    var _x = 0;
    var _y = 0;
    while( el && !isNaN( el.offsetLeft ) && !isNaN( el.offsetTop ) ) {
        _x += el.offsetLeft - el.scrollLeft;
        _y += el.offsetTop - el.scrollTop;
        el = el.parentNode;
    }
    return { top: _y, left: _x };
}

var VariantTypes = new Array();
$(document).ready(
function() {

    $.ajaxSetup({
        contentType: "application/x-www-form-urlencoded; charset=ISO-8859-1",
        dataType: "html"
    });
    
    $("a>input").live("click", function(){ document.location.href=$(this).closest("a").attr("href"); });

    $("input[type='button'][class*='checkoutconfirmed']").live("click", function(){ document.location.href="/Checkout/Confirmed"; });         

    /**
    * General Handler
    * - Topmenu
    * - Login
    * - Search
    */
    if ( $("#navmenu").length > 0 ){

        // Adding handlers for Top navbar ( Login, basket, languate etc. )
        $("#navmenu>ul>li").bind("click", function(){
            if ( $('#'+$(this).attr("name")+'Form').length > 0 ) {

                if ( $(this).is(".active") ){
                    $(this).removeClass("active");   
                    $('#'+$(this).attr("name")+'Form').hide();
                }else{ 
                    $("#navmenu>ul>li").removeClass("active");
                    $("#navmenu>.container").css({'display':'none'});
                    $(this).addClass("active");   
                    $('#'+$(this).attr("name")+'Form').css({'left' : $(this).find('a:first').position().left + 'px' }).show();
                    $('#'+$(this).attr("name")+"Form input:first").focus();
                }
            }
        } );

        // Removes/updates items from the basket
        $(".ItemRemove").live('click', function(){
            $.get( '/index.php?page=wsOrder&getType=partial&action=add&Aid=' + $(this).attr('name') + '&Quantity=0', function(data, textStatus, XMLHttpRequest) {
                $("#OrderForm").html('').html(data);
            }, 'html');          
            return false;
        });
        $("#OrderFormTable>tbody>tr>.col3").live('change', function(){
            $.get( '/index.php?page=wsOrder&getType=partial&action=add&Aid=' + $(this).attr('name') + '&Quantity=' + $(this).find('input').val(), function(data, textStatus, XMLHttpRequest) {
                $("#OrderForm").html('').html(data);
            }, 'html');
            return false;
        });



        // Handlers for Login fields
        $(".username,.password").bind('focus', function(){
            if ( $(this).val() == 'Brukernavn' ){
                $(this).val('');
                $(this).removeClass('inputDescription');
            }
        }).bind('blur', function(){
            if ( $(this).val() == '' ){
                $(this).addClass('inputDescription');
                $(this).val('Brukernavn');
            }     
        });

        // Handler for the main navigation menu.                                  
        $(".menu>ul>li").bind("mouseenter",
        function() {
            $(this).children("a").addClass("active2");
            $("a.active").addClass("activeTemp").removeClass("active");
        }).bind("mouseleave", 
        function() {
            $(this).children("a").removeClass("active2");
            $("a.activeTemp").addClass("active").removeClass("activeTemp"); 
        }
        );


        // Searchbox Handler
        $("#s").focus(
        function() {
            if ($(this).val() == strings['searchString']) {
                $(this).val("");
            }
        }
        ).blur(
        function() {
            if ($(this).val() == "") {
                $(this).val(strings['searchString']);
            }
        }
        ).keypress(
        function(event) {
            // TODO: OLA?? autocomplete
        }
        );

        // hide navboxes when click outside
       /* $("body").click(
        function(event) {
            //console.log(event.clientX + " x " +event.clientY);
            var pos = getOffset($("#navmenu")[0]);
            //console.log(pos);
            if (event.clientX < pos.left ||
            event.clientX > pos.left*1 + $("#navmenu").width()*1 ||
            event.clientY < pos.top ||
            event.clientY > pos.top*1 + $("#navmenu").height()*1
            ) {
                var item = $("#navmenu").find(".active").removeClass("active");
                $('#'+item.attr("name")+'Form').hide();
            }
        }
        );  */

    } // END General Handlers



    /**
    * ProductPage Handlers
    * - Tabnavigation
    * - Slideshow/lightbox
    * - Buy buttons
    * etc.
    */
    if ( $("#productmenu").length > 0 ){

        /**
        * Tabpages on product page.
        */

        $("#productmenu>ul>li").bind("click", function(){
            $(".tabs").hide();
            var li = $(this);
            var obj = $("#"+$(this).attr('name'));
            $(obj).show(); 
            $(this).parent().find('li').removeClass('active');
            $(this).addClass('active');

            if ( $(obj).html().length > 100 )
                return false;
				
			if ( $(this).attr('name') == "AlternativeProducts" ){
				return false;
			}
			
			if ( $(this).attr('name') == "MatchingModels" ){
				return false;
			}

            $(li).find('img').show();

            $.ajax({
                url: '/index.php?page=wsProduct&Id='+ $(li).parent().attr('name') +'&getType=partial&isvariant=true&tpl=Product.'+ $(this).attr('name') +'.tpl',
                type: 'get',
                dataType: 'html',
                success: function(data, textStatus, XMLHttpRequest) {
                    $(obj).html(data);
                },
                complete: function ( XMLHttpRequest, textStatu ){
                    $(li).find('img').hide();  
                } 
            });
        });

        // Handler for Slideshow
        if ( $("a[rel='ProductSlide']").length > 0 ){
            $("#imagecontainer").find('.large').bind( 'click', function(){
                $("a[rel='ProductSlide']:last").click();
            });
            $("a[rel='ProductSlide']").colorbox();
        } 

        // Handler for variants
        $("#VariantSelector").bind("change", function(){
            var Selected = $(this).val();
            $(VariantTypes).each(function(idx){
				//console.log( $(this)[0].Values );
                if ( $(this)[0].ProductId == Selected ){
                    //$("#AdditionalProducts").html("");
                    $("#ProductName").html( $(this)[0].ProductName );
                    $(".productNumber").html( $(this)[0].ProductNumber );
                    $(".productStock").html( $(this)[0].ProductStock );
                    $(".newprice,.price").html( $(this)[0].ProductPrice );
					
					$(".basket").attr("name", Selected );

                    // Fill Additional products with choice from Variant.
                   /* $.ajax({
                        url: '/index.php?page=wsProduct&Id='+$(this)[0].ProductId +'&getType=partial&isvariant=true&tpl=Product.AdditionalProducts.tpl',
                        type: 'get',
                        dataType: 'html',
                        success: function(data, textStatus, XMLHttpRequest) {
                            $("#AdditionalProducts").html(data);
                        },
                        complete: function ( XMLHttpRequest, textStatu ){
                        },
                    });*/

                    return false;
                }
            })
        })

		if ( $("select[name^='Type-']").length > 0 ){
			$("select[name^='Type-']").each(function(idx){
				var obj = $(this)[0];
				obj.length = 0;
				$.each( aVariants, function(idx){
					addOption(obj, {value: aVariants[idx][obj.name], text: aVariants[idx][obj.name] });
				})    
			} );
		}


		// Add field sorter
		$("select[name^='Type-']").each(function(){
			sortSelectType($(this), aSortArray);    
		})

		// Add Varianthandler
		$("select[name^='Type-']").bind('change', function(){
		
			var changedSelect = $(this);
		
			// extract suboptions
			var thisValue = $(this).val();
			var subOptions = new Object();
			var topSelection = $("select[name='Type-0']").val(); 
			$(VariantTypes).each(function( index ){
				//console.log( $(this)[0].Values );
				var values = $(this)[0].Values.split( ";" );
				if ( values[0] == topSelection ){
					if ( typeof( subOptions[values[1]] ) == "undefined" ){
						subOptions[values[1]] = new Object();
					}
					subOptions[values[1]][values[2]]  = 1;
				}
			});
			
			// remove old suboptions and add extracted one
			$("select[name^='Type-']").each( function( index, element ){
				if ( index == 0 ) return;
				var e = $( element );
				// do not rebuild the select that was used
				if ( changedSelect.attr("name") == e.attr("name") ) return;
				
				var oldVal = e.val();
				e.empty();
				
				var optionChain = subOptions;
				if ( index > 1 ){			
					for ( var i = 1; i < index; i++ ){
						var selection = $("select[name='Type-" + i + "']").val();
						optionChain = optionChain[selection];
					}
				}
				for ( var prop in optionChain ) {
					addOption( e, {value: prop, text: prop });
				}
				if ( oldVal ) e.val( oldVal );
			});
			
			// handle selection of product
			var variantIdx = getVariantIdx(); 
			if (variantIdx == -1) {
				return;
			}
			
			var ProductId = aVariants[variantIdx]['ProductId'];
			$("#VariantSelector").val(ProductId).change();
		})

		// Init
		if ( $("select[name^='Type-']").length > 0 ){
			$("select[name^='Type-0']").change();
		}


    }  


    // Handler for adding products to basket            
    if ( $(".basket").length > 0 ){
        $(".basket").live( 'click', function(){
            $.ajax({
                url: '/index.php?page=wsOrder&getType=partial&action=add&Aid=' + $(this).attr('name') + '&Quantity=' + ( $(this).prev().val() != undefined ? $(this).prev().val() : $(this).closest("tr").find("input[name='Quantity']").val() ),
                type: 'get',
                dataType: 'html',
                success: function(data, textStatus, XMLHttpRequest) {
                    $("#OrderForm").html('').html(data);
                }, 
            });  
        });
    }
	
	



    if ( $(".submenuitemlink > a").length > 0 ) {
        $(".submenuitemlink > a").each( function(idx){
            if ( $(this).html() == '' ){
                $(this).parent().parent().parent().remove();
            }
        }); 

    }

    
    
    

/**
* Productmenu selector
*/
if ( groups.head != '' && groups.main == '' ){
    $(".L1-"+groups.head).find('ul').show();
}

if ( groups.main != '' ){
    $(".L2-"+groups.main).parent().parent().parent().show();
    $(".L2-"+groups.main).parent().show();
    $(".L2-"+groups.main).find('ul').show();
    
    if ( groups.sub != '' ){
        $(".L3-"+groups.sub).find("a:first").addClass("activesub");
    }
}



$(".ReadTerms").bind("click", function(){
    $.colorbox({href: '/Betingelser?getType=partial', width: '800px', height: '600px', onComplete: function(){
        $(".DocumentContentContainer,.DocumentHeader").css({'padding' : '5px'}); 
        var text = html_entity_decode( $("#cboxLoadedContent").html() );
        $("#cboxLoadedContent").html( text.replace(/\\n/gi, "").replace(/\\/gi, "") );
    }
    })
});


/**
* Submit Order
*/
$("button.ConfirmOrder").bind("click", function(){
    if ( $("input[name='Order[AcceptTerms]']").length > 0 ){
        if ( $("input[name='Order[AcceptTerms]']:checked").length == 0 ){
            return;
        }
    }
    document.location.href = '/Checkout/Confirmed';
});



// Checkout shipmenttype Handler
$("select[name='Shipment[Type]']").bind('change', function(){
    $("#OrderPaymentTypes > legend > img:first").show();
     
    $.ajax({
        data: {page: 'wsCheckout', getType: 'partial', tpl: 'Checkout(PaymentTypes)', action: 'validPaymentTypes', 'Shipment[Type]': $(this).val() },
        success: function(data, textStatus, XMLHttpRequest) {    
            $("#OrderPaymentTypes").html(data);
            if ( $("input[name='Payment[Type]']:checked").length <= 0 ){
                $("input[name='Payment[Type]']:first").attr({checked: 'checked'});
            }
            $("#OrderPaymentTypes > legend > img:first").hide();
        },
        error: function(){
            $("#OrderPaymentTypes > legend > img:first").hide();
        }
     });    
})


// Checkout paymenttype Handler
$("input[name='Payment[Type]']").live('click', function(){
    // Show ajax loader for ShipmentTypes
    $("#OrderShipmentTypes > legend > img:first").show(); 
    
    $.ajax({
        dataType: 'json', 
        data: {page: 'wsCheckout', getType: 'json', tpl: 'Checkout(ShipmentTypes)', action: 'validShipmentTypes', 'Payment[Type]': $(this).val() },
        success: function(data, textStatus, XMLHttpRequest) {
            
            $("select[name='Shipment[Type]'] > option").each( function(idx){
                var opt = $(this);
                $.each( data['ShipmentTypes'], function(key, item){
                    if ( $(opt).val() == item.Id ){
                        $(opt).html( item.Name + ' (' + item.Price1.Include_money + ')' );
                    }
                })
            } );
            // Hide ajax loader
            $("#OrderShipmentTypes > legend > img:first").hide();                   
        },
        error: function(){
            // Hide ajax loader
            $("#OrderShipmentTypes > legend > img:first").hide();                   
        }
     });    
})


/**
* Init PaymentType in Checkout
*/
if ( $("select[name='Shipment[Type]']").length > 0 ){
    $("select[name='Shipment[Type]']").change();
}


/** modelsearch */
$("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();
	}
});




});



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() * 1 );
        var yVal = ( jQuery(y).val() * 1 );
        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);
};

    


/** ModelSearch */
/*
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"});
    }
    if ( ModelSearch.Brand != "" ){
        $("select[name='Search[Brand]'] > option[value='"+ModelSearch.Brand+"']").attr({"selected" : "selected"});
        $("select[name='Search[Brand]']").change();
    }
    if ( ModelSearch.Volume != "" ){
        $("select[name='Search[Volume]'] > option[value='"+ModelSearch.Volume+"']").attr({"selected" : "selected"});
        $("select[name='Search[Volume]']").change();
    }

    if ( ModelSearch.Year != "" ){
        $("select[name='Search[Year]'] > option[value='"+ModelSearch.Year+"']").attr({"selected" : "selected"});
        $("select[name='Search[Year]']").change();
    }
    if ( ModelSearch.Model != "" && ModelSearch.Model != "|" ){
        $("select[name='Search[Model]'] > option[value='"+ModelSearch.Model+"']").attr({"selected" : "selected"});
        $("select[name='Search[Model]']").change();
    }
}

function ModelsearchTypes(){
    if ( $("select[name='Search[Type]']").length <= 0 ){
        ModelsearchBrands();
    }else{
        $("select[name='Search[Type]'] > option").remove();
        $("select[name='Search[Brand]'] > option").remove();
        $("select[name='Search[Volume]'] > option").remove();
        $("select[name='Search[Year]'] > option").remove();
        $("select[name='Search[Model]'] > option").remove();

        $.each(ModelsearchModels, function(){
            var cur = $(this)[0];
            if ( $("select[name='Search[Type]'] > option[value='"+cur.T+"']").length == 0 && cur.T != "" ){
                $("select[name='Search[Type]']").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[Volume]'] > option").remove();
    $("select[name='Search[Year]'] > option").remove();
    $("select[name='Search[Model]'] > option").remove();

    var isFilled = false;
    $.each(ModelsearchModels, function(){
        var cur = $(this)[0];
        if ( ( cur.T == CurrentType || CurrentType == null ) && $("select[name='Search[Brand]'] > option[value='"+cur.B+"']").length == 0 && cur.B != "" ){
            $("select[name='Search[Brand]']").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 isFilled = false;
    $.each(ModelsearchModels, function(){
        var cur = $(this)[0];
        if ( CurrentYear == "-1" || CurrentYear == null ){
            if ( cur.T == CurrentType && cur.B == CurrentBrand && $("select[name='Search[Volume]'] > option[value='"+cur.C+"']").length == 0 && cur.C != "" ){
                $("select[name='Search[Volume]']").append('<option value="'+cur.C+'">'+cur.C+'</option>');
                isFilled = true;
            }
        }else{
            if ( cur.T == CurrentType && cur.B == CurrentBrand && cur.YF <= CurrentYear && cur.YT >= CurrentYear && $("select[name='Search[Volume]'] > option[value='"+cur.C+"']").length == 0 && cur.C != "" ){
                $("select[name='Search[Volume]']").append('<option value="'+cur.C+'">'+cur.C+'</option>');
                isFilled = true;
            }    
        }
        if ( isFilled && cur.B != CurrentBrand ){return false;}
    })

    if ( CurrentVolume == null ) CurrentVolume = "-1";

    $("select[name='Search[Volume]']").sortOptionsByValue();
    $("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="-1"> Alle</option>');

    $("select[name='Search[Model]'] > option").remove();

    var dt = new Date();
    for ( i = (dt.getFullYear()+1); i >= 1965; i-- ){
        $("select[name='Search[Year]']").append('<option value="'+i+'">'+i+'</option>');       
    }

    if ( CurrentYear == null ) CurrentYear = "-1";

    $("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();

    var isFilled = false;   
    $.each(ModelsearchModels, function(){
        var cur = $(this)[0];
        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' && 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 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 != "" ){
                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,{}));

    
    
    
function addOption(obj, option){
    if ( $(obj).find("option[value='"+option.value+"']").length <= 0 ){
        $(obj).append('<option value="'+option.value+'">' + option.text + '</option>');
    }
}


function sortSelectType(obj, sortarray){
    var mapSort = false;
    if ( $(obj).find('option').length > 0 ){
        var value2check = $(obj).find('option:first').val();
        
        // Check if there is a match in sortarray then we assume there is mapsort
        $.each( sortarray, function( key, value ){
            if ( key == value2check.toUpperCase() ){
                $(obj).sortOptionsByLookup( aSortArray ); 
                mapSort = true;
                return false;    
            }
        });
        
        if ( mapSort){ return true; }
               
        // Check for numeric if there was no match in map
        if ( IsNumeric( value2check ) ){
            $(obj).sortOptionsByValue();
            return true;                
        }
        
        $(obj).sortOptionsByText();
       
    }
}

function getVariantIdx(){
    var key = "";
    var keylen = 0;
    var ret = -1;
    
    if ( $("select[name^='Type-']").length > 0 ){
        $("select[name^='Type-']").each( function(){
            keylen++;
            key = key + $(this).val() + "-";
        })        
    }
    
    if ( key != "" ){
        $.each( aVariants, function(idx){
            var compare = '';            
            for( i=0; i < keylen; i++ ){
                compare = compare + aVariants[idx]['Type-'+i] +"-";
                if ( key == compare ){
                    ret = idx;
                }
            }
        })
    }
    
    return ret;
}

