var destinationNames;

document.observe("dom:loaded" , function() {
	// Le due funzioni seguenti non si devono attivare nella Home
	// dove mancano i DIV necessari ad applicarle
	if ($('centermenu_container')!=null ) {
		new setTabbedBoxPadding('content', 'centerbox_body');
	}
	
	if ($('sidebar')!=null) {
		new setTabbedBoxPadding('sidebar', 'rightbox_body');
		
		if ($('top_banner')!=null) {
			new setSideTop('sidebar', 104);
		}
	}
	
	if ($('sidecolumn')!=null) {
		if ($('top_banner')!=null) {
			new setSideTop('sidecolumn', 98);
		}
	}
	
});


Event.observe(window, 'load' , function() {
	//Da utilizzare quando si usa il campo select per le destinazioni
	//destinationNames = destinations.keys(); //Destinations è definito tramite PHP
	
	//Da attivare quando si utilizza il campo input con autocompleter	
	//new Autocompleter.Local("destinationName" , "destinationChoices" , destinationNames, {afterUpdateElement: getSelectionId});
	new Ajax.Autocompleter('destinationName', 'destinationChoices', '/index.php', {
		method: 'get',
		parameters: 'eID=user_emgoing_pi1&action=autocompleterDestinations',
		minChars: 3,
		indicator: 'topIconsMessages',
		//select: 'destName',
		afterUpdateElement: getSelectionId
	});
	
	new removeBlankClass('insertDestination', hInputValues);
	
	//Visualizziamo tutti i bannerbox più alti di 50 px
	$$('#top_banner .bannerbox').each(function(s) {
	  top_banner_height = s.getHeight();
	  if (top_banner_height > 50) {
	    s.show();
	    new setSideTop('sidebar', (top_banner_height-30) );
	    new setSideTop('sidecolumn', (top_banner_height-35) );
	  }
	});
	$$('#left_banner .bannerbox').each(function(s) { if (s.getHeight() > 50) s.show(); });
	$$('#right_banner .bannerbox').each(function(s) { if (s.getHeight() > 50) s.show(); });
	
});


function getSelectionId(input, li) {
	
	selectedValue = li.innerHTML.stripTags();
	if ($('destinationName').value != selectedValue) {
		$('destinationName').value = selectedValue;
	}
	
	//alert(li.id.split("-")[1]);
	// Dobbiamo splittare l'id del li selezionato
	// perchè è composto da destination-[id]
	idValue = li.id.split("-")[1];
    
    if (typeof(idValue)=='undefined') {
    	$('destination').value = '';
    } else {
    	$('destination').value = idValue;
    }
    
    return idValue;
}


var setTabbedBoxPadding = function(containerBox, classBox ) {
	boxBody = $(containerBox).getElementsByClassName(classBox)[0];
	glowingTabs = $(containerBox).getElementsByClassName('glowingtabs')[0];
	height = glowingTabs.getHeight() - 4;
	if (containerBox=='sidebar') {
		height = glowingTabs.getHeight() - 34;
	}
	// Se siamo nel box centrale
	// E sono presenti i tab grandi, rimuoviamo da height una porzione di 28px
	bigGlowingTabs = $(containerBox).getElementsByClassName('bigGlowingtabs')[0];
	if (bigGlowingTabs) {
		height = height /*- 6*/;
		$('content').setStyle({
			top: '38px'
		});
	}
	boxBody.setStyle({
		paddingTop: height + 'px'
	});
}


var setSideTop = function(element, sideActualTop) {
	headerTopPosition = $('header').positionedOffset()[1];
	if ($('top_banner').empty()==true) {
		topPad = 0;
	} else {
		topPad = 10;
	}
	//sideActualTop = parseInt( $(element).getStyle('top') );
	sideTop = headerTopPosition + sideActualTop + topPad;
	
	$(element).setStyle({
		top: sideTop + 'px'
	});

}


var toggleBoxTabs = function(showLink, menuContainer, containerBox) {
	var linkName = showLink.id;
	var basename = linkName.split('-')[1];
	var contentName = 'div-' + basename;
	var contentHeight = $(contentName).getHeight();
	var activeLink = $(menuContainer).down('li.current');
	var activeDiv = $(containerBox).down('div.current');
	var activeDivHeight = activeDiv.getHeight();

	var contentBox = $(containerBox).down(0);
	var paddingBottomHeight = 30;
	//var viewportDiff = Position.page($(containerBox))[1] + paddingBottomHeight;
	var containerHeight = $(containerBox).getHeight();
	var containerPositionedOffset = Position.positionedOffset( $(containerBox) );
	var containerSetHeight = contentHeight+10;
	
	if ( $(contentName) != activeDiv) {
		
		//Impostiamo il cookie che ricorda il tab attualmente aperto
		setCookie('currentTab', basename);
	
		//Remove current from active link
		//activeLink.removeClassName('current');
		$(activeLink).removeClassName('current');
		activeDiv.removeClassName('current');
		new Effect.Fade(activeDiv, { delay:0.1, duration:0.3 });
	
		new Effect.Morph(containerBox, {
				delay:0.3,
				duration: 0.5,
				style: 'height:' + containerSetHeight + 'px',
				afterFinish: function() {
					contentBox.setStyle({top: '0px'});
				}
		});
	
		// Add current to selected link
		$(showLink).up('li').addClassName('current');
		$(contentName).addClassName('current');
		new Effect.Appear($(contentName), {
			delay: 0.8,
			duration: 0.5,
			afterFinish: function() {
				//Il codice seguente va attivato se la mappa non è il primo tab visualizzato
				// quando si entra in un comune
				if (basename=='mappa') {
					mapInitialize();
				}
			}
					
		});
	}
	
}


function getWindowHeight() {
	var windowHeight=0;
	if (typeof(window.innerHeight)=='number') {
		windowHeight=window.innerHeight;
	} else {
		if (document.documentElement && document.documentElement.clientHeight) {
			windowHeight=
			document.documentElement.clientHeight;
		} else {
			if (document.body&&document.body.clientHeight) {
				windowHeight=document.body.clientHeight;
			}
		}
	}
	return windowHeight;
}

var blurTextboxes = function(element, defValue) {
	if (element.value.match(/^ *$/)) {
		element.value=defValue;
		$(element).addClassName('blank');
	}
}

var focusTextboxes = function(element, defValue) {
	if (element.value == defValue) {
		element.value='';
		$(element).removeClassName('blank');
	}
}


var removeBlankClass = function(form, hashInputValues) {
	form = $(form);
	aFormInputsform = form.getElements();
	aFormInputsform.each(function(field) {
		var sFieldValue = field.value;
		var sFieldName = field.name;
		//alert(sFieldValue);
		//alert(sFieldName);
		if (sFieldValue != eval('hashInputValues.get(\'' + sFieldName + '\')')) {
			$(sFieldName).removeClassName('blank');
		}
		
		if (sFieldValue == '') {
			$(sFieldName).value = eval('hashInputValues.get(\'' + sFieldName + '\')');
			$(sFieldName).addClassName('blank');
		}
	});
}

function loadURL(id, params) {
	returnedParams = id.split(',')
	if (returnedParams[0] != '') {
		urlString = '/index.php?id=' + returnedParams[0] + '&no_cache=1&user_emgoing_pi1[redirect]=1';
		if (returnedParams[1]) {
			urlString = urlString + '&L=' + returnedParams[1];
		}
		
		location.href = urlString
	}
}

function loadServiceImageURL(idDestination, dok) {
	$('topIconsMessages').show();
	//Check before if a location is actually selected!!!
	//var idDestination = $('destination').options[$('destination').selectedIndex].value;
	//var idDestination = $('destination').value;
	if (idDestination != 'undefined' && idDestination != '') {
		//Ajax request to see ID for clicked service for the current location!
		new Ajax.Request(
			'/index.php', {
				method: 'get',
				parameters: {
					eID: 'user_emgoing_pi1',
					doktype: dok,
					destId: idDestination
				},
				onSuccess: function(transport) {
					var notice = $('topIconsMessages');
					/*notice.update(transport.responseText);
					$('topIconsMessages').setStyle({
						backgroundImage: 'none'
					});*/
					if ( isNaN(transport.responseText) ) {
						$('topIconsMessages').setStyle({
							backgroundImage: 'none'
						});
						//$('topIconsMessages').update('Questo servizio non è disponibile per la destinazione scelta');
						$('topIconsMessages').update(serviceNotAvailableForDestination);
					} else {
						loadURL(transport.responseText);
					}
					
				}
			}
		);
	} else {
		$('topIconsMessages').setStyle({
			backgroundImage: 'none',
			left: '10px',
			top: '-80px'
		});
		// Messaggio da mostrare quando funzionerà l'autocompleter per li campo destinazione
		//$('topIconsMessages').update('La destinazione scelta non esiste nel nostro Database');
		//$('topIconsMessages').update(nonExistingDestination);
		// Messaggio das mostrare quando è presente il campo select per la destinazione
		//$('topIconsMessages').update('&Egrave; necessario scegliere una destinazione');
		$('topIconsMessages').update(hInputValues.get('destinationName'));
	}
}

function validateSearchList() {
	//alert($F('sword'));
	if ( $F('sword').length < 3) {
		$('topIconsMessages').show();
		$('topIconsMessages').setStyle({
			backgroundImage: 'none'
		});
		$('topIconsMessages').update(searchListMinChars);
		return false;
	} else {
		$('topIconsMessages').show();
		return true;
	}
}

var displayImageService = function(icon) {
	var icon = $(icon);
	$('displayImageService').update(icon.down(0).readAttribute('title'));
	$('displayImageService').show();
}

var hideImageMessages = function() {
	$('displayImageService').hide();
	$('topIconsMessages').update('');
	$('topIconsMessages').hide();
	$('topIconsMessages').setStyle({ backgroundImage: 'url(fileadmin/templates/main/css/images/loading.gif)'});
}


function goToSelectedDestination() {
	// Se l'id non esiste e non è ricavabile, mostriamo un messagio di errore
	// forse nello stesso campo usato per i messaggi delle topIcons
	//alert($F('destinationName'));
	//alert($F('destination'));
	if ( $F('destinationName')=='' || $F('destinationName') == hInputValues.get('destinationName') ) {
		loadServiceImageURL('');
	} 
	
	// Se i campi suindicati sono compilati correttamente, ma il campo 'destination' è ancora vuoto
	// vuol dire che probabilmente il campo destinationName non è stato scelto tramite autocompleter,
	// ma è stato inserito direttamente a mano.
	// quindi cerchiamo tramite ajax una corrispondenza tra il nome inserito ed il suo id, per decidere se continuare la ricerca
	else {
	//else if ( $F('destination')=='' || $F('destination') == 'undefined' ) {
		//Ajax request to see ID for clicked service for the current location!
		new Ajax.Request(
			'/index.php', {
				method: 'get',
				parameters: {
					eID: 'user_emgoing_pi1',
					action: 'getDestinationId',
					destinationName: $F('destinationName')
				},
				onSuccess: function(transport) {
					if ( isNaN(transport.responseText) ) {
						loadServiceImageURL('');
					} else {
						deleteCookie('currentTab');
						loadURL(transport.responseText);
					}
					
				},
				onFailure: function() { loadServiceImageURL(''); }
			}
		);
		
		//deleteCookie('currentTab');
		// ... e carichiamo la pagina del comune
		//loadURL($F('destination'));
	}
	
	//Se l'id esiste ...
	// ... cancelliamo il cookie che ricorda il tab menù di destra aperto
	/*else {
		//Tramite una chiamata Ajax, verifichiamo se il nome inserito nel campo input "destinationName"
		// corrisponde al campo nascosto "destination"
		
		
		
		
		deleteCookie('currentTab');
		// ... e carichiamo la pagina del comune
		loadURL($F('destination'));
	}*/
			
}

var myrules = {
	'#destinationName' : function(el){
		el.onblur = function(){	blurTextboxes( this, hInputValues.get('destinationName') ); },
		el.onfocus = function(){ focusTextboxes( this, hInputValues.get('destinationName') ); }
	},
	'#destinationSubmit' : function(el){
		el.onclick = function(){ goToSelectedDestination(); return false; }
	},
	'#insertDestination' : function(el){
		el.onsubmit = function(){ goToSelectedDestination(); return false; }
	},
	/*'#destination' : function(el){
		el.onchange = function(){ 
			// Cancelliamo il cookie che ricorda il tab menù di destra aperto
			deleteCookie('currentTab');
			loadURL(this.options[this.selectedIndex].value);
		}
	},*/
	'#icon_trasporti' : function(el){
		el.onmouseover = function(){ displayImageService(this) },
		el.onmouseout = function() { hideImageMessages() },
		el.onclick = function(){ loadServiceImageURL($F('destination'), 101); return false; }
	},
	'#icon_dormire' : function(el){
		el.onmouseover = function(){ displayImageService(this) },
		el.onmouseout = function() { hideImageMessages() },
		el.onclick = function(){ loadServiceImageURL($F('destination'), 102); return false; }
	},
	'#icon_mangiare' : function(el){
		el.onmouseover = function(){ displayImageService(this) },
		el.onmouseout = function() { hideImageMessages() },
		el.onclick = function(){ loadServiceImageURL($F('destination'), 103); return false; }
	},
	'#icon_turismo' : function(el){
		el.onmouseover = function(){ displayImageService(this) },
		el.onmouseout = function() { hideImageMessages() },
		el.onclick = function(){ loadServiceImageURL($F('destination'), 104); return false; }
	},
	'#icon_ambiente' : function(el){
		el.onmouseover = function(){ displayImageService(this) },
		el.onmouseout = function() { hideImageMessages() },
		el.onclick = function(){ loadServiceImageURL($F('destination'), 105); return false; }
	},
	'#icon_educazione' : function(el){
		el.onmouseover = function(){ displayImageService(this) },
		el.onmouseout = function() { hideImageMessages() },
		el.onclick = function(){ loadServiceImageURL($F('destination'), 106); return false; }
	},
	'#icon_tempo_libero' : function(el){
		el.onmouseover = function(){ displayImageService(this) },
		el.onmouseout = function() { hideImageMessages() },
		el.onclick = function(){ loadServiceImageURL($F('destination'), 107); return false; }
	},
	'#icon_servizi_istituzioni' : function(el){
		el.onmouseover = function(){ displayImageService(this) },
		el.onmouseout = function() { hideImageMessages() },
		el.onclick = function(){ loadServiceImageURL($F('destination'), 108); return false; }
	},
	
	
	//Stessa funzionalità delle Top Icons, ma nel menù di sinistra in Home Page
	'#icon_trasporti2' : function(el){
		el.onclick = function(){ loadServiceImageURL($F('destination'), 101); return false; }
	},
	'#icon_dormire2' : function(el){
		el.onclick = function(){ loadServiceImageURL($F('destination'), 102); return false; }
	},
	'#icon_mangiare2' : function(el){
		el.onclick = function(){ loadServiceImageURL($F('destination'), 103); return false; }
	},
	'#icon_turismo2' : function(el){
		el.onclick = function(){ loadServiceImageURL($F('destination'), 104); return false; }
	},
	'#icon_ambiente2' : function(el){
		el.onclick = function(){ loadServiceImageURL($F('destination'), 105); return false; }
	},
	'#icon_educazione2' : function(el){
		el.onclick = function(){ loadServiceImageURL($F('destination'), 106); return false; }
	},
	'#icon_tempo_libero2' : function(el){
		el.onclick = function(){ loadServiceImageURL($F('destination'), 107); return false; }
	},
	'#icon_servizi_istituzioni2' : function(el){
		el.onclick = function(){ loadServiceImageURL($F('destination'), 108); return false; }
	},
	
	
	'#topIconsMessages' : function(el) {
		el.onmouseover = function() { $('topIconsMessages').hide() },
		el.onmouseout = function() { $('topIconsMessages').hide() }
	},
	'#link-numeri_utili' : function(el) {
		el.onclick = function() { new toggleBoxTabs(this, 'rightmenu_container', 'rightcontent_container'); return false; },
		el.onfocus = function() { this.blur() }
		//el.onmouseover = function() { toggleRightTabs(this) }
	},
	'#link-news' : function(el) {
		el.onclick = function() { new toggleBoxTabs(this, 'rightmenu_container', 'rightcontent_container'); return false; },
		el.onfocus = function() { this.blur() }
		//el.onmouseover = function() { toggleRightTabs(this) }
	},
	'#link-eventi' : function(el) {
		el.onclick = function() { new toggleBoxTabs(this, 'rightmenu_container', 'rightcontent_container'); return false; },
		el.onfocus = function() { this.blur() }
		//el.onmouseover = function() { toggleRightTabs(this) }
	},
	'#link-meteo' : function(el) {
		el.onclick = function() { new toggleBoxTabs(this, 'rightmenu_container', 'rightcontent_container'); return false;},
		el.onfocus = function() { this.blur() }
		//el.onmouseover = function() { toggleRightTabs(this) }
	},
	'#link-cinema' : function(el) {
		el.onclick = function() { new toggleBoxTabs(this, 'rightmenu_container', 'rightcontent_container'); return false; },
		el.onfocus = function() { this.blur() }
		//el.onmouseover = function() { toggleRightTabs(this) }
	},
	'#link-links' : function(el) {
		el.onclick = function() { new toggleBoxTabs(this, 'rightmenu_container', 'rightcontent_container'); return false; },
		el.onfocus = function() { this.blur() }
		//el.onmouseover = function() { toggleRightTabs(this) }
	},
	'#link-mappaRegioni' : function(el) {
		el.onclick = function() { new toggleBoxTabs(this, 'rightmenu_container', 'rightcontent_container'); return false; },
		el.onfocus = function() { this.blur() }
		//el.onmouseover = function() { toggleRightTabs(this) }
	},
	'#link-mappa' : function(el) {
		el.onclick = function() { new toggleBoxTabs(this, 'rightmenu_container', 'rightcontent_container'); return false; },
		el.onfocus = function() { this.blur() }
		//el.onmouseover = function() { toggleRightTabs(this) }
	},
	'#link-itinerario' : function(el) {
		el.onclick = function() { new toggleBoxTabs(this, 'rightmenu_container', 'rightcontent_container'); return false; },
		el.onfocus = function() { this.blur() }
		//el.onmouseover = function() { toggleRightTabs(this) }
	},
	'#fromAddress' : function(el){
		el.onblur = function(){	blurTextboxes( this, hFromValue.get('fromAddress') ); },
		el.onfocus = function(){ focusTextboxes( this, hFromValue.get('fromAddress') ); }
	},
	'#sword' : function(el){
		el.onfocus = function(){ hideImageMessages(); }
	}
	
};
	
Behaviour.register(myrules);
