
var pproducts = {};
var poptions = {};
var pcombinations = {};
var pexceptions = {};
var pdiscounts = {};
var ptaxes = {};
var currency = {};


function formatPrice(n){
	var c = 2;
	var d = ",";
	var t = ".";
	c = isNaN(c = Math.abs(c)) ? 2 : c; 
	d = d == undefined ? "," : d;
	t = t == undefined ? "." : t;
	s = n < 0 ? "-" : "";
	i = parseInt(n = Math.abs(+n || 0).toFixed(c)) + "", 
	j = (j = i.length) > 3 ? j % 3 : 0;
	return '<span><span class="price">' + s + (j ? i.substr(0, j) + t : "") + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + t) + '</span><span class="decimal">' + (c ? d + Math.abs(n - i).toFixed(c).slice(2) : "") + '</span><span class="symbol">&#8364;</span>' + '</span>';	
}

function array_contains(a, b){
	for(x in a){
		if(typeof(b[x]) == 'undefined' || a[x] != b[x]){
			return false;
		}
	}
	return true;
}

function array_size(obj){
	var x=0;		
	if(typeof(obj) == "object"){
		for(y in obj){
			x++;	
		}	
	}
	return x;
}	

function sort_array_keys(arr){
	var tmp = [];
	for(var x in arr)
		tmp.push([x, arr[x]]);
	tmp.sort(function () {return arguments[1][0] - arguments[0][0]});
	var out = {};
	for(var y = tmp.length-1; y >=0; y--)
		out[tmp[y][0]] = tmp[y][1];
	return out;
} 


function get_options_hash(arr){
	var x = sort_array_keys(arr);
	var r = '';
	for(y in x){
		if(r != ''){
			r += ';';	
		}			
		r += y+':'+x[y];
	}	
	return r;
}

function checkCombinationOptions(productid, optionid){
	//varianveis:
	var obj_select; 
	var obj_options; 
	var curr_variant;
	var comb_selected;
	var select_variant;
	var selecteds = {};
	var shows = {};
	
	options = poptions[productid];
	combinations = pcombinations[productid];
	exceptions = pexceptions[productid];

	var last = false;
	var to_select = false;
	for(i in options){	
		obj_select = document.getElementById('product_option_'+productid+'_'+i);
		if(!obj_select){
			return false;
		}
		if(obj_select.nodeName.toLowerCase() != "select") return false;
		
		obj_options = obj_select.options;
		curr_variant = obj_select.value;  //verificar se é necessario
	
		if(!optionid || last){
			for(var j = obj_options.length - 1; j >= 0; j--){
				//obj_options[j];
				obj_options[j] = null;
			}
		}
		comb_selected = false;
		for(k in combinations){
		
//			if(exceptions.in_array(k)){
//				continue;				
//			}

			if(array_contains(selecteds, combinations[k]['options'])){	
				if(typeof(combinations[k]['options'][i]) == 'undefined'){
					continue;
				}
				
				select_variant = combinations[k]['options'][i];

				if(typeof(shows[select_variant]) != 'undefined'){
					continue;
				}
				
				shows[select_variant] = true;
				if(!optionid || last){
					var option = document.createElement("OPTION");
					option.value = select_variant;
					option.text = options[i]['variants'][select_variant]['name'];
					if(last && !comb_selected || select_variant == curr_variant){
						option.selected = true;
						comb_selected = true;
					}
					obj_select.options[obj_select.length] = option;	
				}
			}   
		}
			
		selecteds[i] = curr_variant;

		if(i == optionid){
			last = true;
		}
	}

	//actualiza preços
	updateCombPrices(productid, productid);
}



function updateCombPrices(productid, key){
	if(typeof(pcombinations[productid]) == 'undefined') return;
	var pcomb = pcombinations[productid];
	var pprod = pproducts[productid];
	var pdisc = pdiscounts[productid];
	var ptax = ptaxes[productid];
	
	var combsarr = {};
	for(i in options){
		combsarr[i] = $('#product_option_'+productid+'_'+i).val();
	}
	var chash = get_options_hash(combsarr);
	if(typeof(pcomb[chash]) == 'undefined') return;
	var comb = pcomb[chash];

	var _price = parseFloat(pprod['baseprice']);
	var _baseprice = parseFloat(pprod['baseprice']);	
	var _discount = parseFloat(pprod['discount']);
	var _ref = comb['ref']?comb['ref']:pprod['ref'];


	//MODIFIER PRICES
	if(comb['pricetype'] == 'P'){
		_price = _price+_price*parseFloat(comb['modifierprice'])/100;
		_baseprice = _baseprice+_baseprice*parseFloat(comb['modifierprice'])/100;
	}
	else if(comb['pricetype'] == 'A'){
		_price = _price+parseFloat(comb['modifierprice']);
		_baseprice = _baseprice+parseFloat(comb['modifierprice']);
	}
	
	//DISCOUNTS
	if(pdisc && (pdisc['A'] || pdisc['P'])){
		_dvalue = _price*parseFloat(pdisc['P'])/100 + parseFloat(pdisc['A']);
		_price = _price-_dvalue;
	}
	
	//TAXES
	for(i in ptax){
		if(ptax[i]['priceinctax'] == "0"){
			if(ptax[i]['valuetype'] == 'P'){
				_price = _price+_price*parseFloat(ptax[i]['ratevalue'])/100;
				_baseprice = _baseprice+_baseprice*parseFloat(ptax[i]['ratevalue'])/100;
			}
			else if(ptax[i]['valuetype'] == 'A'){
				_price = _price+parseFloat(ptax[i]['ratevalue']);
				_baseprice = _baseprice+parseFloat(ptax[i]['ratevalue']);
			}
		}
	}
	
	//$('#product_subtotal_content_'+productid).html(formatPrice(_subtotal));
	$('#product_price_content_'+productid).html(formatPrice(_price));
	$('#product_baseprice_content_'+productid).html(formatPrice(_baseprice));
	$('#product_discount_content_'+productid).html(formatPrice(_discount));
	$('#product_ref_content_'+productid).html(_ref);
}


function addProductCart(productid){
	form = $('#add_cart_form'+productid);
	if(!form.length) return;
	jQuery.ajaxRequest({
		'url': fronturl+'?mod=catalog&action=addCart',
		'data': $.param(form.serializeArray()),
		'type': 'POST',
		'dataType' : 'json',
		'callback': function(d){
			if(d.cart && d.cart['quantity']){
				var html = '<ul>';
				html =  html + '<li>Items: ' + d.cart['quantity'] + '</li>';
				html =  html + '<li>Subtotal: ' + formatPrice(d.cart['displaysubtotal']) + '</li>';
				html =  html + '<li><a href="' + fronturl + '?mod=catalog&action=viewCart">Ver Carrinho</a></li>';
				html =  html + '<li><a href="' + fronturl + '?mod=catalog&action=checkoutProfile">Checkout</a></li>';
				html =  html + '</ul>';
				$('#block_cart_links').html(html);
			}
			
		}
	});
}
