var RPLV = {};

// fix per IE
var Calendar = Calendar || {};

(function($) {
	$(function() {
			
		$('.edit_fulfilment').click(function(e) {
			e.preventDefault;
			$(this).addClass('show');
		});		
		
		$('.edit_fulfilment').overlay({
			mask: {
				color: '#ebecff',
				loadSpeed: 200,
				opacity: 0.9
			},
			top: 80,
			fixed: false,
			closeOnClick: false,
			onBeforeLoad: function() {
				
				var show = $('.edit_fulfilment.show').parent().attr('class');
				var show = show.replace(" selected", "");
				
				if (show == 'fulfilment_133 fulfilment_sms') {
					$('#overlay').addClass('modal_sms');
				} else if (show == 'fulfilment_134 fulfilment_facebook') {
					$('#overlay').addClass('modal_facebook');
				} else if (show == 'fulfilment_132 fulfilment_ecard') {
					$('#overlay').addClass('modal_ecard');
				} else if (show == 'fulfilment_131 fulfilment_magnete') {
					$('#overlay').addClass('modal_magnete');
				} else if (show == 'fulfilment_135 fulfilment_biglietto') {
					$('#overlay').addClass('modal_biglietto');
				} else if (show == 'fulfilment_143 fulfilment_inserto_verticale') {
					$('#overlay').addClass('modal_inserto_1');
				} else if (show == 'fulfilment_150 fulfilment_inserto_orizzontale') {
					$('#overlay').addClass('modal_inserto_2');
				} else if (show == 'fulfilment_144 fulfilment_lettera_a4_busta') {
					$('#overlay').addClass('modal_lettera');
				}
				
				var wrap = this.getOverlay().find('.contentWrap');
				
				wrap.empty().append($('<img/>', {
					'src': overlayPreloadImg,
					'class': 'fulfilment-loader'
				}));
			
				wrap.load(this.getTrigger().attr('href'));
			},
			onClose: function() {
				$('#overlay').removeAttr('class');
				$('.show').removeClass('show');
			}
		});
		
		// Validatore per i datepicker
		$.validator.addMethod("datetime-picker", function(value, element) {
			return !this.optional(element);
		}, $.validator.messages.required);
		
		// Validatore per i numeri di cellulare
		$.validator.addMethod("mobile-number", function(value, element) {
			return /^((00|\+)39[\. ]??)??3\d{2}[\. ]??\d{6,7}$/.test(value);
		}, $.validator.messages.mobileNumber);
		
		
		/*
		$.validator.addMethod("maximum-length-11", function(value, element) {
			return (value.length <= 11);
		}, 'La lunghezza massima consentita è di 11 caratteri');
		*/

        // Validatore per mittente sms (max 11 char alfanumerici)  
		$.validator.addMethod("maximum-length-11", function(value, element) {
			return /^[a-zA-Z0-9\s.\-]{1,11}$/.test(value);
		}, 'La lunghezza massima è di 11 con caratteri alfanumerici');
		
		


		// Validazione
		// A parte i campi con regole specifiche, vengono considerati obbligatori tutti i campi con classe "required-entry"
		// @see onload.js
		$('#product_addtocart_form').live('submit', function() {
			var validation = $('#product_addtocart_form').validate({
				onkeyup: false,
				onblur: false,
				onsubmit: false,
				// Il date/time picker è formato da diverse select, appendo il messaggio dopo l'hidden "riepilogativo"
				// La select con gli amici di FB è "nascosta"
				errorPlacement: function(error, element) {
					var $element = $(element);
					if ($element.hasClass('datetime-picker')) {
						var optionId = $element.attr('id').replace('options_', '').replace(/_(day|month|year|hour|minute)/, '');
						if ($('label[for="validate-datetime-' + optionId + '"]').length == 0) {
							$(error).attr('for', 'validate-datetime-' + optionId).insertAfter('.validate-datetime-' + optionId);
						}
					} else if ($element.is('#fbFriendsList')) {
						error.insertAfter('#fbFriendsList_msdd');
					} else {
						error.insertAfter(element);
					}
				}
			});
			
			return validation.form();
		});
		
		// Riduzione qty prodotto
		$('body.checkout-cart-index .updade-form').submit(function() {
			var $rows = $('tr.row-rplv'), 
				$row, 
				productName,
				proceed = true;
			
			$rows.each(function(i, el) {
				$row = $(el);
				
				if (parseInt($('.pdt-qty input.qty', $row).val()) < parseInt($('.pdt-qty input.actual_qty', $row).val())) {
					productName = $('h2.product-name a', $row).text();
					if (!confirm("ATTENZIONE! Stai diminuendo la quantità per: " + productName + "\n\nVerranno eliminati i prodotti in ordine di inserimento, vuoi eliminarli?")) {
						proceed = false;
					}
				}
			});
			
			return proceed;
		});
		
		$('body.privati-store .checkout-types .btn-proceed-checkout').click(function() {
			var $rows = $('div.available-fulfilments ul li.selected'), 
				$row,
				onlyNullFulfilment = true;

			$rows.each(function(i, el) {
				if (!$(el).hasClass('fulfilment_niente')) {
					onlyNullFulfilment = false;
				}
			});
			
			if (onlyNullFulfilment && $rows.length > 0) {
				$("#onlyNullFulfilment").fancybox({
					'width'				: '430',
					'height'			: '300',
					'padding'           : '30',
					'autoScale'     	: false,
					'autoDimensions'    : false,
					'transitionIn'		: 'none',
					'transitionOut'		: 'none',
					'overlayColor'      : '#00c1ff'
				}).trigger('click');
			} else {
				window.location.href = checkoutUrl;
			}
		});
		
		$('.btn-force-checkout, .aziende-store .checkout-types .btn-proceed-checkout').live('click', function() {
			window.location.href = checkoutUrl;
		});
		
		$('.add_nulla').click(function() {
			return confirm('Sei sicuro di non voler associare nessun ricordo al tuo acquisto?'); 
		});
		
		$('#fbLogin').live('click', function(e) {
			FB.login(function(response) {
				if (response.authResponse) {
					FB.api({
						method: 'fql.query',
						query: "select name,username,uid from user where uid in (select uid1 from friend where uid2="  + FB.getAuthResponse().userID + ")"
					}, function(fqlResponse) {
						
						var selectFriends = $('#fbFriendsList'),
							friends = [];
						
						$('#facebookLoginBox').hide();
						$('#facebookFriendList, .facebookPostContainer, #overlaySubmitContainer, dt.opt_facebook_friends, dt.opt_facebook_post').show();
						
						$('p.disconnect a').click(function(e) {							
							FB.logout(function() {
								location.reload();
							});
							e.preventDefault();
						});
						
						for (var i in fqlResponse) {
							if (fqlResponse[i].uid && fqlResponse[i].name) {
								friends.push(fqlResponse[i]);
							}
						}
						
						friends.sort(function(a, b) {
							return a.name.toLocaleLowerCase().localeCompare(b.name.toLocaleLowerCase());
						});

						for (var i in friends) {
							if (friends[i].uid && friends[i].name) {
								var option = $('<option value="' + friends[i].uid + '">' + friends[i].name + '</option>');
								selectFriends.append(option);							
							}
						}
						
						document.getElementById('fbFriendsList').refresh();
						
						// Persisto il token lato server
						$.get(fbSaveSessionUrl, { fbjs_access_token: response.authResponse.accessToken });
					});
				}   
			}, {scope:'publish_stream,email', perms:'publish_stream,email'});
			
			e.preventDefault();
		});

		$('#tabs-biglietto li a').live('click', function() {
			var $this = $(this);
			$('#tabs-biglietto li').removeClass('selected');
			$this.parent().addClass('selected');
			$('#panes-biglietto > div').hide();
			$($this.attr('href')).show();
			
			if ($this.attr('href') == '#pane-custom') {
				$('#is_biglietto_custom').val('Si');
				if ($('.modal_biglietto').find('textarea').val() == '') {
					$('#msg_default_1').attr('checked', 'checked').trigger('change');
				}
			} else {
				$('#is_biglietto_custom').val('No');
				$('.modal_biglietto').find('[type="text"],textarea').val('');
				$('.modal_biglietto').find(':radio').removeAttr('checked');
			}
			
			return false;
		});
		
		$('input[name="select_msg_fulfilment"], input.select_msg_fulfilment').live('change', function() {
			var $this = $(this);
			$('#overlay label').removeClass('active');
			$(this).next().addClass('active');
			
			if ($this.val() == 'custom') {
				$('#' + $this.attr('rel')).val('').removeAttr('readonly');
			} else {
				$('#' + $this.attr('rel')).val(fulfilmentDefaultMessages[$this.val()]).attr('readonly', 'readonly');
			}
		});
		
		RPLV.preSelect = function(textareaId) {
			
			var currentValueRaw = $('#' + textareaId).val(),
				currentValue = currentValueRaw.replace(/\n/g, '').replace(/\r/g, ''),
				currentId = null;
			
			if (currentValue != '') {
				for (var i in fulfilmentDefaultMessages) {
					if (fulfilmentDefaultMessages.hasOwnProperty(i)) {
						var message = fulfilmentDefaultMessages[i].replace(/\n/g, '').replace(/\r/g, '');
						if (message.localeCompare(currentValue) == 0) {
							currentId = i;
							break;
						}					
					}
				}
				
				if (currentId == null) {
					currentId = 'custom';
				}
				
				$('#msg_default_' + currentId).attr('checked', 'checked').trigger('change');
				$('#' + textareaId).val(currentValueRaw);
			}
		};
		
		$('input[name="select_default_avatar"]').live('change', function() {
			var $this = $(this);
			
			$('#' + $this.attr('rel')).val($this.val());
		});
		
		$('a.remove_csv').live('click', function() {
			var $this = $(this);
			
			if (confirm('Sei sicuro di voler rimuovere il file caricato?')) {
				$('input.opt_ecard_csv_valid, input.opt_ecard_csv_notvalid, input.opt_ecard_csv').val('').trigger('change');
				$('#csvCounterContainer').empty();
			}
			
			return false;
		});
		
		$('input.opt_ecard_csv_valid').live('change', function() {
			var valid = parseInt($(this).val()),
				notValid = parseInt($('input.opt_ecard_csv_notvalid').val());
			
			if (valid > 0) {
				$('#csvCounterContainer').html($.validator.format('Sono stati caricati <strong class="valid">{0}</strong> indirizzi validi', valid));
				$('.opt_destinatario label, .opt_email label').removeClass('required');
				$('.opt_destinatario label em, .opt_email label em').hide();
				$('.product-custom-option-destinatario, .product-custom-option-email').removeClass('required-entry error').each(function(i, el) { $('label[for="' + el.id + '"]').remove(); });
				
				if (notValid > 0) {
					$('#csvCounterContainer').append($.validator.format(' e <strong class="not-valid">{0}</strong> indirizzi non validi', notValid));
				}

				$('#csvCounterContainer').append(' <a href="#" class="remove_csv">Rimuovi tutti</a>');
				
				if ($('#qty_csv').length == 0) {
					$('<input type="hidden" id="qty_csv" name="qty" />').appendTo('#csvCounterContainer');
				}
				$('#qty_csv').val(valid);
			} else {
				$('.opt_destinatario label, .opt_email label').addClass('required');
				$('.opt_destinatario label em, .opt_email label em').show();
				$('.product-custom-option-destinatario, .product-custom-option-email').addClass('required-entry');
			}
		});
	});
})(jQuery);
