
// JavaScript Document

function controlla_campi_obbligatori(form){
	var n;
	var m = '';
	var campi = form.getElementsByTagName('input');
	var sel = form.getElementsByTagName('select');
	var rad = form.getElementsByTagName('radio');
	var txt = form.getElementsByTagName('textarea');
	s = form.obbligatori.value;
	for(var i=0; i<campi.length;i++){
		campi[i].style.borderColor='';
		if(s.search(campi[i].name)>=0 && (campi[i].value == '' || campi[i].value == '0')){
			campi[i].style.borderColor='#FF0000';
			m = 'Attenzione: completa i campi evidenziati in rosso';
		}
	}
	for(var i=0; i<rad.length;i++){
		rad[i].style.borderColor='';
		if(s.search(rad[i].name)>=0 && (rad[i].value == '' || rad[i].value == '0')){
			campi[i].style.borderColor='#FF0000';
			m = 'Attenzione: completa i campi evidenziati in rosso';
		}
	}
	/*if(sel.length>0){
		for(var i=0; i<sel.length;i++){
			if(sel[i].name == 'giudizio' && (sel[i].value == '2' || sel[i].value == '5'))
				s = s+'-list2_prescrizioni';
			if(s.search('rischio')>=0)
				s = s+'-list2_rischi';
			sel[i].style.borderColor='';
			if(s.search(sel[i].name)>=0 && ((sel[i].value == '' || sel[i].value == '0') || sel[i].options.length == 0)){
				if(sel[i].name.search('list2') < 0 && sel[i].name != 'idcomune_residenza' && sel[i].name != 'idcomune_nascita' && (sel[i].value == '' || sel[i].value == '0')){	
					sel[i].style.borderColor='#FF0000';
					m = 'Attenzione: completa i campi evidenziati in rosso';
					}
				else if (sel[i].name.search('list2') >= 0 && sel[i].options.length == 0){
					sel[i].style.borderColor='#FF0000';
					m = 'Attenzione: completa i campi evidenziati in rosso';
				}
			}
		}
	}*/
	for(var i=0; i<txt.length;i++){
		txt[i].style.borderColor='';
		if(s.search(txt[i].name)>=0 && (txt[i].value == '' || txt[i].value == '0')){
			txt[i].style.borderColor='#FF0000';
			m = 'Attenzione: completa i campi evidenziati in rosso';
		}
	}
	if (m.length > 0){
		if(typeof(form.msgerrore) != 'undefined')
			alert(form.msgerrore.value);
		else alert(m);
	}
	else form.submit();
}


var testo, finestra;
function stampa()
{
    if (document.all)
    {
        testo = document.body.innerText;
        finestra = window.open("about:blank");
        finestra.document.body.innerText = testo;
        finestra.print();
    }
    else
    {
        if (window.confirm("Funzione compatibile solo con MS Internet Explorer.\n\nVuoi comunque stampare la pagina?"))
        {
            window.print();
        }
    }
}


function controlla_file(elem){
	if(elem.value != ''){
		var ext = elem.value.split('.')[elem.value.split('.').length - 1].toLowerCase();
		if (ext != 'jpg' && ext != 'png' && ext !='jpeg' && ext !='jpe'){
			alert("Atenzione! puoi caricare esclusivamente\n file con estensione .jpg (.jpeg, .jpe) o .png");
			elem.value = "";
			}
	}
	return true;
	}

function controlla_campi_form_richiesta(id){
	var msg="";
	var form = document.getElementById(id);
	if (form.nome.value.length==0)
		var msg=msg+"Inserire il nome\n";

	if (form.cognome.value.length==0)
		var msg=msg+"Inserire il cognome\n";

	if (form.nomeazienda.value.length==0)
		var msg=msg+"Inserire il nome dell'azienda\n";

	if (form.ragionesociale.value.length==0)
		var msg=msg+"Inserire la ragione sociale\n";
		
	if (form.email.value.length==0)
		var msg=msg+"Inserire l'indirizzo email\n";
	/*else {
		var espressione = /^[a-z0-9]/;
		var stringa = form.email.value;
		if (!espressione.test(stringa))
		{
			var msg=msg+"L'indirizzo email non è valido\n";
		}
*/
		
	if (form.nomeutente.value.length==0)
		var msg=msg+"Inserire un nomeutente\n";
	var psw = form.password.value;
	var pswc = form.passwordconfirm.value;
	
	if(psw.length !=0 && pswc.length!=0){	
		if(psw != pswc)
			var msg=msg+"I testi nel campo password e nel campo Conferma password non coincidono\n";
	}
	else {
		if (psw.length==0)
			var msg=msg+"Inserire una password\n";
		if (pswc.length==0)
			var msg=msg+"Riempire il campo Conferma passsword\n";
	}
	if (msg.length > 0)
		alert(msg);
	else
	doAjaxPost('', id, 'processa.cfm?azione=demo', 'demoaccount');
}

function doAjaxPost(attributo, valore, url, display){ 
	var message='';
	if(attributo !='' && valore !='') {
		var message=attributo+"="+valore;
	}
if(attributo == "" && valore != "") {
	var form = document.getElementById(valore);
	var campi = form.elements;
	var y = 0;
	for(var i=0; i<campi.length;i++){
		if(y>0) message = message +'&';
		message = message + campi[i].name +'='+ campi[i].value; 
		y++;
	}	
}
var request=null;
if(window.XMLHttpRequest){
   request=new XMLHttpRequest();
}
else if(window.ActiveXObject){
   request = new ActiveXObject("Microsoft.XMLHTTP");
}   
if(request) {
   request.open("POST", url, true);
   request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
   request.setRequestHeader('Content-length', message.length);
   request.setRequestHeader('Connection', 'close');
	   
   if(message!=''){
  	request.send(message);
   }
   else request.send(null);
   
   if(display != ''){
   	request.onreadystatechange = function() { 
  			 if(request.readyState==4) {document.getElementById(display).innerHTML = request.responseText;}											}
   }
}
else
   return;
}

function riporta_selezione(elem, sel, cosa) {
	var appendi = true;
	if(document.getElementById && document.createElement){
		if(elem.checked){
		   var div = document.getElementById('selezioni_'+cosa);
		   var figli = div.childNodes;
		   for(var i=0; i<figli.length; i++){
			   if(figli[i].id == 'e'+elem.value){
				   appendi = false;
				   }
		   }
		   if(appendi){
			   var div_figlio = document.createElement('div');
			   div_figlio.id='e'+elem.value;
			   /*div_figlio.setAttribute('style', 'margin-left:15px');*/
			   div_figlio.style.margin='5px 0 5px 15px';
			   var etichetta = document.createTextNode(sel);
			   div_figlio.appendChild(document.createTextNode(sel));
			   var img = document.createElement('img');
			   img.src='ico/close.png';
			   img.onclick = function(){elimina_selezione(this, elem.value, cosa); };
			   var spazio = document.createElement('img');
			   spazio.src='images/img_space_grande.png';
			   div_figlio.appendChild(spazio);
			   div_figlio.appendChild(img);
			   div.appendChild(div_figlio);
			   }
		}
		else {	
			   var div = document.getElementById('selezioni_'+cosa);
			   var div_etichetta = document.getElementById('e'+elem.value);
			   div.removeChild(div_etichetta);
			}
	}
}

function elimina_selezione(elem, idelem, cosa) {
	if(document.getElementById && document.createElement){
		document.getElementById('selezioni_'+cosa).removeChild(elem.parentNode);
		var check = document.getElementById(cosa+"_"+idelem);
		check.checked=false;
		popola_select_da_check();
	}
}

//visualizza in un div grande l'immagine da cui è partito l'evento 
function cambiaImmagine(imm) {
	if(document.getElementById && document.createElement){
		var div = document.getElementById("mainfoto");
		var img = div.getElementsByTagName("img").item(0);
		img.src=imm.src;
	}
}

//modifca il valore dell'attributo href in modo da settare una variabile url
function modifica_url(elem){
	var nuovo_url = "";
	var array_vecchio_url = elem.href.split("/");
	var vecchio_url = array_vecchio_url[array_vecchio_url.length-1];
	//estraggo le coppie valore-variabile
	var coppia_var_val = vecchio_url.split("&");
	for (var i=0; i<coppia_var_val.length; i++){
		//metto in un array il nome e il valore di ogni variabile
		var array_var_val = coppia_var_val[i].split("=");
		if(array_var_val[0] == "ordine"){
			if(array_var_val[1] == 'asc')
				array_var_val[1] = 'desc';
			else array_var_val[1] = 'asc';
			nuovo_url = nuovo_url + "&" + array_var_val[0] + "=" + array_var_val[1];
		}
		else { 
			if (i != 0)
				nuovo_url = nuovo_url + "&" + coppia_var_val[i];
			else nuovo_url = coppia_var_val[i];
		}
	}
	elem.setAttribute('href', nuovo_url);
}

//modifica dinamicamente l'attributo onclick dell'elemento che la richiama
//per poter rendere visibili o invisibile un div
function gestisci_div(aprire, idDiv, elem){
	//aprire è un booleano
	if(aprire){
		document.getElementById(idDiv).style.display="block";
		elem.onclick = function(){gestisci_div(false, idDiv, this) };
		var percorso_immagine = elem.src;
		//percorso immagine è del tipo: nomecartella/idDiv_azione.ext
		var percorso = percorso_immagine.split("_");
		var estensione = percorso_immagine.split(".");
		var nuovo_percorso = percorso[0]+"_chiude."+estensione[estensione.length - 1]
		elem.setAttribute("src", nuovo_percorso);
		//elem.replaceChild(newTesto, elem.firstChild);
		if (idDiv == 'marca') {
			var selezioni = document.getElementById('selezioni');
			selezioni.style.display="block";
			}
		if (idDiv == 'allestimento'){
			var selezioni_allestimenti = document.getElementById('selezioni_allestimenti');
			selezioni_allestimenti.style.display="block";
			}
	}
	else{//aprire == false, il div si deve chiudere 
		document.getElementById(idDiv).style.display="none";
		//var newTesto = document.createTextNode("Cerca per "+idDiv);
		elem.onclick = function() {gestisci_div(true, idDiv, this) };
		//elem.replaceChild(newTesto, elem.firstChild);	
		var percorso_immagine = elem.src;
		var percorso = percorso_immagine.split("_");
		var estensione = percorso_immagine.split(".");
		var nuovo_percorso = percorso[0]+"_apre."+estensione[estensione.length - 1]
		elem.setAttribute("src", nuovo_percorso);
		if (idDiv == 'marca'){
			var selezioni = document.getElementById('selezioni');
			selezioni.style.display="none";
			}
		if (idDiv == 'allestimento'){
			var selezioni_allestimenti = document.getElementById('selezioni_allestimenti');
			selezioni_allestimenti.style.display="none";
			}
	}
	return false;
}

/*//nasconde i div corrispondenti e ripristina il colore originale a tutti i link
function nascondi_div(elem, idDiv){
		var gruppolink = elem.parentNode.getElementsByTagName('a');
		for(var i=0; i<gruppolink.length; i++){
			gruppolink[i].style.color='#004f4d';
		}
		for(var i=65; i<90; i++){
			var div = document.getElementById(idDiv+i);	
			div.style.display='none';
		}
}*/

function applica_deselezione(elem){
		var gruppolink = elem.parentNode.getElementsByTagName('a');
		for(var i=0; i<gruppolink.length; i++){
			gruppolink[i].style.color='#004f4d';
		}
}


function reset_select(id){ 
	var subselect = document.forms['form1'].formmodello;
		for (var i = subselect.length - 1; i >= 0; i--)
			subselect.remove(i);
	}


function popola_select_da_radio(url){
	var seleziona = document.forms['form1'].formmarca;  //Recupero la SELECT		
	// Recupero la categoria selezionata
	var cat = 0;
	if(seleziona.length){
		for(var i=0; i<seleziona.length; i++){
			if(seleziona[i].checked){
			   cat = seleziona[i].value;
			   break;
			}
		}
	}
	else cat = seleziona.value;
	doAjaxPost('id', cat, url, 'box_modello');
}

function popola_select_da_check(url){
	var seleziona = document.forms['form1'].formmarca; //Recupero la marca
	var subselect = document.forms['form1'].formmodello; //Recupero la seconda SELECT
   
   // Recupero la marca selezionata	
	var cat = 0;
	var mat = new Array();
	var y = 0;
		for(var i=0; i<seleziona.length; i++){
			if(seleziona[i].checked){		   
			   mat[y] = seleziona[i].value;
			   y++;
			}
		}
	//Controllo che sia stata selezionata una sola marca
	if(mat.length == 1){
		cat = mat[0];
		//definisco l'elemento che rappresenta il link "seleziona il modello"
		var linkesterno = document.getElementById("esternoModello");
		//Azzero il contenuto della seconda select
		for (var i = subselect.length - 1; i > 0; i--)
			subselect.remove(i);
	    doAjaxPost('id', cat, url, 'box_modello');		
		var boxmodello = document.getElementById("box_modello");
		boxmodello.style.display='block';
		linkesterno.style.display='block';				
	}
	else { 
		//nascondo il div di scelta del modello	
		var linkesterno = document.getElementById("esternoModello");
		linkesterno.style.display='none';
		var boxmodello = document.getElementById("box_modello");
		boxmodello.style.display='none';
	}
}

//forza l'input da tastiera ai soli caratteri numerici
function controllo_campo_num(elem, id)
{
 var lunghezza = elem.value.length;
 var codascii=elem.value.charCodeAt(lunghezza -1);
 if ( codascii==46 || ( codascii>=48 && codascii<=57))
 {
  return true;
 }
 else
 {
  document.getElementById(id).value=elem.value.substr(0,lunghezza -1);
 }
}

function switchTab(tab){
	var tabsContainer=tab.parentNode;
	var tabPanels=tabsContainer.parentNode.getElementsByTagName('DIV')[1].childNodes; // all tabpanels child
	var tabs=tabsContainer.getElementsByTagName('A'); // all tabs
	var tabPos; // clicked tab position
	var tempArr=new Array(1);
	var j=0;
	for (var i=0;i<tabs.length;i++) 
		if (tabs[i]==tab) {
			tabPos=i;
			tab.className='selected';
			tab_attivo=i;
		}
		else tabs[i].className='';	
	for (var i=0;i<tabPanels.length;i++) // retrieve only divs from the tabpanels
		if (tabPanels[i].nodeName=='DIV') {
			tempArr[j]=tabPanels[i];
			j=j+1;
		}

	for (var i=0;i<tempArr.length;i++)	
		i==tabPos?tempArr[i].style.display='block':tempArr[i].style.display='none';
}

