var boxFonteFx;
var onlyRCFamilyFx;
var capFx;
var stringLoc = "locValid($('loc').value,session,'','C')";
var stringLoc2 = "loc2Valid($('loc2').value,session,'','C')";
var slideDuration = 300;

window.addEvent('domready', function() {
	initData(true);
} );

function initData(ricaricaLocalita) {

	var selectTipoAbitazioneList = new Array("tipoAbitazione");
	updateSelectList(selectTipoAbitazioneList);
	
	var selectFontePubblicitariaList = new Array("fontePubblicitaria");
	updateSelectList(selectFontePubblicitariaList);
	
	if ($('fonteDiv') != null && $('fonteDiv').style.display != 'none'){
		boxFonteFx = new CustomSlide('fonteDiv',{link:'cancel'});
		if (logged || fonte != '') {
			boxFonteFx.slideOut();
		} else {
			boxFonteFx.slideIn();
		}
	}
	
	onlyRCFamilyFx = new CustomSlide('onlyRCFamily',{link:'cancel'});
	capFx = new CustomSlide('CAP',{link:'cancel'});
	if ($('abitazioneRCFamiglia').checked) {
		onlyRCFamilyFx.slideIn();
	} else {
		onlyRCFamilyFx.slideOut();
	}
	
	if ($('proprietarioAbitazioneYvivo').checked) {
		/*
		var boxFx = new Fx.Slide('CAP', { duration: slideDuration, transition: Fx.Transitions.linear });
		var boxFx2 = new Fx.Slide('onlyRCFamily', { duration: slideDuration, transition: Fx.Transitions.linear });
		boxFx.slideOut();
		setTimeout(function(){boxFx2.slideIn();},slideDuration);
		*/
		capFx.slideOut();

		$('valComId').style.visibility ='visible';
	} else {
		/*
		var boxFx = new Fx.Slide('CAP', { duration: slideDuration, transition: Fx.Transitions.linear });
		var boxFx2 = new Fx.Slide('onlyRCFamily', { duration: slideDuration, transition: Fx.Transitions.linear });
		boxFx.slideIn();
		setTimeout(function(){boxFx2.slideIn();},slideDuration);
		*/
		capFx.slideIn();
		if ($('proprietarioAbitazioneN').checked) {
			$('valComId').style.visibility ='hidden';
		} else {
			$('valComId').style.visibility ='visible';
		}

	}
	
	if (ricaricaLocalita) {
		if (!logged) {
			//<%-- New management Locality Search --%>
			//locValid($('loc').value, session, comboLoc,'C');
			localities_by_zipcode($('loc').value,$('sel_loc'),'C',LocAbit);
		} else {
			var slap = $('sel_loc');
			slap.innerHTML = '';
	        var opt = document.createElement('option');
	        opt.value = LocAbit;
	        opt.innerHTML = $('loc').value + ', ' + comboLoc;
	        slap.appendChild(opt);

	        /*localities_by_zipcode($('loc').value,$('sel_loc'),'C',LocAbit, function(){
				$('sel_loc').set('disabled','disabled');
				
				combo = $(sel_loc);
				if ( combo.options[ combo.selectedIndex ].value )
					retrieve_info.apply( combo , [] );	// fire 'selected event'
			});*/
		}
		//loc2Valid($('loc2').value, session, comboLoc2,'C');
		localities_by_zipcode($('loc2').value,$('sel_loc2'),'C',LocAbit2);
	}
}

//<%-- New management Locality Search --%>
function checkCap_searchLocality(event,cap,combo,type,defaultValue){
	return isNumberKey(event) && localities_by_zipcode.delay(1,this,[cap,combo,type,defaultValue]);
}

/* Non so perchè l'agenzia l'aveva creato, crea un casino di problemi e da un effetto inutile
function toggleBox(labelObj, boxId, mode) {
	if (!labelObj.getElementsByTagName('input')[0].checked) {
		var boxFx = new Fx.Slide(boxId, { duration: slideDuration, transition: Fx.Transitions.linear });
		if (boxId != 'onlyRCFamily') {
			var boxFx2 = new Fx.Slide('onlyRCFamily', { duration: slideDuration, transition: Fx.Transitions.linear });
		}
		if (mode == 'show') {
			boxFx.slideIn();
			if(boxId != 'onlyRCFamily'){
				setTimeout(function(){boxFx2.slideIn();},slideDuration);
			}
		} else {
			boxFx.slideOut();
			if (boxId != 'onlyRCFamily') {
				setTimeout(function(){boxFx2.slideIn();},slideDuration);
			}
		}
		return void(0);
	}
}
*/

function checkMq() {
	var minVal = 20;
	var maxVal = 600;
	var curVal = parseInt($('mq').value.split('.').join('').split(',').join(''));

	var err = 0;
	$('errorMq').style.display = 'none';
	if (minVal <= curVal && curVal <= maxVal) {
		err = 0;
	} else {
		$('errorMq').style.display = 'inline';
		highlightField('errorMq');
		err = 1;
	}
	//initData(false);
	return err;
}

function checkValCom() {
	var minVal = 50;
	var maxVal = 5000;
	var curVal = parseInt($('valCom').value.split('.').join('').split(',').join(''));
	
	var err = 0;
	$('errorValCom').style.display = 'none';
	if (minVal <= curVal && curVal <= maxVal) {
		err = 0;
	} else {
		$('errorValCom').style.display = 'inline';
		highlightField('errorValCom');
		err = 1;
	}
	//initData(false);
	return err;
}

function checkEmail(){
	var err = 0;
	if (isMandatory('insertEmail','insertEmailErr') == 1) {
		err++;
	} else if(isEmail('insertEmail', 'emailFormatErr') == 0) {
		return 0;
	} else {
		$('emailFormatErr').style.display = 'inline';
		//highlightField('emailFormatErr');
		err++;
	}
	return err;
}

function checkForm() {
	totErrori = 1;
	var allErrors = $$('.error');
	for (var i = 0; i < allErrors.length; i++) {
	    allErrors[i].style.display = 'none';
	}
	
	if (!logged) {
    	totErrori += isMandatory('sel_loc','comboLocalitaError');
    	
    	var cmbAdvSource = null;
	
		if ( $('comboFontePubblicitaria') && $('comboFontePubblicitaria2') ){
			if (  $('comboFontePubblicitaria2').hasClass( 'displayed' )  )
				cmbAdvSource = $('comboFontePubblicitaria2');
			else
				cmbAdvSource = $('comboFontePubblicitaria');
		}
		if ($('fonteDiv') != null && $('fonteDiv').style.display != 'none') {
			if( cmbAdvSource )
				totErrori += isMandatory( cmbAdvSource.id , 'comboFontePubblicitariaError');
		}
    	
    }
    
    if ($('abitazioneRCFamiglia').checked) {
		totErrori += isMandatory(new Array('proprietarioAbitazioneYvivo','proprietarioAbitazioneYnonvivo','proprietarioAbitazioneN'),'errorProprietarioAbitazione');
		if (!$('proprietarioAbitazioneYvivo').checked) {
			totErrori += isMandatory('sel_loc2','comboLocalita2Error');
		}
		totErrori += isMandatory('tipoAbitazione','errorTipoAbitazione');
		
		totErrori += isMandatory('mq','errorMq');
		totErrori += isNumeric('mq','errorMq');
		totErrori += checkMq('mq');
		if (!$('proprietarioAbitazioneN').checked) {
			totErrori += isNumeric('valCom','errorValCom');
			totErrori += isMandatory('valCom','errorValCom');
			totErrori += checkValCom('valCom');
		}
	}
	
	totErrori += checkEmail();
	
	if (totErrori > 1) {
		//initData(false);
	    return false;
	} else {
        if (logged == false){
        	var indIndex = $('sel_loc').selectedIndex;
        	if (indMap.isEmpty()) {
        		$('indHidField').value = $('sel_loc').options[indIndex].value;
        	} else {
           		$('indHidField').value = indMap.get($('sel_loc').options[indIndex].value);
       	 	}
       	}
	    if ($('abitazioneRCFamiglia').checked) {
	    
			var t = $('tipoAbitazione').selectedIndex;
			$('ctTipoAbitazioneString').value = $('tipoAbitazione').options[t].text;
			
			if (!$('proprietarioAbitazioneYvivo').checked) {
	        	var indIndex2 = $('sel_loc2').selectedIndex;
	        	if (indMap.isEmpty()) {
	        		$('indHidField2').value = $('sel_loc2').options[indIndex2].value;
	        	} else {
	           		$('indHidField2').value = indMap.get($('sel_loc2').options[indIndex2].value);
	       	 	}
       		}
       	}
        disableControls(document);
	    return true;
	}
}

/*
 * Funzioni sulla località copiate dalla common_gll per gestire 
 * una seconda ricerca località nella stessa pagina
 */
 /*
function loc2Valid(searchLoc, sessionId, defaultValue, modalitySearch) {
	if(defaultValue==null)
		defaultValue = '';
//	var delay = 2000; // impostato a 2 secondi per simulare il caricamento, nel caso reale andrebbe impostato a 300-500 millisecondi per evitare di inviare troppe chiamate al server digitando tanti caratteri di seguito.
	var delay = 1000;
    var s1;
    var locVL = $('loc2').length;
    sla2 = $('sel_loc2');
    if (s1) clearTimeout(s1);
    
    if(modalitySearch == null || modalitySearch == ''){ 			
    	modalitySearch = 'L';
     }
    
	if (searchLoc.length >= 5 && isNum(searchLoc)) {
		locVL = searchLoc.length;
		if (isNum(searchLoc)) {
	        if (searchLoc.length == 5) {
            	if (/^\d{2}[0189]\d{2}$/.test(searchLoc)) {
                  	document.getElementById('loading2').style.visibility = 'visible';
                    s1 = setTimeout('loadLoc2("'+searchLoc+'", "cap","'+sessionId+'","'+defaultValue+'","'+modalitySearch+'")', delay); 
                } else {
                    $('loading2').style.visibility = 'hidden';
                    $('sel_loc2').disabled = 'disabled';
                    //alert("Il cap inserito non e' valido");
                    s1 = setTimeout('hideLoc2()', 500);
                    
                }
             } else if(searchLoc.length < 5){
             	s1 = setTimeout('loadLoc2("'+searchLoc+'", "cap","'+sessionId+'","'+defaultValue+'","'+modalitySearch+'")', delay);
				$('loading2').style.visibility = 'visible';
            	$('sel_loc2').disabled = 'disabled';
             } else {
				//s1 = setTimeout('loadLoc("'+searchLoc+'", "cap","'+sessionId+'","'+defaultValue+'")', delay);
				//$('loading').style.visibility = 'visible';
            	//$('sel_loc').disabled = 'disabled';
          		$('loading2').style.visibility = 'hidden'; 
        		$('sel_loc2').disabled = 'disabled'; 
        		s1 = setTimeout('hideLoc2()', 500);
	         }
    	} else if(isWord(searchLoc)){
        	$('loading2').style.visibility = 'visible';
	        s1 = setTimeout('loadLoc2("'+searchLoc+'", "loc2","'+sessionId+'","'+defaultValue+'","'+modalitySearch+'")', delay);
    	    $('loading2').style.visibility = 'visible';
        	$('sel_loc2').disabled = 'disabled';
        
    	} else {
        	$('loading2').style.visibility = 'hidden'; 
        	$('sel_loc2').disabled = 'disabled'; 
        	s1 = setTimeout('hideLoc2()', 500);
    	}
	} else {
    	s1 = setTimeout('hideLoc2()', 500);
	}
}

function loadLoc2(x,t,idSess,defaultValue,modalitySearch) {
//	alert('loadLocNew');
	if(t == 'cap'){
		var call = "jsonFactory.searchLocalityByZipCode";
	} else {
		var call = "jsonFactory.searchLocalityByDescription";
	}
    sla2.empty();
    // Richiesta Ajax ad-hoc per JSON , info -> http://docs.mootools.net/Request/Request.JSON
                
	var jsonRequest = new Request.JSON({url: host, 
		data: JSON.encode({"id":2,"method":call,"params":[x,idSess,modalitySearch]}),
		                        
		onRequest: function() {
//			alert("request: " + JSON.encode({"id":2,"method":call,"params":[x,idSess]}));
			$('loading2').setStyle( 'visibility' , 'visible' );
			$('loc2').setProperty( 'disabled' , 'disabled');
	    },
	    onLoading: function() {
	    	$('loading2').setStyle( 'visibility' , 'visible' );
			$('loc2').setProperty( 'disabled' , 'disabled');
	    },
	    onComplete: function(jsonItem){
	    	var i = 0;
	    	sla2.empty();
	        jsonLoc = JSON.decode(jsonItem.result.locs);
	        
	        var sel_localita_option = new Element('option', {
	        	'value':''
	        }).set('html' , selLocalita ).inject( sla2 , 'top' ) ;
	        
	        jsonLoc.each(function(item) {
	        	var opt = new Element('option');
	            if( t == 'loc' ){
	                if( item.capVis )
		                opt.set( 'html' , item.loc + ', ' + item.capVis );
		            else
		            	opt.set( 'html' , item.loc );
	            } else {
	            	//ATTENZIONE! modificare anche CarInsuranceEstimatePrepareAction se si modifica questa parte
			       	// opt.value = item.loc+', '+item.cap+', '+item.pr+', '+item.codLoc+', '+item.key;
			        if( item.capVis )
	        			opt.set( 'html' , item.capVis + ', ' + item.loc );
	        		else
	        			opt.set( 'html' , item.loc );
	    		}
             	opt.setProperty( 'value' , item.loc );
	            
	            valoreOpt = item.loc + ', ' + item.cap + ', ' + item.pr + ', ' + item.codLoc + ', ' + item.key;
	            
	            indMap.set( item.loc , valoreOpt );
	    		
	    		if( defaultValue == opt.value )
					opt.setProperty( 'selected' , 'selected' );
					
	    		opt.inject( sla2 );
	            i++;
	        });

	        if ( !i ) {	// i == 0
	        	sla2.empty();
				var opt = new Element('option', {
					'value': ''
				}).set( 'html' , locNotFound ).inject( sla2 );
				
				$('loading2').setStyle('visibility' , 'hidden' );
				$('sel_loc2').setProperty( 'disabled' , 'disabled' );
				$('loc2').removeProperty( 'disabled' );
				$('loc2').addClass( 'text' );
			} else if ( i == 1 ){
	        	sel_localita_option.dispose();
	        }
	        	
			displayLoc2(); 
	}}).send();
}

function displayLoc2() {
    $('sel_loc2').removeClass( 'error_select' );
	$('loc2').removeProperty( 'disabled' );
	$('loc2').addClass( 'text' );
    $('comboLocalita2Error').setStyle( 'display' , 'none' );
    $('loading2').setStyle( 'visibility' , 'hidden' );
    $('sel_loc2').removeProperty( 'disabled' );
}

function hideLoc2() {
    $('loading2').style.visibility = 'hidden';
    if($('sel_loc2').value==null || $('sel_loc2').value=='-1' || $('sel_loc2').value=='')
	    $('sel_loc2').disabled = 'disabled';
}
*/

/*
function checkPasteFF(method) {
    newCharCount = $(method).value;
    oldCharCount = charCount;
    charCount = newCharCount;
    if(newCharCount != oldCharCount) {
        locValid2($(method).value);
    }
}
*/

function pasteEvent(x) {
    if (navigator.userAgent.match('MSIE')) {
        setTimeout(x,100);
    }
}

