// JavaScript Document
var ie = document.all;
var ie6 = !window.XMLHttpRequest;

function show(id){
	if(document.getElementById(id)){
		document.getElementById(id).style.display = 'block';
	}
}
function hide(id){
	if(document.getElementById(id)){
		document.getElementById(id).style.display = 'none';
	}
}
function del(id){
	if(document.getElementById(id)){
		document.body.removeChild(document.getElementById(id));
	}
}
function showhide(id){
	if(document.getElementById(id)){
		var el = document.getElementById(id);
		if(!el.style || el.style.display == 'none')
			show(id);
		else
			hide(id);
	}
}


function trim(s) {
  while (s.substring(0,1) == ' ') {
    s = s.substring(1,s.length);
  }
  while (s.substring(s.length-1,s.length) == ' ') {
    s = s.substring(0,s.length-1);
  }
  return s;
}
function loading(){
	return true;
}

function get(url,id,func,field) {
	loading();
	  if (document.getElementById) {
		var x = (window.ActiveXObject) ? new ActiveXObject("Microsoft.XMLHTTP") : new XMLHttpRequest();
	  }
	  if (x) {
		x.onreadystatechange = function() {
		  if (x.readyState == 4 && x.status == 200) {
			var text = x.responseText;
			if(id){
				el = document.getElementById(id);
				el.innerHTML = text;
			}
			if(func)
				eval(func);
			
			loading();
			
		  }
		}
		x.open("GET", url, true);
		x.send(null);
	  }
}

var f = false;
function post(url, formname, id, action) {
	loading();
	if (document.getElementById) {
	var http = (window.ActiveXObject) ? new ActiveXObject("Microsoft.XMLHTTP") : new XMLHttpRequest();
	}
	if (!f && http) {
		var fields = new Array();
		if(formname != ""){
			var ajax = formname;
			//loop through form elements and retrieve field NAMEs and Values
			for (var x = 0; x < eval("document."+ajax+".elements.length"); x++){
				// join them into a string.

				var el = eval("document."+ajax+".elements[x];");
				if((el.type == 'checkbox' || el.type == 'radio') && el.checked == true || (el.type != 'checkbox' && el.type != 'radio'))
					fields.push(el.name+'='+encodeURIComponent(el.value));
			}
		}
		//sendf looks like "username=myusername&password=mypass"
		var sendf = fields.join('&');
		http.open("POST", url, true);
		http.onreadystatechange = function() {
			if (http.readyState == 4 && http.status == 200) {
				var text = http.responseText;
				if(id)
					document.getElementById(id).innerHTML = text;
				
				if(action)
					eval(action+';');
					
				f = false;
				loading();
			}
		}
		http.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
		http.send(sendf);
		f = true;
	}
}

function stradario(type,cod,id){
	if(type == 'via'){
		document.getElementById('strad_civico').innerHTML = '';
		document.getElementById('strad_coord').innerHTML = '';
	}
	if(type == 'civico'){
		document.getElementById('strad_coord').innerHTML = '';
	}
	if(type == 'coord'){
		cod += '&id='+document.getElementById('ID_STRADA').value;
	}
	get('../stradario.php?type='+type+'&cod='+cod,id);
}
function natopera(cod){
	document.getElementById('natopera02').innerHTML = '';
	get('../natopera.php?cod='+cod,'natopera02');
}

function attspec(el,campo){
	get('../attivitaspec.php?field='+campo+'&cod='+el.value+'&source='+el.name,campo);
}

function opaco(onoff){
	if(onoff == 'on'){
		var el = document.createElement('DIV');
		el.id = 'p5-opaco';
		//nascondo elementi che passano attraverso il layer in IE6
		ie6 ? showhideIE6() : null;
		if(document.body)
			document.body.appendChild(el);
	}else if(onoff == 'off'){
		if(document.getElementById('p5-opaco')){
			document.body.removeChild(document.getElementById('p5-opaco'));
			ie6 ? showhideIE6() : null;
		}
	}
}
function showhideIE6(){
	document.getElementById('p5-opaco');
	var els = document.getElementsByTagName('SELECT');
	for(var i=0;i<els.length;i++)
		if(els[i].style.visibility == 'hidden')
			els[i].style.visibility = '';
		else
			els[i].style.visibility = 'hidden';
}

function lightShow(onoff,url){
	if(onoff == 'on'){
		opaco('on');
		noscroll(1);
		var el = document.createElement('DIV');
		el.setAttribute('id','p5-content');
		document.body.appendChild(el);
		if(url)
			get(url,'p5-content');
	}else{
		document.body.removeChild(document.getElementById('p5-content'));
		opaco('off');
		noscroll();
	}
}
function noscroll(hide){
	if(!document.body)
		return false;
	ie? elHideScroll = document.body.parentNode : elHideScroll = document.body;
	if(hide)
		elHideScroll.style.overflow = 'hidden';
	else
		elHideScroll.style.overflow = '';
		
}
function impreseInsert(type,el){
	//in base alla maschera che ha richiamato la visualizzazione imprese, compio diverse azioni
	switch(type){
		case 'rlst':
			rlstInsertImp(el);
			break;
	}
}
function impreseInsertManual(id){
	//inserimento manuale impresa. Possibilità di mostrare un div
	show(id);
	lightShow('off');
	
}
function impreseSearch(){
	if(trim(document.impresaSearch.anagrafica.value) == '' && trim(document.impresaSearch.codfispiva.value) == ''){
		alert("Inserire l'anagrafica o Partita iva / Codice fiscale");
	}else{
		post('/reserved/imprese-search.php','impresaSearch','p5-mainContent');
	}
	return false;
}

var restoreP5 = false;
function alert(str,goto){
	if(!document.body)
		return false;

	if(document.getElementById('alert')){
		document.body.removeChild(document.getElementById('alert'));
		if(!restoreP5){
			noscroll();
			opaco('off');
			return false;
		}else{
			show('p5-content');
			restoreP5 = false;
			return false;
		}
	}else{
		if(!document.getElementById('p5-content')){
			opaco('on');
			noscroll(1);
		}else{
			hide('p5-content');
			restoreP5 = true;
		}
		var el = document.createElement('DIV');
		el.id = 'alert';
		el.innerHTML = str;
		var button = new Image();
		button.onclick = function() { alert(); if(goto) window.location = goto};
		button.src = '/reserved/images/alertclose.gif';
		el.appendChild(button);
		document.body.appendChild(el);
		var al = document.getElementById('alert');
		al.style.top = f_scrollTop() + 'px';
	}
}

function f_scrollTop() {
	return f_filterResults (
		window.pageYOffset ? window.pageYOffset : 0,
		document.documentElement ? document.documentElement.scrollTop : 0,
		document.body ? document.body.scrollTop : 0
	);
}
function f_filterResults(n_win, n_docel, n_body) {
	var n_result = n_win ? n_win : 0;
	if (n_docel && (!n_result || (n_result > n_docel)))
		n_result = n_docel;
	return n_body && (!n_result || (n_result > n_body)) ? n_body : n_result;
}

function isDate(dateStr) {
var datePat = /^(\d{2})(\/)(\d{2})(\/)(\d{4})$/;
var matchArray = dateStr.match(datePat); // is the format ok?

if (matchArray == null)
return false;

day = matchArray[1]; // p@rse date into variables
month = matchArray[3];
year = matchArray[5];

if (month < 1 || month > 12) // check month range
return false;

if (day < 1 || day > 31) 
return false;

if ((month==4 || month==6 || month==9 || month==11) && day==31) 
return false;


if (month == 2) { // check for february 29th
	var isleap = (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0));
	if (day > 29 || (day==29 && !isleap)) 
	return false;
}
return true; // date is valid
}

function isTime(timeStr) {

	var timePat = /^(\d{2}):(\d{2})?$/;

	var matchArray = timeStr.match(timePat);
	if (matchArray == null)
		return false;
	
	hour = matchArray[1];
	minute = matchArray[2];
	
	if (hour < 0  || hour > 23)
		return false;
	if (minute<0 || minute > 59)
		return false;

return true;
}

function findPos(obj) {
	var curleft = curtop = 0;
	if (obj.offsetParent) {
		do {
			curleft += obj.offsetLeft;
			curtop += obj.offsetTop;
		} while (obj = obj.offsetParent);
	}
	return [curleft,curtop];
}

function errore(arr,formName){
	removeError(formName);
	var str = '';
	var campo;
	var pos = 0;
	var cont = 0;
	if(arr){
		for (var i in arr){
			
			cont++;
			eval("campo = document."+formName+"."+i+";");
			str += '<li>'+arr[i]+'</li>';
			campo.style.color='#F00';
			campo.style.background='#CF0';
			pos = findPos(campo);
			var el = document.createElement('A');
			el.className = 'errorDiv';
			el.rel = campo.name;
			
			el.style.left = pos[0] - 15 + 'px';
			el.style.top = pos[1] - 35 + 'px';
			
			//link per spostare la pagina al primo errore
			if(cont == 1){
				el.name = 'err_'+campo.name + cont;
				el.id = 'err_'+campo.name + cont;
				var goto = '#err_'+campo.name + cont;
			}
			
			document.body.appendChild(el);
			campo.onclick = function(){ 
				this.style.color = '';
				this.style.background='';
				removeError(this.name);
			};
			
		}
	}
	alert(str,goto);
	return false;
}

function removeError(name){
	var els = document.getElementsByTagName('A');
	for(var i=0; i<els.length;i++)
		if(name != 'tutti' && els[i].className == 'errorDiv' && els[i].rel == name || name == 'tutti')
			document.body.removeChild(els[i]);
}

function checkcontrol(formName,fieldName,val){
	eval("var field = document."+formName+"."+fieldName+";");
	if(val != '' && field.checked == false)
		field.checked = true;
	else if(val == '')
		field.checked = false;
}

function changePass(img){
	if(!document.getElementById('changePsw')){
		var el = document.createElement('DIV');
		el.id = "changePsw";
		var imgpos = findPos(img);
		el.style.left = imgpos[0]+'px';
		el.style.top = imgpos[1]+20+'px';
		
		document.body.appendChild(el);
		get('../changePsw.php','changePsw');
	}else{
		del('changePsw');
	}
}
function savePass(){
	var pass = document.formPsw.psw.value;
	if(pass.length < 5){
		alert('La password deve essere di minimo 6 caratteri');
		return false;
	}
	var confronto = pass.replace(/[^A-Za-z0-9_-]/gi, "").toLowerCase();
	if(confronto != pass){
		alert("La password puo' contenere solo lettere e numeri");
		return false;
	}
	post('../changePsw.php','formPsw');
	del('changePsw');
}
function loading(){
	if(!document.getElementById('loading')){
		var el = document.createElement('loading');
		el.id = "loading";
		document.body.appendChild(el);
	}else{
		document.body.removeChild(document.getElementById('loading'));	
	}
}

function AttachEvent(obj,evt,fnc,useCapture){
	if (!useCapture) useCapture=false;
	if (obj.addEventListener){
		obj.addEventListener(evt,fnc,useCapture);
		return true;
	} else if (obj.attachEvent) return obj.attachEvent("on"+evt,fnc);
	else{
		MyAttachEvent(obj,evt,fnc);
		obj['on'+evt]=function(){ MyFireEvent(obj,evt) };
	}
} 

function MyAttachEvent(obj,evt,fnc){
	if (!obj.myEvents) obj.myEvents={};
	if (!obj.myEvents[evt]) obj.myEvents[evt]=[];
	var evts = obj.myEvents[evt];
	evts[evts.length]=fnc;
}
function MyFireEvent(obj,evt){
	if (!obj || !obj.myEvents || !obj.myEvents[evt]) return;
	var evts = obj.myEvents[evt];
	for (var i=0,len=evts.length;i<len;i++) evts[i]();
}