// JavaScript Document

function getElementsByClassName(className, tag, elm){
	var testClass = new RegExp("(^|\\\\s)" + className + "(\\\\s|$)");
	var tag = tag || "*";
	var elm = elm || document;
	var elements = (tag == "*" && elm.all)? elm.all : elm.getElementsByTagName(tag);
	var returnElements = [];
	var current;
	var length = elements.length;
	for(var i=0; i<length; i++){
		current = elements[i];
		if(testClass.test(current.className)){
			returnElements.push(current);
		}
	}
	return returnElements;
}

function Left(str, n) {
	if (n <= 0)
		return "";
	else if (n > String(str).length)
		return str;
	else
		return String(str).substring(0,n);
}

function Right(str, n) {
	if (n <= 0)
		return "";
	else if (n > String(str).length)
		return str;
	else
		return String(str).substring((String(str).length-n),String(str).length);
}



function showHide(target,view){
	if($(target).prev("canvas").val()==""){
		target2="canvas";
	}else{
		target2="div";
	}
	if(view==1){
		$(target).show();
		$(target).prev(target2).show();
	}else{
		$(target).hide();
		$(target).prev(target2).hide();
	}
}


//alert(myLang);

////////////////////////////////////////////////////////////////////////////////////////////////////////////////
///	GESTORE DI CHIAMATE ASINCRONE (GCA)
/// sviluppato da Marco Campanelli
///
///	ISTRUZIONI
///	GCA utilizza la libreria jQuery nella versione jquery-1.3.2.min.js. E' necessario dunque includere tale 
///	libreria prima di utilizzare GCA.
///
///	ARGOMENTI
///
/// myUrl:		č la pagina da caricare dinamicamente eventualmente compresa di percorso e variabili in GET

///	myMethod:	č il metodo di trasporto dati. Accetta GET o POST

/// idForm:		č l'id del form da inviare (lasciare vuoto nel caso di invii in GET)

/// obb:		č la sequenza di campi obbligatori nel formato 0,1,2... (lasciare vuoto nel caso non ci siano 
///				campi obbligatori o in caso di invii in GET)

///	myTarget:	č il DIV dove verrā caricato il file.

///	clear:		valore boleano. True o 1 elimina il contenuto del DIV target prima di caricare 
///				la pagina al suo interno. False o 0 aggiunge al contenuto preesistente la pagina caricata.
///
///	ESEMPI
///	Richiesta pagina GET
///	<a href="javascript:loadObj('pagina.asp?miaVariabile1=mioValore1&miaVariabile2=mioValore2','GET','','','divBersaglio','1');" title="il mio link">il mio link</a>
///	L'esempio carica la pagina "pagina.asp" dentro il div che ha id="divBersaglio" inviando le 2 coppie "variabile" "valore"
///
///	Richiesta pagina POST
///	<a href="javascript:loadObj('pagina.asp?miaVariabile1=mioValore1','POST','clienti','0,1','divBersaglio','1');" title="il mio link">il mio link</a>
///	L'esempio carica in POST la pagina "pagina.asp" dentro il div che ha id="divBersaglio" inviando in GET variabile1=valore1 e 
///	in POST tutti i dati del form che ha come id="clienti". Il valore "0,1" di obb specifica che nel caso il primo o il secondo elemento
///	della form assuma valore='' la richiesta non verrā completata.
///
////////////////////////////////////////////////////////////////////////////////////////////////////////////////
///
///
///


function attivaErrori(stato){
	if(stato==0){
		showHide('#errorMessage',0);
		$('#errorTitle').empty();
		$('#errorTxt').empty();
	}else{
		showHide('#errorMessage',1);
	}
}

function loadObj(myUrl,myMethod,idForm,obb,myTarget,clear){
    
	//////////////////////////////////////
	///// OGGETTO LOADING
	//////////////////////////////////////

	forceRandom = Math.random()*99999999;
	forceRandom = Math.round(forceRandom);
	
	nSize=18;
	sUnit="px";
	
	myLoadObj=	"<script src='js/loading/loading.js'></script>"+
				"<div style='position: relative; float: left; width: 100%; padding: 25px;'>"+
					"<div id='imgLoad' style='position: relative; float: left; width: "+nSize+sUnit+"; padding-right: 8px;'>"+
						"<div id='imgLoad1' style='position: relative; width: "+nSize+sUnit+"; display: block;'>"+
							"<img src='js/loading/img/1.png' width='"+nSize+"' height='"+nSize+"' />"+
						"</div>"+
						"<div id='imgLoad2' style='position: relative; width: "+nSize+sUnit+"; display: none;'>"+
							"<img src='js/loading/img/2.png' width='"+nSize+"' height='"+nSize+"' />"+
						"</div>"+
						"<div id='imgLoad3' style='position: relative; width: "+nSize+sUnit+"; display: none;'>"+
							"<img src='js/loading/img/3.png' width='"+nSize+"' height='"+nSize+"' />"+
						"</div>"+
						"<div id='imgLoad4' style='position: relative; width: "+nSize+sUnit+"; display: none;'>"+
							"<img src='js/loading/img/4.png' width='"+nSize+"' height='"+nSize+"' />"+
						"</div>"+
						"<div id='imgLoad5' style='position: relative; width: "+nSize+sUnit+"; display: none;'>"+
							"<img src='js/loading/img/5.png' width='"+nSize+"' height='"+nSize+"' />"+
						"</div>"+
						"<div id='imgLoad6' style='position: relative; width: "+nSize+sUnit+"; display: none;'>"+
							"<img src='js/loading/img/6.png' width='"+nSize+"' height='"+nSize+"' />"+
						"</div>"+
						"<div id='imgLoad7' style='position: relative; width: "+nSize+sUnit+"; display: none;'>"+
							"<img src='js/loading/img/7.png' width='"+nSize+"' height='"+nSize+"' />"+
						"</div>"+
						"<div id='imgLoad8' style='position: relative; width: "+nSize+sUnit+"; display: none;'>"+
							"<img src='js/loading/img/8.png' width='"+nSize+"' height='"+nSize+"' />"+
						"</div>"+
					"</div>"+
					"<div style='position:relative; float:left; width: 50px; padding-top: 2px; color: black;'>loading...</div>"+
				"</div>";
	//////////////////////////////////////
	
	
	//////////////////////////////////////
	///// FUNZIONI AJAX
	//////////////////////////////////////
	function beforeFunction(){
		$("#"+myTarget).empty();
		if(clear==true){$("#"+myTarget).empty();}
		$("#"+myTarget).append(myLoadObj);
	}
	
	function successFunction(data){
		clearInterval(timerID);
		if(clear==true){$("#"+myTarget).empty();}
		$("#"+myTarget).append(data);
	}
	//////////////////////////////////////
	
	

	forceRandom = Math.random()*99999999;
	forceRandom = Math.round(forceRandom);
	if (Right(myUrl,4)=='.asp'){
		myUrlDef = myUrl+'?forceRand='+forceRandom;
	}else{
		myUrlDef = myUrl+'&forceRand='+forceRandom;
	}
	
	//////////////////////////////////////
	///// CONTROLLO I CAMPI OBBLIGATORI PER L'INVIO IN POST
	//////////////////////////////////////
	if(myMethod=='POST'){
		error = 0;
		if(obb!='' || obb!=0){
			//var obbArray = obb.split(',');
			myLoop=0;
			
			// OLD E FUNZIONANTE// $("[nNumber]").each(function(){
																
			// NUOVO IN TEST // 
			$("[nObb]").each(function(){
				if($(this).attr("nObb")=="1"){
					if($(this).attr("type")=="text" && $(this).val()=="" || $(this).attr("type")=="password" && $(this).val()=="" || $(this).attr("type")=="checkbox" && $(this).attr("checked")=="" || $(this).attr("type")=="textarea" && $(this).val()==""){ 
						error++;
						alert('Il campo '+$(this).attr("alert")+' e\' vuoto.');
					}
				}
		  	});
		}
		//////////////////////////////////////
		
		
		if(error==0) {
			//////////////////////////////////////
			///// INVIO POST
			//////////////////////////////////////
			$.ajax({
				type: myMethod,
				url: myUrlDef,
				data: $("#"+idForm).serialize(),
				dataType: "html",
				beforeSend: function() { 
					beforeFunction();
				},
				success: function(data){
					successFunction(data);
				},
				error:function (xhr, ajaxOptions, thrownError){
					$("#errorMessage").append(xhr.responseText);
					attivaErrori(1);
				}
			});
			//////////////////////////////////////
		}else{
			$("[type='password']").attr("value","");
		}
		
    }else{
		//////////////////////////////////////
		///// INVIO GET
		//////////////////////////////////////
        $.ajax({
            type: myMethod,
            url: myUrlDef,
            dataType: "html",
			beforeSend: function() { 
				beforeFunction();
			},
            success: function(data){
				successFunction(data);
            },
			error:function (xhr, ajaxOptions, thrownError){
				$("#errorMessage").append(xhr.responseText);
				attivaErrori(1);
			}
        });
		//////////////////////////////////////
    }
}

///
///
///
////////////////////////////////////////////////////////////////////






function submitIt(nomeForm) {
	form = document.getElementById(nomeForm);
	myFormElements = form.elements;
	var error = 0;
	var errorMail = 0;
	for(i=0;i<myFormElements.length;i++) {
		document.getElementById("cont_"+myFormElements[i].name).style.backgroundColor = '';
		if(myFormElements[i].value=="") {
			//if(i != 7 && i != 8 && i != 11) {
				error++;
				document.getElementById("cont_"+myFormElements[i].name).style.backgroundColor = '#CADEFF';
			//}
		}else if(myFormElements[i].name=='email') {
			myEmail = myFormElements[i].value.indexOf("@");
			if(myEmail==-1) {
				alert("indirizzo e-mail non valido");
				errorMail++;
				document.getElementById("cont_"+myFormElements[i].name).style.backgroundColor = '#CADEFF';
			}
			
		}
	}
	if(error > 0) {
		alert("Compilare i campi obbligatori");
	} else if(error==0 && errorMail==0) {
		form.submit();
		myTxt="<p>Richiesta inviata correttamente</p><p><a href='index.asp?zona=4' title='invia un\'altra richiesta'>invia un'altra richiesta</a></p>";
		loadObj('autoText.asp?txt='+myTxt,'GET','#prenotaEventoDiv','1');
	}
}

function resetIt(nomeForm) {
	form = document.getElementById(nomeForm);
	myFormElements = form.elements;
	//for(i=0;i<myFormElements.length;i++) {
	//	document.getElementById("cont_"+myFormElements[i].name).style.backgroundColor = '';
	//}
	form.reset();
}

function submitForm(form) {
	myForm = document.getElementById(form);
	myForm.submit();
}

function rollOverBttMenu(id) {
	if (loaded == 1) {
		//document.getElementById('bttMenu'+id).style.background  = 'url(img/bckBttActive.jpg) repeat-x';
		//document.getElementById('bttMenu'+id).style.width = '114px';
		//document.getElementById('bttMenu'+id).style.borderLeft = '1px solid #404040';
		if(id !== 1) {
			//document.getElementById('bttMenu'+id).style.borderTop = '1px solid #d0f0c0';
		}
		document.getElementById('a'+'bttMenu'+id).style.color = '#45de00';
		document.getElementById('bttMenu'+id).style.cursor = 'default';
	}
}
function rollOutBttMenu(id) {
	if (loaded == 1) {
		if(id !== 1) {
			//document.getElementById('bttMenu'+id).style.borderTop = '1px dotted black';
		} else {
			//document.getElementById('bttMenu'+id).style.borderTop = '0px';
		}
		//document.getElementById('bttMenu'+id).style.borderLeft = 'none';
		//document.getElementById('bttMenu'+id).style.width = '114px';
		//document.getElementById('bttMenu'+id).style.background  = 'url(img/bckBtt.jpg) repeat-x';
		document.getElementById('a'+'bttMenu'+id).style.color = '#8c8c8c';
	}
}

function rollOverBttMenu1(id) {
	element = document.getElementById('velina'+id);
	bytefx.alpha(element, 0);
	element.style.display = 'block';
	bytefx.fade(element, 0, 100, 10);
	//bytefx.alpha(element, 10);
}
function rollOutBttMenu1(id) {
	element = document.getElementById('velina'+id);
	bytefx.fade(element, 100, 0, 10);
	element.style.display = 'none';
	//bytefx.alpha(element, 60);
}

function rollOverBttMenu2(id) {
	if(document.getElementById('a'+'bttMenu2'+id)){
		element = document.getElementById('a'+'bttMenu2'+id);
		element.style.color = 'white';
	}
	//bytefx.fade(element, 40, 10, 2);
	//bytefx.alpha(element, 10);
}
function rollOutBttMenu2(id) {
	if(document.getElementById('a'+'bttMenu2'+id)){
		element = document.getElementById('a'+'bttMenu2'+id);
		element.style.color = '#8F1A22';
	}
	//bytefx.fade(element, 10, 40, 2);
	//bytefx.alpha(element, 60);
}

function rollBtt(stato,btt) {
	myBtt = document.getElementById(btt);
	if(stato==1) {
		myBtt.style.color = '#8F1A22';
	} else {
		myBtt.style.color = 'white';
	}
}

function goToPage(pag) {
	//if (loaded == 1) {
		document.location.href = 'index.asp?zona='+pag;
	//}
}

function gotoAHAH(url,target) {
	completeAHAH.ahah(url,target,'0','GET');
}


//FUNZIONI DELLA HOME

function detectFF() {
	if(navigator.userAgent.indexOf("Firefox")!=-1){
		trovato = 'FF';
	} else if (navigator.appVersion.indexOf("MSIE")!=-1){
		trovato = 'IE';
	} else {
		trovato = 'UNKNOW';
	}
}

function ridOscura(zona) {
	width = document.body.offsetWidth;
	height = document.body.offsetHeight;
	
	if(document.getElementById('contenitore'+zona)){
		cont = document.getElementById('contenitore'+zona);
		contH = cont.offSetHeight;
	}else{
		contH = 0;
	}
	//alert('height = '+height+' - contH = '+contH);
	detectFF();
	if(height == null || height == 0) {
		if (trovato == 'IE') {
			
			height1 = document.documentElement.scrollHeight;
			height2 = document.documentElement.clientHeight;
			if(height1 >= height2) {
				height = height1;
			} else {
				height = height2;
			}
			//alert("IE - "+height);
		} else if (trovato == 'FF') {
			height = document.documentElement.scrollHeight;
			//alert("FF - "+height);
		} else {
			height = document.documentElement.clientHeight;
			//alert("ELSE - "+height);
		}
	}
	
	if(height > contH) {
		h = height;
	} else {
		h = contH;
	}
	
		
	
	//alert('w='+width+' h='+height);
	element = document.getElementById('oscura');
	element.style.Width = width+'px';
	element.style.Height = h+'px';
}

function popDoc(cCount,zona) {
	window.open('doc.asp?cCount='+cCount+'&zona='+zona,'allegato','700,500');
}

function popUp(vis,id,zona) {
	if (vis == 1) {
		
		ridOscura();
		
		element = document.getElementById('oscura');
		rand = Math.floor(Math.random()*99999999);
		pageToLoad = zona+'.asp';

		if(document.getElementById('popUp').style.display != 'block') {	
			if(document.body.scrollTop) {	
				document.getElementById('popUp').style.top = (document.body.scrollTop+25)+'px';
			} else {
				document.getElementById('popUp').style.top = (document.documentElement.scrollTop+25)+'px';
			}
			bytefx.alpha(element, 0);
			element.style.display = 'block';
			bytefx.fade(element, 0, 80, 15,
				function() {
					document.getElementById('popUp').style.display = 'block';
					completeAHAH.ahah(pageToLoad+'?id='+id+'&rnd='+rand,'popUp','0','GET');
				}
			);
		} else {
			completeAHAH.ahah(pageToLoad+'?id='+id+'&rnd='+rand,'popUp','0','GET');
		}
	} else {
		completeAHAH.ahah('blank.asp','popUp','0','GET');
		document.getElementById('popUp').style.display = 'none';
		element = document.getElementById('oscura');
		bytefx.fade(element, 80, 0, 15, function(){
			document.getElementById('oscura').style.display = 'none';
		});
		//bytefx.alpha(element, 0);
		
		
	}
}

var IE = document.all?true:false;
if (!IE) document.captureEvents(Event.MOUSEMOVE);

function getMouseXY(e,posizione) {
	
	//var tempX = 0;
	//var tempY = 0;

	if (IE) { // grab the x-y pos.s if browser is IE
		tempX = event.clientX + document.body.scrollLeft;
		if(document.body.scrollTop) {
			tempY = event.clientY + document.body.scrollTop;
		} else {
			tempY = event.clientY + document.documentElement.scrollTop;
		}
		
	} else {  // grab the x-y pos.s if browser is NS
		tempX = e.pageX;
		tempY = e.pageY;
		//alert(tempX, tempY);	
	}  
	// catch possible negative values in NS4
	if (tempX < 0) {
		tempX = 0;
	}
	
	if (tempY < 0) {
		tempY = 0;
	} 
	
	//if (cCount2 != 0) {
					
		objDiv = document.getElementById('popUpImg');
		objHeight = objDiv.offsetHeight;
		objW = objDiv.style.width;
		//alert(objW);
		//Y = objDiv.style.top = tempY-(objHeight/2)+'px';
		objDiv.style.top = tempY-500+'px';
		//alert(posizione);
		//if (posizione == 1) {
		objDiv.style.left = tempX-(objW/2)+'px';
		//} else {
			//X = objTipDiv.style.left = tempX-300+'px';
		//}
		
	//}
  return true
}


function popUpImg(vis,img,imgmdl) {
	if (vis == 1) {
		
		ridOscura();
		
		//element = document.getElementById('oscura');
		//bytefx.alpha(element, 0);
		//element.style.display = 'block';
		//bytefx.alpha(element, 0);
		//bytefx.fade(element, 0, 80, 15, function(){
		//});
		//rand = Math.floor(Math.random()*99999999);
		
		pageToLoad = 'popupImg.asp?img='+img+'&imgmdl='+imgmdl;
		
		//document.getElementById('popUp').style.top = tempY-15+'px';
		document.getElementById('popUpImg').style.display = 'block';
		completeAHAH.ahah(pageToLoad,'popUpImg','0','GET');
		document.onmousemove = getMouseXY;
	} else {
		completeAHAH.ahah('blank.asp','popUpImg','0','GET');
		document.getElementById('popUpImg').style.display = 'none';
		//element = document.getElementById('oscura');
		//bytefx.fade(element, 80, 0, 15, function(){
			//document.getElementById('oscura').style.display = 'none';									 
		//});
	}
}


function controlloCampi() {
	var stopIt = 0;
	var form = document.contact;
	var nome = form.nome.value;
	var cognome = form.cognome.value;
	var azienda = form.azienda.value;
	var indirizzo = form.indirizzo.value;
	var cap = form.cap.value;
	var citta = form.citta.value;
	var tel = form.tel.value;
	var email = form.email.value;
	var oggettoMsg = form.oggettoMsg.value;
	var corpoMsg = form.corpoMsg.value;
	corpoMsg.replace("\r","<br />");
	
	//CONDIZION
	
	if (nome == "") {
		alert("non hai inserito il nome");
		stopIt = 1;
	}
	if (cognome == "") {
		alert("non hai inserito il cognome");
		stopIt = 1;
	}
	if (email == "") {
		alert("non hai inserito la mail");
		stopIt = 1;
	}
	if (oggettoMsg == "") {
		alert("non hai inserito l'oggetto");
		stopIt = 1;
	}
	if (corpoMsg == "") {
		alert("non hai inserito il corpo del messaggio");
		stopIt = 1;
	}
	if (stopIt == 0) {

				
		//Applico replace per sostituire Pippo con Pluto
		corpoMsg = corpoMsg.replace(/\n/g, '<br>');
		
		
		//alert(corpoMsg);
		completeAHAH.ahah('popup.asp?step=2&nome='+nome+'&cognome='+cognome+'&azienda='+azienda+'&indirizzo='+indirizzo+'&cap='+cap+'&citta='+citta+'&tel='+tel+'&email='+email+'&oggettoMsg='+oggettoMsg+'&corpoMsg='+corpoMsg,'popup','0','GET');
		//ahah('insertCliente.asp','toDb');
	}
}


//FUNZIONI DELLA GALLERY
function allineaImg(target) {
	element = document.getElementById(target);
	hImg = element.offsetHeight;
	wImg = element.offsetWidth;
	hBox = document.getElementById('out'+target).clientHeight;
	wBox = document.getElementById('out'+target).clientWidth;
	topImg = (hBox-hImg)/2;
	leftImg = (wBox-wImg)/2;
	element.style.marginTop = topImg+'px';
	element.style.marginLeft = leftImg+'px';
}


sel = '';
//tot = 0;
//img = new Array();

function inizializzaGallery(iniSel,idrand) {	
	rand = Math.floor(Math.random()*99999999);
	if(sel!='') {
		document.getElementById('outtmb'+sel).style.borderColor = '#ccc';
	}
	document.getElementById('outtmb'+iniSel).style.borderColor = '#FF5700';
	completeAHAH.ahah('zoom.asp?id='+iniSel+'&idrand='+idrand+'&rnd='+rand,'zoom','0','GET');
	sel = iniSel;
	
	//alert(iniSel);
}

function tmbClick(id) {
	if(id == '-2') {
		id = sel+1;
	} else if(id == '-1') {
		id = sel-1;
	} else {
	}
	
	tot = document.getElementById('tot').value;
	//tot = parseInt(tot);
	bttPrev = document.getElementById('bttPrev');
	bttNext = document.getElementById('bttNext');
	
	bttPrev.style.display = 'block';
	bttNext.style.display = 'block';
	
	if(id == 0) {
		bttPrev.style.display = 'none';
	} 
	if(id == tot) {
		bttNext.style.display = 'none';
	}
	
	lrg = document.getElementById('img'+id).value;
	
	document.getElementById('outtmb'+sel).style.borderColor = 'white';
	document.getElementById('outtmb'+id).style.borderColor = 'black';
	sel = id;
	document.getElementById('lrg').src = 'mdb-database/Media/'+lrg;
}

function navFoto(actual,dir,tot,actPage,maxForPage) {
	
	if(dir == 0 && actual !== 0) {
		toLoad = actual-1;
		if(actPage !== 0) {
			if (toLoad < ((actPage+1)*maxForPage)) {
				loadPage(actPage-1);
			}
		} else {
			if(toLoad >= 0) {
				sel = toLoad;
				completeAHAH.ahah('zoom.asp?id='+toLoad,'zoom','0','GET');
			}
		}
	} else {
		if(dir == 1 && actual !== tot) {
			toLoad = actual+1;
			if (toLoad > ((actPage+1)*maxForPage)) {
				loadPage(actPage+1);
			} else {
				if(toLoad <= (tot-1)) {
					sel = toLoad;
					completeAHAH.ahah('zoom.asp?id='+toLoad,'zoom','0','GET');
				}
			}
		}
	}
}


function tmbOn(id) {
	document.getElementById('outtmb'+id).style.borderColor = '#66ff00';
}

function tmbOff(id) {
	if(sel !== id) {
		document.getElementById('outtmb'+id).style.borderColor = '#2f4f4f';
	}
}

function loadPage(nPage) {
	completeAHAH.ahah('tmbGallery.asp?page='+nPage,'tmb','0','GET');
}


