
$(document).ready(function(){
	
	addTooltip('leftGreen', 'leftToolTip', 130, 160);
	addTooltip('rightGreen', 'rightToolTip', 270, 300);
	jQuery.extend(jQuery.validator.messages, {
		required: "Campo obbligatorio.",
		remote: "Riempire questo campo per continuare.",
		email: "Inserire un indirizzo email valido.",
		url: "Inserire un indirizzo URL valido.",
		date: "Inserire una data in formato gg/mm/aaaa.",
		dateDE: "Inserire una data in formato gg-mm-aaaa.",
		dateISO: "Inserire una data in formato aaaa-mm-gg.",
		number: "Inserire un numero.",
		digits: "Inserire (solo) un numero.",
		creditcard: "Inserire un numero di carta di credito valido.",
		equalTo: "Inserire lo stesso valore usato sopra.",
		accept: "Usare un'estensione valida.",
		maxlength: jQuery.format("Inserire al massimo {0} caratteri."),
		minlength: jQuery.format("Inserire almeno {0} caratteri."),
		rangelength: jQuery.format("Inserire da {0} a {1} caratteri."),
		range: jQuery.format("Inserire un numero compreso tra {0} e {1}."),
		max: jQuery.format("Inserire un numero minore o uguale a {0}."),
		min: jQuery.format("Inserire un numero maggiore o uguale a {0}.")
	});

	$('.lnk_button_blue').hover(
		function(){
			$(this).addClass('ui-state-hover');
		}, 
		function(){
			$(this).removeClass('ui-state-hover');
		}
	);
	
	$('.lnk_button_red').hover(
		function(){
			$(this).addClass('ui-state-error');
		}, 
		function(){
			$(this).removeClass('ui-state-error');
		}
	);
	
	//*** SEGNALAZIONE LOCALITA'
	if( $(".placeReport").size() > 0 ){
		
		$(".placeReport").dialogDynForm({
			boxTitle: 'Segnala localit&agrave;',
			boxWidth: 400, 
			boxHeight: 400, 
			dialogBoxId: 'dialogPlaceReport',
			formGetAction: 'place-report-dialog',
			formSendAction: 'place-report-insert',
			formOkAction: '',
			formKoAction: ''
		});
		
	}
	
});

function trim(str) {
    str = str.replace(/^\s+/, '');
    for (var i = str.length - 1; i >= 0; i--) {
        if (/\S/.test(str.charAt(i))) {
            str = str.substring(0, i + 1);
            break;
        }
    }
    return str;
}

	

$.fn.clearForm = function() {
		// iterate each matching form
		return this.each(function() {
		  // iterate the elements within the form
		  $(':input', this).each(function() {
		    var type = this.type, tag = this.tagName.toLowerCase();
		    if (type == 'text' || type == 'password' || tag == 'textarea')
		      this.value = '';
		    else if (type == 'checkbox' || type == 'radio')
		      this.checked = false;
		    else if (tag == 'select')
		      this.selectedIndex = 0;
		  });
		});
	};


// Eliminazione dei caratteri speciali
$.fn.stripSpecialChar = function(){
	var current_val = $(this).val();
	var findReplace = [[/([^a-zA-Z \'])/g, ""]]
	
	for(item in findReplace){
		current_val = current_val.replace(findReplace[item][0], findReplace[item][1]);
	}
	return current_val;
}

// Limito l'inserimento in un input ai soli numeri
function onKeyNumeric(e) {
	// Accetto solo numeri e backspace <-
	if ( ((e.keyCode >= 48) && (e.keyCode <= 57)) || (e.keyCode == 8) ) {
		return true;
	} else {
		return false;
	}
}



// Apertura dettaglio ordine
function openDetail(btn){
	window.location = '/user/segui-spedizione?orders_id='+btn.attr('value');
}

var chage_city = false;
// Modifica dell'elenco delle citt� in base alla provincia
function changeCityPr(pr){
	if(chage_city) return true;
	
	chage_city = true;
	id_city = $('#id_city');
	id_city.empty();
	$.ajax({
		type: "GET",
		url: "/ajax/get-city-by-pr",
		data: "pr="+pr.find('option:selected').text(), 
		dataType: 'json', 
		success: function(json) {
			for(var cursor in json){
				//alert(cursor);
				var id_text = cursor;
				var name_text = json[cursor];
				$('<option value="'+id_text+'"></option>').html(name_text).appendTo(id_city);
			}
			chage_city = false;
		}
	}); 
}

var get_city = false;
// Recupero delle citt� in base alla provincia selezionata
function getCityByPr(pr,city,cap){
	if(get_city) return true;
	
	get_city = true;
	if(pr.val() == '') pr_val = '';
	else pr_val = pr.find('option:selected').text();
	
	pr.prev().val(pr_val);
	
	if(pr.val() == '') pr_val = '';
	else pr_val = pr.find('option:selected').text();
	
	pr.prev().val(pr_val);
	
	cap.empty();
	city.empty();
	$.ajax({
		type: "GET",
		url: "/ajax/get-city-by-pr",
		data: "pr="+pr_val, 
		dataType: 'json', 
		success: function(json) {
			for(var cursor in json){
				//alert(cursor);
				var id_text = cursor;
				var name_text = json[cursor];
				$('<option value="'+id_text+'"></option>').html(name_text).appendTo(city);
			}
			get_city = false;
			getCapByCity(city,cap);
		}
	}); 
}

var get_cap = false;
// Modifica dell'elenco delle citt� in base alla provincia
function getCapByCity(city,cap){
	if(get_cap) return true;
	
	if(city.val() == '') city_val = '';
	else city_val = city.find('option:selected').text();
	
	city.prev().val(city_val);
	
	
	if(city.val() == '') city_val = '';
	else city_val = city.find('option:selected').text();
	
	city.prev().val(city_val);
	
	get_cap = true;
	cap.empty();
	$.ajax({
		type: "GET",
		url: "/ajax/get-cap-by-city",
		data: "city="+city.find('option:selected').val(), 
		dataType: 'json', 
		success: function(json) {
			for(var cursor in json){
				var id_text = cursor;
				var name_text = json[cursor];
				$('<option value="'+id_text+'"></option>').html(name_text).appendTo(cap);
			}
			get_cap = false;
		}
	}); 
}


function noFest(date){
  var daysett = date.getDay();
  var day = date.getDate();
  var month = date.getMonth()+1;
  var year = date.getFullYear();
	  
	//domenica
	if (daysett == 0) return false;
	if (daysett == 6) return false;

	//1� gennaio - Capodanno  
	if (day == 1 && month ==1) return false;
	
	//6 gennaio - Epifania di Nostro Signore  
	if (day == 6 && month ==1) return false;
	
	//17 marzo - Festa 150 anni unit� d'italia  
	if (day == 17 && month ==3) return false;
	//18 marzo - chiusura aziendale  
	if (day == 18 && month ==3) return false;
	
	//25 aprile - Anniversario della Liberazione  
	if (day == 25 && month ==4) return false;

	//1� maggio - Festa del Lavoro  
	if (day == 1 && month ==5) return false;

	//2 giugno - Festa della Repubblica  
	if (day == 2 && month ==6) return false;

	//15 agosto - Assunzione di Maria Vergine   
	if (day == 15 && month ==8) return false;

	//1� novembre - Tutti i Santi  
	if (day == 1 && month ==11) return false;

	//8 dicembre - Immacolata Concezione  
	if (day == 8 && month ==12) return false;
	
	//24 dicembre - Il corriere non effettua consegne
	if (day == 24 && month ==12) return false;
	
	//25 dicembre - Natale di Nostro Signore   
	if (day == 25 && month ==12) return false;

	//26 dicembre - Santo Stefano  
	if (day == 26 && month ==12) return false;

	//31 dicembre - Il corriere non effettua consegne
	if (day == 31 && month ==12) return false;
	
	//PASQUA
	if (month == 3 || month == 4){
		pasqua = calcolaPasqua(year);

		if (day == (pasqua['giorno'])+1 && month == pasqua['mese']) return false;
	}

    return [1];
  }; 
  
  
function calcolaPasqua(year) 
{
	year = parseInt(year, 10);
	if (isNaN(year)) year = 0;

	var jDay;
	jDay = parseInt(jDay, 10);
	if (isNaN(jDay)) jDay = 0;
		
	var g;
	var i;
	var j;
	var p;
	
	g = year % 19;
	i = (19 * g + 15) % 30;
	j = (year + Math.floor(year / 4) + i) % 7;
	p = i - j + 28;

	if (p <= 31)
	{
		jDay = p;
		 FPasqua = {'giorno':jDay,'mese':3};
	}
	if (p > 31)
	{
		jDay = p - 31;
		FPasqua = {'giorno':jDay,'mese':4};

	}

	
	var wDay;
	var oDay;


	wDay = parseInt(wDay, 10);
	if (isNaN(wDay))wDay = 0;

	oDay = parseInt(oDay, 10);
	if (isNaN(oDay))oDay = 0;


	var g;
	var i;
	var j;
	var p;

   g = year % 19;
   i = (19 * g + 15) % 30;
   j = (year + Math.floor(year / 4) + i) % 7;
   p = i - j + 28;


	var a;
	var c;
	var h;
	var b;
	var d;
	var q;


   a = year % 19;
   c = Math.floor(year / 100);
   h = (c - Math.floor(c / 4) - Math.floor((8 * c + 13) / 25) + 19 * a + 15) % 30;
   b = h - Math.floor(h / 28) * (1 - Math.floor(29 / (h + 1)) * Math.floor((21 - a) / 11));
   d = (year + Math.floor(year / 4) + b + 2 - c + Math.floor(c / 4)) % 7;
   q = b - d + 28;

	var extra = 10;
	var tmp;

	tmp = Math.floor(year / 100) - 16;
	extra = 10 + tmp - Math.floor(tmp / 4);
	oDay = p + extra;

	if (q <= 31)
	{
		wDay = q;
		//FPasqua = wDay + " " + "marzo";
		FPasqua = {'giorno':wDay,'mese':3};		
	}
	if (q > 31)
	{
		wDay = q - 31;
		//FPasqua = wDay + " " + "aprile";�
		FPasqua = {'giorno':wDay,'mese':4};		

	}

	return FPasqua
}




function addTooltip(element_id, tooltip_id, left_show, left_hide) {
		$(".toolTip").hide();
		$('#' + element_id).live('mouseover', function() {
			$('#' + tooltip_id).animate({opacity:'show', left: left_show + 'px'}, 300);
		});

		$('#' + element_id).live('mouseout', function() {
			$('#' + tooltip_id).animate({opacity:'hide', left: left_hide + 'px'}, 300);
		});
	}


