FastInit.addOnLoad(cartInit);

var item_id = null;

function cartInit() {
	if ($('sortby_popdown')) Event.observe($('sortby_popdown'), 'click', toggle_sortby_popdown);
	var quantities_fields = $A($('cart').getInputs('text'));

	quantities_fields.each(function (field) {
		Event.observe(field, 'keyup', quantity_change);
	});
}

function quantity_change(e) {

	var field = Event.element(e);
	var quantity = parseInt($F(field));	

	if(quantity == 'NaN'){
		return false;
		exit;
	}

	item_id = $(field).id.replace('item_quantity_', '');		
	
	$('item_tot_price_int_'+	item_id).innerHTML = '';
	$('total_amount_int').innerHTML = '';
	
	//TODO tradurre calcolo
	$('item_tot_price_dec_'+	item_id).innerHTML = 'calculating...';
	$('total_amount_dec').innerHTML = 'calculating...';
	
	var url = baseurl + 'change_quantity.ajax';
	var pars = 'item='+item_id + '&quantity=' + quantity;
	var myAjax = new Ajax.Request(
			url, 
			{
				method: 'post', 
				parameters: pars,
				asynchronous: true, 
				onComplete: quantity_changed
			});
}

function quantity_changed (req) {

	eval('var response_object = ' + req.responseText);

	var item_price = String(response_object.item_price);
	var cart_total = String(response_object.cart_total);
	var num_items = String(response_object.num_items);
	var item_id_ = String(response_object.item_id);

	if(!isNaN(item_price)) {

		var comma_pos = item_price.indexOf('.');
		
		var int_price;
		var dec_price;
		
		if(comma_pos == -1) {
			int_price = item_price;
			dec_price = '00 €';
		} else {
			int_price = item_price.substring(0, comma_pos);
			dec_price = item_price.substring(comma_pos + 1) + ' €';
		}
		
		$('item_tot_price_int_'+	item_id_).innerHTML = int_price + ',';
		$('item_tot_price_dec_'+	item_id_).innerHTML = dec_price;
	}
	
	if(!isNaN(cart_total)) {

		var comma_pos = cart_total.indexOf('.');
		
		var int_price;
		var dec_price;
		
		if(comma_pos == -1) {
			int_price = cart_total;
			dec_price = '00 €';
		} else {
			int_price = cart_total.substring(0, comma_pos);
			dec_price = cart_total.substring(comma_pos + 1) + ' €';
		}
		
		$('total_amount_int').innerHTML = int_price + ',';
		$('total_amount_dec').innerHTML = dec_price;
	}
	
	if(!isNaN(num_items)) {
		if(num_items == 1) {
			$('cart_items_count').innerHTML = num_items + ' item';
		} else {
			$('cart_items_count').innerHTML = num_items + ' items';
		}
	}
}

function toggle_sortby_popdown(e) {
	if ($('shopbycombo')) $('shopbycombo').style.visibility = 'hidden';
	Event.stop(e);
	
	if($('sortbycombo').style.visibility == 'visible') {
		$('sortbycombo').style.visibility = 'hidden';
	} else {
		$('sortbycombo').style.visibility = 'visible';
	}
}

function show_sortby_popdown(e) {
	if($('shopbycombo')) $('shopbycombo').style.visibility = 'hidden';
	$('sortbycombo').style.visibility = 'visible';
}

function hide_sortby_popdown(e) {
	$('sortbycombo').style.visibility = 'hidden';
}