// funzioni globali

function addEvent(obj, evType, fn){
 if (obj.addEventListener){
    obj.addEventListener(evType, fn, true);
    return true;
 } else if (obj.attachEvent){
    var r = obj.attachEvent("on"+evType, fn);
    return r;
 } else {
    return false;
 }
}

function buildUri(obj){
  var strUri = "";
  for(var n=0; n<obj.elements.length; n++){
    if(obj.elements[n].name!=""){
		stri = obj.elements[n].value;
    	reg = new RegExp("\\+","g");
    	stri = stri.replace(reg,"caratzPiu");
    	reg = new RegExp("€","g");
    	stri = stri.replace(reg,"caratzEuro");
		strUri += "&"+obj.elements[n].name+"="+escape(stri);
		strUri = strUri.replace("caratzPiu","%2B","g");
		strUri = strUri.replace("caratzEuro","%26euro;","g");
	}
  }
  return strUri;
}

function buildUriSc(fields){
  var strUri = "";
  fieldsAr = fields.split(";");
  for(var n=0; n<fieldsAr.length; n++){
  	obj = document.getElementById(fieldsAr[n]);
	stri = obj.value;
   	reg = new RegExp("\\+","g");
   	stri = stri.replace(reg,"caratzPiu");
   	reg = new RegExp("€","g");
   	stri = stri.replace(reg,"caratzEuro");
	strUri += "&"+fieldsAr[n]+"="+escape(stri);
	strUri = strUri.replace("caratzPiu","%2B","g");
	strUri = strUri.replace("caratzEuro","%26euro;","g");
  }
  return strUri;
}

function normalizeCampo(obj){
  obj.style.borderColor = "#71706a";
}

function resetBorder(obj) {
	for(var n=0; n<obj.elements.length; n++){
	  if(obj.elements[n].name!=""){
    	obj.elements[n].style.borderColor = "#71706a";
	  }
	}
}

function indirizzoEmailValido(indirizzo) {
  if (window.RegExp) {
    var nonvalido = "(@.*@)|(\\.\\.)|(@\\.)|(\\.@)|(^\\.)";
    var valido = "^.+\\@(\\[?)[a-zA-Z0-9\\-\\.]+\\.([a-zA-Z]{2,4}|[0-9]{1,3})(\\]?)$";
    var regnv = new RegExp(nonvalido);
    var regv = new RegExp(valido);
    if (!regnv.test(indirizzo) && regv.test(indirizzo))
      return true;
    return false;
  }else {
    if(indirizzo.indexOf("@") >= 0)
      return true;
    return false;
  }
}

function controlField(nome,id,id2,tipo){
  switch(tipo){
    case "_":       // controlla se il campo Ã¨ vuoto
    if(document.getElementById(id).value == false){
    	alert(nome+": campo mancante");
    	document.getElementById(id).focus();
    	document.getElementById(id).style.border = "1px solid #FF0000";
    	return false;
    }else{
    	return true;
    }
    break;
    case "__":      // controlla se il campo Ã¨ vuoto con ""
    if(document.getElementById(id).value == ""){
    	alert(nome+": campo mancante");
    	document.getElementById(id).focus();
    	document.getElementById(id).style.border = "1px solid #FF0000";
    	return false;
    }else{
      return true;
    }
    break;
    case "@":       // controlla la validitÃ  del campo mail
    if(!indirizzoEmailValido(document.getElementById(id).value)){
      alert(nome+": campo non valido");
      document.getElementById(id).style.border = "1px solid #FF0000";
      document.getElementById(id).focus();
      return false;
    }else{
      return true;
    }
    break;
    case "=":       // confrontÃ  due campi
    if(document.getElementById(id).value != document.getElementById(id2).value){
      alert("Le Password non Coincidono");
      document.getElementById(id).focus();
      document.getElementById(id).style.border = "1px solid #FF0000";
      document.getElementById(id2).value = "";
      return false;
    }else{
      return true;
    }
    break;
    case "h":       // controlla se il campo Ã¨ vuoto
    if(document.getElementById(id2).value == false){
    	alert(nome+": campo mancante");
    	document.getElementById(id).focus();
    	document.getElementById(id).style.border = "1px solid #FF0000";
    	return false;
    }else{
    	return true;
    }
    break;
    case "c":       // controlla se il campo e' piu' lungo di un tot
    if(document.getElementById(id).value.length > id2){
        alert(nome+": il campo deve contenere un massimo di "+id2+" caratteri");
        document.getElementById(id).focus();
        document.getElementById(id).style.border = "1px solid #FF0000";
        return false;
    }else{
        return true;
    }
    break;
    case "n":       // controlla se il campo e' un numero
    if(isNaN(document.getElementById(id).value)){
        alert(nome+": il campo deve contenere solo numeri");
        document.getElementById(id).focus();
        document.getElementById(id).style.border = "1px solid #FF0000";
        return false;
    }else{
        return true;
    }
    break;
    case "img": // controllo se il file è una img
	    obj = document.getElementById(id);
	    var extensions = new Array();  
	 	extensions[1] = "jpg";  
		extensions[0] = "jpeg";  
		extensions[2] = "gif";  
		/*extensions[3] = "png";  
		extensions[4] = "bmp";*/   
		var image_file = obj.value;
		var image_length = image_file.length;
		var pos = image_file.lastIndexOf('.') + 1;   
		var ext = image_file.substring(pos, image_length);   
		var final_ext = ext.toLowerCase();   
		  
		for (i = 0; i < extensions.length; i++){   
		    if(extensions[i] == final_ext){
				return true;   
		    }   
		}
		alert("Seleziona un'immagine con una delle seguenti estensioni:\n\n gif, jpeg, jpg");
		return false;
    break;
    default:
    alert("tipo non riconosciuto");
    return false;
  }
}

function viewMex(mex){
	dTop = document.body.scrollTop+200;
	document.getElementById('loader').innerHTML = "<img src=\"img/wait.gif\" style=\"vertical-align: -10px\">&nbsp;"+mex;
	document.getElementById('loader').style.top = dTop+"px";
	document.getElementById('loader').style.display = "block";
}

function hideMex(cont,dbg){
	if(dbg){
		document.getElementById('loader').innerHTML = cont;
	}else{
		document.getElementById('loader').style.display = "none";
		document.getElementById('loader').innerHTML = "";
	}	
}

function ctrlKey(e,o){
	if(e.keyCode==13) document.getElementById(o).click();
}

function getPosX(obj) {
	var curleft = 0;
	if (obj.offsetParent) {
		while (obj.offsetParent) {
			curleft += obj.offsetLeft
			obj = obj.offsetParent;
		}
	}
	else if (obj.x)
	curleft += obj.x;
	return curleft;
}

function getPosY(obj) {
	var curtop = 0;
	if (obj.offsetParent) {
		while (obj.offsetParent) {
			curtop += obj.offsetTop
			obj = obj.offsetParent;
		}
	}
	else if (obj.y)
	curtop += obj.y;
	return curtop;
}
/*
function openDiv(w,idOpen,urlAj,corrX,corrY){
	this.win = document.getElementById('win');
	xx = corrX;//getPosX(document.getElementById(idOpen))+corrX;
	yy = corrY+document.body.scrollTop;//getPosY(document.getElementById(idOpen))+corrY+document.body.scrollTop;;
	win.style.width = w+"px";
	//win.style.overflow = "visible";
	viewMex("Caricamento in corso...");
	//ajaxGetRand(urlAj,myHandler);
	myajax.post(urlAj,"");
  	myajax.echoFunction=function(response){
		hideMex(response,0);
    	if(win.style.display !="block"){
    		win.style.top=yy+"px";
    		win.style.left=xx+"px";
    	}
	    win.innerHTML = response;
	    win.style.display="block";
	    Drag.init(document.getElementById("handle"),document.getElementById('win'));
	    //tinyMCE.execCommand("mceAddControl",true,"bio");
	    //tinyMCE.execCommand("mceReplaceContent",false,"bio");
  }
}
*/
function openDivEvent(w,idOpen,urlAj,corrX,corrY,doEvent){
	this.win = document.getElementById('win');
	xx = corrX;//getPosX(document.getElementById(idOpen))+corrX;
	yy = corrY+document.body.scrollTop;//getPosY(document.getElementById(idOpen))+corrY+document.body.scrollTop;;
	win.style.width = w+"px";
	//win.style.overflow = "visible";
	viewMex("Caricamento in corso...");
	//ajaxGetRand(urlAj,myHandler);
	myajax.post(urlAj,"");
  	myajax.echoFunction=function(response){
		hideMex(response,0);
    	if(win.style.display !="block"){
    		win.style.top=yy+"px";
    		win.style.left=xx+"px";
    	}
	    win.innerHTML = response;
	    win.style.display="block";
	    Drag.init(document.getElementById("handle"),document.getElementById('win'));
		doEvent();
  }
}


function openSelect(w,h,idName,idValue,urlAj,corrX,corrY,multi,any){
	this.win = document.getElementById('select');
	selIds = "";
	if(!multi){
		document.onmouseup=function(){
			document.getElementById('select').style.display='none';
			document.onmouseup='';
		}
	}else {
		selIds = document.getElementById(idValue).value;
	}
	
	xx = getPosX(document.getElementById(idName))+corrX;
	yy = getPosY(document.getElementById(idName))+corrY;
	win.style.width = w+"px";
	win.style.height = h+"px";
	win.style.overflow = "auto";
	viewMex("Caricamento in corso...");
	myajax.post(urlAj,'idName='+idName+'&idValue='+escape(idValue)+'&multi='+multi+'&any='+any+'&selIds='+selIds);
	myajax.echoFunction=function(response){
		hideMex(response,0);
	    win.style.top=yy+"px";
	    win.style.left=xx+"px";
	    win.style.textAlign = "left";
	    win.innerHTML = response;
	    win.style.display="block";
	}
}

function openTooltip(punto,w,h,idName,urlAj,corrX,corrY){
	//if (!e) var e = window.event;
	//clickedItem = (e.target) ? e.target : e.srcElement;
	
	this.win = document.getElementById('tooltip');
	document.onmouseup=function(){
		document.getElementById('tooltip').style.display='none';
		document.onmouseup='';
	}
	/*punto.onmouseout=function(){
		
		opacity('tooltip', 100, 0, 500);
		this.onmouseout='';
	}*/
	
	

	xx = getPosX(document.getElementById(idName))+corrX;
	yy = getPosY(document.getElementById(idName))+corrY;
	win.style.width = w+"px";
	win.style.height = h+"px";
	win.style.overflow = "auto";
	viewMex("Caricamento in corso...");
	myajax.post(urlAj,'');
	myajax.echoFunction=function(response){
		hideMex(response,0);
	    win.style.top=yy+"px";
	    win.style.left=xx+"px";
	    win.style.textAlign = "left";
	    win.innerHTML = response;
	    opacity('tooltip', 0, 100, 500);
	}
}

function closeDiv(letWin){
	if(letWin) document.getElementById('win').style.display='none';
	document.getElementById('select').style.display='none';
	document.getElementById('tooltip').style.display='none';
}

function opacity(id, opacStart, opacEnd, millisec) {
    var speed = Math.round(millisec / 100);
    var timer = 0;
    if(opacStart > opacEnd) {
        for(i = opacStart; i >= opacEnd; i--){
            setTimeout("changeOpac(" + i + ",'" + id + "')",(timer * speed));
            timer++;
        }
    } else if(opacStart < opacEnd) {
        for(i = opacStart; i <= opacEnd; i++){
            setTimeout("changeOpac(" + i + ",'" + id + "')",(timer * speed));
            timer++;
        }
    }
}

function changeOpac(opacity, id) {
    var object = document.getElementById(id).style;
    if(opacity==0){
    	object.display='none';
    }else{
    	object.display='block';
    }
    object.opacity = (opacity / 100);
    object.MozOpacity = (opacity / 100);
    object.KhtmlOpacity = (opacity / 100);
    object.filter = "alpha(opacity=" + opacity + ")";
}

function openSelectEvent(w,h,idName,idValue,urlAj,corrX,corrY,multi,any,doEvent){
	
	this.win = document.getElementById('select');
	selIds = "";
	if(!multi){
		document.onmouseup=function(){
			document.getElementById('select').style.display='none';
			document.onmouseup='';
		}
	}else {
		selIds = document.getElementById(idValue).value;
	}
	
	xx = getPosX(document.getElementById(idName))+corrX;
	yy = getPosY(document.getElementById(idName))+corrY;
	win.style.width = w+"px";
	win.style.height = h+"px";
	win.style.overflow = "auto";
	viewMex("Caricamento in corso...");
	myajax.post(urlAj,'idName='+idName+'&idValue='+escape(idValue)+'&multi='+multi+'&any='+any+'&selIds='+selIds);
	myajax.echoFunction=function(response){
		hideMex(response,0);
	    win.style.top=yy+"px";
	    win.style.left=xx+"px";
	    win.style.textAlign = "left";
	    win.innerHTML = response;
	    win.style.display="block";
	    doEvent();
	}
}


function setControl(val, obj){
  var parentObj = obj.parentNode.childNodes;
    for(i=0; i<parentObj.length; i++){
    	if(parentObj[i].nodeName == "A") parentObj[i].style.fontWeight = "normal";
	    if(parentObj[i].nodeName == "INPUT") parentObj[i].value = val;
    }
    obj.style.fontWeight = "bolder";
}

function multiSel(idInput,idHidden,valueInput,valueHidden,obj){
	var i=0;
	valsAr = document.getElementById(idHidden).value;
	valsAr = valsAr.split(";");
	flag = false;
	for(var i=0;i<valsAr.length;i++){
		if(valueHidden == valsAr[i]) flag = true;		
	}
	inPut = document.getElementById(idInput);
	hiPut = document.getElementById(idHidden);
	if(flag){
		// toglie item
		obj.style.fontWeight='normal';
		arText = inPut.value;
		dummy = arText.split(" - ");
		arText = dummy;
		newText = new Array();
		for(var i=0; i<arText.length; i++){
			if(arText[i] != valueInput) newText.push(arText[i]);
		}
		inPut.value = newText.join(" - ");
		// hidden
		arText = hiPut.value;
		dummy = arText.split(";");
		arText = dummy;
		newText = new Array();
		for(var i=0; i<arText.length; i++){
			if(arText[i] != valueHidden) newText.push(arText[i]);
		}
		hiPut.value = newText.join(";");
	}else {
		// aggiunge item
		obj.style.fontWeight='bolder';
		if(inPut.value != "") inPut.value += " - ";
		inPut.value += valueInput;
		// hidden
		if(hiPut.value != "") hiPut.value += ";";
		hiPut.value += valueHidden;
	}
}

function switchOnOff(idInput,idImg){
	idInputOld = document.getElementById(idInput).value;
	idInputNew = idInputOld=='0'?"1":"0";
	document.getElementById(idInput).value = idInputNew;
	img = idInputOld=='0'?"gre.gif":"red.gif";
	document.getElementById(idImg).src = "img/"+img;
}

function addCampi(tmpl,idContainer,nCampi){
	/*if(nCampi>9){
		alert("Troppi Campi");
		return false;
	}*/
	//nCampi++;
	//alert(nCampi);
	tmpl = tmpl.replace(/\$/g, nCampi+"");
	div = document.createElement('DIV');
	div.innerHTML = tmpl;
	
	document.getElementById(idContainer).appendChild(div);

}

function selCal(anno,mese,campo){
	this.win = document.getElementById("select");
	var poststr = "mese="+mese+"&anno="+anno+"&campo="+campo;
	myajax.post("?cmd=selCal",poststr);
	myajax.echoFunction=function(response){
		hideMex("",1);
		xx = getPosX(document.getElementById(campo));
		yy = getPosY(document.getElementById(campo))+21;
		win.style.width = "";
		win.style.height = "";
		win.style.left = xx+"px";
		win.style.top = yy+"px";
		win.innerHTML = response;
		win.style.display = "block";
	}
}
// fine funzioni globali

function controllaLogin(obj){
	resetBorder(obj); 
	flag = true;
	flag = flag && controlField('USER','user','','_');
	flag = flag && controlField('PASSWORD','password','','_');
	if(flag){
		viewMex("Autenticazione in corso...");
		myajax.post("?cmd=validation",buildUri(obj));
		myajax.echoFunction=function(response){
		    hideMex(response,0);
		    if(response=="noo"){
				alert("Account non valido");
		    }else if(response=="oki"){
				location.href="./?cmd=home";
		    }else if(response=="disabled"){
		    	viewMex("La Vs utenza è stata sospesa<br>Pregasi contattare NoCard");
		    }
		}
	}
}

function openCalendar(idName){
	this.win = document.getElementById('ifCal');
	xx = getPosX(document.getElementById(idName));
	yy = getPosY(document.getElementById(idName))+20;
	win.style.width = "200px";
	win.style.height = "200px";
	win.style.top=yy+"px";
  win.style.left=xx+"px";
  calDataRead('include/ajax_calendar.php'+'?lang=it_IT'+'&campo='+idName);
  win.style.display="block";
}

/*
function get() {
	var content = document.getElementById("editor").value;
	var poststr = "content="+escape(content)+"&id=" + encodeURI( document.getElementById("id").value );
	makePOSTRequest('?cmd=saveContent', poststr);
}
*/
function get() {
	var content = document.getElementById("editor").value;
	var poststr = "content="+escape(content)+"&id=" + encodeURI( document.getElementById("id").value );
	viewMex("Salvataggio in corso...");
	//makePOSTRequest('?cmd=saveContent', poststr);
	myajax.post("?cmd=saveContent",poststr);
	myajax.echoFunction=function(response){
		hideMex("",0);
		alert(response);
	}
}

function startUploadFoto() {
	// make something useful before submit (onStart)
	flag = true;
  	flag = flag && controlField('FILE','frmFile','','_');
  	flag = flag && controlField('','frmFile','','img');
	if(flag) viewMex("Upload in corso");
	return flag;
}

function inviaFoto(obj,id){
   	flag = true;
  	flag = flag && controlField('FILE','frmFile'+id,'','_');
  	flag = flag && controlField('','frmFile'+id,'','img');
    if(flag) {
    	viewMex("Upload foto in corso...");
        obj.submit();
    }
}
function getForm(obj){
	while(obj.nodeName!="FORM"){
		obj = obj.parentNode;
		if(obj.nodeName == "BODY"){
			alert("FORM NOT FOUND");
			break;
		}
	}
	return obj;
}

function rePass(obj){
	flag = true;
	flag = flag && controlField("E-MAIL",'blabla','','_');
	flag = flag && controlField("E-MAIL",'blabla','','@');
	if(flag){	
		strUri = buildUri(obj);
		viewMex("Invio password in corso...");
    	myajax.post("?cmd=exRePass", strUri);
	
		myajax.echoFunction=function(aa){
		  	hideMex(aa,0);
		    if(aa=="ok"){
		   		alert("Email inviata al'indirizzo indicato");
		    }else{
		    	alert("Impossibile inviare l'email");
		    }
		}    
  	}
}

//*************************inizio blocco gestione utenti ***************
//**********************************************************************

function controllaAddUtente(obj){
	resetBorder(obj);
	flag = true;
	flag = flag && controlField('nick','nick','','_');
	flag = flag && controlField('password','password','','_');
	flag = flag && controlField('email','email','','_');
	flag = flag && controlField('email','email','','@');
	if(flag){
		viewMex("Inserimento in corso...");
		myajax.post("?cmd=addUser",buildUri(obj));
		myajax.echoFunction=function(response){
			hideMex(response,0);
			if(response=="ko"){
				alert("Errore durante l'inserimento");
			}else{
				eval(response);
				if(resp.old){
					alert("Utente già esistente");
				}else{
					alert("Inserimento effettuato");
					//window.location.reload(false);
					//alert("./?cmd=home&opendiv=detailUser&id="+String(resp.id));
					location.href="./?cmd=home&opendiv=detailUser&iddiv="+resp.id;
				}
			}
		}
	}  
}

function controllaModUser(obj){
	resetBorder(obj);
	flag = true;
	flag = flag && controlField('nick','nickM','','_');
	flag = flag && controlField('password','passwordM','','_');
	flag = flag && controlField('email','emailM','','_');
	flag = flag && controlField('email','emailM','','@');
	if(flag){
		viewMex("Aggiornamento in corso...");
		poststr = buildUri(obj);
		myajax.post("?cmd=modUser",poststr);
		myajax.echoFunction=function(response){
	    	hideMex(response,0);
	    	 eval(response);
	    	if(resp.status=="ko"){
		      alert("Errore durante la modifica, il nick potrebbe essere già in uso");
		    }else if(resp.status=="ok"){
		    	alert("Modifica effettuata");
		    	//window.location.reload(false);
		    	location.href="./?cmd=home&opendiv=detailUser&iddiv="+resp.id;
		    }
		}
	}
}

function modStatoS(obj,hid){
	obj = document.getElementById(obj);
	hid = document.getElementById(hid);
	att = hid.value;
	if(att===""){
		obj.src = "img/gre.gif";
		hid.value = "1";
	}else if(att==="1"){
		obj.src = "img/red.gif";
		hid.value = "0";
	}else{
		obj.src = "img/yellow.gif";
		hid.value = "";
	}
}

function modStatoUtente(flag,obj,id){
	viewMex("Modifica in corso...");
	myajax.post("?cmd=modStatoUtente","id="+id+"&stato="+flag);
	myajax.echoFunction=function(response){
		hideMex(response,0);
		img = flag?"gre.gif":"red.gif";
		obj.firstChild.src = "img/"+img;
		title = flag?"attivo":"inattivo";
		obj.firstChild.title = title;
		obj.onclick = function() {modStatoUtente(!flag,obj,id)};
		if(document.getElementById('win').style.display=="block"){
		 openDivEvent('700','win','?cmd=detailUser&id='+id,100,100,function() {var oTextbox = new AutoSuggestControl(document.getElementById('provinciaM'), document.getElementById('provinciaMId'), new SuggestionProvider('provincie','nome','id'))});
		}
	}
}

function deleteUser(id,obj){
  	if(confirm("Conferma Eliminazione")){
	  viewMex("Eliminazione in corso...");
	  myajax.post("?cmd=deleteUser&id="+id,"");
	}
	myajax.echoFunction=function(aa){
    	hideMex(aa,0);
    	if(aa=="ok"){
	    	alert("Eliminazione effettuata");
	    	obj.parentNode.parentNode.nextSibling.style.display = 'none';
			obj.parentNode.parentNode.style.display = 'none';
	    }else{
	      alert("Errore durante l'eliminazione");
	    }
	}
}

//*************************inizio blocco gestione convenzionati ***************
//**********************************************************************

function controllaAddConvenzionato(obj){
	resetBorder(obj);
	flag = true;
	flag = flag && controlField('nick','nick','','_');
	flag = flag && controlField('password','password','','_');
	flag = flag && controlField('email','email','','_');
	flag = flag && controlField('email','email','','@');
	if(flag){
		viewMex("Inserimento in corso...");
		myajax.post("?cmd=addConvenzionato",buildUri(obj));
		myajax.echoFunction=function(response){
			hideMex(response,0);
			if(response=="ko"){
				alert("Errore durante l'inserimento");
			}else{
				eval(response);
				if(resp.old){
					alert("Convenzionato già esistente");
				}else{
					alert("Inserimento effettuato");
					location.href="./?cmd=convenzionati&opendiv=detailConvenzionato&iddiv="+resp.id;
				}
			}
		}
	}  
}

function controllaModConvenzionato(obj){
	resetBorder(obj);
	flag = true;
	flag = flag && controlField('Nick','nickD','','_');
	flag = flag && controlField('Password','passwordD','','_');
	flag = flag && controlField('Email','emailD','','_');
	flag = flag && controlField('Email','emailD','','@');
	if(flag){
		document.getElementById('editor').value = myEditor.nicInstances[0].getContent();
		viewMex("Modifica in corso...");
		myajax.post("?cmd=modConvenzionato",buildUri(obj));
		myajax.echoFunction=function(response){
		    hideMex(response,0);
	    	 if(response=="nick"){
		   		alert("User esistente, cortesemente, inserite un nome differente");
		   		document.getElementById('nickD').focus();
    			document.getElementById('nickD').style.border = "1px solid #FF0000";
		    }else if(response=="email"){
		     	alert("Email già usata da un'altra utenza");
		     	document.getElementById('emailD').focus();
    			document.getElementById('emailD').style.border = "1px solid #FF0000";
		    }else{
		    	eval(response);
			    if(resp.status=="email"){
			      alert("Il tuo profilo ha cambiato email.\nTi è stata inviata un email con il link per la conferma.");
			    }else if(resp.status=="ok"){
			      alert("Modifica effettuata");
			    }
			    window.location.reload(false);
		    }
		}
	}  
}

function modDescrizioneConv(obj){
	viewMex("Modifica in corso...");
	myajax.post("?cmd=modDescrConv",buildUri(obj));
	myajax.echoFunction=function(response){
		hideMex(response,0);
		if(response=="ko"){
	     	alert("Errore durante la modifica");
	    }else if(response=="ok"){
	    	alert("Modifica effettuata");
	    }	
	}  
}

function deleteLogoConv(obj){
	viewMex("Eliminazione in corso...");
	myajax.post("?cmd=delLogoConv",buildUri(obj));
	myajax.echoFunction=function(response){
		hideMex(response,0);
		if(response=="0"){
	     	alert("Errore durante l'eliminazione");
	    }else{
	    	alert("Eliminazione effettuata");
	    	window.location.reload(false);
	    }	
	}  
}

function callbackPhotoConvenzionati(aa){
	hideMex(aa,0);
	window.location.reload(false);
}

function modStatoConvenzionato(flag,obj,id){
	viewMex("Modifica in corso...");
	myajax.post("?cmd=modStatoConvenzionato","id="+id+"&stato="+flag);
	myajax.echoFunction=function(response){
		hideMex(response,0);
		img = flag?"gre.gif":"red.gif";
		obj.firstChild.src = "img/"+img;
		title = flag?"attivo":"inattivo";
		obj.firstChild.title = title;
		obj.onclick = function() {modStatoConvenzionato(!flag,obj,id)};
		if(document.getElementById('win').style.display=="block"){
		 openDivEvent('700','win','?cmd=detailConvenzionato&id='+id,100,100,function() {var oComuni = new AutoSuggestControl(document.getElementById('comuneD'),document.getElementById('comuneDId'),new SuggestionProvider('comuni','nome','id'));myEditor = new nicEditor({buttonList: ['bold','italic','underline','left','center','right','ol','ul','subscript','superscript','indent','outdent','link','unlink','bgcolor','forecolor','xhtml']}).panelInstance('editor');});
		}
	}
}

function deleteConvenzionato(id,obj){
  	if(confirm("Conferma Eliminazione")){
	  viewMex("Eliminazione in corso...");
	  myajax.post("?cmd=deleteConvenzionato&id="+id,"");
	}
	myajax.echoFunction=function(aa){
    	hideMex(aa,0);
    	if(aa=="ok"){
	    	alert("Eliminazione effettuata");
	    	obj.parentNode.parentNode.nextSibling.style.display = 'none';
			obj.parentNode.parentNode.style.display = 'none';
	    }else{
	      alert("Errore durante l'eliminazione");
	    }
	}
}
//******************************************fine blocco conv ******************************
//****************************************** Ticket ******************************
function controllaAddTicket(obj){
	resetBorder(obj);
	flag = true;
	flag = flag && controlField('numero','numero','','_');
	if(flag){
		viewMex("Modifica in corso...");
		myajax.post("?cmd=addTicket",buildUri(obj));
		myajax.echoFunction=function(response){
			hideMex(response,0);
			if(response=="ko"){
				alert("Errore durante la modifica");
			}else{
				alert("Modifica effettuata");
				window.location.reload(false);
			}
		}
	}  
}

function modStatoTicket(flag,obj,id){
	viewMex("Modifica in corso...");
	xint = flag?"1":"0";
	myajax.post("?cmd=modStatoTicket","id="+id+"&stato="+xint);
	myajax.echoFunction=function(response){
		hideMex(response,0);
		img = flag?"gre.gif":"red.gif";
		obj.firstChild.src = "img/"+img;
		title = flag?"usato":"emesso";
		obj.firstChild.title = title;
		obj.onclick = function() {modStatoTicket(!flag,obj,id)};
		//alert("Modifica effettuata");
		window.location.reload(false);
	}
}

function archiviaTicket(id,obj){
	if(confirm("Conferma Eliminazione")){
	  viewMex("Eliminazione in corso...");
	  myajax.post("?cmd=archiviaTicket","id="+id);
	}
	myajax.echoFunction=function(response){
		hideMex(response,0);
    	if(response=="ok"){
	    	alert("Eliminazione effettuata");
	    	obj.parentNode.parentNode.nextSibling.style.display = 'none';
			obj.parentNode.parentNode.style.display = 'none';
	    }else{
	      alert("Errore durante l'eliminazione");
	    }
	}
}

function ticketPdf(obj){
	frm = getForm(obj);
	lastAction = frm.action;
	uri = buildUri(frm);
	addr = lastAction.split("?");
	frm.action = addr[0]+"?cmd=ticketPdf"+uri;
	frm.target = "_blank";
	frm.submit();
	frm.action = lastAction;
	frm.target = "_self";
}
//****************************************** Fine Ticket ******************************
//*************************inizio blocco gestione promozioni ******************************
//*****************************************************************************************
function controllaAddPromozione(obj){
	resetBorder(obj);
	flag = true;
	flag = flag && controlField('titolo','titoloA','','_');
	if(flag){
		viewMex("Inserimento in corso...");
		myajax.post("?cmd=addPromozione",buildUri(obj));
		myajax.echoFunction=function(response){
			hideMex(response,0);
			if(response=="ko"){
				alert("Errore durante l'inserimento");
			}else{
				eval(response);
				alert("Inserimento effettuato");
				location.href="./?cmd=promozioni&opendiv=detailPromozione&iddiv="+resp.id;
			}
		}
	}  
}

function controllaModPromozione(obj){
	resetBorder(obj);
	flag = true;
	flag = flag && controlField('titolo','titoloD','','_');
	if(flag){
		document.getElementById('editor').value = myEditor.nicInstances[0].getContent();
		viewMex("Modifica in corso...");
		myajax.post("?cmd=modPromozione",buildUri(obj));
		myajax.echoFunction=function(response){
			hideMex(response,0);
			 eval(response);
	    	if(resp.status=="ok"){
	    	  	alert("Modifica effettuata");
		    	location.href="./?cmd=promozioni&opendiv=detailPromozione&iddiv="+resp.id;
	    	}else {
		        	alert("Errore durante la modifica");
		    }
		}
	}  
}

function modStatoPromozione(flag,obj,id){
	viewMex("Modifica in corso...");
	myajax.post("?cmd=modStatoPromozione","id="+id+"&stato="+flag);
	myajax.echoFunction=function(response){
		hideMex(response,0);
		img = flag?"gre.gif":"red.gif";
		obj.firstChild.src = "img/"+img;
		title = flag?"attivo":"inattivo";
		obj.firstChild.title = title;
		obj.onclick = function() {modStatoPromozione(!flag,obj,id)};
		if(document.getElementById('win').style.display=="block"){
			openDivEvent('700','win','?cmd=detailPromozione&id='+id,100,100,function() {myEditor = new nicEditor({buttonList: ['bold','italic','underline','left','center','right','ol','ul','subscript','superscript','indent','outdent','link','unlink','bgcolor','forecolor','xhtml']}).panelInstance('editor');});
		}
	}
}

function deletePromozione(id,obj){
  	if(confirm("Conferma Eliminazione")){
	  viewMex("Eliminazione in corso...");
	  myajax.post("?cmd=delPromozione&id="+id,"");
	}
	myajax.echoFunction=function(aa){
    	hideMex(aa,0);
    	if(aa=="ok"){
	    	alert("Eliminazione effettuata");
	    	obj.parentNode.parentNode.nextSibling.style.display = 'none';
			obj.parentNode.parentNode.style.display = 'none';
	    }else{
	      alert("Errore durante l'eliminazione");
	    }
	}
}

function callbackPhotoPromozione(aa){
	hideMex(aa,0);
	openDivEvent('700','win','?cmd=fotoPromozione&id='+aa,100,100,function(){});
}


function deleteFotoPromo(obj){
	viewMex("Eliminazione in corso...");
	myajax.post("?cmd=delFotoPromo",buildUri(obj));
	myajax.echoFunction=function(response){
		hideMex(response,0);
		if(response=="0"){
	     	alert("Errore durante l'eliminazione");
	    }else{
	    	alert("Eliminazione effettuata");
	    	openDivEvent('700','win','?cmd=fotoPromozione&id='+response,100,100,function(){});
	    }	
	}  
}

function modDescrizioneFotoPromo(obj){
	viewMex("Modifica in corso...");
	myajax.post("?cmd=modDescrFotoPromo",buildUri(obj));
	myajax.echoFunction=function(response){
		hideMex(response,0);
		if(response=="ko"){
	     	alert("Errore durante la modifica");
	    }else if(response=="ok"){
	    	alert("Modifica effettuata");
	    }	
	}  
}

function inviaFotoPromozione(obj,id){
   	flag = true;
  	flag = flag && controlField('FILE','frmFile'+id,'','_');
  	flag = flag && controlField('','frmFile'+id,'','img');
    if(flag) {
    	viewMex("Upload foto in corso...");
    	lastAction = obj.action;
		uri = buildUriSc("descr");
		obj.action = lastAction+uri;
    	obj.submit();
    }
}
//*************************inizio blocco gestione Termini ***************
//*****************************************************************************
function controllaAddTermine(obj){
	resetBorder(obj);
	flag = true;
	flag = flag && controlField('termine','termineA','','_');
	if(flag){
		viewMex("Inserimento in corso...");
		myajax.post("?cmd=addTermine",buildUri(obj));
		myajax.echoFunction=function(response){
			hideMex(response,0);
			if(response=="ko"){
				alert("Errore durante l'inserimento");
			}else{
				eval(response);
				if(resp.old){
					alert("Termine già esistente");
				}else{
					alert("Inserimento effettuato");
					window.location.reload(false);
					location.href="./?cmd=termini";
				}
			}
		}
	}  
}

function modChiave(obj,id){
	resetBorder(obj);
	flag = true;
	flag = flag && controlField('termine',id,'','_');
	viewMex("Modifica in corso...");
	strUri = buildUri(obj);
	myajax.post("?cmd=modTermine",buildUri(obj));
	myajax.echoFunction=function(response){
		hideMex(response,0);
		if(response=="ko"){
			alert("Errore durante la modifica");
		}else{
			eval(response);
			if(resp.old){
				alert("Termine già esistente");
			}else{
				alert("Modifica effettuata");
				window.location.reload(false);
				location.href="./?cmd=termini";
			}
		}
	}
}


function deleteChiave(id,obj){
	if(confirm("Conferma eliminazione")){
		viewMex("Eliminazione in corso...");
		myajax.post("?cmd=delTermine","&id="+id);
		myajax.echoFunction=function(response){
			hideMex(response,0);
			if(response=="error"){
				alert("Errore durante l'eliminazione");
			}else if(response=="ok"){
				alert("Eliminazione effettuata");
				oObj=getForm(obj);
				oObj.parentNode.style.display = 'none';
			
			}
		}
	}
}

/*google map*/
var COLORS = [["orange", "#ff8800"]];
var options = {};
var lineCounter_ = 0;
var shapeCounter_ = 0;
var markerCounter_ = 0;
var colorIndex_ = 0;
var featureTable_;
var map;
var cellX = 0;
var cellY = 0;
var marker = null;

function getColor(named) {
  return COLORS[(colorIndex_++) % COLORS.length][named ? 0 : 1];
}

function getIcon(color) {
  var icon = new GIcon();
  icon.image = "http://google.com/mapfiles/ms/micons/" + color + ".png";
  icon.iconSize = new GSize(32, 32);
  icon.iconAnchor = new GPoint(15, 32);
  return icon;
}

function initMap(x,y) {
	cellX = document.getElementById(x);
	cellY = document.getElementById(y);
	zoom = 14;
	if(cellX.value == "") cellX.value = "38.9423209";
	if(cellY.value == "") {
		cellY.value = "13.0627441";
		zoom=6;
	}; 
  if (GBrowserIsCompatible()) {
  	var opts = {resultList : G_GOOGLEBAR_RESULT_LIST_SUPPRESS, showOnLoad: true, onGenerateMarkerHtmlCallback:doGenerateMarkerHtmlCallback};
    map = new GMap2(document.getElementById("map"), {googleBarOptions: opts});
    map.setCenter(new GLatLng(Number(cellX.value),Number(cellY.value)), zoom);
    map.enableGoogleBar();
    map.addControl(new GSmallMapControl());
    map.addControl(new GMapTypeControl());
    map.clearOverlays();
    placeMarker();
  }
}

function doGenerateMarkerHtmlCallback(mark,html,result) {
		mark.hide();
        html.innerHTML+="<b>Coordinate Trovate: "+result.lat+","+result.lng+"<\/b><br>";
        //html.innerHTML+="<b>Marker Location: "+marker.getLatLng().toUrlValue()+"<\/b>";
        marker.setLatLng(mark.getLatLng());
        var latlng = mark.getPoint();
	  cellY.value = String(Math.round(latlng.x * 1000000) / 1000000);
	  cellX.value = String(Math.round(latlng.y * 1000000) / 1000000);
        return html;
}



function placeMarker() {
	if(cellX.value=="" && cellY.value==""){
	  	var listener = GEvent.addListener(map, "click", function(overlay, latlng) {
	    	if (latlng) {
		      GEvent.removeListener(listener);
		      var color = getColor(true);
		      marker = new GMarker(latlng, {icon: getIcon(color), draggable: true});
		      map.addOverlay(marker);
		      updateMarker(marker);
		      GEvent.addListener(marker, "dragend", function() {
		        updateMarker(marker);
		      });
		      GEvent.addListener(marker, "click", function() {
		        updateMarker(marker, true);
		      });
	    	}
  		});
  	}else{
  	  var color = getColor(true);
      var latlng = new GLatLng(cellX.value, cellY.value);
      marker = new GMarker(latlng, {icon: getIcon(color), draggable: true});
      map.addOverlay(marker);
      GEvent.addListener(marker, "dragend", function() {
        updateMarker(marker);
      });
      GEvent.addListener(marker, "click", function() {
        updateMarker(marker, true);
      });
    }
}

function updateMarker(marker, opt_changeColor) {
  if (opt_changeColor) {
    var color = getColor(true);
    marker.setImage(getIcon(color).image);
  }
  var latlng = marker.getPoint();
  cellY.value = String(Math.round(latlng.x * 1000000) / 1000000);
  cellX.value = String(Math.round(latlng.y * 1000000) / 1000000);
}

