(function($){
	$.fn.getEasyId = function(){
		if(typeof this.attr("id") != "string"){
			throw "Can't find anything suitable to get the id";
		}else{
			var reg = new RegExp(/^.*?(\d+)$/);
			return reg.exec(this.attr("id"))[1];
		}
	};
})(jQuery);

function mysum () {
  	$("input[name^=d_sum]").sum("change", "#d_tot");
    $("input[name^=l_sum]").sum("change", "#l_tot");
    $("input[class=tot_p]").sum("change", "#tot");

    $("input[type='text']:not(#n-email,#discount)").each(function() {
        $(this).val(parseFloat($(this).val()).toFixed(2));
    });
    
    var tot_old = 0;
    $("input[name^=d_sum],input[name^=l_sum]").each(function() {
    	var regex = /(\d+(\.(\d+))?)/;
    	var old_price = $(this).prev('span');
    	if (old_price.length > 0) {
    		var new_price = $(this).val().match(regex)[1];
    		var diff = old_price.text().match(regex)[1]-new_price;
    		tot_old += parseFloat(diff);
    	}
    });
    if (parseFloat(tot_old) > parseFloat(0)) {
    	$('#tot_old').parent().css('display', 'inline');
    	$('#tot_old').val(parseFloat(parseFloat($('#tot').val())+parseFloat(tot_old)).toFixed(2));
    } else {
    	if ($('#tot_old')) {
    		$('#tot_old').parent().css('display', 'none');
    	}
    }
}

espressionechevinceunmilionedisimpatia = /^\[\d*\](.*)$/;

function mycart () {
	var cartContent = '';
    $("#vertical_container input[type=text]:not([name=incopy])").each(function() {
        if ($(this).attr('name') == 'd_sum')
            text = $(this).parent().prev().children('label').text();
        else if ($(this).attr('name') == 'l_sum') {
            //text = $(this).parent().parent().prev('.row1').children('label').text();
            text = $(this).parent().parent().parent().prev('.row2').children('label').text();
            if (text == '')
                text = $(this).prev('strong').text();
            else
                lonfo = $(this).parent().prev('.left').children().children().children().children().children("select[id^='option_']").children('option:selected').text();
                text += ' <i>'+lonfo.match(espressionechevinceunmilionedisimpatia)[1]+'</i>';
        } else if ($(this).attr('name') == 'd_tot')
            text = "<b>Totale design</b>";
        else if ($(this).attr('name') == 'l_tot')
            text = "<b>Totale stampa</b>";
        if($(this).val()!=0) {cartContent = cartContent+'<tr><td width="65%">'+text+'</td><td width="35%">'+parseFloat($(this).val()).toFixed(2)+' &euro;</td></tr>';}
	});
    
    if (cartContent == '')
        $("#carrello-list").html('Nessun prodotto nel tuo carrello.');
    else
        $("#carrello-list").html("<table width=\"100%\">"+cartContent+"</table>");
	$("#totale").val($("#tot").val());
	$("#tot2").val($("#tot").val());
}

$(document).ready(function()
{	
  $("select").removeAttr('selected');
  $(".vertical_accordion_subcontent").hide();
  $(".vertical_accordion_subcontent .row3").hide();
  
  $.fn.clearForm = function() {
  $( this ).
    find( ':text' ).
      attr( 'value', '0' ).end().
	find( ':password, textarea' ).
      attr( 'value', '' ).end().
    find( ':checkbox, :radio' ).
      attr( 'checked', false ).end().
    find( 'select' ).
      attr( 'selectedIndex', 0 );
  }
  
  function close_design() {
	 $('#d_content').clearForm();	 
	 $('#d_opzioni').slideUp("slow");
  }
  
  function close_stampa() {
	 $('#s_content').clearForm();
	 $(".vertical_accordion_subcontent .row3").slideUp("slow");
	 $(".vertical_accordion_subcontent").slideUp("slow");
  }
  
  $("#vertical_container input").change(function() {
  	mycart();
  });
  
  $("#vertical_container select").click(function() {
  	mycart();
  });
  
  //$("#vertical_container select").change(function() {
	//	var myval = $(this).val();
	//	$(this).parents().next().children().val(myval);
	//	mysum();
	//	mycart();
	//});
  
  $(".vertical_accordion_subcontent .row1").click(function() {
	if($(this).children().attr('checked')) {
		$(this).next().slideDown("slow");
	} else {
		$(this).next().slideUp("slow");
	}     
  });  
  
  $("#d_content .row2").click(function() {
	
	var myck = 0;
	
	$("#d_content INPUT[type='checkbox']").each( function() {
		if($(this).attr('checked')) {
			myck = 1;
		} 
    });
	
	if(myck==0) {
		$('#d_content').clearForm();
		mysum();
	}
  });
  
  $("#s_content .row2").click(function() {
		if ($(this).children().attr("checked"))
        {
            $(this).next().slideDown("slow");
        }
        else
        {     
            $(this).next().slideUp("slow", function(){$(this).children(".row3").hide();});
			$(this).next().clearForm();
        }
		
		mysum();			
			
	});

  $("#s_content .row1").click(function() {
      if ($(this).children().attr("checked"))
        {
            $(this).next().slideDown("slow");
        }
        else
        {
            $(this).next().slideUp("slow");
			$(this).next().clearForm();
        }

		mysum();
  });
  /*
  $("#vertical_container h4").click(function() {
		
		if ($(this).children().attr('checked'))
        {
            $(this).next().slideDown("slow");
			$(this).addClass('open');
        }
        else
        {     
            $(this).next().slideUp("slow");
			$(this).removeClass('open');
			if($(this).attr('id')=='title_design') {
				close_design();
			}
			if($(this).attr('id')=='title_stampa') {
				close_stampa();
			}
        }
		
		mysum();
  });
*/
	
	
	
	

});

/**
 * calcolo del totale dell'ordine via javascript
 */
var updatePartialLogoDesign = function(){
    if ($("input[id^=pacchetti_]:checked").length > 0) {
        $("input[id^=pacchetti_]:checked").each(function(){
            var id = $(this).attr('id').match(/pacchetti_(\d+)/)[1];
            $(this).parents().next().children().val(pacchetti[id]['price']);
            if (discount && (parseFloat(pacchetti[id]['price']) != parseFloat(pacchetti[id]['old_price']))) {
            	$(this).parent().next().css('width', 'auto');
            	$(this).parent().next().children('span').remove();
            	$(this).parent().next().prepend('<span style="text-decoration: line-through;">'+pacchetti[id]['old_price']+' &euro;</style>');
            }
        });
        $("#graphic_number").each(function(){
            $(this).parents().next().children().val(parseFloat(graphic_number[$("#graphic_number > option:selected").attr('value')]['cost']));
            if (discount) {

            	$(this).parent().next().css('width', 'auto');
            	$(this).parent().next().children('span').remove();
            	if ((parseFloat(graphic_number[$("#graphic_number > option:selected").attr('value')]['cost']) != parseFloat(graphic_number[$("#graphic_number > option:selected").attr('value')]['old_cost'])) && (parseFloat(graphic_number[$("#graphic_number > option:selected").attr('value')]['old_cost']) > parseFloat(0))) {
            		$(this).parent().next().prepend('<span style="text-decoration: line-through;">'+parseFloat(graphic_number[$("#graphic_number > option:selected").attr('value')]['old_cost'])+' &euro;</style>');
            	}
            }
        });
        $("#graphic_type").each(function(){
            $(this).parents().next().children().val(parseFloat(graphic_type[$("#graphic_type > option:selected").attr('value')]['customer_price']));
        });
    }
    $("input[id^=pacchetti_]:not(:checked)").each(function(){
        $(this).parent().next().children('span').remove();
        $(this).parent().next().css('width', '70px');
        $(this).parents().next().children().val(0);
    });

    mysum();
    mycart();
};

var setTotalDelivery = function(){
	var total = 0;
    var usedDelivery = new Array();
	var i;
    for (i = 0; i < servicesId.length; i++) {
        if ($("#enable_"+servicesId[i]).attr('checked')) {
            var deliveryId = $("#dts_"+servicesId[i]+" > option:selected").attr('value');
            if (usedDelivery[deliveryId] != 1) {
                total += parseFloat(dts[deliveryId]['customer_price']);
                usedDelivery[deliveryId] = 1;
            }
        }
    }
	return total;
};

var updatePartialPrint = function(){
    for (i = 0; i < servicesId.length; i++) {
        if ($("#enable_"+servicesId[i]).attr('checked')) {
            var optionId = $("#option_"+servicesId[i]+" > option:selected").attr('value');
			//console.log("optionId: %d, servicesId[i]: %d qta: %s",optionId,servicesId[i],$("#qta_"+optionId+" > option:selected").attr('value'));
            tmp = parseFloat(qtas[optionId][$("#qta_"+optionId+" > option:selected").attr('value')]['price']);
            $("#enable_"+servicesId[i]).parent().next('.row3').children('.right').children('input').val(tmp);
            var old_price = parseFloat(qtas[optionId][$("#qta_"+optionId+" > option:selected").attr('value')]['old_price'])
            if (discount && (tmp != old_price)) {
            	var ele = $("#enable_"+servicesId[i]).parent().next('.row3').children('.right').children('input');
            	ele.parent().children('span').remove();
            	ele.before('<span style="text-decoration: line-through;">'+old_price+' &euro;</style>');
            }
        }
    }

    $('#dt_tot').val(setTotalDelivery());
    mysum();
    mycart();

    //$("select[id^='qta_'],select[id^='option_'],select[id^='dts_'],input[id^='enable_'],input[id^='ck']").live('change',updatePartialPrint);
};


$(document).ready(function(){
	$('#ordine').submit(function(evt){
		if($('#tot').val() == 0){
			alert("Seleziona almeno un servizio");
			evt.preventDefault();
			return false;
		}
	});

	$('#graphic_number,#graphic_type').live('click',updatePartialLogoDesign).live('keyup',updatePartialLogoDesign);
	$("input[id^=pacchetti_]").live('click',updatePartialLogoDesign);

    $("select[id^='option_']").bind('change',function() {
        i = $(this).parent().parent().parent().parent().parent().parent().prev('.row1').children('input').attr('value');
        opt = $(this).children(':selected').attr('value');
        $('#qtasCont_'+i).html(selectQta[opt]);
    }).change();

    $("select[id^='qta_'],select[id^='option_'],select[id^='dts_']").live('click',updatePartialPrint).live('keyup',updatePartialPrint);
    $("input[id^='enable_'],input[id^='ck']").live('click',updatePartialPrint);

    autofill();
});


$(function(){


/* TOGGLE DESCRIZIONI */

	$("div.more").click(function(){ $(this).toggleClass('moreopen'); });

	$("div.more_infos").click(function(){
		$(this).next('div.description').slideToggle('fast');
	});

/* SEZIONE DESIGN */

	function carbutt(){
		var id = $(this).getEasyId(), carbutt = this;
		//Inserisco un delay di 50ms perch� altrimenti mi becca lo status della checkbox al contrario
		setTimeout(function(){$("#carbutt_"+id).toggleClass("toglicarrello",$(carbutt).attr("checked"));},50);

	}

	$("input[id^=pacchetti_]").each(carbutt).live('click',carbutt);

	$("div.carrello.design").click(function(){
		var id = $(this).getEasyId();
		$("#pacchetti_"+id).click();
	});

/* DA QUI IN POI SEZIONE STAMPA */

	//Apro e chiudo il box via "scegli il formato di stampa"
	function catbutt(){
		var id = $(this).getEasyId(), carbutt = this;

		//Inserisco un delay di 50ms perch� altrimenti mi becca lo status della checkbox al contrario
		setTimeout(function(){
			$("#more_print_"+id).toggleClass("moreopen",$(carbutt).attr("checked"));
		},50);

	}

	//Callback di cui sopra e binding con evento
	$("input[id^=ck]").each(catbutt).click(catbutt);

	function chabutt(rel){
		setTimeout(function(){
			var inputs = $("input[id^=enable_][rel="+rel+"]");
			var l_sum = $("input[id^=l_sum_][rel="+rel+"]");
			$("#cartbutt_"+rel).toggleClass("toglicarrello", inputs.filter(":checked").size() > 0);
			$("#incopy_"+rel).val(l_sum.sum().toFixed(2));
			inputs.each(function(){
				var id = $(this).getEasyId();
				$("#servbutt_"+id).toggleClass("meno",$(this).attr("checked"));
				//Attenzione! Bugfix per il bug delle opzioni di stampa che non si aggiornano se cambi opzione, chiudi e apri il box relativo
				if(!$(this).attr("checked")){
					var option = $("#option_"+id);
					if(option.size() > 0){
						var optid = $(">option:selected",option).val();
						$('#qtasCont_'+id).html(selectQta[optid]);
					}
				}
			});

		}, 50);
	}

	//Richiamo la procedura di aggiornamento
	$("div.more_print").click(function(){
		var id = $(this).getEasyId();
		$("#ck"+id).click();
		chabutt(id);
	});


	function chabuttrel(){
		chabutt($(this).attr("rel"));

	}

	$("input[id^=enable_]").each(chabuttrel).click(chabuttrel);


	$("div.carrello.print").click(function(){
		var id = $(this).getEasyId();
		$("#ck"+id).click();
		chabutt(id);
	});

	$("div.piu").click(function(){
		var id = $(this).getEasyId();
		$("#enable_"+id).click();
	});
//
	$("select[id^=option_],select[id^=qta_],select[id^=dts_]").live('change', function(){
		chabutt($(this).parents(".print_options").getEasyId());
	});

});
