// 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);
}


////////////////////////////////////////////////////////////////////////////////////////////////////////////////
///	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 loadObj(myUrl,myMethod,idForm,obb,myTarget,clear){
    
	//////////////////////////////////////
	///// OGGETTO LOADING
	//////////////////////////////////////
	myLoadObj="<div style='position: relative; float: left; width: 100%; padding: 25px;'><div style='position: relative; float: left; width: 16px; padding-right: 10px;'><img src='img/loading.gif' /></div><div style='position:relative; float:left; width: 50px;'>loading...</div></div>";
	//////////////////////////////////////
	
	//////////////////////////////////////
	///// STATI AJAX
	//////////////////////////////////////
	function beforeFunction(){
		if(clear==true){$("#"+myTarget).empty();}
		$("#"+myTarget).append(myLoadObj);
	}
	
	function successFunction(data){
		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!=''){
			var obbArray = obb.split(',');
			myLoop=0;
			$("[nNumber]").each(function(){
				if($(this).val()==""){
					for(k=0;k<obbArray.length;k++) {
						if(myLoop==(obbArray[k])) {
							error++;
							alert('Il campo '+$(this).attr("id")+' e\' vuoto.');
						}
					}
				}
				myLoop=myLoop+1;
		  	});
		}
		//////////////////////////////////////
		
		
		if(error==0) {
			//////////////////////////////////////
			///// INVIO POST
			//////////////////////////////////////
			$.ajax({
				type: myMethod,
				url: myUrlDef,
				data: $("#"+idForm).serialize(),
				dataType: "html",
				beforeSend: function() { 
					beforeFunction();
				},
				success: function(data){
					successFunction(data);
				}
			});
			//////////////////////////////////////
		}
		
    }else{
		//////////////////////////////////////
		///// INVIO GET
		//////////////////////////////////////
        $.ajax({
            type: myMethod,
            url: myUrlDef,
            dataType: "html",
			beforeSend: function() { 
				beforeFunction();
			},
            success: function(data){
                successFunction(data);
            }
        });
		//////////////////////////////////////
    }
}

///
///
///
////////////////////////////////////////////////////////////////////






function verPass(verNam1,verNam2,idForm,obb) {
	//pass1 = document.getElementsByName(verNam1)[0].value;
	//pass2 = document.getElementsByName(verNam2)[0].value;
	//if(pass1!=pass2) {
		//alert('I campi password non corrispondono');
	//} else {
		submitIt(idForm,obb);
	//}
}


function userPannell(stato,action,step) {
	element = document.getElementById('userPannell');
	//aLink = document.getElementById('aUser1');
	
	if(action=='log') {
		hSize = 160;
	} else if(action=='mod') {
		hSize = 450;
	}
	
	a1Link = document.getElementById('aUser1');
	a2Link = document.getElementById('aUser2');
	
	if(stato==1) {
		
		loadObj('blank.asp','GET','','','userInt',1);
		//completeAHAH.ahah('blank.asp','userInt','0','GET');
		
		if(action=='log') {
			//if(logUser=='') {
				a1Link.href = "javascript:userPannell('0','"+action+"','');";
			//}
			a2Link.href = "javascript:userPannell('1','mod','');";
		} else {
			if(logUser==0) {
				a1Link.href = "javascript:userPannell('1','log','');";
			}
			//a1Link.href = "javascript:userPannell('1','log','');";
			a2Link.href = "javascript:userPannell('0','"+action+"','');";
		}
		
		element.style.height = '0px';
		element.style.display = 'block';
		bytefx.size(
			element,
			{width:960,height:hSize},
			35,
				function(){
					//forceRandom = Math.random()*99999999;
					//forceRandom = Math.round(forceRandom);
					loadObj('user.asp?action='+action+'&step='+step,'GET','','','userInt',1);
					//completeAHAH.ahah('user.asp?action='+action+'&step='+step+'&rnd='+forceRandom,'userInt','0','GET');
				}
			);
	} else {
		
		if(action=='log') {
			a1Link.href = "javascript:userPannell('1','"+action+"','');";
			a2Link.href = "javascript:userPannell('1','mod','');";
		} else {
			if(logUser==0) {
				a1Link.href = "javascript:userPannell('1','log','');";
			}
			//a1Link.href = "javascript:userPannell('1','log','');";
			a2Link.href = "javascript:userPannell('1','"+action+"','');";
		}

		bytefx.size(
			element,
			{width:960,height:0},
			35,
				function(){
					loadObj('blank.asp','GET','','','userInt',1);
					//completeAHAH.ahah('blank.asp','userInt','0','GET');
					element.style.height = '0px';
					element.style.display = 'none';
				}
			);
	}
}


function verificaExt(ext,target) {
	nomeFile = document.getElementById(target).value;
	extFile = nomeFile.split('.');
	extLow = ext;
	extFirstUp = ext.substring(0,1).toUpperCase();
	extUp = ext.toUpperCase();
	if(extFile[(extFile.length-1)]==extLow || extFile[(extFile.length-1)]==extFirstUp || extFile[(ext.length-1)]==extUp) {
	} else {
		alert('Il file selezionato non è un file '+ext+'. Selezionare solo file '+ext+'.');
		document.getElementById(target).value = '';
	}
}

//function controlloLog() {
	//document.getElementById('logForm').submit();
	//completeAHAH.ahah('controlloLog.asp','errorLog','0','GET');
//}

function submitIt(nomeForm,obb) {
	myForm = document.getElementById(nomeForm);
	myFormElements = myForm.elements;
	//obbArray = new Array();
	var obbArray = obb.split(',');
	//alert(obbArray[2]);
	error = 0;
	for(i=0;i<myFormElements.length;i++) {
		//document.getElementById("cont_"+myFormElements[i].name).style.backgroundColor = '';
		if(myFormElements[i].value=="") {
			for(k=0;k<obbArray.length;k++) {
				if(i==(obbArray[k])) {
					error++;
					//document.getElementById("cont_"+myFormElements[i].name).style.backgroundColor = '';
					alert('Il campo '+myFormElements[i].id+' e\' vuoto.');
				}
				
			}
		}
		
	}
	if(error==0) {
		myForm.submit();
	}
}


function verificaJPG() {
	nomeFile = document.getElementsByName('imgtmb')[0].value;
	ext = nomeFile.split('.');
	if(ext[(ext.length-1)]=='jpg' || ext[(ext.length-1)]=='Jpg' || ext[(ext.length-1)]=='JPG') {
	} else {
		alert('L\'immagine selezionata non &egrave; un JPG. Selezionare solo immagini formato JPG.');
		document.getElementsByName('imgtmb')[0].value = '';
	}
}

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,img1,img2) {
	//element = document.getElementById('velina'+id);
	if (loaded == 1) {
		if(id !== 1) {
		}
		//bytefx.fade(element, 0, 70, 5);
		//document.getElementById('a'+'bttMenu'+id).style.color = '#FD5F00';
		//document.getElementById('bttMenu'+id).style.cursor = 'default';
		document.getElementById('imgMenu'+id).src = 'mdb-database/Media/'+img2;
		document.getElementById('bttMenu'+id).style.backgroundPosition = '0px -15px';
	}
}
function rollOutBttMenu(id,img1,img2) {
	//element = document.getElementById('velina'+id);
	if (loaded == 1) {
		if(id !== 1) {
		} else {
		}
		//bytefx.fade(element, 70, 0, 5);
		//document.getElementById('a'+'bttMenu'+id).style.color = '#00008B';
		document.getElementById('imgMenu'+id).src = 'mdb-database/Media/'+img1;
		document.getElementById('bttMenu'+id).style.backgroundPosition = '0px 0px';
	}
}


function rollOverBttSubMenu(id) {
	element = document.getElementById('velina'+id);
	if (loaded == 1) {
		if(id !== 1) {
		}
		//bytefx.alpha(element, 0);
		bytefx.fade(element, 0, 70, 5);
		document.getElementById('a'+'bttMenu'+id).style.color = '#FD5F00';
		document.getElementById('bttMenu'+id).style.cursor = 'default';
	}
}
function rollOutBttSubMenu(id) {
	element = document.getElementById('velina'+id);
	if (loaded == 1) {
		if(id !== 1) {
		} else {
		}
		//bytefx.alpha(element, 70);
		bytefx.fade(element, 70, 0, 5);
		document.getElementById('a'+'bttMenu'+id).style.color = '#00008B';
	}
}



function rollBtt(stato,btt) {
	myBtt = document.getElementById(btt);
	if(stato==1) {
		myBtt.style.color = 'black';
	} 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() {
	width = document.body.offsetWidth;
	height = document.documentElement.clientHeight;
	
	contH = document.getElementById('contInt').clientHeight;
	//alert(contH);
	if(height == 0) {
		detectFF();
		if (trovato == 'IE') {
			if(height1 >= height2) {
				height = document.documentElement.scrollHeight;
			} else {
				height = document.documentElement.clientHeight;
			}
			//alert(trovato);
		} else if (trovato == 'FF') {
			height = document.documentElement.scrollHeight;
			//alert(trovato);
		} else {
			height = document.documentElement.offsetHeight;
			//alert(trovato);
		}
	}
	//alert('w='+width+' h='+height);
	element = document.getElementById('oscura');
	element.style.width = width+'px';
	
	if(height<contH) {
		height = contH+100;
	}
	element.style.height = height+'px';
}

function popDoc(cCount,zona) {
	window.open('doc.asp?cCount='+cCount+'&zona='+zona,'allegato','700,500');
}

function popUp(vis,id,zona) {
	if (vis == 1) {
		pageToLoad = zona+'.asp';
		if (document.getElementById('popUp').style.display != 'block') {
			ridOscura();
			bytefx.alpha(element, 0);
			bytefx.fade(element, 0, 80, 15, function(){
			});
			element.style.display = 'block';
		
		
			rand = Math.floor(Math.random()*99999999);
			
			//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';
			//}
			
			document.getElementById('popUp').style.display = 'block';
		}
		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;
	} 
	

					
		objDiv = document.getElementById('popUpImg');
		objHeight = objDiv.offsetHeight;
		
		objDiv.style.top = tempY+25+'px';
		//objDiv.style.top = tempY-(objHeight/2)-50+'px';
		
		objDiv.style.left = tempX-55+'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);
		rand = Math.floor(Math.random()*99999999);
		document.onmousemove = getMouseXY;
		pageToLoad = 'popupImg.asp?img='+img+'&imgmdl='+imgmdl+'&rnd='+rand;
		
		//document.getElementById('popUp').style.top = tempY-15+'px';
		document.getElementById('popUpImg').style.display = 'block';
		completeAHAH.ahah(pageToLoad,'popUpImg','0','GET');
	} 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);
	//bytefx.alpha(element, 0);
	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;
	//if (topImg > 0) {
		element.style.marginTop = topImg+'px';
		element.style.marginLeft = leftImg+'px';
	//}
	
	//bytefx.alpha(element, 100);
}

sel = 0;

function inizializzaGallery(iniSel,lrg) {
	document.getElementById('navS').style.display = 'none';
	document.getElementById('navD').style.display = 'none';
	
	wFoto = document.getElementById('lrg').clientWidth;
	hFoto = document.getElementById('lrg').clientHeight;
	
	element = document.getElementById('lrgCont');
	bytefx.alpha(element, 0);
	//element.style.height = hFoto+'px';
	//alert(hFoto);
	if(hFoto != '') {
		document.getElementById('loading').style.paddingTop = ((hFoto/2)-15)+'px';
	} else {
		document.getElementById('loading').style.paddingTop = '180px';
	}
	document.getElementById('loading').style.display = 'block';
	document.getElementById('loading').innerHTML = '<img src="img/loading.gif" border="0" />';

	element = document.getElementById('outtmb'+iniSel);
	element.style.borderColor = '#ec651d';
	if(sel != '' || sel != iniSel) {
		element = document.getElementById('outtmb'+sel);
		element.style.borderColor = '#0094D3';
	}
	
	//document.getElementById('titTxt').innerHTML = txtXS;
	//document.getElementById('descTxt').innerHTML = txtS;
	
	document.getElementById('lrg').src = lrg;
	//document.getElementById('lrgCont').style.display = 'block';
	sel = iniSel;
}


function galleryLoaded(maxForPage) {
	document.getElementById('loading').innerHTML = '';
	document.getElementById('loading').style.display = 'none';
	element = document.getElementById('lrgCont');
	bytefx.fade(element, 0, 100, 15, function(){
		//document.getElementById('loading').style.display = 'none';
	});
	
	wFoto = document.getElementById('lrg').clientWidth;
	hFoto = document.getElementById('lrg').clientHeight;
	
	document.getElementById('nav').style.width = (wFoto+30)+'px';
	document.getElementById('nav').style.marginLeft = ((document.getElementById('zoom').clientWidth-(wFoto+30))/2)+'px';
	
	sel = sel*1;
	actImg = document.getElementById('img'+sel).value;
	//tImg = document.getElementsByName('totImg')[0].value;
	//tImg=tImg*1;
	//maxForPage=maxForPage*1;
	
	//if(maxForPage>=tImg) {
//		maxImg = maxForPage;
//	} else {
//		maxImg = tImg;
//	}
//	alert(maxForPage);

	myForm = document.getElementsByName('zzzForm')[0];
	myFormEl = myForm.elements;
	myFormTotEl = myFormEl.length-1;
	
	if(maxForPage>=myFormTotEl) {
		maxImg = myFormTotEl;
	} else {
		maxImg = maxForPage;
	}
	//alert(maxImg);
	
	
	if(sel == 0) {
		document.getElementById('navS').style.display = 'none';
		document.getElementById('navD').style.display = 'block';
		nextImg = document.getElementById('img'+(sel+1)).value;
		document.getElementById('navD').href = 'javascript:inizializzaGallery("'+(sel+1)+'","'+nextImg+'")';
	} else if(sel >= maxImg) {
		document.getElementById('navS').style.display = 'block';
		document.getElementById('navD').style.display = 'none';
		prevImg = document.getElementById('img'+(sel-1)).value;
		document.getElementById('navS').href = 'javascript:inizializzaGallery("'+(sel-1)+'","'+prevImg+'")';
	} else {
		document.getElementById('navS').style.display = 'block';
		document.getElementById('navD').style.display = 'block';
		prevImg = document.getElementById('img'+(sel-1)).value;
		nextImg = document.getElementById('img'+(sel+1)).value;
		document.getElementById('navS').href = 'javascript:inizializzaGallery("'+(sel-1)+'","'+prevImg+'")';
		document.getElementById('navD').href = 'javascript:inizializzaGallery("'+(sel+1)+'","'+nextImg+'")';
	}
}

function tmbOn(id) {
	document.getElementById('outtmb'+id).style.borderColor = '#66ff00';
}

function tmbOff(id) {
	if(sel !== id) {
		document.getElementById('outtmb'+id).style.borderColor = '#2f4f4f';
	}
}

function tmbClick(id,txtXS,txtS,lrg) {
	document.getElementById('outtmb'+sel).style.borderColor = '#ccc';
	document.getElementById('outtmb'+id).style.borderColor = '#ec651d';
	sel = id;
	document.getElementById('titTxt').innerHTML = txtXS;
	document.getElementById('descTxt').innerHTML = txtS;
	document.getElementById('lrg').src = 'mdb-database/Media/'+lrg;
}

function loadPage(nPage) {
	completeAHAH.ahah('tmbGallery.asp?page='+nPage,'tmb','0','GET');
}

