/*BOF FORM CONTATTI*/

//restituisco true in caso di errore
function validateFormElement(elem)
{
	if(elem.value=="")
	{
		errorOnFormElement(elem);
		return true;
	}
	else 
	{
		return false;
	}
}


function validateHiddenElement(element)
{
	if(validateFormElement(element))
	{
		errorOnFormElement('fieldset_dettagli_richiesta');
		errorOnFormElement('fieldset_dettagli_preventivo');
		return true;
	}
	else return false;
}

function validateCheckBoxElement(elem)
{
	if(elem.checked)
	{
		return false;
	}
	else
	{
		errorOnFormElement(elem.parentNode);	
		return true;
	}
}

function validateFormEmail(elem)
{
	var emailRegexp = RegExp('^[A-Za-z0-9._-]+[@]([A-Za-z0-9-]+[.])+([A-za-z]{2,4})$', 'i');
	
	if (emailRegexp.test(elem.value))
	{
		return false;
	}
	else
	{
		errorOnFormElement(elem);
		return true;
	}
}


function errorOnFormElement(elem)
{
	Effect.Shake(elem);
	new Effect.Highlight(elem);
}






function submitConfirm()
{
	var d = new Date()
	param = d.getTime();
	var form = $('confirm_form');
	
//inizio validazione
	var error_found = 0;			
	if(validateFormElement(form.frm_nome)) error_found++;
	if(validateFormEmail(form.frm_email)) error_found++;
//fine validazione	

	if(error_found==0)
	{
		Effect.BlindUp('form_confirm_all_fields');

		form.request({
		
		  onComplete: function()
		  { 	
			Effect.BlindDown('form_confirm_thanks');
			

			  return false; 
		   }
		
		});


//	document.forms['confirm_form'].submit();		

	}	
	return false;
	
}






function submitTherealguestbook()
{
	var d = new Date()
	param = d.getTime();
	var form = $('guestbooksign');
	
	document.forms['guestbooksign'].secure.value = param;
	document.forms['guestbooksign'].secure.value = param;

//inizio validazione
	var error_found = 0;			
	if(validateFormElement(form.frm_nome)) error_found++;
	if(validateFormEmail(form.frm_email)) error_found++;
//fine validazione	

	if(error_found==0)
	{
		Effect.BlindUp('form_guestbook_all_fields');


		form.request({
		
		  onComplete: function()
		  { 	
			Effect.BlindDown('form_guestbook_thanks');
			Form.reset('guestbooksign');

			  return false; 
		   }
		
		});


//	document.forms['guestbooksign'].submit();		

	}	
	return false;
	
}



function submitGuestBook()
{
	var d = new Date()
	param = d.getTime();
		
	var form = $('guestbooksign');
	document.forms['guestbooksign'].secure.value = param;


	//copio testo della text area
	if (document.forms['guestbooksign'].frm_tipo_richiesta.value=="richiesta preventivo")
	{
		document.forms['guestbooksign'].frm_messaggio.value=document.forms['guestbooksign'].frm_messaggio_a.value;
	}
	else
	{
		document.forms['guestbooksign'].frm_messaggio.value=document.forms['guestbooksign'].frm_messaggio_b.value;	
	}

	//ASSEGNATO DI DEFAULT
	//document.forms['guestbooksign'].frm_tipo_richiesta.value = 'richiesta informazioni';

//inizio validazione
	var error_found = 0;
			
	if(validateFormElement(form.frm_nome)) error_found++;
	if(validateFormEmail(form.frm_email)) error_found++;
	if(validateFormElement(form.frm_telefono)) error_found++;
	if(validateCheckBoxElement(form.frm_privacy_a) && validateCheckBoxElement(form.frm_privacy_b)) error_found++;
	//if(validateHiddenElement(form.frm_tipo_richiesta)) error_found++;
//fine validazione	


	if(error_found==0)
	{
		Effect.BlindUp('form_email_all_fields');


		form.request({
		
		  onComplete: function()
		  { 	
			Effect.BlindDown('form_email_thanks');
			Form.reset('guestbooksign');

			  return false; 
		   }
		
		});

/*
	document.forms['guestbooksign'].submit();		
*/	
	}	
	return false;
}



function showOnClick(element)
{
	
	if($(element).style.display == '') return false;
	else
	{
		if(element == 'frm_dettagli_richiesta')
		{
			Effect.BlindUp($('frm_dettagli_preventivo'), {afterFinish: down=function()
			{
				Effect.BlindDown(element, {afterFinish: down2=function()
				{
				
				}
				});				
												
				document.forms['guestbooksign'].frm_tipo_richiesta.value = 'richiesta informazioni';				
				
			}});
		}
		else
		{
			Effect.BlindUp($('frm_dettagli_richiesta'), {afterFinish: down=function()
			{
				Effect.BlindDown($('frm_dettagli_preventivo'), {afterFinish: down2=function()
				{
							
				}
				});
				document.forms['guestbooksign'].frm_tipo_richiesta.value = 'richiesta preventivo';
				
			}});
		}
	}
	
}

/*EOF FORM CONTATTI*/





//preload immagini
function preloadIMG(){	
	var images = document.getElementsByTagName('img');
	var immagini=new Array();	
	var cont = 0;
	
	//percorro tutte le immagini		
	for (var i=0; i<images.length; i++){
		var image = images[i];
		var relAttribute = String(image.getAttribute('name'));
	
		//se hanno match preload... associo funzioni di preload
		if (relAttribute.toLowerCase().match('preload')){
			immagini[cont]=new Image();
			immagini[cont].src=image.src;
			cont++;
		}
	}
}

// Over delle immagini <img src=""..>
function attachSwitch(){	
	var images = document.getElementsByTagName('img');
	
	//percorro tutte le immagini		
	for (var i=0; i<images.length; i++){
		var image = images[i];
		var relAttribute = String(image.getAttribute('name'));
		
		//se hanno match over... associo funzioni di swap img
		if (relAttribute.toLowerCase().match('over')){
			image.onmouseover = function(){
				if(this.className!="active"){
					this.src= this.src.replace('_off', '_on');	
				}
			};
			image.onmouseout = function(){
				if(this.className!="active"){
					this.src= this.src.replace('_on', '_off');	
				}
			};			
		}
		if(image.className == "active") image.src= image.src.replace('_off', '_on');
	}
}


/************************************************************************************************************************/
//	CALCOLO DELL'ALTEZZA DEL MAIN (INIZIO FUNZIONI)


//	Richiamando le altre funzioni calcolo al volo l'altezza del main
function mainHeight(){

	var main;
	var heightTotale = 0;
	
	var head;
	var container;
	var colonnaSx;
	var colonnaDx;
	var footer;	
	
	main = document.getElementById('main');
	
	head = document.getElementById('head');
	container = document.getElementById('container');
	colonnaSx = document.getElementById('colonnaSx');	
	colonnaDx = document.getElementById('colonnaDx');
	footer = document.getElementById('footer');
	
	
	var 	container_offsetHeight = container.offsetHeight
	
	if($('frm_dettagli_richiesta')) container_offsetHeight += 350;	
	
	// richiamo le funzioni precedenti
	
//	questa quando il layout e' a tre colonne	
	heightTotale = Math.max(colonnaSx.offsetHeight,Math.max(colonnaDx.offsetHeight,container_offsetHeight)) + head.offsetHeight + footer.offsetHeight;
	
	main.style.height = heightTotale + 'px';



	// sistemo immagine di sfondo nella classe virtuale
	var virtuale = $$('.virtuale');
	for(var j=0;j<virtuale.length;j++)
	{
		var elemento = virtuale[j];
		if(elemento.descendants() && elemento.firstChild.nodeName!='#text')
		{
			//alert(elemento.firstChild.nodeName);
			elemento.setStyle(
			{
				'padding-left': '0px',
				'background': 'none'
			});
		}
	}

}

//	CALCOLO DELL'ALTEZZA DEL MAIN (FINE FUNZIONI)
/***************************************************************************************************************************/

//	Corregge la visualizzazione dei PNG in explorer
function correctPNG() {
	for(var i=0; i<document.images.length; i++){
		var img = document.images[i];
		var imgName = img.src.toUpperCase();
		if (imgName.substring(imgName.length-3, imgName.length) == "PNG"){
			var imgID = (img.id) ? "id='" + img.id + "' " : "";
			var imgClass = (img.className) ? "class='" + img.className + "' " : "";
			var imgTitle = (img.title) ? "title='" + img.title + "' " : "title='" + img.alt + "' ";
			var imgStyle = "display:inline-block;" + img.style.cssText ;
			if (img.align == "left") imgStyle = "float:left;" + imgStyle;
			if (img.align == "right") imgStyle = "float:right;" + imgStyle;
			if (img.parentElement.href) imgStyle = "cursor:hand;" + imgStyle;     
			var strNewHTML = "<span " + imgID + imgClass + imgTitle
			+ " style=\"" + "width:" + img.width + "px; height:" + img.height + "px;" + imgStyle + ";"
			+ "filter:progid:DXImageTransform.Microsoft.AlphaImageLoader"
			+ "(src=\'" + img.src + "\', sizingMethod='crops');\"></span>";
			img.outerHTML = strNewHTML;
			i = i-1;
		}
	}
}









function collapseMenu(node) {
	if (!document.getElementById) return false;
	if (!document.getElementById("menu")) return false;
	if (!node) node = document.getElementById("menu");

	if (node.childNodes.length > 0) {
		for (var i=0; i<node.childNodes.length; i++) {
			var child = node.childNodes[i];
			if (child.nodeName == "UL") {
					child.style.display = "none";
			}
			if(child.nodeName == "LI" && child.className.match('active'))
			{
				child.parentNode.style.display = 'block';
			}
			collapseMenu(child);
		}		
	}

}

function prepareMenu() {
	if (!document.getElementById || !document.getElementsByTagName) return false;
	if (!document.getElementById("menu")) return false;

	var links = document.getElementById("menu").getElementsByTagName("a");
	for (var i=0; i<links.length; i++) {		
		links[i].onclick = function() {
			toggleMenu(this.parentNode.getElementsByTagName("UL")[0], this.href);
			return false;
		}
	}
}

function toggleMenu(node, link) {
	
	if (!document.getElementById) return false;
	if (!link) return false;

	//apro href nel caso in cui non abbia node (cioe ul figlio)
	if (!node) 
	{
		location.href = link;
		return false;
	}

	//apro href nel caso in cui non abbia un ul figlio

/*
	if(!node.getElementsByTagName("UL")[0])
	{
		location.href = link;
		return false;
	}		
	
*/	

	// Collapse all nodes, and only show clicked node (when clicking top level of menu)
	
	var OBJmenu = $('menu');	
		
	if(!OBJmenu.title.match('moving')) 
	{

		if (node.parentNode.parentNode.id == "menu") {
			hideTopLevels();
		}

		OBJmenu.title += 'moving';
		
		if (node.style.display == "") 
		{
			Effect.BlindUp(node, {duration: 0.8, afterFinish: a1=function()
				{
						
						OBJmenu.title = OBJmenu.title.replace('moving', '');
						mainHeight();
				}
			});
	
		} else 
		{					
			Effect.BlindDown(node, {duration: 0.8, afterFinish: a2=function()
				{						
						OBJmenu.title = OBJmenu.title.replace('moving', '');
						mainHeight();
				}
			});
			
		}
			
	}
	else
	{		
		return;
	}

}

function hideTopLevels() {
	if (!document.getElementById) return false;
	if (!(node = document.getElementById("menu"))) return false;	
	
	if (node.childNodes.length > 0) {
		for (var i=0; i<node.childNodes.length; i++) {
			var child = node.childNodes[i];
			for(var j=0; j<child.childNodes.length; j++) {
				var grandchild = child.childNodes[j];
				if (grandchild.nodeName == "UL") {
					if (grandchild.style.display == '') {
						Effect.BlindUp(grandchild, {duration: 0.8, afterFinish: mainHeight });										
					}
				}
			}
		}		
	}
}








// <![CDATA[

var scrollDiv;
var hDiv;
var tClip;
var bClip;
var wClip;
var interval;
var topPos = 0;



function initScroller(id) {
    scrollDiv = document.getElementById(id);   
    var margin = parseInt(scrollDiv.offsetTop);
    
    var scrollDiv__controls = document.getElementById(id + '__controls');

    /* Style per il div interno (testo) */
    //scrollDiv.style.width    = (scrollDiv.parentNode.offsetWidth - (margin * 2)) - 24 + 'px';
    scrollDiv.style.height   = 'auto';
    scrollDiv.style.overflow = 'hidden';
    
    /* Style per il div esterno (contenitore) */
    scrollDiv.parentNode.style.overflow = 'hidden';
    
    /* Style per il div con i controlli (testo) */
    scrollDiv__controls.style.display = 'block';  


    /* Impostazioni per visualizzare la parte di testo superiore */
    hDiv  = scrollDiv.offsetHeight;

    tClip = 0;   
    wClip = scrollDiv.parentNode.offsetWidth - (margin * 2);
    bClip = scrollDiv.parentNode.offsetHeight - (margin * 2);

    scrollDiv.style.clip = 'rect('+ tClip +'px,'+ wClip +'px,'+ bClip +'px,0)';   
    // alert("tClip:"+tClip+"\nwClip:"+wClip+"\nbClip:"+bClip+"\n");
}

function scroll(scrollBy, time) {
    tClip += scrollBy;
    bClip += scrollBy;
    topPos -= scrollBy;

    
    if (tClip < 0 || bClip > hDiv) {
        tClip -= scrollBy;
        bClip -= scrollBy;
        topPos += scrollBy;    
    }
    
    
    scrollDiv.style.clip = 'rect('+ tClip +'px, '+ wClip +'px, '+ bClip +'px, 0)';   
    scrollDiv.style.top = topPos + 'px';    
    interval = setTimeout('scroll('+ scrollBy +', '+ time +')', time);
}

function stopScroll() {
    if (interval) clearTimeout(interval);
}

// ]]>



function showNewsDetail(el, type)
{



	try
	{
		var body = $$('body')[0];
		var scroll_top = getPageScroll();
		var left_position = ((body.offsetWidth/2) - 300);
		var top_position = (body.offsetWidth/ 15) + scroll_top[1];
	
	//	CUSTOM OVERLAY SETTINGS	
		var custom_overlay = document.createElement('div');
		custom_overlay.setAttribute('id', 'custom_overlay');

		body.appendChild(custom_overlay);

		custom_overlay.onclick = function(){closeDetail()};		
		Element.setStyle('custom_overlay',{
			'position': 'absolute',
			'top': '0px',
			'left':'0px',
			'height': body.offsetHeight + 'px',
			'width': body.offsetWidth + 'px',
			'background': '#000000',
			'display': 'none',
			'z-index': '30'
		});
		var left_position = ((body.offsetWidth/2) - 300);
		
	//	NEWS_DETAIL SETTINGS	
		var news_detail = document.createElement('div');
		news_detail.setAttribute('id', 'news_detail');
		body.appendChild(news_detail);
		Element.setStyle('news_detail',{
			'position': 'absolute',
			'top': top_position + 'px',
			'left': left_position+'px',
			'height': '450px',
			'width': '620px',
			'background': '#ece9d8',
			'display': 'none',
			'text-align':'justify',
			'border': '1px solid #000000',
			'z-index': '40'
		});		

	//	NEWS_DETAIL_CONTAINER SETTINGS	
		var news_detail_container = document.createElement('div');
		news_detail_container.setAttribute('id', 'news_detail_container');
		news_detail.appendChild(news_detail_container);
		Element.setStyle('news_detail_container',{'font-size':'12px','max-height':'400px','position': 'absolute','left':'14px','top':'9px','width': '565px','padding': '0px 25px 0px 10px','overflow': 'auto'});
		news_detail_container.setStyle({'color':'#000000'});
		
	
	

	
	//	NEWS_DETAIL_CLOSER SETTINGS		
		var news_detail_closer = document.createElement('img');
		news_detail_closer.setAttribute('src', 'images/cancel.gif');
		news_detail_closer.setAttribute('id', 'news_detail_closer');
		news_detail.appendChild(news_detail_closer);
		news_detail_closer.onclick = function(){closeDetail()};
		Element.setStyle('news_detail_closer',{
			'position':'absolute',
			'right':'30px',
			'top':'15px',
			'height':'14px',
			'display': 'none',
			'cursor':'pointer'
		});
				
		Effect.Appear(custom_overlay,{from:0.0, to:0.5,afterFinish:openNews = function()
		{
			catchHtmlViaAjax(el.href,news_detail_container,type);
			
			Effect.Appear(news_detail,{afterFinish: ciao=function()
			{
				Effect.Appear(news_detail_closer);
	
			}});
	
			
		}});

	}
	catch(e){alert(e.toString());}
}



function catchHtmlViaAjax(url,elem,type)
{
	

	new Ajax.Request(url, {
	  method: 'get',
	  onSuccess: function(transport) 
	  {		
			//scrivo dentro elem il transport text
			//alert(transport.responseText);
		   $(elem).innerHTML='<div style="text-align:center;margin-bottom:12px;"><img src="images/logo_ajax.gif"></div>';
		    $(elem).innerHTML += transport.responseText;

		   
	  },
	  
	onFailure: function()
	{
		$(elem).innerHTML = 'Notizia non piu\' presente in archivio.';		
	}
	});
}


function closeDetail()
{
	Effect.Fade('news_detail',{duration: 0.5,afterFinish: ciao=function()
		{
			Effect.Fade('custom_overlay',{duration: 0.4,afterFinish: remove=function(){
				Element.remove('news_detail');
	Element.remove('custom_overlay');
			}});
		}});
}







// Richiamo delle funzioni precedenti in un unica funzione
function allFunctions() {
	
	var loading = document.getElementById('page_loading');		
	var main = document.getElementById('main');
	main.style.visibility="hidden";	
	
	preloadIMG();
	collapseMenu();
	prepareMenu();
	mainHeight();
	if($('news_in')) initScroller('news_in');
//	attachSwitch();
//	startMenu();
	if(navigator.userAgent.match('MSIE')) correctPNG();

	var loading_page = document.getElementById('page_loading');
	loading_page.style.display = 'none';
	main.style.visibility="visible";
}