﻿/*global $ document window alert reg window GeoCoding gotoStep rnd*/
function onlyNumbers(e) {
	var key = window.event ? e.keyCode : e.which;	
	var keychar = String.fromCharCode(key);
	reg = /\d/;
	return reg.test(keychar) || (key === 8) || (key === 9);
}



function validateDateNumber(datepart, val) {
	var re;
	if (datepart === 'dd') {
		re =  /^[0-9]*$/;
	} else if (datepart === 'mm') {
		re = /^([1-9]|[1-9]\d|12)$/;
	} else if (datepart === 'yyyy') {
		re = /^\d{4}$/;
	}
	return re.test(val);
}

function isEMail(val) {
	var re = /^[A-Za-z0-9](([_\.\-]?[a-zA-Z0-9]+)*)@([A-Za-z0-9]+)(([\.\-]?[a-zA-Z0-9]+)*)\.([A-Za-z]{2,})$/;
	return (re.test(val));
}


function isDate(element) { 			
	var regDate = new RegExp();
	regDate = /^(((0[1-9]|[12][0-9]|3[01])([\-.\/])(0[13578]|10|12)([\-.\/])(\d{4}))|(([0][1-9]|[12][0-9]|30)([\-.\/])(0[469]|11)([\-.\/])(\d{4}))|((0[1-9]|1[0-9]|2[0-8])([\-.\/])(02)([\-.\/])(\d{4}))|((29)(\.|-|\/)(02)([\-.\/])([02468][048]00))|((29)([\-.\/])(02)([\-.\/])([13579][26]00))|((29)([\-.\/])(02)([\-.\/])([0-9][0-9][0][48]))|((29)([\-.\/])(02)([\-.\/])([0-9][0-9][2468][048]))|((29)([\-.\/])(02)([\-.\/])([0-9][0-9][13579][26])))$/;
	if (typeof(element.value) !== "undefined") {
		return regDate.test(element.value);
	} else {
		return regDate.test(element);
	}		
}
		


/*function isDate(szData,lang){
	 var retValue = false;
	var bLongFormat = true;
	var arr_date;
	var re_date;
	if(isUndefined(lang)){lang="it";}
	if(lang=="us"){re_date=/^(\d{4})[-\/](\d{1,2})[-\/](\d{1,2})\s+(\d{1,2})[:\.](\d{1,2})[:\.]{0,1}(\d{1,2}){0,1}$/;}else{re_date = /^(\d{1,2})[-\/](\d{1,2})[-\/](\d{4})\s+(\d{1,2})[:\.](\d{1,2})[:\.]{0,1}(\d{1,2}){0,1}$/;}
	arr_date = re_date.exec(szData);
	if(!arr_date){
		bLongFormat = false;
		if(lang=="us"){re_date=/^(\d{4})[-\/](\d{1,2})[-\/](\d{1,2})$/;}else{re_date=/^(\d{1,2})[-\/](\d{1,2})[-\/](\d{4})$/;}
		arr_date = re_date.exec(szData);
	}
	if(!arr_date) {return retValue;}

	// Controlla il mese
	var tmpMonth = Number(arr_date[2]);
	if ((tmpMonth >12) || (tmpMonth < 1)) {	return retValue; }
	// Controlla l'anno
	var tmpYear = (lang=="us") ? String(arr_date[1]) : String(arr_date[3]);
	if (tmpYear.length == 2) tmpYear = "20" + tmpYear;
	tmpYear	= Number(tmpYear);
	if ((tmpYear > 9999) || (tmpYear < 1763)) {	return retValue; }
	// Controlla il giorno
	var numDayMonth = GetDaysInMonth(tmpMonth,tmpYear);
	var tmpDay = (lang=="us") ? Number(arr_date[3]) : Number(arr_date[1]);
	if ((tmpDay > numDayMonth) || (tmpDay < 1))  {	return retValue; }

	if(bLongFormat){
		// Controlla l'ora
		var tmpHH = Number(arr_date[4])
		if ((tmpHH > 23) || (tmpHH < 0)) return retValue;
		// Controlla i minuti
		var tmpMM = Number(arr_date[5])
		if ((tmpMM > 59) || (tmpMM < 0)) return retValue;
		// Controlla i secondi
		if (arr_date.length == 7) {
			var tmpSS = Number(arr_date[6])
			if ((tmpSS > 59) || (tmpSS < 0)) return retValue;
		}
	}
	return true; 
}*/

function GetDaysInMonth(tmpMonth, tmpYear) {
	var szOut;
	var dPrevDate = new Date(tmpYear, tmpMonth, 1);
	var MinMilli = 1000 * 60;
	var HrMilli = MinMilli * 60;
	var DyMilli = HrMilli * 23;
	var lastDayMonth = dPrevDate.getTime();
	lastDayMonth = lastDayMonth - DyMilli;
	dPrevDate.setTime(lastDayMonth);
	szOut = dPrevDate.getDate();
	return szOut;
}

function setStep(step) {
	$.cookie('regstep', step);
}
  
function getStep() {
    return $.cookie('regstep');
}
  
function gotoStep(step) {    
	if (step) {
		setStep(step);
	}	
    // nasconde tutti i div 
    $('div.step').hide();
    // va sul desiderato        
    $('div#pnlstep' + getStep()).show();     
    $('div#pnlstep' + getStep() + ' input:first').focus();         
} // function

function clientValidation_panel3() {
    var errCount = 0;
    var errMsg   = "";

    
    // check email secondaria
	if ($('input#tbusrMail2').val() !== '') {
		if (!isEMail($('input#tbusrMail2').val())) {
			errCount ++;
			errMsg += errCount + ')' + 'Il campo E-mail secondaria presenta un formato non valido. Esempio: Mario.Rossi@dominio.it.\n';
		}
	}
	
	
    if (errCount > 0) {     
        setStep(3);
		gotoStep();
        alert(errMsg);
        return false;
    } else {
        return true;
    }// if  

}

function clientValidation_panel4() {
    var errCount = 0;
    var errMsg   = "";	
    var datanascitaconiuge = $('#tbusrSpouseBornDateDD', 'div#pnlstep4').val() + '/' +  $('#tbusrSpouseBornDateMM', 'div#pnlstep4').val() + '/' +  $('#tbusrSpouseBornDateYYYY', 'div#pnlstep4').val();    
    if (datanascitaconiuge !== '//') {
        if (!isDate(datanascitaconiuge)) {
			errCount ++;
			errMsg += errCount + ')' + 'La data di nascita del coniuge non è valida. Es: 08/10/1978.\n';
        } // if
    }

    if (errCount > 0) {     
        setStep(4);
		gotoStep();
        alert(errMsg);
        return false;
    } else {
        return true;
    }// if  
}

function clientValidation_panel5() {
	var errCount = 0;
	var errMsg   = "";

	if (!document.getElementById('chkacceptrules').checked) {
		errCount ++;
		errMsg += errCount + ')' + 'E\' necessario accettare i termini di regolamento.\n';        
	} // if

	if (!document.getElementById('chkacceptprivacy1').checked) {
		errCount ++;
		errMsg += errCount + ')' + 'E\' necessario sottoscrivere l\' informativa sulla privacy.\n';        
	} // if
	
	if (errCount > 0) {     
		setStep(5); 
		gotoStep();
		alert(errMsg);
		return false;
	} else {
		return true;
	}// if  
}

function isEmptyString(str) {
	return (str === '');
}


function clientValidation_panel2() {
	return true;
}

function clientValidation_panel1() {
	var errCount = 0;
	var errMsg   = "";
	if (isEmptyString($("div#pnlstep1 #tbusrLogin").val())) {
		errCount ++;
		errMsg += errCount + ')' + 'Il campo E-mail è obbligatorio.\n';
	} else {
		if (!isEMail($("div#pnlstep1 #tbusrLogin").val())) {
			errCount ++;
			errMsg += errCount + ')' + 'Il campo E-mail presenta un formato non valido. Esempio: Mario.Rossi@dominio.it.\n';
		}
	}// if
 
	if (!$("div#pnlstep1 #tbusrPassword").attr("disabled")) {
		if (isEmptyString($("div#pnlstep1 #tbusrPassword").val()))  {
			errCount ++;
			errMsg += errCount + ')' + 'Il campo Password è obbligatorio.\n';
		} // if
	}

	if (isEmptyString($("div#pnlstep1 #tbusrName").val())) {
		errCount ++;
		errMsg += errCount + ')' + 'Il campo Nome è obbligatorio.\n';
	} // if

	if (isEmptyString($("div#pnlstep1 #tbusrSurname").val())) {
		errCount ++;
		errMsg += errCount + ')' + 'Il campo Cognome è obbligatorio.\n';
	} // if
  
	if ($("span#usrGender :radio:checked", "div#pnlstep1").size() === 0) {
		errCount ++;
		errMsg += errCount + ')' + 'Il campo Sesso è obbligatorio.\n';
	} // if
  
  
	if (isEmptyString($("div#pnlstep1 #tbusrAddress").val())) {
		errCount ++;
		errMsg += errCount + ')' + 'Il campo Indirizzo è obbligatorio, meglio se completo di numero civico.\n';
	} // if

	if (isEmptyString($("div#pnlstep1 #tbusrAddressCity").val())) {
		errCount ++;
		errMsg += errCount + ')' + 'Il campo Comune è obbligatorio.\n';
	} // if

	if (isEmptyString($("div#pnlstep1 #ddlProv").val())) {
		errCount ++;
		errMsg += errCount + ')' + 'Il campo Provincia è obbligatorio.\n';
	} // if

	var bDateDD = $('#tbusrBornDateDD', 'div#pnlstep1').val();
	var bDateMM = $('#tbusrBornDateMM', 'div#pnlstep1').val();
	var bDateYY = $('#tbusrBornDateYYYY', 'div#pnlstep1').val();
	

	var datanascita =  bDateDD + '/' + bDateMM + '/' + bDateYY;
	if (datanascita !== '//') {
		if (!isDate(datanascita, 0)) {
			errCount ++;
			errMsg += errCount + ')' + 'La data di nascita non è valida. Es: 08/10/1978.\n';
		} // if
	}

	if (errCount > 0) {     
		setStep(1); 
		gotoStep();
		alert(errMsg);
		return false;
	} else {
		return true;
	}// if  
  
}





function clientValidation() {
    var p1 = clientValidation_panel1();    
    if (!p1) {
		return p1;
	}
    
	var p3 = clientValidation_panel3();  
	if (!p3) {
		return p3;	
	}
	
    var p4 = clientValidation_panel4();    
    if (!p4) {
		return p4;
	}
    	
    var p5 = clientValidation_panel5();    
    if (!p5) {
		return p5;
	}    
}


function validation1() {	
	if (clientValidation_panel1()) {
		gotoStep(2);
	}
}

function validation2() {	
	gotoStep(3);
}

function validation3() {	
	if (clientValidation_panel3()) {
		gotoStep(4);
	}
}

function validation4() {	
	if (clientValidation_panel4()) {
		gotoStep(5);
	}
}

function clientRadioBind(base, todo) {
	var obj = $('input#showCases' + todo, $(base));                                 
	if (!isEmptyString($(obj).val())) {                                   
		var path = "";
		var V =  $(obj).val().split(','); 		
		for (var i = 0; i <= V.length - 1; i++) {                                                                                                              
			path += (i > 0 ? ',': '') + "input:checkbox[showcaseid='" + V[i] + "'][todo='" + todo + "']";                                   
		} // for
		$(path, $(base)).attr('checked', true);
	}
}

function syncChoices(todo) {  
	var ids = 
	$.map(
		$('input:checkbox:checked[todo=\'' + todo + '\']', 'div#insegne'), 
		function (o, i) {
			return $(o).attr('showcaseid');
		}
	);
	$('input#showCases' + todo).val(ids);                                                       
}
  



function holdCats(base) {
	var v = $.map(
		$(':checkbox:checked', $(base)),
		function (o) {
			return $(o).val();
		}
	);			
	$('input:eq(0)', $(base)).val(v);
}
  
function holdCatsBinder(base) {
	$(":checkbox", $(base)).bind(
	'click',
	function (e) {		    
		holdCats(base);
	} // function 
	);	
}

/* CATEGORIE */  
function bindCategories(base) {
    // base è il div contenitore dei checkbox e del campo dati"
    // bind dei check box dal campo hidden	
	var v = $('input:eq(0)', $(base)).val();
	if ((v !== null) && (v !== '')) {	    
		$.each(
			v.split(','),
			function (i, item) {                                         				
				$(":checkbox[value='" + item +  "']", $(base)).attr("checked", true);
			}              
		);
	} // if	
	// bind events. allineamento campo hidden ad ogni click.... previene la perdita dati con eventuale postback
	holdCatsBinder(base);
}
  	        
		    
function SyncCategories2to3() {
	// Mantiene allineate le strutture delle categorie al click
	$(":checkbox", 'div#_cats').bind(
		'click',
		function (e) {				
			var val = $(this).val();
			var checked = $(this).attr('checked');
			$(":checkbox[value='" + val + "']", 'div#_catsPA').attr('checked', checked);
			$("input:eq(0)", 'div#_catsPA').val($("input:eq(0)", 'div#_cats').val());
		} // function
	);
}    		        


function buildPerson(obj) {
	var html = "";          
	html += '<tr>';
	html += '<td dbID="' + obj.dbID + '" ptype="' + obj.TypeId + '">' + obj.TypeDesc + '</td>';
	html += '<td>' + obj.Gender + '</td>';
	html += '<td>' + obj.bDateDD + '</td>';
	html += '<td>' + obj.bDateMM + '</td>';
	html += '<td>' + obj.bDateYYYY + '</td>';
	html += '<td><a href="#" onclick="deletePerson($(this).parent().parent()); return false;">Elimina</a></td>';
	html += '</tr>';       
	$('td#Persone table:eq(0)').append(html);         
}

// aggiune una persona alla tabella prendendo il dato dal campo testo
function bindPerson(rIndex) {              
	if (!isEmptyString($('input#HIPersone').val())) {
		var V = $.trim($('input#HIPersone').val()).split(',');          
		// tutti
		if (V.length > 0) {
			$('td#Persone table:eq(0) tr:gt(1)').remove();
			for (var i = 0; i <= V.length - 1; i++) {                
				var dati = V[i];
				var obj = {};           
				obj.bDateDD = dati.split('|')[0];
				obj.bDateMM = dati.split('|')[1];
				obj.bDateYYYY = dati.split('|')[2];
				obj.Gender = dati.split('|')[3];
				obj.TypeId = dati.split('|')[4];                   
				obj.dbID = dati.split('|')[5];                   
				obj.TypeDesc = $('select#ddlPersonType option[value=\'' + obj.TypeId + '\']').text();
				buildPerson(obj);
			} // for            
		} // if
	} // if
}                                   

function buildControls() {                  
	// CLICK
	/*
	$('div#insegne input:checkbox').bind(
		'click',
		function (e) {                       
			// per prima cosa deve deselezionare i pari insegna
			$('input[todo!=\'' + $(this).attr('todo') + '\'][showcaseid=\'' + $(this).attr('showcaseid') + '\']:checkbox:checked', 'div#insegne').attr('checked', '');
			// aggiorno i campi multivalore
			syncChoices('IN');
			//syncChoices('OUT');
			syncChoices('PLUS');
		}
	);
	*/
	// aggiorno i campi multivalore
	// syncChoices('IN');
	// syncChoices('OUT');
	// syncChoices('PLUS');
	// BIND DA CAMPO                                 
	// clientRadioBind($('div#insegne'), 'IN');
	// clientRadioBind($('div#insegne'), 'OUT');
	// clientRadioBind($('div#insegne'), 'PLUS');
	// CATEGORIES            
	bindCategories($('div#_cats'));
	bindCategories($('div#_catsPA'));
	// PERSONS
	bindPerson();
}




    

   
// aggiunge una persona al campo testo
function appendPerson() {   
	var html = '';
	html += $('input#addSonDD').val();          
	html += '|' + $('input#addSonMM').val();
	html += '|' + $('input#addSonYYYY').val();                    
	var gender = $('input[name=\'rbAddSonGender\']:checked').attr('value');
	html += '|' + gender;          
	var type = $('select#ddlPersonType option:selected').val();
	html += '|' + type;                   
	html += '|0';
	if (!isEmptyString($('input#HIPersone').val())) {
		$('input#HIPersone').val($('input#HIPersone').val() + ',' + html);
	} else {
		$('input#HIPersone').val(html);
	}
} //

       
function deletePerson(obj) {
	$(obj).remove();
	$('input#HIPersone').val('');            
	$.each(
		$('td#Persone table:eq(0) tr:gt(1)'),
		function (i, item) {
			var html = '';
			html += $('td:eq(0)', item).text(); //$('input#addSonDD').val();                          
			html += '|' + $('td:eq(1)', item).text();
			html += '|' + $('td:eq(2)', item).text();         
			html += '|' + $('td:eq(3)', item).text();         
			html += '|' + $('td:eq(4)', item).attr('ptype');//text();         
			html += '|' + $('td:eq(4)', item).attr('dbID');//text();         
			
			if (!isEmptyString($('input#HIPersone').val())) {
				$('input#HIPersone').val($('input#HIPersone').val() + ',' + html);
			} else {
				$('input#HIPersone').val(html);
			}
		}
	);                                
}



       
       

                
       
// aggiunge una persona
function addPerson(o) {       	
	var d = $('input#addSonDD').val() + '/' + $('input#addSonMM').val() + '/' + $('input#addSonYYYY').val();            
	if (isDate(d)) {
		$(o).next().html('');
		appendPerson();
		bindPerson();
	} else {
		$(o).next().html('Data di nascita non corretta. Es: 08/10/1978.');
	}            	
} // function

	   
	   
function syncField1to2(e, from, to) {	   
	$('#' + from, 'div#pnlstep1').bind(e, 
		function () {
			$('#' + to, 'div#pnlstep2').val($(this).val());
		}
	);
}

function syncField1to3(e, from, to) {	   
	$('#' + from, 'div#pnlstep1').bind(e,
		function () {
			$('#' + to, 'div#pnlstep3').val($(this).val());
		}
	);
}
	   

function SyncAddress1to2() {	   	        
	syncField1to2('keyup', 'tbusrAddress', 'tbusrStartAddrStreet');
	syncField1to2('keyup', 'tbusrAddressNumber', 'tbusrStartAddrNumber');
	syncField1to2('keyup', 'tbusrAddressCity', 'tbusrStartAddrCity');
	syncField1to3('keyup', 'tbusrLogin', 'tbusrMail2');
	syncField1to2('change', 'ddlProv', 'ddlStartAddrProv');			
}
	   
function RegGeoCheck() {			
	var via = $('#tbusrStartAddrStreet').val();
	var civico = $('#tbusrStartAddrNumber').val();
	var comune = $('#tbusrStartAddrCity').val();
	var provincia = $('option:selected', '#ddlStartAddrProv').text();
	var address = via + (civico !== '' ? ', ' + civico : '') + ',' + (comune !== '' ? ', ' + comune: '') +  ',' +  (provincia !== '' ? ', ' + provincia: '');			
	GeoCoding(
		address, 
		function (point) {										
			$('span#geocoding').text('Indirizzo localizzato correttamente').css({'color': 'green'});			
			$('input#tblat').val(point.lat());
			$('input#tblng').val(point.lng());
		},
		function () {
			$('span#geocoding').text('Indirizzo non localizzabile').css({'color': 'red'});
			$('input#tblat').val('');
			$('input#tblng').val('');
		}
	);
}
	   
	   

$(document).ready(
	function () {
	
		if ($('input#tblat').val() === '') {
			$('input#tblat').val('0');
		}

		if ($('input#tblng').val() === '') {
			$('input#tblng').val('0');
		}

	
	
		//var tipi = 'Piazza,Via,Viale,Vicolo,Largo,Corso,Piazzale,Porta,Porto';
		var tipi = 'Calle,Centro,Centro Com.,Centro Dir.,Circ.one,Contrada,Corsia,Corso,Foro,Fondamenta,Galleria,Largo,Località,Lungo,Palazzo,Piaz.tta,Piazza,Piazzale,S.S.,Salita,Sestiere,Stazzo,Strada,Via,Viale,Vico,Zona Ind.le, ';
		$("#tbusrAddress").autocomplete(tipi.split(','));
		$("#tbusrStartAddrStreet").autocomplete(tipi.split(','));
		var o = 'select#ddlBornNation';
		if ($(o).val() === '') {
			$(o).val('105');
		}
		
		$('input#tbusrAddressCity').autocomplete(
			'/comuni.aspx', 
			{	    
				width: 300,
				minChars: 1,
				delay: 5,
				selectFirst: true,			
				extraParams: {
					provSigla: function () { 
						return $('#ddlProv').attr('provsigla'); 
					},
					output: 'BIND'			
				}
			}		
		);
		
		$('input#tbusrBornCity').autocomplete(
			'/comuni.aspx', 
			{	    
				width: 300,
				minChars: 1,
				delay: 5,
				selectFirst: true,			
				extraParams: {
					provSigla: function () { 
						return $('#ddlBornProv').attr('provsigla'); 
					},
					output: 'BIND'			
				}
			}		
		);
		

		
		
		
		
		
		
		$('input#tbusrStartAddrCity').autocomplete(
			'/comuni.aspx', 
			{	    
				width: 300,
				minChars: 1,
				delay: 5,
				selectFirst: true,			
				extraParams: {
					provSigla: function () { 
						return $('#ddlStartAddrProv').attr('provsigla'); 
					},
					output: 'BIND'			
				}
			}		
		);
		
		
		// bind on click province		
		$('select[provsigla]').bind(
			"change",
			function () {		
				var obj = $(this);
				var val = $(this).val();
				if (val !== "") {
					$.getJSON(
						"/siglaprovincia.aspx",
						{provId: val, output: 'JSON'},
						function (data) {
							var sigla = data.Table[0].provSigla;						
							$(obj).attr('provsigla', sigla);
						}
					);
				} else {
					$(obj).attr('provsigla', '');
				}
			}
		);
		
		$('#addSonDD, #addSonMM, #addSonYYYY').one('focus', 
			function () {
				$(this).val('');
			}
		);
		
		
		
	}
);
	

function InitDataFields() {		
	$('input[value=\'AAAA\'], input[value=\'GG\'], input[value=\'MM\']').one('focus', 
		function () {
			$(this).val('');
		}
	);	
}
	
	
	
/**********************************************************************************************************************
Carica il box richiesto in ricerca avanzata.
***********************************************************************************************************************/
function advsearchreg(o, mode) {	
	$('.pnlAdvSearchContainer').remove();

	var win_h = $(window).height();	
	var win_w = $(window).width();	


	
	var max_h  =  Math.floor(Number(win_h / 100 * 70)) + 'px';
	
	var lat = String($('input#tblat').val()).replace(',', '.');
	var lng = String($('input#tblng').val()).replace(',', '.');
	
	$.get(
		'/advsearchparam2.aspx',
		{rnd: rnd(), mode: mode, session: '', _lat: lat, _lng: lng, reg: '1', _all: 1},
		function (data) {		
			var id = "popup_" + mode;
			//var headerdiv = "<div style=\"background-color: #9BAC45; height: 20px; display:block;\">&nbsp;</div>";			
			$('body').append("<div id=\"" + id + "\" class=\"pnlAdvSearchContainer\" style=\"padding:0px; margin:0px;\"><div style=\"height: " + max_h + "; margin:0px; position:relative; display:block;\">" + data + "</div></div>");
			var div_h = $('#' + id).height();			
			var div_w = $('#' + id).width();
			$('#' + id).css({'left': ((win_w / 2) - (div_w / 2)) + 'px', 'top':'70px'});														
			$('.content div:eq(0)', '#' + id).css({'height': max_h});
			$('.content', '#' + id).css({'overflow-y':'scroll'});
			$('.cpopup', '#' + id).click(
				function () {
					$('.pnlAdvSearchContainer').fadeOut('fast');
					return false;
				}
			);			
			
			
			
			$('#' + id).fadeIn('slow');				
			/*						
			$('body').append("<div id=\"" + id + "\" class=\"pnlAdvSearchContainer\">" + data + "</div>");			
			var div_h = $('#' + id).height();			
			var div_w = $('#' + id).width();						
			$('#' + id).css({'z-index': '99', 'position': 'fixed', 'left': ((win_w / 2) - (div_w / 2)) + 'px', 'top': ((win_h / 2) - (div_h / 2)) + 'px'});					
			$('#' + id + ' .cpopup').click(
				function () {
					$('.pnlAdvSearchContainer').fadeOut('fast');
					return false;
				}
			);			
			$('#' + id).fadeIn('slow');				
			*/
			
		}
	);
}


function selectCatsAllReg(o, root) {
	var checked = $(o).attr('checked');
	var base = $('div#' + root);
	$(':checkbox', base).attr('checked', checked);
	holdCats(base);
	
}

	

