$(document).ready(function(){

	/**
	 *	Aggiungi un elemento al carrello al click sull'apposito pulsante
	 */
	$('.cart_add').live('click', function() {
		/* Id dell'album */
		var album_id = $(this).attr('href').replace('#', '');
		/* Carica il carello aggiornato */
		$("#sidebar_cart").load( "ajax/cart.php", {"product": album_id, "operation": 'add'} );
		if($('#buy_confirm').is(':hidden'))
			$('#buy_confirm').show();
	});
	
	
	/**
	 *	Aggiorna la quantita' di prodotti nella pagina del carrello
	 */
	$('.product_quantity').blur(function() {
		
		/* Seleziona l'id del prodotto */
		var product_id_array = $(this).attr('id').split('_');
		var product_id = product_id_array[2];
		/* Seleziona la quantita' del prodotto */
		var product_quantity = $(this).val();
		
		/* Invia la quantita'  */
		$.ajax({
			type: "POST",
			url: "ajax/cart_quantity.php",
			data: { "product_id": product_id, "product_quantity": product_quantity },
			dataType: "json",
			success: function(msg) {
				if(msg.success != '') {
					$('#product_quantity_'+product_id).val(msg.data.quantity);
					$('#product_totalprice_'+product_id).text(msg.data.totalprice);
					$('#shipment_cost').text(msg.data.shipment_cost);
					$('#shipment_name').text(msg.data.shipment_name);
					$('#total_cost').text(msg.data.total_cost);
				} else {
					alert(msg.failure);
				}
				
			}
		});
	});
	
	/**
	 *	Cambia i metodi di pagamento sulla base dei valori selezionati
	 */
	$('.payment_method a').click(function() {
		/* Seleziona l'id del metodo di pagamento */
		var payment_method_id = $(this).attr('href').replace('#', '');
		$('#payment_method').val(payment_method_id);
		
		$('.payment_method a').each(function(i) {
			var this_pmid = $(this).attr('href').replace('#', '');
			if(this_pmid == payment_method_id) {
				$(this).removeClass('not_selected');
				$(this).addClass('selected');
			} else {
				$(this).addClass('not_selected');
				$(this).removeClass('selected');
			}
		});
	});
	
	/* Nascondi i messaggi d'errore e di successo */
	$('.failure').hide();
	
	/**
	 *	Effettua l'ordine di acquisto
	 */
	$('#cart_order .submit_button').click(function() {
		
		/* Nascondi i messaggi d'errore e di successo */
		$('.failure').hide();
		
		var form_data = $('#cart_order').serialize();
		
		/* Invia i dati per l'acquisto  */
		$.ajax({
			type: "POST",
			url: "ajax/cart_order.php",
			data: form_data+'&payment_method='+$('#payment_method').val(),
			dataType: "json",
			success: function(msg) {
				if(msg.success != '') {
					$('#albums').html(msg.success);
				} else {
					$('.failure').html(msg.failure);
					$('.failure').show(100);
				}
				
			}
		});
		
	});

});

jQuery.fn.decHTML = function() { 
  return this.each(function(){ 
    var me   = jQuery(this); 
    var html = me.html(); 
    me.html(html.replace(/&amp;/g,'&').replace(/&lt;/g,'<').replace(/&gt;/g,'>')); 
  }); 
}; 


