	// * * * * * * * * * * * * * * * *
	// * * * * * * * * * * * * * * * *
$(document).ready(function($) {

  $('.lazyload').each(function(){
    $(this).attr('src', $(this).attr('src').replace(/\/\.t/i, '/.m'));
  });
  /* */
			$.ajaxSetup({
					url: window.location.href.replace(/#\w*/g, ''),
					type: 'post'
			});
	// * * * * * * * * * * * * * * * *
 $('.hidden').hide();
	// * * * * * * * * * * * * * * * *
$('.unhide').live('click', function(e){
 e.preventDefault();
		$(this).fadeOut();
		$(this).parent().nextAll('.hidden').fadeIn();
  return false;
});
// * * * * * * * * * * * * * * * *
if ($('#guestbook').length){
$("#guestbook").buildMbExtruder({
        position:"left",
        top:420,
        width: 630,
        positionFixed: false,
        extruderOpacity:.8,
        onExtOpen:function(){},
        onExtContentLoad:function(){},
        onExtClose:function(){}
      }).click(function() {
	 if ($(this).hasClass('open')) {
	  if (! $('.review-box', this).length) {
	   $('.ajax-loading', this).load("index.php?ajax=getGuestBook"+(__kLOGGED?('&'+__kLOGGED+'=1'):''), function(html){
 			 $(this).removeClass('ajax-loading');

					$(this).polaroidize();

 			 if (__kLOGGED) {
     $(this).addClass('edit_area').editable(
 				__BASE_URL+'?&'+__kLOGGED+'=1', {
 height    : $('.ext_wrapper').height()-100,
 width     : $(this).width(),
 type      : 'textarea',
	cancel    : 'Annulla',
	submit    : 'OK',
	indicator : '<img src="'+__kLIB_IMG_URL+'indicator.gif">',
	tooltip   : 'Click to edit...',
	loadurl: __BASE_URL+'&ajax=getGuestBook&'+__kLOGGED+'=1&of='+__kLOGGED,
	submitdata: {save: 1, review: 1, of: __kLOGGED},
	callback : function() {
	 $('', this).remove();
	 $(this).polaroidize();
	}
     });//.prependTo('#guestbook .text');
 			 };


	   });
	  };
	 };
	});
	};

	if ($('#partner').length){
$("#partner").buildMbExtruder({
        position:"right",
        top:25,
        width: 240,
        positionFixed: false,
        extruderOpacity:.8,
        onExtOpen:function(){},
        onExtContentLoad:function(){},
        onExtClose:function(){}
      }).click(function() {
	 if ($(this).hasClass('open')) {
	  if (! $('.review-box', this).length) {
	   $('.ajax-loading', this).load("index.php?ajax=getPartner&"+__kLANG, function(html){
 			 $(this).removeClass('ajax-loading');
	    $(this).find("a[href*='http://']:not([href*='"+location.hostname+"'])").addClass('external').attr("target","_blank").attr('rel', 'nofollow');
	   });
	  };
	 };
	});
	};
	// * * * * * * * * * * * * * * * *
	// MENU
	$('#menu li .active').clone().prependTo('#text').addClass('');
	// * * * * * * * * * * * * * * * *
	// EXTERNAL LINKS
	$("a[href*='http://']:not([href*='"+location.hostname+"'])").addClass('external').attr("target","_blank").attr('rel', 'nofollow');
	// * * * * * * * * * * * * * * * *
	// GALLERIA
	if ($('.galleria').length) {

	//select all the a tag with name equal to modal
	$('.popup').click(function(e) {
	//Cancel the link behavior
	e.preventDefault();

	var src = $(this);
	var id = src.next().detach();
	var container = $('#overlay').length ? $('#overlay').append(id) : id.wrap('<div id="overlay"></div>').parent().appendTo('body').after('<div id="mask"></div>');

	//if mask is clicked
	$('#mask,#overlay').click(function () {
		$('#mask').fadeOut(1000);
		id.insertAfter(src);
		$('#mask').empty();
		$('#overlay').empty();
	});

	//Get the screen height and width
	var maskHeight = $(document).height();
	var maskWidth = $(document).width();

	//Set heigth and width to mask to fill up the whole screen
	$('#mask').css({'position': 'absolute','top':0, 'left':0,'width':maskWidth,'height':maskHeight});

	//transition effect
	$('#mask').fadeTo("slow",0.8);

	//Get the window height and width
	var winH = $(window).height();
	var winW = $(window).width();

	//Set the popup window to center
		$(id).css('top',  winH/2-$(id).height()/2);
		$(id).css('left', winW/2-$(id).width()/2);

	//transition effect
	$(id).fadeIn(1000);
	$('a', id).nyroModal().click(function() {
		$('#mask').click();
	});

	//Get our elements for faster access and set overlay width
	var div = $('div.slideshow', container),
	ul = $('ul', container),
	ulPadding = 15;

	//Get menu width
	var divWidth = div.width();

	//Remove scrollbars
	div.css({overflow: 'hidden'});

	//Find last image container
	var lastLi = ul.find('li:last-child');

	//When user move mouse over menu
	div.mousemove(function(e){
	//As images are loaded ul width increases,
	//so we recalculate it each time
	var ulWidth = lastLi[0].offsetLeft + lastLi.outerWidth() + ulPadding;
	var left = (e.pageX - div.offset().left) * (ulWidth-divWidth) / divWidth;
	div.scrollLeft(left);
	});


	});

	};
	// * * * * * * * * * * * * * * * *
	// SLIDESHOW
	$('#player.slideshow img:first').addClass('active');
	setInterval( "slideSwitch()", 4000 );
	// * * * * * * * * * * * * * * * *
	// TEXT SCROLLER
	if ($('.scroll-pane').length) {
		$('.scroll-pane').jScrollPane({
			scrollbarWidth: 12
		});
	};
// * * * * * * * * * * * * * * * *
// $( "form" ).clearForm();
if ($('#richiesta').length) {


$('#richiesta input[name*=form_durata]').datePicker({createButton: false, clickInput: true, showYearNavigation: false});

$('#richiesta option').click(function () {
 $('#'+$(this).attr('rel')).click();
});

$('#richiesta form').ajaxContactForm( '', {
 language: __kLANG,
 extraValues: {
  __kLANG: '',
  'form': ''
 },
 method: 'POST',
	falseMessageFunc:	function(form, language) {
		switch (language) {
			case 'en':
				msg = 'Attention, not all the fields have been filled out correctly.';
				break;

			case 'de':
				msg = 'Achtung, nicht alle Felder sind korrekt ausgefuellt.';
				break;

			default:
				msg = 'Attenzione, non tutti i campi sono stati riempiti correttamente.';
				break;
		}
	$.gritter.add({
			title: '[ ! ]',
			text: msg,
			sticky: false,
			class_name: 'KO'
		});
		scrollToSelect('#richiesta');
	}
});

$('#richiesta input[name*=form_cognome]').attr('name', 'form_cognome__v__d');
$('#richiesta input[name*=form_nome]').attr('name', 'form_nome__v__d');
$('#richiesta input[name*=form_citta]').attr('name', 'form_citta__v__d');
$('#richiesta input[name*=form_paese]').attr('name', 'form_paese__v__d');
$('#richiesta input[name*=form_tel]').attr('name', 'form_tel__n__d');
$('#richiesta input[name*=form_email]').attr('name', 'form_email__e__d');

};
// * * * * * * * * * * * * * * * *
if (__kREQ_FORM_RESULT) {
	$.gritter.add({
			title: __kREQ_FORM_TITLE,
			text: __kREQ_FORM_RESULT,
			sticky: (__kREQ_FORM_CLASS=='OK'),
			class_name: __kREQ_FORM_CLASS
		})
 };
// * * * * * * * * * * * * * * * *
	if ($('#select li').length) {
		$('#select li').click(function() {
  	/* */
			$('#select li.active').removeClass('active');
			$(this).addClass('active');
  	/* */
			$('#descrizione').load('#descrizione', {ajax: 'getAptDescription', of: this.id});
			$('#tarOne').load('#tariffe', {ajax: 'getAptTariffe', of: this.id});
			$('#tarOne,#calOne').attr('rel', this.id);
  	/* */
			var g_xjson;
			$.ajax({
			cache: false,
   data: 'ajax=getAptPrenota&of='+this.id,
			dataType: 'json',
			error: function(jqXHR, textStatus, errorThrown) {
			 alert(textStatus);
			},
			success: function(xjson, textStatus, jqXHR) {
    //xjson = [item.toString() for each (item in xjson)];
    g_xjson = xjson.toString();
				/* */

				$('#calOne').datePickerMultiMonth({
						selectWeek: false,
						selectMultiple: false,
						showYearNavigation: false,
						numMonths: 3,
						monthStep: 3,
						inline: true,
						renderCallback: function ($td, thisDate, month, year) {
							// do stuff as each td is rendered dependant on the date in the td and the displayed month and year
						// $td.addClass('disabled');
						if (g_xjson.indexOf(thisDate.format('Y-m-d')) != -1) {
							$td.addClass('half-before');//disabled
						}
						var halfDate = new Date();
						halfDate = thisDate.addDays(-1);
						if (g_xjson.indexOf(halfDate.format('Y-m-d')) != -1) {
							$td.addClass('half-after');
						};
						}
					});


					if (__kLOGGED) {

      var f = '';
      f += '<div><br/><table id="vRsvd" class="edit_area"><tr><th>Arrivo</th><th>Partenza</th><th rowspan="2">Se il periodo scelto é vacante, le date vengono prenotate.<br/>Se il periodo è prenotato, le date vengono rese disponibili. </th></tr><tr>';
      f += '<td><input name="vDate1" id="vDate1" type="text" size="10" maxlength="10" /></td>';
      f += '<td><input name="vDate2" id="vDate2" type="text" size="10" maxlength="10" /></td>';
      f += '</tr>';
      f += '<tr><td colspan="3"><input name="vSave" id="vSave" type="button" value="Registra" /></td>';
      f += '</tr></table></div>';

				$(f).
				find('#vDate1').datePicker({createButton: false, clickInput: true, showYearNavigation: true, autoFocusNextInput: true}).end().
				find('#vDate2').datePicker({createButton: false, clickInput: true, showYearNavigation: true, autoFocusNextInput: true}).end().
				find('#vSave').click(function(){
				var sDay = $('#vDate1').val();
				var eDay = $('#vDate2').val();

				if (sDay!='' && eDay!='') {

 			var dCursor = new Date(sDay.substr(6),sDay.substr(3,2),sDay.substr(0,2));

				if (dCursor) {
		  var dCursor2 = new Date(eDay.substr(6),eDay.substr(3,2),eDay.substr(0,2));
				if (dCursor2) {
				var days = (dCursor2-dCursor)/(1000 * 60 * 60 * 24);
				if (days > 0) {
				 var data = new Array();
				 for (var di=0; di < days; di++) {
				  data[di] = dCursor.getFullYear()+'-'+(dCursor.getMonth())+'-'+dCursor.getDate();
				  dCursor.setDate( dCursor.getDate() + 1 );
				 }
					 $.ajax({
			    cache: false,
					  url: __BASE_URL,
			    cache: false,
       data: 'id=D-'+($('#calOne').attr('rel'))+'&value='+data+'&status='+status+'&date=1&'+__kLOGGED+'=1&save=1',
       success: function(data) {
							$.gritter.add({
									title: 'Aggiornamento effettuato',
									text: sDay+' - '+eDay,
									sticky: false,
									class_name: 'OK'
								});
        g_xjson = data;
			     $('#calOne').dpmmRerenderCalendar();
       }
      });
				} else {
				 alert('La data di partenza deve essere successiva alla data di arrivo...');
				 };
				} else {
				 alert('Seleziona una data di partenza...');
				 };
				} else {
				 alert('Seleziona una data di arrivo...');
				};

				} else {
				 alert('Seleziona una data di arrivo e una data di partenza...');
				};
				}).end().
				appendTo('#calOne');



// 					$('#calOne').bind(
// 					'dateSelected',
// 					function(event, date, $td, status) {
// 						// uncomment if you have firebug and want to confirm this works as expected...
// 					 // console.log('dateSelected', arguments);
// 					 var d1 = date.getFullYear()+'-'+(date.getMonth()+1)+'-'+date.getDate();
// 					 var d2 = date.getDate()+'/'+(date.getMonth()+1)+'/'+date.getFullYear();
// 					 // console.log('dateSelected', $td);
// 					 $.ajax({
// 			    cache: false,
// 					  url: __BASE_URL,
// 			    cache: false,
//        data: 'id=D-'+($('#calOne').attr('rel'))+'&value='+d1+'&status='+status+'&date=1&'+__kLOGGED+'=1&save=1',
//        success: function(data) {
//         g_xjson = data;
// 			     $('#calOne').dpmmRerenderCalendar();
// 			     $('#calOne td').addClass('edit_area');
//        }
//       });
//
// 	/*
// 					 var dd = new Date();
// 					 dd.setDate(date.getDate() + 7);
// 					 var d1 = date.getDate()+'/'+date.getMonth()+'/'+date.getFullYear();
// 					 var d2 = dd.getDate()+'/'+dd.getMonth()+'/'+dd.getFullYear();
//       $('#richiesta input[name=form_durata_dal1]').val(d1);
//       $('#richiesta input[name=form_durata_al1]').val(d2);
//       // scrollToSelect('#richiesta');
//       // $('#richiesta input:first').focus();
//
// 					*/
// //      $('#calOne td').removeClass('half-before half-after');
// //       $('#calOne .selected').addClass('half-before');
// // 						$('#calOne .selected').next('tr:first').find('td:first', this).addClass('half-after');
//
// 					}).find('td').addClass('edit_area');
					};

    $('#choose .footer-c').show();

// 					.click(function(e) {
// 					 $(this).trigger('dateSelected', [ new Date(), $(this), true]);
// 					});

	$('#tarOne .edit_area').editable(__BASE_URL+'?&'+__kLOGGED+'=1', {
	data: function(value, settings) {
      /* Convert <br> to newline. */
      var retval = value.replace(/<br[\s\/]?>/gi, '\n');
      return retval;
    },
	type      : 'textarea',
	cancel    : 'Annulla',
	submit    : 'OK',
	indicator : '<img src="'+__kLIB_IMG_URL+'indicator.gif">',
	tooltip   : 'Click to edit...',
	submitdata: {save: 1, rate: 1},
	width     : 200,
	height    : 80
     });

				}
			});
  	/* */
  $('#richiesta option[rel='+this.id+']').attr('selected', 'selected');
  $('#richiesta input[name*=form_durata_dal1]').val('');
  $('#richiesta input[name*=form_durata_al1]').val('');
  	/* */

		});

  if (__kREQ_OF) scrollToSelect('#select');
  $('#text .check-c').click(function() {
   scrollToSelect('#select');
  });

	// * * * * * * * * * * * * * * * *
	} else {
  if (__kREQ_OF) scrollToSelect('#'+__kREQ_OF);
	};
	// * * * * * * * * * * * * * * * *
	// * * * * * * * * * * * * * * * *
	function scrollToSelect (selector) {
			if ($(selector).length) {
				var targetOffset = $(selector).offset().top;
				$('html,body').animate({scrollTop: targetOffset}, 1000, 'linear', function() {
					if (__kREQ_OF && (selector=='#select')) $('#'+__kREQ_OF).click();
				});
			};
	 }
	// * * * * * * * * * * * * * * * *
 Date.firstDayOfWeek = 1;
	// * * * * * * * * * * * * * * * *
	// TOGGLER
// 	if ($('.toggler-c').length) {
// 		$('.toggler-c').toggleElements( {
// 			fxAnimation:'slide',
// 			fxSpeed:'slow',
// 			className:'toggler'
// 		});
// 	};
	// * * * * * * * * * * * * * * * *
	if ($('.content-c img').length) {
		$('.content-c img').each(function () {
		 var url = $(this).attr('src').replace('/.t','/');
		 $(this).wrap('<a class="slideshow-c" href="'+url+'" title="'+$(this).attr('alt')+'" rel="'+url.replace(/.*\/(\d+\-\d+).*/, '$1')+'"></a>').removeAttr('rel');
		}).end().find('.slideshow-c').nyroModal().filter(':first-child').prepend('<span class="play"/>');
	};
	// * * * * * * * * * * * * * * * *
	// * * * * * * * * * * * * * * * *
  if ($.fn.nyroModal) {
  $.fn.nyroModal.settings.processHandler = function(settings) {
    var from = settings.from;
    if (from && from.href && from.href.indexOf('http://www.youtube.com/watch?v=') == 0) {
						var url = from.href.replace(new RegExp("watch\\?v=", "i"), 'v/');
						url += '?';
						url += 'autoplay=1&amp;';
						url += 'enablejsapi=1&amp;';
						url += 'version=3&amp;';
						url += 'fs=0&amp;';
						url += 'autohide=1&amp;';
						url += 'loop=0&amp;';
						url += 'rel=0&amp;';
						url += 'showinfo=0&amp;';
						url += 'cc_load_policy=3&amp;';
						url += 'iv_load_policy=3';
      $.nyroModalSettings({
        type: 'swf',
								allowScriptAccess: "always",
								wmode: "transparent",
								allowFullScreen: "false",
        width: 480,
        height: 360+25,
        url: url
      });
    }
  };
	$('.nyroModal').nyroModal();
  };
	// * * * * * * * * * * * * * * * *
 });
/***
    Simple jQuery Slideshow Script
    Released by Jon Raasch (jonraasch.com) under FreeBSD license: free to use or modify, not responsible for anything, etc.  Please link out to me if you like it :)
***/
function slideSwitch() {
    var $active = $('#player.slideshow img.active');

    if ( $active.length == 0 ) $active = $('#player.slideshow img:last');
    // use this to pull the images in the order they appear in the markup
    var $next =  $active.next().length ? $active.next() : $('#player.slideshow img:first');
    // uncomment the 3 lines below to pull the images in random order
// 				var $sibs  = $active.siblings();
// 				var rndNum = Math.floor(Math.random() * $sibs.length );
// 				var $next  = $( $sibs[ rndNum ] );
    $active.addClass('last-active').animate({opacity: 0.0}, 1000);
    $next.css({opacity: 0.0})
        .addClass('active')
        .animate({opacity: 1.0}, 1000, function() {
            $active.removeClass('active last-active');
        });
}

	// * * * * * * * * * * * * * * * *
$.fn.polaroidize = function() {
   var zindexnr = 1;
   var offS = 30;
   var offX = 300;
   var offY = 300;
     $('.review-box.polaroid', this).draggable().mouseup(function(e){
						// Bring polaroid to the foreground
						zindexnr++;
						var cssObj = { 'z-index' : zindexnr};
						$(this).css(cssObj);
 			 }).each(
 			 function(){
         var tempVal = Math.round(Math.random());
         if(tempVal == 1) {
            var rotDegrees = randomXToY(340, 360); // rotate left
         } else {
            var rotDegrees = randomXToY(0, 20); // rotate right
         };
									var posX = randomXToY(0, offX-offS); // rotate left
									var posY = randomXToY(0, offY-offS); // rotate left
         var cssObj = {
            '-moz-transform' : 'rotate('+ rotDegrees +'deg)',
            '-webkit-transform' : 'rotate('+ rotDegrees +'deg)',
            'transform' : 'rotate('+ rotDegrees +'deg)',
            'z-index' : zindexnr,
            'top': posY,
            'left': posX,
            'position': 'absolute',
            'behavior': 'url(assets/css/PIE.htc)'
            };
         $(this).css(cssObj);
 			 });
}
	// * * * * * * * * * * * * * * * *
$.fn.clearForm = function() {
  return this.each(function() {
 var type = this.type, tag = this.tagName.toLowerCase();
 if (tag == 'form')
   return $(':input',this).clearForm();
 if (type == 'text' || type == 'password' || tag == 'textarea')
   this.value = '';
 else if (type == 'checkbox' || type == 'radio')
   this.checked = false;
 else if (tag == 'select')
   this.selectedIndex = -1;
  });
};
	// * * * * * * * * * * * * * * * *
  function randomXToY(minVal,maxVal,floatVal) {
      var randVal = minVal+(Math.random()*(maxVal-minVal));
      return typeof floatVal=='undefined'?Math.round(randVal):randVal.toFixed(floatVal);
   }
	// * * * * * * * * * * * * * * * *
function isArray(a) {
	return Object.prototype.toString.apply(a) === '[object Array]';
}
// * * * * * * * * * * * * * * * *
function getAbsolutePath() {
    var loc = window.location;
    var pathName = loc.pathname.substring(0, loc.pathname.lastIndexOf('/') + 1);
    return loc.href.substring(0, loc.href.length - ((loc.pathname + loc.search + loc.hash).length - pathName.length));
}
// * * * * * * * * * * * * * * * *
Date.prototype.format=function(format){var returnStr='';var replace=Date.replaceChars;for(var i=0;i<format.length;i++){var curChar=format.charAt(i);if(replace[curChar]){returnStr+=replace[curChar].call(this);}else{returnStr+=curChar;}}return returnStr;};Date.replaceChars={shortMonths:['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'],longMonths:['January','February','March','April','May','June','July','August','September','October','November','December'],shortDays:['Sun','Mon','Tue','Wed','Thu','Fri','Sat'],longDays:['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday'],d:function(){return(this.getDate()<10?'0':'')+this.getDate();},D:function(){return Date.replaceChars.shortDays[this.getDay()];},j:function(){return this.getDate();},l:function(){return Date.replaceChars.longDays[this.getDay()];},N:function(){return this.getDay()+1;},S:function(){return(this.getDate()%10==1&&this.getDate()!=11?'st':(this.getDate()%10==2&&this.getDate()!=12?'nd':(this.getDate()%10==3&&this.getDate()!=13?'rd':'th')));},w:function(){return this.getDay();},z:function(){return"Not Yet Supported";},W:function(){return"Not Yet Supported";},F:function(){return Date.replaceChars.longMonths[this.getMonth()];},m:function(){return(this.getMonth()<9?'0':'')+(this.getMonth()+1);},M:function(){return Date.replaceChars.shortMonths[this.getMonth()];},n:function(){return this.getMonth()+1;},t:function(){return"Not Yet Supported";},L:function(){return(((this.getFullYear()%4==0)&&(this.getFullYear()%100!=0))||(this.getFullYear()%400==0))?'1':'0';},o:function(){return"Not Supported";},Y:function(){return this.getFullYear();},y:function(){return(''+this.getFullYear()).substr(2);},a:function(){return this.getHours()<12?'am':'pm';},A:function(){return this.getHours()<12?'AM':'PM';},B:function(){return"Not Yet Supported";},g:function(){return this.getHours()%12||12;},G:function(){return this.getHours();},h:function(){return((this.getHours()%12||12)<10?'0':'')+(this.getHours()%12||12);},H:function(){return(this.getHours()<10?'0':'')+this.getHours();},i:function(){return(this.getMinutes()<10?'0':'')+this.getMinutes();},s:function(){return(this.getSeconds()<10?'0':'')+this.getSeconds();},e:function(){return"Not Yet Supported";},I:function(){return"Not Supported";},O:function(){return(-this.getTimezoneOffset()<0?'-':'+')+(Math.abs(this.getTimezoneOffset()/60)<10?'0':'')+(Math.abs(this.getTimezoneOffset()/60))+'00';},P:function(){return(-this.getTimezoneOffset()<0?'-':'+')+(Math.abs(this.getTimezoneOffset()/60)<10?'0':'')+(Math.abs(this.getTimezoneOffset()/60))+':'+(Math.abs(this.getTimezoneOffset()%60)<10?'0':'')+(Math.abs(this.getTimezoneOffset()%60));},T:function(){var m=this.getMonth();this.setMonth(0);var result=this.toTimeString().replace(/^.+ \(?([^\)]+)\)?$/,'$1');this.setMonth(m);return result;},Z:function(){return-this.getTimezoneOffset()*60;},c:function(){return this.format("Y-m-d")+"T"+this.format("H:i:sP");},r:function(){return this.toString();},U:function(){return this.getTime()/1000;}};
