var status_on_empty;

function savea_FilterSelectsBy( id ) {
	var i = option_id_to_index[ id ]; // index på aktuell drop-down, 0 - n-1
	var n = index_to_option_id.length;
	var e = savea_GetObj( 'option_' + id );
	var x = e.options[ e.selectedIndex ].value;
	var cv = new Array();
	var j,k,m;
	selectedValues[i]=x;
	var must_refresh=false;refresh_index=-1;
	for(m=0;m<selectedOrder.length;++m){
		if(selectedOrder[m]==i){
			refresh_index=x>0?m+1:m;must_refresh=true;break;
		}
	}
	if(!must_refresh){
		selectedOrder[selectedOrder.length]=i;
	}else{
		for(m=refresh_index;m<selectedOrder.length;++m){
			selectedValues[selectedOrder[m]]=0;
		}
		selectedOrder.splice(refresh_index,selectedOrder.length);
	}
	for ( j = 0; j < n; ++j ) {
		if ( j == i || selectedValues[ j ] > 0 ) continue;
		/// töm <select>-boxen på alla värden utom det första "(Välj)"
		e=savea_GetObj('option_'+index_to_option_id[j]);
		cv[ j ] = e.options[ e.selectedIndex ].value;
		for(k=e.options.length-1;k>0;--k)e.remove(k);
	}
	var val, name;
	var added=new Array();
	var chk = function(k) {
		for ( var m = 0; m < n; ++m ) {
			if ( selectedValues[ m ] > 0 && valid_combinations[ k ][ m ] != selectedValues[ m ] ) {
				return false;
			}
		}
		return true;
	}
	for ( k = 0; k < valid_combinations.length; ++k ) {
		/// om detta är en kombination där vårt värde ingår..
		if ( chk( k ) ) {
			/// .. fyll de övriga listorna med deras värden
			for ( j = 0; j < n; ++j ) {
				if ( j == i || selectedValues[ j ] > 0 ) continue;
				/// lägg till nytt värde i <select>-boxen
				val = valid_combinations[ k ][ j ];
				if ( ! added[ val ] ) {
					added[ val ] = true;
					name = value_names[ val ];
					selected = ( last_selected[ j ] && last_selected[ j ] == val );
					e=savea_GetObj('option_'+index_to_option_id[j]);
					o=document.createElement('option');
					o.text=name;o.value=val;
					if(selected){o.selected=true;}
					if(savea_GetObj('ie')){e.add(o);}else{e.appendChild(o);}
				}
			}
		}
	}
	last_selected[ i ] = x;

	var ok = true;
	for ( j = 0; j < n; ++j ) {
		e = savea_GetObj( 'option_' + index_to_option_id[j] );
		if ( e.selectedIndex <= 0 ) { ok = false; break; }
	}

	if ( ok ) {
		var p,oid,pd="product_id="+PRODUCT_ID,varopts="variation_";
		p=index_to_option_id;
		for(j=0;j<p.length;++j){
			e=savea_GetObj('option_'+p[j]);
			oid=e.options[e.selectedIndex].value;
			pd+="&option_"+p[j]+"="+oid;
			varopts+=oid+(j<p.length-1?"_":"");
		}
		pd+="&s="+PRODUCT_KEY;
		if(typeof statics[varopts] != 'undefined'){
			var response = statics[varopts];
			savea_SetPrice(response.actual_product.price);
			savea_SetInventoryStatusText(response.actual_product.in_stock);
			savea_SetBuyButton(current_in_stock>0);
			savea_SetImage(response.actual_product.var_image);
		}
		else {
			savea_SetProgress(true);
			var callback={success:savea_OnValidVariation,failure:savea_OnFailedVariation,argument:['v',id,varopts]};
			var request = YAHOO.util.Connect.asyncRequest('POST',ROOT_PATH+'v/'+Math.round(Math.random()*2e12)+"/",callback,pd);
		}
	}
	else {
		savea_SetInventoryStatusText(-1);
		savea_SetPrice(-1);
		savea_SetBuyButton(false);
		savea_SetImage(-1);
	}
}

function savea_SetProgress(on){
	var div=savea_GetObj('container');
	var o=savea_GetObj('progressbar');
	if(!o && on){
		o=document.createElement('img');
		o.src = ROOT_PATH+'images/progressbars/orange.gif';
		o.style.width = '256px';
		o.style.height = '24px';
		o.style.position = 'absolute';
		o.id = 'progressbar';
		div.appendChild(o);
	}
	if(o)o.style.display=on?'block':'none';
}

var savea_OnValidVariation = function(o){
	savea_SetProgress(false);
	var e;
	if(o.responseText !== undefined){
		var response=null;
		try{response=eval('('+o.responseText+');');}catch(ex){}
		if ( response && response.actual_product && response.actual_product.price && response.always_in_stock ) {
			statics[o.argument[2]]=response;
			status_on_empty=response.actual_product.status_on_empty;
			savea_SetPrice(response.actual_product.price);
			savea_SetInventoryStatusText(response.actual_product.in_stock);
			savea_SetBuyButton(current_in_stock>0 || status_on_empty=='on_preorder' || response.always_in_stock);
			savea_SetImage(response.actual_product.var_image);
			return;
		}
	}
	savea_SetPrice(-1);
	savea_SetInventoryStatusText(-1);
	savea_SetBuyButton(false);
	savea_SetImage(-1);
};

var savea_OnFailedVariation = function(o){
	savea_SetProgress(false);
	savea_SetInventoryStatusText(-1);
	savea_SetPrice(-1);
	savea_SetBuyButton(false);
	savea_SetImage(-1);
};

function savea_SetBuyButton(ok){
	var e=savea_GetObj('buy_button');
	e.enabled=ok;
	e.className = ok?'button_buy_product':'button_buy_product_inactive';
}

function savea_SetImage(var_image){
	var a,e,fn=""+PRODUCT_ID;
	if(-1!=var_image && var_image.var_id){
		fn=""+var_image.var_id;
	}
	fn+=".jpg";
	a=savea_GetObj('pim_link');
	e=savea_GetObj('pim_image');

	// bilder kan komma på formaten: nn.jpg, nn_nn.jpg, nn__xyz.jpg eller nn_nn__xyz.jpg
	p = /\/(([0-9]+\_[0-9]+\_\_.*?|[0-9]+\_\_.*?|[0-9]+\_[0-9]+|[0-9]+)\.jpg)$/;
	a.href=a.href.replace(p,"/"+fn);
	e.src=e.src.replace(p,"/"+fn);
}

function savea_SetPrice(price){
	var e,t;
	if(-1==price){t=def_price;}
	else{
		if(SETTINGS_NO_VAT){t=SETTINGS_NO_DECIMALS?price.formatted_no_vat_no_decimals:price.formatted_no_vat;}
		else {t=SETTINGS_NO_DECIMALS?price.formatted_no_decimals:price.formatted;}
	}
	e=savea_GetObj('price_current');if(e)e.innerHTML=t;
	e=savea_GetObj('quickfacts_price');if(e)e.innerHTML=t;
	if(-1!=price&&statics['last_price']!=t)savea_FlashDiv('price_current');
	statics['last_price']=t;
}

function savea_SetInventoryStatusText(in_stock){

	// uppdatera inte lagerstatusen om flaggan always_in_stock är satt till 1
	if (always_in_stock == 1)
		return;

	current_in_stock=in_stock;
	var t;
	if(in_stock<0)t="<em>Beror på utformning</em>";
	else if(!in_stock) {
		if(status_on_empty == 'on_preorder')t="Tar emot förhandsordrar";
		else t="<strong>Tillfälligt slutsåld</strong>";
	}
	else if(in_stock < 10)t="<strong>Fåtal kvar!</strong>";
	else t="Finns i lager";
	var e=savea_GetObj('in_stock_output');
	if(e)e.innerHTML=t;
	if(in_stock>=0&&statics['last_in_stock']!=t)savea_FlashDiv('in_stock_output');
	statics['last_in_stock']=t;
}

function savea_CanBuy(){
	if(can_buy)return true;
	var e,j,n,ok=true;
	if(typeof index_to_option_id != 'undefined'){
		n=index_to_option_id.length;
		for ( j = 0; j < n; ++j ) {
			e = savea_GetObj( 'option_' + index_to_option_id[j] );
			if ( e.selectedIndex <= 0 ) { ok = false; break; }
		}
	}
	if ( ! ok ) {
		alert( 'Välj värden för alla egenskaper först.' );
		return false;
	}
	else if ( current_in_stock < 1 && status_on_empty != "on_preorder") {
		alert( 'Produkten är för tillfället tyvärr slutsåld i valt utförande.' );
		return false;
	}
	return true;
}

function savea_FlashDiv(id){
	var e = savea_GetObj(id);
	var to_rgb,from_rgb;
	var s = 'flashdiv_bkg_'+id;
	if(typeof statics[s] != 'undefined'){
		to_rgb = from_rgb = statics[s];
	} else {
		to_rgb = from_rgb = e.style.backgroundColor;
		statics[s] = from_rgb;
	}
	if ( from_rgb == "transparent" || from_rgb == "" ) {
		to_rgb = 'rgb(255,255,255)';
	}
	e.style.backgroundColor = 'rgb(255,255,0)';
	var attributes = {
		backgroundColor: { to: to_rgb }
	};
	var fadeEnd = function() {
		var el = this.getEl();
		el.style.backgroundColor = from_rgb;
	}
	var anim = new YAHOO.util.ColorAnim(e, attributes, 1.25);
	anim.onComplete.subscribe(fadeEnd);
	anim.animate();
}

