

///////////////////////////////////////////

function resetType(id, status){
	if(status == undefined) status = "";
	if (document.getElementById(id)){
		var obj = document.getElementById(id);
		if (id == "Nome"){
			if(obj.value == varName && status == "") {
				obj.value="";
			} else if(obj.value=="" && status == "x") {
				obj.value=varName;
			}
		} else if (id == "num_tel") {
			if(obj.value == varPhone && status == "") {
				obj.value="";
			} else if(obj.value=="" && status == "x") {
				obj.value=varPhone;
			}
		}
	}
}

function checkCallback(){
	var testo_err = varCallError+'\n\n';
	var mancato_ins = false;	
	if (document.forms['callback']['Nome'].value == varName || document.forms['callback']['Nome'].value == "") {
		testo_err = testo_err + '- '+ varName +'\n';
		document.forms['callback']['Nome'].focus();
		mancato_ins = true;
	} else {
		if(!checkValue(document.forms['callBack']['Nome'].value, "text")){
			testo_err = testo_err + '- '+ varName +'\n';
			document.forms['callback']['Nome'].value = "";
			document.forms['callback']['Nome'].focus();
			mancato_ins = true;
		}
	}
	if (document.forms['callback']['num_tel'].value == varPhone || document.forms['callback']['num_tel'].value == "") {
		testo_err = testo_err + '- '+ varPhone +'\n';
		document.forms['callback']['num_tel'].focus();
		mancato_ins = true; 
	} else {
		if(!checkValue(document.forms['callback']['num_tel'].value, "number")){
			testo_err = testo_err + '- '+ varPhone +'\n';
			document.forms['callback']['num_tel'].value = "";
			document.forms['callback']['num_tel'].focus();
			mancato_ins = true;
		}
	}
	if (document.forms['callback']['indirizzo_posta'].value == varEmail || document.forms['callback']['indirizzo_posta'].value == "") {
		testo_err = testo_err + '- '+ varEmail +'\n';
		document.forms['callback']['indirizzo_posta'].focus();
		mancato_ins = true; 
	} else {
		if(!checkValue(document.forms['callback']['indirizzo_posta'].value, "mail")){
			testo_err = testo_err + '- '+ varEmail +'\n';
			document.forms['callback']['indirizzo_posta'].value = "";
			document.forms['callback']['indirizzo_posta'].focus();
			mancato_ins = true;
		}
	}
	if (mancato_ins == true) {
		alert (''+testo_err+'');
		return false;
	} else {
		return true;
	}
}

function checkValue(string, type){
	if(type == undefined || type == "number"){
		var validi = "0123456789";
		var myNumberNew = string;
		myNumberNew = myNumberNew.replace(/\ /g, "");
		myNumberNew = myNumberNew.replace(/\+/g, "");
		myNumberNew = myNumberNew.replace(/\./g, "");
		myNumberNew = myNumberNew.replace(/\-/g, "");
		if(myNumberNew == ''){
			return false;
		}
		for(var i = 0; i < myNumberNew.length; i++ ){
			if( validi.indexOf( myNumberNew.charAt(i) ) == -1 ){
				return false;
			}
		}
	} else if(type == "mail") {
		if (string.length > 9){
			var filter = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
			if (!filter.test(string)) {
				return false;
			}
		} else {
			return false;
		}
	} else if(type == "text") {
		var filter = /^([a-zA-Z\ \'])/;
		if (!filter.test(string)) {
			return false;
		}
	}
	return true;
}


/*******************************************************    */

function equalColumns(){
	
	var myCol1 = $('#box_left_home').outerHeight()-146;
	var myCol2 = $('#box_center').outerHeight();
	
	//console.log('1:'+myCol1+'  2:'+myCol2);
	
	if(myCol1 < myCol2) {
		$('#box_left_minisite').css('height',(myCol2+146)+'px');	
	}
}

function goToUrl(url) {
	location.href=url;
}

/******************************************************* BOX OFFERTE HOMEPAGE */


function newsInit() {
	//alert("aaaa");
	
	list = $('#boxOffersList > li');
	//console.log('>>> '+list.length);
	if(list.length > 2) {
		setInterval ( "newsScroll()", 7000 );
	}
}

function newsScroll() {
				

				$('#boxOffersList > li:first').animate(			
					{opacity:0,
					marginTop: '-75px'
					},
					700,
					'',
					function(){
						$(this).remove().insertAfter('#boxOffersList > li:last');
						$('#boxOffersList > li').removeAttr('style');
					});	

}

function scrollOffers(item) {
	var item = $(item);
	if (item.children().length > 4) {
		item.children(':first').animate(
			{opacity:0,
			marginTop: item.children(':first').outerHeight(true)*-1
			},
			500,
			'',
			function(){
				$(this).remove().insertAfter(item.children(':last'));
				item.children().removeAttr('style');
			}
		);
	}
}

function setRoomHome(nrooms, label_adults, label_children, label_children_age, label_room) {
	var myResults = '';
	
	if (nrooms > 1)	// se viene scelta pił di una camera...
	{
		for (var i=2; i<=nrooms; i++)	// preparo la stringa da accodare alla prima camera, contenente i campi necessari
		{
			myResults = myResults + '<li class="room'+ i +' roomTitle">'+ label_room +' '+ i +':</li>';
			
			myResults = myResults +	'<li class="room'+ i +' adults">'+
										'<label>'+ label_adults +'</label>'+
										'<select name="bform[reqRooms]['+ i +'][adults]">'+
											createSelect(4, 1, label_adults, "", 2)+
										'</select>'+
									'</li>'+
									'<li class="room'+ i +' children">'+
										'<label>'+ label_children +'</label>'+
										'<select name="bform[reqRooms]['+ i +'][child]" onchange="setChildAge(this.value,\'chdAge_'+ i +'\', '+ i +',\''+ label_children_age +'\');">'+
											createSelect(3, 0, label_children, "", 0)+
										'</select>'+
									'</li>'+
									'<li class="room'+ i +' childAge" id="chdAge_'+ i +'"></li>';
		}
		
		$('li.room1.roomTitle').remove();				// rimuovo il titolo della camera 1 (per evitare duplicazioni nel caso sia gią presente: vedi istruzione successiva)
		$('li.room1:first').before('<li class="room1 roomTitle">'+ label_room +' 1:</li>');		// aggiungo il titolo della camera 1, prima del primo campo della camera 1
		$('li.room1:last').nextAll().remove();			// rimuovo tutti gli elementi dopo l'ultimo elemento della camera 1
		$('li.room1:last').after(myResults);			// aggiungo dopo l'ultimo elemento della camera 1, la stringa preparata in precedenza
	}
	else			// se viene scelta una sola camera...
	{
		//$('li.room1.roomTitle').remove();				// rimuovo il titolo della camera 1
		$('li.room1:last').nextAll().remove();			// rimuovo tutti gli elementi dopo l'ultimo elemento della camera 1
	}
}


function setChildAge(nchild, chdid, roomn, label_children_age){
	var selectHtml = "";
	if(nchild > 0){
		selectHtml = '<label>'+ label_children_age +'</label>';
		for (var cc=1; cc<=nchild; cc++) {
			selectHtml =  selectHtml + '<select name="bform[reqRooms]['+roomn+'][childAge][' + cc + ']">' +
                '<option value="0">&lsaquo; 1</option>';
				for(var k=1; k<=18; k++){
					k_opt = k<10 ? "&nbsp;"+ k : k;
					selectHtml =  selectHtml + "\n" + '<option value="'+ k +'">'+ k_opt +'</option>';
				}
				selectHtml =  selectHtml + '</select>';
		}
	}

	if($('#'+chdid)){
		$('#'+chdid).html(selectHtml);
	}
}


function createSelect(num, init, label, labels, selected){
	if(label != ""){
		label = " "+ label;
	}
	if(labels != ""){
		labels = " "+ labels;
	} else {
		labels = label;
	}
	var mySel = "";
	for(var k=init; k<=num; k++){
		if(k!=init) label = labels;
		if (selected != 0 && selected == k){
			//mySel = mySel + "\n" + '<option value="'+ k +'" selected="selected">'+ k + label +'</option>';	// numero + nome
			mySel = mySel + "\n" + '<option value="'+ k +'" selected="selected">'+ k + '</option>';				// solo numero
		} else {
			//mySel = mySel + "\n" + '<option value="'+ k +'">'+ k + label +'</option>';	// numero + nome
			mySel = mySel + "\n" + '<option value="'+ k +'">'+ k + '</option>';				// solo numero
		}
	}
	return mySel;
}

var jbase64={_keyStr:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",encode:function(input){var output="";var chr1,chr2,chr3,enc1,enc2,enc3,enc4;var i=0;input=jbase64._utf8_encode(input);while(i<input.length){chr1=input.charCodeAt(i++);chr2=input.charCodeAt(i++);chr3=input.charCodeAt(i++);enc1=chr1>>2;enc2=((chr1&3)<<4)|(chr2>>4);enc3=((chr2&15)<<2)|(chr3>>6);enc4=chr3&63;if(isNaN(chr2)){enc3=enc4=64;}else if(isNaN(chr3)){enc4=64;}output=output+this._keyStr.charAt(enc1)+this._keyStr.charAt(enc2)+this._keyStr.charAt(enc3)+this._keyStr.charAt(enc4);}return output;},decode:function(input){var output="";var chr1,chr2,chr3;var enc1,enc2,enc3,enc4;var i=0;input=input.replace(/[^A-Za-z0-9\+\/\=]/g,"");while(i<input.length){enc1=this._keyStr.indexOf(input.charAt(i++));enc2=this._keyStr.indexOf(input.charAt(i++));enc3=this._keyStr.indexOf(input.charAt(i++));enc4=this._keyStr.indexOf(input.charAt(i++));chr1=(enc1<<2)|(enc2>>4);chr2=((enc2&15)<<4)|(enc3>>2);chr3=((enc3&3)<<6)|enc4;output=output+String.fromCharCode(chr1);if(enc3!=64){output=output+String.fromCharCode(chr2);}if(enc4!=64){output=output+String.fromCharCode(chr3);}}output=jbase64._utf8_decode(output);return output;},_utf8_encode:function(string){string=string.replace(/\r\n/g,"\n");var utftext="";for(var n=0;n<string.length;n++){var c=string.charCodeAt(n);if(c<128)utftext+=String.fromCharCode(c);else if((c>127)&&(c<2048)){utftext+=String.fromCharCode((c>>6)|192);utftext+=String.fromCharCode((c&63)|128);}else{utftext+=String.fromCharCode((c>>12)|224);utftext+=String.fromCharCode(((c>>6)&63)|128);utftext+=String.fromCharCode((c&63)|128);}}return utftext;},_utf8_decode:function(utftext){var string="";var i=0;var c=c1=c2=0;while(i<utftext.length){c=utftext.charCodeAt(i);if(c<128){string+=String.fromCharCode(c);i++;}else if((c>191)&&(c<224)){c2=utftext.charCodeAt(i+1);string+=String.fromCharCode(((c&31)<<6)|(c2&63));i+=2;}else{c2=utftext.charCodeAt(i+1);c3=utftext.charCodeAt(i+2);string+=String.fromCharCode(((c&15)<<12)|((c2&63)<<6)|(c3&63));i+=3;}}return string;}};


function openModal(url) {
	url = decodeURIComponent((jbase64.decode(url) + '').replace(/\+/g, '%20'));
	if (window.showModalDialog) {
		window.showModalDialog(url, "socials", "dialogHeight:450px;dialogWidth:880px");
	} else {
		window.open(url, 'socials', 'height=450,width=880,toolbar=no,directories=no,status=no,menubar=no,scrollbars=no,resizable=no,modal=yes');
	}
}

/*******************************************************   GALLERYONE BODY MULTIPLE */

/* Copyright (c) 2006 Brandon Aaron (brandon.aaron@gmail.com || http://brandonaaron.net)
 * Dual licensed under the MIT (http://www.opensource.org/licenses/mit-license.php)
 * and GPL (http://www.opensource.org/licenses/gpl-license.php) licenses.
 * Thanks to: http://adomas.org/javascript-mouse-wheel/ for some pointers.
 * Thanks to: Mathias Bank(http://www.mathias-bank.de) for a scope bug fix.
 *
 * $LastChangedDate: 2007-12-20 09:02:08 -0600 (Thu, 20 Dec 2007) $
 * $Rev: 4265 $
 *
 * Version: 3.0
 * 
 * Requires: $ 1.2.2+
 */

(function($) {

$.event.special.mousewheel = {
	setup: function() {
		var handler = $.event.special.mousewheel.handler;
		
		// Fix pageX, pageY, clientX and clientY for mozilla
		if ( $.browser.mozilla )
			$(this).bind('mousemove.mousewheel', function(event) {
				$.data(this, 'mwcursorposdata', {
					pageX: event.pageX,
					pageY: event.pageY,
					clientX: event.clientX,
					clientY: event.clientY
				});
			});
	
		if ( this.addEventListener )
			this.addEventListener( ($.browser.mozilla ? 'DOMMouseScroll' : 'mousewheel'), handler, false);
		else
			this.onmousewheel = handler;
	},
	
	teardown: function() {
		var handler = $.event.special.mousewheel.handler;
		
		$(this).unbind('mousemove.mousewheel');
		
		if ( this.removeEventListener )
			this.removeEventListener( ($.browser.mozilla ? 'DOMMouseScroll' : 'mousewheel'), handler, false);
		else
			this.onmousewheel = function(){};
		
		$.removeData(this, 'mwcursorposdata');
	},
	
	handler: function(event) {
		var args = Array.prototype.slice.call( arguments, 1 );
		
		event = $.event.fix(event || window.event);
		// Get correct pageX, pageY, clientX and clientY for mozilla
		$.extend( event, $.data(this, 'mwcursorposdata') || {} );
		var delta = 0, returnValue = true;
		
		if ( event.wheelDelta ) delta = event.wheelDelta/120;
		if ( event.detail     ) delta = -event.detail/3;
//		if ( $.browser.opera  ) delta = -event.wheelDelta;
		
		event.data  = event.data || {};
		event.type  = "mousewheel";
		
		// Add delta to the front of the arguments
		args.unshift(delta);
		// Add event to the front of the arguments
		args.unshift(event);

		return $.event.handle.apply(this, args);
	}
};

$.fn.extend({
	mousewheel: function(fn) {
		return fn ? this.bind("mousewheel", fn) : this.trigger("mousewheel");
	},
	
	unmousewheel: function(fn) {
		return this.unbind("mousewheel", fn);
	}
});

})(jQuery);


function galleryOneInit(gallery,itemNumber) {
	
	var gal;
	var elemWidth;
	gallery = (gallery==undefined || gallery=='')? '.galleryOne': gallery ;
	itemNumber = (itemNumber==undefined || itemNumber=='')? 4 : itemNumber ;

	$(gallery).each(function() {  
		
		gal = $(this);
		items = $('a:not(.sx,.dx)', gal);
		elemWidth = $('a:first',gal).outerWidth(true);
		
		
		if(items.length > itemNumber) {  // se ci sono pił di "n" immagini attivo lo scroll

			var hovered = false;
				
			$(gal).hover(function() {
				hovered = true;
			}, function() {
				hovered = false;
			});
			
			$(window).bind("mousewheel", function() {
				if (hovered === true) {
					return false;
				}
			});
			
			$(gal).bind('mousewheel', function(event, delta) {
				if(delta === 1){
					moveLeft($('.sx',$(this)));
				} else if(delta === -1){
					moveRight($('.dx',$(this)));
				}
			});
			
			$('.sx', gal).click(function(){moveLeft($(this))});
			$('.dx', gal).click(function(){moveRight($(this))});
			
		} else { // Altrimenti disattivo i pulsanti dello scroll	
			$('.sx',gal).hide();
			$('.dx',gal).hide();
		}
	
	});
}

// move Left
function moveLeft(puls) {
	
	var thumbsContainer = puls.nextAll('.wrapGallery');	
	var myLast = $('a:last',thumbsContainer);
	var myFirst = $('a:first',thumbsContainer);
	var elemWidth = myFirst.outerWidth();
		
	if(!myFirst.is(':animated') && !myLast.is(':animated')){	
		
		myFirst.animate(
					{ marginLeft:-elemWidth
					},
					300,
					'',
					function(){
						var tempFirst = myFirst.clone(true);
						myFirst.remove();
						tempFirst.insertAfter(myLast).css({marginLeft:0}).removeAttr('style');		
						}		
					);		
	} 	
}

// move Right
function moveRight(puls) {	

	var thumbsContainer = puls.nextAll('.wrapGallery');	
	var myLast = $('a:last',thumbsContainer);
	var myFirst = $('a:first',thumbsContainer);
	var elemWidth = myFirst.outerWidth();
	
	if(!myFirst.is(':animated') && !myLast.is(':animated')){	
		
		var tempLast = myLast.clone(true);
		myLast.remove();
		tempLast.insertBefore(myFirst).css({marginLeft:-elemWidth}).animate(
																		{ marginLeft:0
																		},
																		300,
																		'',
																		function(){
																			$(this).removeAttr('style');	
																			}		
																		);
		
	} 	
}

function multiBoxesInit() {
	if($('#multiGalWrapper').length > 0) {
		$('#box1, #box2',$('#multiGalWrapper ')).slideUp();
	}
	
	$('a.titleLink',$('#multiGalWrapper ')).click(function() {
	  	selectedId = $(this).attr('id').replace('titleLink','');
		
		$('#multiGalWrapper').children().each(function(index) { // prendo i figli del box principale
			if($(this).hasClass('titleLink')) { // pulsanti "label" 
				if($(this).attr('id')=='titleLink'+selectedId) {
					$(this).addClass('sel');
				} else {
					$(this).removeClass('sel');
				}
			}
			
			if($(this).hasClass('galleryOne')) { // pulsanti "label" 
				if($(this).attr('id')=='box'+selectedId) {
					$(this).slideDown();
				} else {
					$(this).slideUp();
				}
			}			
			
		});
	});
}

/*******************************************************   shadowbox Seo */

function shadowRel(){
    $('a.shadowBox').each(function() {
		var title = $('img', this).attr('alt');
		
		$(this).attr('title',title);						   
        $(this).attr('rel', 'shadowbox['+ $(this).attr('class').replace(/ /g, '_') +']');
    });	
	
	
	
	$('a.shadowBoxVideo').each(function(){
		params = $(this).attr('class').split('_');

	    gallery	= (typeof(params[1]) !== 'undefined' && params[1] != '')? '['+params[1]+'];' : ';';
		width	= (typeof(params[2]) !== 'undefined')? 'width='+params[2]+';' : '';
		height	= (typeof(params[3]) !== 'undefined')? 'height='+params[3]+';' : '';
		
		
		$(this).attr('rel', 'shadowbox'+gallery+width+height);
		
		// inserisco il play e lo faccio animare all'hover dell'ancora
		$(this).prepend('<img class="thumbOverlay" src="/images/playOverlay.png" width="150" height="100" />');
		$('.thumbOverlay',$(this)).animate({opacity: 0}, 1);
		
		$(this).hover(
		  function () {
			$('.thumbOverlay',$(this)).stop(true).animate({opacity: 1}, 200);
		  }, 
		  function () {
			$('.thumbOverlay',$(this)).stop(true).animate({opacity: 0}, 200);
		  }
		);

		
	});
}


$(document).ready(function(){
						   
	galleryOneInit();
	multiBoxesInit();
	shadowRel();
	
	Shadowbox.init({
		overlayOpacity:0.8
	});
						   
	//=============================== DATEPICKER
	$(".cal > input").datepicker({dateFormat: "dd-mm-yy", minDate: 0, changeMonth: true, changeYear: true});
	//$(".cal > input").datepicker($.datepicker.regional['<?= $PAGE['iso2']; ?>']);
	
	date1 = $("#bform\\[checkin\\]").datepicker( 'getDate' );
	$("#bform\\[checkout\\]").datepicker('option', 'minDate',date1);
	
	$("#bform\\[checkin\\]").change(
		function() {
			date1 = $("#bform\\[checkin\\]").datepicker( 'getDate' );
			date2 = new Date(date1);
			date2.setDate(date1.getDate() + 1);
			$("#bform\\[checkout\\]").datepicker('option', 'minDate',date2);
		}
	);
	
	$(".date").datepicker({ dateFormat: 'dd-mm-yy' });
	
	//=============================== SCROLL OFFERTE
	setInterval( 'scrollOffers("#struct_48 ul")', 4500 );
	setInterval( 'scrollOffers("#struct_49 ul")', 5000 );
	setInterval( 'scrollOffers("#struct_50 ul")', 5500 );
	
});
