/*BOF randomizzazione*/

(function($){

	$.fn.shuffle = function() {
		return this.each(function(){
			var items = $(this).children();
			return (items.length) ? $(this).html($.shuffle(items)) : this;
		});
	}
	
	$.shuffle = function(arr) {
		for(var j, x, i = arr.length; i; j = parseInt(Math.random() * i), x = arr[--i], arr[i] = arr[j], arr[j] = x);
		return arr;
	}
})(jQuery);

/*EOF randomizzazione*/


/*BOF FORM CONTATTI*/

function HasNoValue(string)
{
	if(string==null || string == undefined || string == '')
	return true;
	else return false;
}


function validateFormElement(elem)
{
	if(elem==null) return true;
	if(HasNoValue(elem.attr('value')))
	{
		errorOnFormElement(elem);
		return true;
	}
	else 
	{
		elem.css({'background':'#ffffff'});
		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(HasNoValue(elem.attr('checked')))
	{
		errorOnFormElement(elem.parent());			
		return true;
	}
	else
	{
		elem.css({'background':'#ffffff'});
		return false;
	}
}

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

function errorOnFormElement(elem)
{
//	alert(elem);

	elem.css({'position':'relative'});
	elem.css({'background':'#ffee5b'});
	elem.animate({left: '-10'},120).animate({left: '+10'},120).animate({left: '-10'},120).animate({left: '0'},120);
	
}

function showOnClick(element)
{
	if(element == 'frm_dettagli_richiesta')
	{		
		$j('#'+element).slideToggle('slow');
		if($j('#frm_dettagli_preventivo:visible')) $j('#frm_dettagli_preventivo').slideToggle('slow');
		document.forms['guestbooksign'].frm_tipo_richiesta.value = 'richiesta informazioni';

	}
	else
	{

		$j('#'+element).slideToggle('slow');
		if($j('#frm_dettagli_richiesta:visible')) $j('#frm_dettagli_richiesta').slideToggle('slow');
		document.forms['guestbooksign'].frm_tipo_richiesta.value = 'richiesta preventivo';

	}

}

function submitGuestBook()
{
	var d = new Date()
	param = d.getTime();
		
	var form = $j('#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;	
	}
*/

//inizio validazione
	var error_found = 0;
	
	if(validateFormElement($j('#frm_nome'))) error_found++;
	if(validateFormEmail($j('#frm_email'))) error_found++;
	if(validateFormElement($j('#frm_telefono'))) error_found++;
	//if(validateFormElement($j('#frm_citta'))) error_found++;
	if(validateFormElement($j('#frm_numero_adulti'))) error_found++;
	if(validateFormElement($j('#frm_tipologia_albergo'))) error_found++;
	if(validateFormElement($j('#frm_mezzo_trasporto'))) error_found++;	
	
	if(validateFormElement($j('#frm_data_arrivo_calendar'))) error_found++
	if(validateFormElement($j('#frm_data_partenza_calendar'))) error_found++
	
	
	if(validateCheckBoxElement($j('#frm_privacy'))) error_found++;
//alert(error_found);
	if(error_found==0)
	{
			
			document.getElementById("guestbooksign").action = "email.php";
			document.getElementById("guestbooksign").submit();
	
	}	
}
/*EOF FORM CONTATTI*/

//	inizio funzioni di debug
debug_msg = false;
function toDebug(string)
{
	if (debug_msg)
	{
		if((typeof window.console=="undefined")) {alert(string);}
		else {
			console.error();
			console.group(string);
			console.trace();
			console.groupEnd();
		}
	}
}
function toConsole(string)
{
	if((typeof window.console=="undefined")) {alert(string);}
	else console.log(string);
}
//	fine funzioni di debug
//--------------------------------------------------------------------
function mainHeight()
{
try
{
	var main = $('#main');
	var head = $('#head');
	var container = $('#container');
	var colonnaSx = $('#colonnaSx');
	var contenuto = $('#contenuto');
	var colonnaDx = $('#colonnaDx');
	var footer = $('#footer');
	var box_height = Math.max(colonnaSx.height(),Math.max(contenuto.height(),colonnaDx.height()));
	var page_dimensions = getPageSize();
	var total_height;
	if(box_height < 700) box_height = 700;
	container.css({'top':head.height()+'px'});
	//container.height(box_height+13+35);
	container.height(box_height+113+35);
	colonnaSx.height(box_height);
	contenuto.height(box_height);
	colonnaDx.height(box_height);
	total_height = head.height() + box_height + footer.height();
	//footer.css({'top':total_height-footer.height() +50 + 35 +'px'});
	footer.css({'top':total_height-footer.height() +150 + 35 +'px'});		// fix
	main.height(total_height);
	/* margino le immagini in float */
	if(document.getElementById('contenuto'))
	{
		var array_img = document.getElementById('contenuto').getElementsByTagName('IMG');
		for(var i=0;i<array_img.length;i++)
		{
			if($j(array_img[i]).attr('style').match('float:left') || $j(array_img[i]).attr('style').match('float: left')) {array_img[i].style.marginRight = '10px';}
			else if($j(array_img[i]).attr('style').match('float:right') || $j(array_img[i]).attr('style').match('float: right')) {array_img[i].style.marginLeft = '10px';}
		}

	}
	//overMenu();

}
catch(e) {toDebug(e);}
}
//--------------------------------------------------------------------
//	inizio funzioni di scroll
var moving = false;
var timer;
var top = 0;
function scrollGallery()
{
try
{
	var freccia_su = $('div.freccia-su');
	var freccia_giu = $('div.freccia-giu');
	linkImages();
	freccia_su.hover(function(){scrollUp();},function(){moving = false;clearTimeout(timer);});
	freccia_giu.hover(function(){scrollDown()},function(){moving = false;clearTimeout(timer);});
}
catch(e) {toDebug(e);}
}

function scrollUp()
{
	var gallery = $('#miniature');
	if(gallery.offset().top >= 298) return false;
	moving = true;
	top +=5;
	gallery.animate({ 
		top:top
      }, 10 );
	if(moving) timer = setTimeout(scrollUp,10);
	else return false;
}

function scrollDown()
{
	var gallery = $('#miniature');
	if(gallery.offset().top < -(gallery.height()-710)){return false;}
	moving = true;
	top -=5;
	gallery.animate({ 
		top:top
      }, 10 );
	if(moving) timer = setTimeout(scrollDown,10);
	else return false;	
}
function linkImages()
{
try
{
	var link_array = $('#miniature a');
	link_array.click(function()
	{ 
		$('#big-image').attr('src',this.href);
		return false;
	 });
}
catch(e) {toDebug(e);}
}

//	fine funzioni di scroll
//--------------------------------------------------------------------

function overMenu() {
	var link_array = $('#menu a');
	link_array.hover(function()
	{
		$(this).animate(
		{
			paddingLeft: 42
		}, 500);
		$(this).css({'background':'url("images/background/menu-on.gif") no-repeat left top;', 'color':'#ffffff;'});
	},
	function()
	{
		if(!$(this).hasClass('active'))
		{
			$(this).animate(
			{
				paddingLeft: 31
			}, 500);
			$(this).css({'background':'url("images/background/menu-off.gif") no-repeat left top;', 'color':'#906c3e;'});
		}
	});
}

//--------------------------------------------------------------------
// inizio funzioni per prendere dimensioni finetra
function getPageSize() 
{
	var xScroll, yScroll;
	if (window.innerHeight && window.scrollMaxY) {	
		xScroll = window.innerWidth + window.scrollMaxX;
		yScroll = window.innerHeight + window.scrollMaxY;
	} else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
		xScroll = document.body.scrollWidth;
		yScroll = document.body.scrollHeight;
	} else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
		xScroll = document.body.offsetWidth;
		yScroll = document.body.offsetHeight;
	}
	var windowWidth, windowHeight;
	if (self.innerHeight) {	// all except Explorer
		if(document.documentElement.clientWidth){
			windowWidth = document.documentElement.clientWidth; 
		} else {
			windowWidth = self.innerWidth;
		}
		windowHeight = self.innerHeight;
	} else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
		windowWidth = document.documentElement.clientWidth;
		windowHeight = document.documentElement.clientHeight;
	} else if (document.body) { // other Explorers
		windowWidth = document.body.clientWidth;
		windowHeight = document.body.clientHeight;
	}	
	// for small pages with total height less then height of the viewport
	if(yScroll < windowHeight){
		pageHeight = windowHeight;
	} else { 
		pageHeight = yScroll;
	}
	// for small pages with total width less then width of the viewport
	if(xScroll < windowWidth){	
		pageWidth = xScroll;		
	} else {
		pageWidth = windowWidth;
	}
	arrayPageSize = new Array(pageWidth,pageHeight,windowWidth,windowHeight) 
	return arrayPageSize;
};

function getPageScroll() 
{
	var xScroll, yScroll;
	if (self.pageYOffset) {
		yScroll = self.pageYOffset;
		xScroll = self.pageXOffset;
	} else if (document.documentElement && document.documentElement.scrollTop) {	 // Explorer 6 Strict
		yScroll = document.documentElement.scrollTop;
		xScroll = document.documentElement.scrollLeft;
	} else if (document.body) {// all other Explorers
		yScroll = document.body.scrollTop;
		xScroll = document.body.scrollLeft;	
	}
	arrayPageScroll = new Array(xScroll,yScroll) 
	return arrayPageScroll;
};
// fine funzioni per prendere dimensioni finetra
//--------------------------------------------------------------------
function showNewsletter()
{
try
{
	var overlay = $('#my_overlay');
	var box = $('#box-newsletter');
	var overlay_height  = getPageSize();
	var page_scroll  = getPageScroll();
	overlay.css({'height': overlay_height[1], 'opacity':'0'});
	box.css({'top':page_scroll[1]});
	overlay.one("click", function(){
		hideNewsletter();
	});
	overlay.show();
	overlay.fadeTo('slow',0.5,function(){box.slideToggle('slow');});
}
catch(e) {toDebug(e);}
}
function hideNewsletter()
{
try
{
	var overlay = $('#my_overlay');
	var box = $('#box-newsletter');
	box.slideToggle('fast',function(){overlay.fadeOut('fast');});
}
catch(e) {toDebug(e);}
}
//--------------------------------------------------------------------
function $j(argument)
{
	var result = jQuery(argument);
	if (result.length == 0) return null;
	else return result;
}
// esecuizione delle funzioni a caricamento effettuato
$(document).ready(function()
{		
	if ($j('.rotate_child'))
   	{
	   	$('.rotate_child').shuffle();
	   	if($j('.input-date')){ $('.input-date').each(function(){ $(this).datepicker({showButtonPanel: true,numberOfMonths: 3,dateFormat: 'dd/mm/yy'}); }); }
		
		$("#frm_data_arrivo_calendar").change(
		function(){
			date1 = $("#frm_data_arrivo_calendar").datepicker( 'getDate' );
			// devo controllare che la data sia valida
			check = false;
			dateCheck = date1;
			date2 = new Date(dateCheck);						
			$("#frm_data_partenza_calendar").datepicker('option', 'minDate',date2);
		}
	);

   	}	
		
	if ($j('#wrapper_form')) $('#wrapper_form').formSubmitter();
	
	$('#loader').css({'opacity':'0.8'});
	mainHeight();
//	scrollGallery();
	
	/*inizio lightbox init*/
	$(function() 
	{
		$('a[rel*=lightbox]').lightBox(); 
	});
	/*fine lightbox init*/
	
	$('#loader').hide();
	
	
	//funzioni di onclick sulle vetrine
	if ($j('#vetrine .box'))
	{
		
		var track_prefix = $('body').attr('track_prefix');
		
		$('#vetrine .box').bind('click',function(){
					
			var href = $('a',this).attr('href');						
			var nome=$('h4',this).text();

			var url_to_register = '/click-away' + track_prefix + '/' + nome;
			
			//toConsole(url_to_register);	
			pageTracker._trackPageview(url_to_register);			
			
			window.open(href);
			
			return false;
			
		});
	}
	
});


function cambia_bambini(n) {
	frm = document.getElementById("form_ins");
	camere = 1;	//parseInt(document.getElementById("numRooms").value);
	if (n>4) n=4;
	if ((n>0)&&(camere==1))
	{
		var contenuto = "";
		var name = "";
		for (i=1; i<=n; i++){
			name="childAge["+i+"]";
			contenuto += "<select name='"+name+"' id='"+name+"'><option value='-1'>-?-</option><option value='0'>&lt;1</option><option>1</option><option>2</option><option>3</option><option>4</option><option>5</option><option>6</option><option>7</option><option>8</option><option>9</option><option>10</option><option>11</option><option>12</option></select>";
		}
		document.getElementById("bam_div").innerHTML=contenuto+"&nbsp;";
		document.getElementById("bam_div").style.visibility = "visible";
		document.getElementById("bam_div").style.display = "block";
		document.getElementById("bam_div1").style.visibility = "visible";
		document.getElementById("bam_div1").style.display = "block";
	} else {
		document.getElementById("bam_div").style.visibility = "hidden";
		document.getElementById("bam_div").style.display = "none";
		document.getElementById("bam_div1").style.visibility = "hidden";
		document.getElementById("bam_div1").style.display = "none";
	}

}

