(function($) {
	$(function() {
		// Verifico che sia nella sezione aziende e nella scheda prodotto di un prodotto personalizzabile
		if ($('body.aziende-store .wizardOverlay').length > 0) {
			
			var currentStep = 'step_prodotto',
				currentOverlay, formValidate,
				readyToSubmit = false;
			
			var gotoStep = function(nextStep, forcePassValidation) {
				
				var proceed = false;
				if (forcePassValidation) {
					proceed = true;
				} else {
					if (formValidate.form()) {
						proceed = true;
						$('.wizardTabs ol li.for_' + currentStep).addClass('completed');
						updateCustomizationPrice();
					} else {
						$('.wizardTabs ol li.for_' + currentStep).removeClass('completed');
					}
				}
				
				if (proceed) {
					$('#' + currentStep).fadeOut(500, function() {
						currentStep = nextStep;
						$('#' + nextStep).fadeIn(500, function() {
							currentOverlay.getOverlay().trigger('show_' + nextStep);
							$('.wizardTabs ol li').removeClass('active');
							$('.wizardTabs ol li.for_' + nextStep).addClass('active');
						});
					});
				}
			};
			
			var formReset = function() {
				readyToSubmit = false;
				currentOverlay.getOverlay().find('input:text, textarea, select').val('');
				currentOverlay.getOverlay().find('input:checkbox').removeAttr('checked');
				$('#step_riepilogo dd > span').html('');
				$('.wizardTabs ol li').removeClass('completed');
				gotoStep('step_prodotto', true);
				$('#step_riepilogo').hide();
			};
			
			var updateCustomizationPrice = function() {
				var totalPrice = 0,
					totalPriceString = '--',
					qty = parseInt($('input[name="wizard_qty"]').val());

				totalPrice += (parseFloat(customizationPriceConfig.price) * qty) + parseFloat(customizationPriceConfig.setupCost);
				
				// Aggiungo l'IVA
		    	if (totalPrice > 0) {
					totalPrice += ((totalPrice / 100) * parseInt(customizationPriceConfig.taxRate));
				}
		    	
		    	// Aggiungo il prezzo del biglietto "liscio"
		    	totalPrice += (parseFloat($('#productFinalPrice').val()) * qty);
		    	
				totalPriceString = (totalPrice ? '&euro; ' + totalPrice.toFixed(2).replace('.', ',') : '--');
				$('.calculatedPrice strong').html(totalPriceString);				
			};
			
			$('.overlay').overlay({
				mask: {
					color: '#ebecff',
					loadSpeed: 200,
					opacity: 0.9
				},
				top: 80,
				fixed: false,
				closeOnClick: false,
				onBeforeClose: function() {
					if (!readyToSubmit && typeof configPersonalizzazione == 'undefined') {
						$('#tipo_personalizzazione').val('nessuna');
						formReset();
					}
				}
			});
			
			// Se l'elemento corrente è visibile allora è obbligatorio
			$.validator.addMethod("requiredVisible", function(value, element) {
				if ($(element).is(':visible')) {
					return (value !== '0' && value !== 'null' && !this.optional(element));
				}
				return "dependency-mismatch";
			}, $.validator.messages.required);
			
			formValidate = $("#product_addtocart_form").validate({
				onkeyup: false,
				onblur: false,
				onsubmit: false
			});
			
			// Add to cart senza Personalizzazione
			$('#product_addtocart_form .product-shop .btn-cart').click(function() {
				$('#tipo_personalizzazione').val('nessuna');
				
				productAddToCartForm.submit(this);
			});
			
			$('.start_personalizzazione').click(function(e) {
				
				var $this = $(this);
				
				if (typeof configPersonalizzazione != 'undefined' && !$this.hasClass('active') && !$this.hasClass('edit_customization')) {
					if (!confirm("Attenzione! Modificando la personalizzazione perderai i dati inseriti precedentemente.\n\nVuoi procedere?")) {
						return false;
					}
				}
				
				// Apro l'overlay specifico
				var customerSelection = $this.attr('rel');
				$('#tipo_personalizzazione').val(customerSelection);
				
				if (customerSelection == 'nessuna') {
					$(this).addClass('selected');
				} else {

					currentStep = 'step_prodotto';

					populateForm();

					currentOverlay = $(".overlay").data("overlay");
					
					$('.wizardTabs li.for_step_prodotto').addClass('first active').show();
					$('.wizardTabs li.for_step_riepilogo').removeClass('first active completed');

					$('#step_prodotto').show();
					$('#summary_prodotto').show();
					$('#step_riepilogo').hide();
					
					$('input[name="wizard_qty"]', currentOverlay.getOverlay()).val($('#qty').val());

					if (typeof configPersonalizzazione != 'undefined') {
						updateCustomizationPrice();
					}
					
					currentOverlay.load();
				}
				
				e.preventDefault();
			});
			
			$('input[name="wizard_qty"]').change(function() {
				updateCustomizationPrice();
			});
			
			$('#step_riepilogo .btn-cart').click(function() {
				$('#qty').val($(this).parents('.overlay').find('input[name="wizard_qty"]').val());
				
				readyToSubmit = true;
				
				currentOverlay.close();
				
				productAddToCartForm.submit(this);
				
				// Non essendoci una callback alla fine del submit, per sicurezza il reset del form lo faccio dopo mezzo secondo
				var rf = formReset;
				setTimeout(function() { rf.call(); }, 500);
			});
			
			$('.goto_step').click(function() {
				var $this = $(this);
				gotoStep($this.attr('rel'), $this.hasClass('prev_step'));
			});
			
			$('.wizardTabs a').click(function() {
				gotoStep($(this).attr('rel'));
				return false;
			});
			
			// Popolamento riepilogo
			$('.overlay').bind('show_step_riepilogo', function() {
				
				// Ragione sociale
				$('#riepilogo_ragione_sociale .riepilogo_ragione_sociale').text($('#personalizzazione_ragione_sociale').val());
				
				// Colore rag. soc.
				$('#step_riepilogo .riepilogo_colore_ragione_sociale').html($('#personalizzazione_pantone_ragione_sociale').val());
				
				// Colori logo
				$('#riepilogo_logo .riepilogo_colore_logo').html($('#personalizzazione_colore_logo').val());
				
				// Mostro il pezzo di riepilogo per il tipo di personalizzazione scelta
				if ($('#personalizzazione_tipo_personalizzazione').val() == 'ragione_sociale') {
					$('#riepilogo_ragione_sociale').show();
					$('#riepilogo_logo').hide();
				} else {
					$('#riepilogo_ragione_sociale').hide();
					$('#riepilogo_logo').show();
				}
			});
			
			// Scelta del tipo di personalizzazione
			$('#personalizzazione_tipo_personalizzazione').change(function() {
				if ($(this).val() == 'ragione_sociale') {
					toFadeOut = 'logo_container';
					toFadeIn = 'ragione_sociale_container';
				} else {
					toFadeOut = 'ragione_sociale_container';
					toFadeIn = 'logo_container';
				}

				$('#' + toFadeOut).fadeOut(500, function() {
					$('#' + toFadeIn).fadeIn(500);
				});
			});
			
			$('.delete_customization').click(function() {
				return confirm("Confermi l'eliminazione della personalizzazione effettuata?");
			});
			
			var populateForm = function() {
				if (typeof configPersonalizzazione != 'undefined') {
					for (var field in configPersonalizzazione.prodotto) {
						switch (field) {
							case 'pantone':
								if (configPersonalizzazione.prodotto['tipo_personalizzazione'] == 'ragione_sociale') {
									$('[name="personalizzazione\\[prodotto\\]\\[' + field + '\\]\\[ragione_sociale\\]"]').val(configPersonalizzazione.prodotto[field].ragione_sociale).trigger('change');
								} else {
									$('[name="personalizzazione\\[prodotto\\]\\[' + field + '\\]\\[logo\\]"]').val(configPersonalizzazione.prodotto[field].logo).trigger('change');
								}
								break;
								
							case 'lavorazione_caldo':
								if (configPersonalizzazione.prodotto[field] == '1') {
									$('[name="personalizzazione\\[prodotto\\]\\[' + field + '\\]"]').attr('checked', 'checked').trigger('change');
								}
								break;
								
							case 'tipo_personalizzazione':
								if (configPersonalizzazione.prodotto[field] == 'ragione_sociale') {
									$('#logo_container').hide();
									$('#ragione_sociale_container').show();
								} else {
									$('#logo_container').show();
									$('#ragione_sociale_container').hide();
								}
								$('[name="personalizzazione\\[prodotto\\]\\[' + field + '\\]"]').val(configPersonalizzazione.prodotto[field]).trigger('change');
								break;
								
							case 'logo':
								break;
								
							default:
								$('[name="personalizzazione\\[prodotto\\]\\[' + field + '\\]"]').val(configPersonalizzazione.prodotto[field]).trigger('change');
								break;
						}
					}
				}
			};
			
			populateForm();
		}
	});
})(jQuery);
