var aVariants = new Array();
var SortLookup = { 'XS' : 50 , 'EXTRA SMALL' : 51 , 'S' : 60 , 'SMALL' : 61 , 'M' : 70 , 'MEDIUM' : 71 , 
                                'L' : 80 , 'LARGE' : 81 , 'XL' : 90 , 'EXTRA LARGE' : 91 , 'XXL' : 100 , '2X LARGE' : 101 };

$(document).ready( function() {

/**
* Initialize default Ajax settings
*/
/*$.ajaxSetup({
    url: '/index.php',
    type: 'get',
    contentType: "application/x-www-form-urlencoded; charset=utf-8",
    beforeSend:function(xhr) {}
})*/ 

  
  

$("a[href='#']").bind("click", function(){return false;});


// Zoom-icons
$("span.zoom-icon").bind("click", function(){
	$.colorbox({href: $(this).attr('title') }); 
})

// Builds the pages links
if ( $("div.Pages").length > 0 && (Pages.Total*1) > 1 ){
	if ( document.location.href.indexOf('advsearch') > 0 ){
		var url = 'main.php3?PI=advsearch'; 
	}else{
		if ( document.location.href.indexOf('PI=search') > 0 ){
			var url = 'main.php3?PI=search';
		}else{
			var url = 'main.php3?PI=list&amp;MG='+Categories.Group+'&amp;SG='+Categories.Sub;
		}
	}
	$("div.Pages").append('<ul>');
	$("div.Pages > ul").append('<li>Side:</li>');
	
	if ( (Pages.Total*1) <= 10 ){
		for ( i = 1; i <= (Pages.Total*1); i ++ ){
			$("div.Pages > ul").append('<li><a href="'+url+'&amp;CP='+i+'" '+ ( i == (Pages.Current*1) ? 'class="active"' : '' ) + '>'+i+'</a></li>');
		}
	}else{
		for ( i = 1; i <= (Pages.Total*1); i ++ ){ 
			if ( i == ((Pages.Current*1)-2) && i > 3){
				$("div.Pages > ul").append('<li>...</li>'); 
			}
			if ( i <= 3 || (i >= ((Pages.Current*1)-1) && i <= ((Pages.Current*1)+1) ) || (i > ((Pages.Total*1)-3) ) ){ 
				$("div.Pages > ul").append('<li><a href="'+url+'&amp;CP='+i+'" '+ ( i == (Pages.Current*1) ? 'class="active"' : '' ) + '>'+i+'</a></li>');
			}
			if ( i == ((Pages.Current*1)+2) && i < ((Pages.Total*1)-2) ){
				$("div.Pages > ul").append('<li>...</li>');         
			}
		}
	}
}


var menu = ""; 
$.each( aOG, function( idx ){
	var OGidx = idx; 
	var SGSidx = 0;
	var submenu = '';
	var subsubmenu = '';
	
	if ( Categories.Headgroup == aOG[idx][0] ){
		menu += '<li><a href="main.php3?PI=main&OG='+aOG[idx][0]+'#menu" class="active"><img src="Template/nmi/gfx/icon.collapse.png" width="9" height="9" alt="" />'+aOG[idx][1]+'</a>';
	}else{
		menu += '<li><a href="main.php3?PI=main&OG='+aOG[idx][0]+'#menu"><img src="Template/nmi/gfx/icon.expand.png" width="9" height="9" alt="" />'+aOG[idx][1]+'</a>';
	}
	$.each( aSGS, function( i ){
		SGSidx = i;
		if ( SGSidx == 0 ){ submenu += '<ul>';}
		if ( aSGS[SGSidx][0] == aOG[OGidx][0] && aSGS[SGSidx][3] == '' ){ 
			if ( subsubmenu != '' ){
				submenu += subsubmenu + '</ul>'; 
			}
			subsubmenu = '';
			submenu += '<li><a href="main.php3?MG='+ aSGS[SGSidx][1] +'&SG=nil#menu">'+aSGS[SGSidx][2]+'</a>';
		}
		if ( aSGS[SGSidx][0] == aOG[OGidx][0] && aSGS[SGSidx][3] != '' ){
			if ( subsubmenu == '' ){ subsubmenu += '<ul id="Cat-'+aSGS[SGSidx][1]+'">' };
			subsubmenu += '<li><a href="main.php3?PI=list&MG='+ aSGS[SGSidx][1] +'&SG='+ aSGS[SGSidx][3] +'">'+aSGS[SGSidx][4]+'</a></li>';
		}
	});
	if ( subsubmenu != '' ){ submenu += subsubmenu + '</ul>'; };
	if ( SGSidx > 0 ){ submenu += '</ul>';}
	if ( submenu != '<ul></ul>' ){ menu += submenu; };
	menu += '</li>';
});
$("ul.ProductMenu").append(menu);



// Fetch product fits
if ( $("#ProductFitsOnContent").length > 0 && ProductId != ''  ){
$("#ProductFitsOn").bind("mousedown", function(){
	 $.ajax({
		url: 'ajax_fetch_matching_products.php?ID=' + ProductId,
		success: function(data, textStatus, XMLHttpRequest) {    
			$("#ProductFitsOnContent").html(data);    
		}
	 });
});
}



// Collapsable items in leftcolum
$(".collapsable").bind("mousedown", function(){
	$(this).next().toggle();
	$(this).next().next().toggle();
});



// Remove add on all pages except front
if ( document.location.href.indexOf('OG=') > 0 ){
	if ( document.location.href.indexOf('OG=42') < 0 ){
		$("div.FlashAdvertisement").remove();
	} 
}


// Expand menu
if ( Categories.Group != '' && $("#Cat-"+Categories.Group).length > 0 ){
	$("#Cat-"+Categories.Group).show()
	$("#Cat-"+Categories.Group).prev().addClass("subactive");
} 



$("#ProductNavigation > ul.NavigationMenu > li").bind("mousedown", function(){
	$("div.ProductTabContent").hide();
	$("#"+ $(this).attr('id') + "Content").show();
	
	$("#ProductNavigation > ul.NavigationMenu").find('a').removeClass('active');
	$(this).find('a').addClass("active"); 
	/*var html = $(this).find('a').html();
	$(this).find('a').html('<strong>'+html+'</strong>');*/
});

//Slideshow
if ( $("a[rel='ProductSlideshow']").length > 0 ){
    $("a[rel='ProductSlideshow']").colorbox();   
}



$("button").live("click", function(){
	var value = $(this).get(0).getAttributeNode('value').value;
    if ( value !== null && value != '' ){
        document.location.href = value; 
    }
})



// Clean up echos in advsearch index
if ( document.location.href.indexOf('PI=advsearchindex') > 0 ){
	var prevval = '';
	$(".ProductListing > tbody > tr").each( function(){
		if ( $(this).html() == prevval ){
			$(this).attr({ title : 'remove' });
		}
		prevval = $(this).html();
	});
	$(".ProductListing > tbody > tr[title='remove']").remove(); 
}



// Init Varianter
if ( $("select[id^='_formVariantType']").length > 0 ){
	$("select[id^='_formVariantType']:first").change()
} 



// Fix notloggedin
$(".notloggedin > form").remove();
if ( $(".notloggedin").length == 0 ){ $(".buyinfo").remove(); }   
if ( $(".isVariantTrue").length > 0 ){ 
	$(".isVariantTrue").each(function(){
		$(this).parent().parent().find(".isVariant").show();
	});
 }
 
 
 
 
 // Remove customer prices
 if ( !ShowOnlyOutPrice ){
	$(".Resellerprice").show();
 }
 
 

} );     






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;
}




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








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 WrongUsernamePassword(){ 
	$.colorbox({html: '<div class="errorbox"><p><img src="/Template/NMI/gfx/q3design1/Silk/16x16/exclamation.png" width="16" height="16" alt="" /> Feil brukernavn / passord. </p><p>Du har tastet inn ett ukjent brukernavn eller ett feil passord.<br /><br />Kontakt oss på <a href="mailto:post@norskmotorimport.no">post@norskmotorimport.no</a> for hjelp.</p></div>', width: '300px', height: '120px', scrolling: false, onComplete: function(){
		}
    })
}

function UserBlocked(){ 
	$.colorbox({html: '<div class="errorbox"><p><img src="/Template/NMI/gfx/q3design1/Silk/16x16/exclamation.png" width="16" height="16" alt="" /> Konto sperret. </p><p>Denne kontoen har blitt sperret.<br /><br />Kontakt oss på <a href="mailto:post@norskmotorimport.no">post@norskmotorimport.no</a> for hjelp.</p></div>', width: '300px', height: '120px', scrolling: false, onComplete: function(){
		}
    })
}
