(function($){
    $(function(){

    	if(typeof pageLoaded != 'undefined')
    	{
	    	switch( pageLoaded )
	    	{
	    		case 'home': initHome(); break;
	    		case 'registrazione': initRegistrazione(); break;
	    	}
    	}
    	
    	function initHome()
    	{
    		/*$(".MapList a").click(function(){
    			$.getJSON("/ajax.php", { act: "getPV", regione: $(this).attr('title') }, function(json){
    				if (json['tot'] > 0)
    				{
						$('#WinSellers div.Bod').html(json['html']);
						$('#WinSellers').modal();
    				}
    				else
    				{
    					alert('Non ho trovato punti vendita in tale regione');
    				}
				});

    		});*/
    	}
    	function initRegistrazione()
		{
			if ($("div.BxReg").hasClass("Hidden")){ return false; }
			    
			
				/*if ($("input[name=indirizzo_coincide]").attr('checked'))
				{
					alert		
				}*/
			

		
			
			
			    $("form[name=userMod]").validate({
			    	rules : {
			    		imei : { required: true, min_length : 4 },
			    		booking_code : { required: true, min_length : 4 },
			    		email : { required: true, email : true },
			    		name : { required : true, minlength : 2 },
			    		name_pv : { required : true, minlength : 2 },
			    		surname : { required : true, minlength : 2 },
			    	//	phone : { required : true, minlength : 2 },
			    		address : { required : true, minlength : 2 },
			    		address_pv : { required : true, minlength : 2 },
			    		cap : { required : true, minlength : 2 },
			    		city : { required : true, minlength : 2 },
			    		address_sped : { required : "input[name=indirizzo_coincide]:not(:checked)", minlength : 2 },
			    		city_sped : { required : "input[name=indirizzo_coincide]:not(:checked)", minlength : 2 },
			    		cap_sped : { required : "input[name=indirizzo_coincide]:not(:checked)", minlength : 2 },
			    		
			    		privacy : { required:true }
			    	},
			    	messages : {
			    		imei : "Inserire il codice IMEI",
			    		booking_code : "Inserire il codice di prenotazione",
			    		email : "Inserire un indirizzo email valido",
			    		name : "Inserire il campo nome",
			    		name_pv : "Inserire il campo nome del punto vendita",
			    		surname : "Inserire il campo cognome",
			    	//	phone : "Inserire il numero di telefono",
			    		address : "Inserire un indirizzo valido",
			    		address_pv : "Inserire l'indirizzo del punto vendita",
			    		cap : "Inserire un cap valido",
			    		city : "Inserire una citt&agrave; valida",
			    		
			    		address_sped : "Inserire un indirizzo valido",
			    		city_sped : "Inserire una citt&agrave; valida",
			    		cap_sped : "Inserire un cap valido",
			    		
			    		privacy : "Accettare le condizioni sulla privacy"
			    	},
			    	errorElement: "span",
			    	errorClass: "Error"
			    });
			    
			    
			    gestisciData();
			    
			    $("input[name=indirizzo_coincide]").click(function(){ 
			    	$("#ind_sped").slideToggle();
			    });
			    
			    $("select[name=prov_pv]").change( function(){
			    	
			    	if ($(this).val() != 'none')
			    	{
				    	$.getJSON("/ajax.php", { act: "getCom", provincia: $(this).val() }, function(json){
				    		if (json.length < 1) return false; 
		    				var sel_comuni = $('select[name=comune_pv]').get(0);
		    				sel_comuni.innerHTML = '';
		    				sel_comuni.options[0] = new Option('seleziona il comune','none');
		    				sel_comuni.options[1] = new Option('','none');
							for( com in json )
					        {
					        	sel_comuni.options[sel_comuni.options.length] = new Option( json[com],json[com] );
					        }
					        $(sel_comuni).removeClass('Disabled');
					        $(sel_comuni).attr('disabled','');
					        
					        var sel_nomi_pv = $('select[name=nome_pv]').get(0);
					        $(sel_nomi_pv).addClass('Disabled');
					        $(sel_nomi_pv).attr('disabled','disabled');
					        $("input[name=address_pv]").val('');
					        sel_nomi_pv.options[0].selected = true;
						});
			    	}
			    	else
			    	{
			    		var sel_comuni = $('select[name=comune_pv]').get(0);
			    		var sel_nomi_pv = $('select[name=nome_pv]').get(0);
						$(sel_comuni).addClass('Disabled');
						$(sel_comuni).attr('disabled','disabled');
						$(sel_nomi_pv).addClass('Disabled');
						$(sel_nomi_pv).attr('disabled','disabled');
						$("input[name=address_pv]").val('');
						sel_comuni.options[0].selected = true;
						sel_nomi_pv.options[0].selected = true;
			    	}
			    } );
			    			    
			    $("select[name=comune_pv]").change( function(){
			    	
			    	if ($(this).val() != 'none')
			    	{
				    	$.getJSON("/ajax.php", { act: "getPV", comune: $(this).val() }, function(json){
				    		if (json.length < 1) return false; 
		    				var sel_nomi_pv = $('select[name=nome_pv]').get(0);
		    				sel_nomi_pv.innerHTML = '';
		    				sel_nomi_pv.options[0] = new Option('seleziona il punto vendita','none');
		    				sel_nomi_pv.options[1] = new Option('','none');
							for( com in json )
					        {
					        	sel_nomi_pv.options[sel_nomi_pv.options.length] = new Option( json[com]['name'],json[com]['id']+"#"+json[com]['ind'] );
					        }
					        $(sel_nomi_pv).removeClass('Disabled');
					        $(sel_nomi_pv).attr('disabled','');
					        
					        $("input[name=address_pv]").val('');
						});
			    	}
			    	else
			    	{
			    		var sel_nomi_pv = $('select[name=nome_pv]').get(0);
						$(sel_nomi_pv).addClass('Disabled');
						$(sel_nomi_pv).attr('disabled','disabled');
						$("input[name=address_pv]").val('');
						sel_nomi_pv.options[0].selected = true;
			    	}
			    } );
			    
			    $("select[name=nome_pv]").change( function(){
			    	var va = $(this).val();
			    	if (va != 'none')
			    	{
			    		$("input[name=address_pv]").val(va.replace(/^[0-9]+#(.*)$/,"$1"));
			    		$("input[name=id_pv]").val(va.replace(/^([0-9]+)#.*$/,"$1"));
			    	}
			    	else
			    	{
			    		$("input[name=address_pv]").val('');
			    		$("input[name=id_pv]").val('');
			    	}
			    
			    } );
			    
			    
   			   
		}
		
		function gestisciData()
		{
			var buy_date = $("input[name=buy_date]").val();
			var date_arr = new Array;
			
			date_arr[0]=new Option("Gennaio",31);
			date_arr[1]=new Option("Febbraio",28);
			date_arr[2]=new Option("Marzo",31);
			date_arr[3]=new Option("Aprile",30);
			date_arr[4]=new Option("Maggio",31);
			date_arr[5]=new Option("Giugno",30);
			date_arr[6]=new Option("Luglio",31);
			date_arr[7]=new Option("Agosto",30);
			date_arr[8]=new Option("Settembre",30);
			date_arr[9]=new Option("Ottobre",31);
			date_arr[10]=new Option("Novembre",31);
			date_arr[11]=new Option("Dicembre",30);
			
			var my_date = new Date();
			
			month_now = parseInt( my_date.getMonth() );
			day_now = parseInt( my_date.getDay() );
			year_now = parseInt( my_date.getFullYear() );
			
		    var days = '<select name="days" class="Campo">';
		    for (x=1;x<date_arr[(month_now - 1)].value;x++)
		    {
		    	days += '<option value="'+ x +'" ' + ((x == (day_now +1)) ? 'selected="selected"' : '')+'>' + x + '</option>'
		    }
		    days += '</select>';
		    var mesi = '<select name="months" class="Campo">';
		    for (i in date_arr)
		    {
		    	mesi += '<option value="'+ date_arr[i].value +'" ' + ((i == (month_now ))  ? 'selected="selected"' : '')+'>' + date_arr[i].text + '</option>'
		    }
		    mesi += '</select>';
		    var anni = '<select name="years" class="Campo">';
		    for (x=(year_now - 2);x<( year_now + 1);x++)
		    {
		    	anni += '<option value="'+ x +'" '+(x == year_now ? 'selected="selected"' : '')+'>' + x + '</option>'
		    }
		    anni += '</select>';
		    $('input[name=buy_date]').css('display','none');
		    $('input[name=buy_date]').after( days + mesi + anni );
		    
		    
		    if (buy_date != '' && typeof buy_date != 'undefined')
			{
				
				var anno = buy_date.replace(/^([0-9]+)-.*/,"$1");
				var mese = buy_date.replace(/^([0-9]+)-([0-9]+)-.*/,"$2");
				var giorno = buy_date.replace(/.*?-([0-9]+)$/, "$1");
			
				
				var sel_g = $("select[name=days]").get(0);
				sel_g.options[ sel_g.selectedIndex ].selected = '';
				sel_g.options[(parseInt(giorno) - 1)].selected = true;
				$("select[name=months]").get(0).options[(parseInt(mese) - 1)].selected = true;
				//$("select[name=months]").get(0).options[(parseInt(mese) - 1)].selected = true;
				
				var sel_a = $("select[name=years]").get(0);
				var ind = 0;
				for(i=0;i<sel_a.options.length;i++)
				{
					sel_a.options[i].selected = ( sel_a.options[i].value == anno) ? true : '';
				}
			
				
			}
			else
			{
			    updateDays();

			}
			
		    $('select[name=days],select[name=months],select[name=years]').change(function(){updateDays();});
		}
		
		function updateDays()
		{
			temp = $('select[name=days]').get(0).selectedIndex;
			
			var mese_sel = $('select[name=months]').val();
			var anno_sel = $('select[name=years]').val();
			var giorno_sel = $('select[name=days]').val();

			var ret_val = (mese_sel == 28) ? ((anno_sel % 4 != 0 || anno_sel % 100 == 0) ? 0 : 1) : 0;
			
			var sel_giorni = $('select[name=days]').get(0);
			
			sel_giorni.innerHTML = ""; 
			
			var selection = parseInt(mese_sel) + ret_val;
			for(x=1;x < selection+1;x++)
	        {
	        	sel_giorni.options[sel_giorni.options.length] = new Option( x,x );
	        }
	        
	        if (temp >= mese_sel){ sel_giorni.options[0].selected = true; }
	        else{ sel_giorni.options[(parseInt(temp))].selected = true; }
	        
	        var data_selezionata = $('select[name=years]').val() + "-" + ($('select[name=months]').get(0).selectedIndex + 1) + "-" + $('select[name=days]').val();
	        $("#buy_date").val( data_selezionata );
		}
		
    });
})(jQuery);



