﻿/*!
 * liScroll 1.0
 * Examples and documentation at: 
 * http://www.gcmingati.net/wordpress/wp-content/lab/jquery/newsticker/jq-liscroll/scrollanimate.html
 * 2007-2010 Gian Carlo Mingati
 * Version: 1.0.2.1 (22-APRIL-2011)
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
 * Requires:
 * jQuery v1.2.x or later
 * 
 */
jQuery.fn.liScroll = function(settings) {
	settings = jQuery.extend({
		travelocity: 0.07
	}, settings);		
	return this.each(function(){
		var $strip = jQuery(this);
		$strip.addClass("newsticker");
		var stripWidth = 0;
		$strip.find("li").each(function(i){
			stripWidth += jQuery(this, i).outerWidth(true); // thanks to Michael Haszprunar and Fabien Volpi
		});
		var $mask = $strip.wrap("<div class='mask'></div>");
		var $tickercontainer = $strip.parent().wrap("<div class='tickercontainer'></div>");								
		var containerWidth = $strip.parent().parent().width();	//a.k.a. 'mask' width 	
		$strip.width(stripWidth);			
//		var totalTravel = stripWidth+containerWidth;
		var totalTravel = stripWidth;
		var defTiming = totalTravel/settings.travelocity;	// thanks to Scott Waye		
		function scrollnews(spazio, tempo){
			$strip.animate({left: '-='+ spazio}, tempo, "linear", function(){$strip.css("left", containerWidth); scrollnews(totalTravel, defTiming);});
		}
		scrollnews(totalTravel, defTiming);
		$strip.hover(function(){
			jQuery(this).stop();
		},
		function(){
			var offset = jQuery(this).offset();
			var residualSpace = offset.left + stripWidth;
			var residualTime = residualSpace/settings.travelocity;
			scrollnews(residualSpace, residualTime);
		});			
	});	
};

function isDate(txtDate){ 
	var objDate;  									// date object initialized from the txtDate string  
	var mSeconds; 									// milliseconds from txtDate  
	if (txtDate.length != 10) return false;  
	var month = txtDate.substring(3,5) - 1;  		// because months in JS start with 0  
	var day = txtDate.substring(0,2) - 0; 
	var year = txtDate.substring(6,10) - 0;  
	if (txtDate.substring(2,3) != '/') return false;  
	if (txtDate.substring(5,6) != '/') return false;  
	if (year < 999 || year > 3000) return false;  
	mSeconds = (new Date(year, month, day)).getTime();  
	objDate = new Date();  
	objDate.setTime(mSeconds);  
	if (objDate.getFullYear() != year) return false;  
	if (objDate.getMonth() != month) return false;  
	if (objDate.getDate() != day) return false;  
	return true;  
}

var text_content, current_size, target_size, size_unit;

(function($){
 	$.fn.extend({ 
 		carousel: function(options) {
			var defaults = {
				easing: 'easeInOutQuad',
				speed: 500,
				visible: 3
			}
			var options =  $.extend(defaults, options);

    		return this.each(function() {
				var o = options;
				var el = $(this);
				var box = $(el).parent();
				var wrapper=$(box).parent();
				var items = $("li", el);
				var itemWidth = $(items[0]).outerWidth(true);
				var pages = Math.ceil(items.length / o.visible);
				var currentPage = 0;
				// add some empty LIs to complete the page
				for(var i=0; i<(pages*o.visible)-items.length; i++){
					$(el).append('<li class="empty">&nbsp;</li>');
				}
				// count again
				items = $("li", el);
				// put them in line
				el.css({
					overflow: 'hidden',
					width: itemWidth * items.length
				});

				// build the pager
				if (pages>1) { // if needed
					$(wrapper).append('<div class="hr" style="display:block"><hr /></div>');
					$(wrapper).append('<ul class="pages"></ul>');

					var pager=$(wrapper).children('.pages').css('display', 'block');
					for(i=0; i<pages; i++){
						$(pager).append('<li class="page_'+ i +'"><a href="#"></a></li>');
					}

					var bullets=$(pager).children();
					bullets.filter('.page_'+currentPage).addClass('current');
					bullets.click(function(e){
						bullets.removeClass('current');
						$(this).addClass('current');

						if(bullets.index(this) > currentPage) {
							currentPage=bullets.index(this)-1;
							right.click();
						} else if(bullets.index(this) < currentPage) {
							currentPage=bullets.index(this)+1;
							left.click();
						}
						return false;
					});
				}

				// build the arrow controls
				$(wrapper).append('<span class="previous">&nbsp;</span>');
				$(wrapper).append('<span class="next">&nbsp;</span>');

				var left=$(box).siblings('.previous').css('display', 'block').css('top', $(box).position().top+30).addClass('disabled');
				var right=$(box).siblings('.next').css('display', 'block').css('top', $(box).position().top+30);
				if (pages<2) { $(right).addClass('disabled'); }

				// add events
				left.click(function(){
					if (currentPage>0) {
						currentPage--;
						$(el).animate({ 'margin-left': 0-currentPage*(itemWidth * o.visible) }, o.speed, o.easing);
						$(right).removeClass('disabled');
						bullets.removeClass('current').filter('.page_'+currentPage).addClass('current');
						if(currentPage==0){
							$(this).addClass('disabled');
						}
					}
				});
				right.click(function(){
					if (currentPage<(pages-1)) {
						currentPage++;
						$(el).animate({ 'margin-left': 0-currentPage*(itemWidth * o.visible) }, o.speed, o.easing);
						$(left).removeClass('disabled');
						bullets.removeClass('current').filter('.page_'+currentPage).addClass('current');
						if(currentPage==(pages-1)){
							$(this).addClass('disabled');
						}
					}
				});
			});
    	}
	});
})(jQuery);

/*-------------------------------------------------------------------- 
 * jQuery plugins: toEm() and toPx()
 * by Scott Jehl (scott@filamentgroup.com), http://www.filamentgroup.com
 * Copyright (c) Filament Group
 * Dual licensed under the MIT (filamentgroup.com/examples/mit-license.txt) and GPL (filamentgroup.com/examples/gpl-license.txt) licenses.
 * Article: http://www.filamentgroup.com/lab/update_jquery_plugin_for_retaining_scalable_interfaces_with_pixel_to_em_con/
 * Options:  	 								
 		scope: string or jQuery selector for font-size scoping		  
 * Usage Example: $(myPixelValue).toEm(); or $(myEmValue).toPx();
--------------------------------------------------------------------*/
$.fn.toEm = function(settings){
	settings = jQuery.extend({
		scope: 'body'
	}, settings);
	var that = parseInt(this[0],10);
	var scopeTest = jQuery('<div style="display: none; font-size: 1em; margin: 0; padding:0; height: auto; line-height: 1; border:0;">&nbsp;</div>').appendTo(settings.scope);
	var scopeVal = scopeTest.height();
	scopeTest.remove();
	return (that / scopeVal).toFixed(8) + 'em';
};
$.fn.toPx = function(settings){
	settings = jQuery.extend({
		scope: 'body'
	}, settings);
	var that = parseFloat(this[0]);
	var scopeTest = jQuery('<div style="display: none; font-size: 1em; margin: 0; padding:0; height: auto; line-height: 1; border:0;">&nbsp;</div>').appendTo(settings.scope);
	var scopeVal = scopeTest.height();
	scopeTest.remove();
	return Math.round(that * scopeVal) + 'px';
};


/*-------------------------------------------------------------------- 
 * JQuery Plugin: "EqualHeights"
 * by:	Scott Jehl, Todd Parker, Maggie Costello Wachs (http://www.filamentgroup.com)
 *
 * Copyright (c) 2008 Filament Group
 * Licensed under GPL (http://www.opensource.org/licenses/gpl-license.php)
 *
 * Description: Compares the heights or widths of the top-level children of a provided element 
 		and sets their min-height to the tallest height (or width to widest width). Sets in em units 
 		by default if pxToEm() method is available.
 * Dependencies: jQuery library, pxToEm method	(article: 
		http://www.filamentgroup.com/lab/retaining_scalable_interfaces_with_pixel_to_em_conversion/)							  
 * Usage Example: $(element).equalHeights();
  		Optional: to set min-height in px, pass a true argument: $(element).equalHeights(true);
 * Version: 2.0, 08.01.2008
--------------------------------------------------------------------*/
$.fn.equalHeights = function(px) {
	$(this).each(function(){
		var currentTallest = 0;
		$(this).children().each(function(i){
			if ($(this).height() > currentTallest) { currentTallest = $(this).height(); }
		});
		if (!px || !Number.prototype.toEm) currentTallest = $(currentTallest).toEm(); //use ems unless px is specified
		// for ie6, set height since min-height isn't supported
		if ($.browser.msie && $.browser.version == 6.0) { $(this).children().css({'height': currentTallest}); }
		$(this).children().css({'min-height': currentTallest}); 
	});
	return this;
};


/* jQuery MaxLength for INPUT and TEXTAREA fields v1.0
* Last updated: Oct 15th, 2009. This notice must stay intact for usage 
* Author: JavaScript Kit at http://www.javascriptkit.com/
* Visit http://www.javascriptkit.com/ for full source code
*/
var thresholdcolors=[['20%','darkred'], ['10%','red']]; //[chars_left_in_pct, CSS color to apply to output]
var uncheckedkeycodes=/(8)|(13)|(16)|(17)|(18)/;  //keycodes that are not checked, even when limit has been reached.

thresholdcolors.sort(function(a,b){return parseInt(a[0])-parseInt(b[0])}); //sort thresholdcolors by percentage, ascending

function setformfieldsize($fields, optsize, optoutputdiv){
	var $=jQuery;
	$fields.each(function(i){
		var $field=$(this);
		$field.data('maxsize', optsize || parseInt($field.attr('data-maxsize'))); //max character limit
		var statusdivid=optoutputdiv || $field.attr('data-output'); //id of DIV to output status
		$field.data('$statusdiv', $('#'+statusdivid).length==1? $('#'+statusdivid) : null);
		$field.unbind('keypress.restrict').bind('keypress.restrict', function(e){
			setformfieldsize.restrict($field, e);
		});
		$field.unbind('keyup.show').bind('keyup.show', function(e){
			setformfieldsize.showlimit($field);
		});
		setformfieldsize.showlimit($field); //show status to start
	});
}

setformfieldsize.restrict=function($field, e){
	var keyunicode=e.charCode || e.keyCode;
	if (!uncheckedkeycodes.test(keyunicode)){
		if ($field.val().length >= $field.data('maxsize')){ //if characters entered exceed allowed
			if (e.preventDefault) {
				e.preventDefault();
			}
			return false;
		}
	}
}

setformfieldsize.showlimit=function($field){
	if ($field.val().length > $field.data('maxsize')){
		var trimmedtext=$field.val().substring(0, $field.data('maxsize'));
		$field.val(trimmedtext);
	}
	if ($field.data('$statusdiv')){
		$field.data('$statusdiv').css('color', '').html($field.val().length);
		var pctremaining=($field.data('maxsize')-$field.val().length)/$field.data('maxsize')*100; //calculate chars remaining in terms of percentage
		for (var i=0; i<thresholdcolors.length; i++){
			if (pctremaining<=parseInt(thresholdcolors[i][0])){
				$field.data('$statusdiv').css('color', thresholdcolors[i][1]);
				break;
			}
		}
	}
}

function changeCap() {                        	
	$('#captchaImg').attr('src','');
	$('#captchaImg').attr('src','addons/captcha.asp?ck='+Math.random());
	return false;
}

$(document).ready(function() {
	$('#keyword').inputLabel(false, { color:'#b0b0b0' });
	
	if ($('ul.resizable').length>0) {
		$('ul.resizable').each(function(){
			var top = $(this).children('li:first-child').position().top;
			var pos = $(this).children('li:last-child').position().top;
			var fsize = $(this).children('li').css('font-size').replace('px','');
			while(pos>top && fsize>10){ 
				fsize-=1 ;
				$(this).children('li').css({'font-size':fsize+'px'});
				pos = $(this).children('li:last-child').position().top;
			}
			$(this).css({'visibility':'visible'});
		});
	}

	var dates = $('#check_in');
	if (dates.length>0) {
		var defaultEmptyMessage=$('#check_in').val();
		dates.addClass('empty').addClass('calendar');
		dates.datepicker({
			altField: '#check-in_day',
			altFormat: 'DD',
			maxDate: '+1y',
			minDate: +1,
			numberOfMonths: 2,
			beforeShow: function(input, inst) {
				$(this).addClass('empty');
			},
			onSelect: function(selectedDate) {
				var option = this.id == "check_in" ? "minDate" : "maxDate";
				var instance = $(this).data("datepicker");
				var date = $.datepicker.parseDate(instance.settings.dateFormat || $.datepicker._defaults.dateFormat, selectedDate, instance.settings);
				dates.not(this).datepicker("option", option, date);
				var d=date;
				d.setDate(parseInt(d.getDate()) + parseInt($('#nights').val()));
				$('#check-out_date').val($.datepicker.formatDate('DD d M yy', d));
				showRooms();
			},
			onClose: function(selectedDate, instance) {
				try {
					if (!$.datepicker.parseDate(instance.settings.dateFormat || $.datepicker._defaults.dateFormat, selectedDate, instance.settings)) {
						this.value=defaultEmptyMessage;
						$('#check-in_day').val('');
						$('#check-out_date').val('');
						$(this).addClass('empty');
					} else {
						$(this).removeClass('empty');
					}
				} catch(e) {
	//				console.log('Invalid check-in date');
				}
			}
		});
	}

	var nights = $('#nights');
	if (nights.length>0) {
		nights.change(function(){
			var num=this.value;
			var date_in=$('#check_in');
			try {
				var d=$.datepicker.parseDate($.datepicker._defaults.dateFormat, $(date_in).val());
				d.setDate(parseInt(d.getDate()) + parseInt(num));
				$('#check-out_date').val($.datepicker.formatDate('DD d M yy', d));
			} catch(e) {
//				console.log('Invalid check-in date');
			}
		});
	}
	
	var pr_dates = $('#pr_check_in');
	if (pr_dates.length>0) {
		var pr_defaultEmptyMessage=$('#pr_check_in').val();
		pr_dates.addClass('empty').addClass('calendar');
		pr_dates.datepicker({
			altField: '#pr_check-in_day',
			altFormat: 'DD',
			maxDate: '+1y',
			minDate: +1,
			numberOfMonths: 2,
			beforeShow: function(input, inst) {
				$(this).addClass('empty');
			},
			onSelect: function(selectedDate) {
				var option = this.id == "pr_check_in" ? "minDate" : "maxDate";
				var instance = $(this).data("datepicker");
				var date = $.datepicker.parseDate(instance.settings.dateFormat || $.datepicker._defaults.dateFormat, selectedDate, instance.settings);
				pr_dates.not(this).datepicker("option", option, date);
				var d=date;
				d.setDate(parseInt(d.getDate()) + parseInt($('#pr_nights').val()));
				$('#pr_check-out_date').val($.datepicker.formatDate('DD d M yy', d));
				showRooms();
			},
			onClose: function(selectedDate, instance) {
				try {
					if (!$.datepicker.parseDate(instance.settings.dateFormat || $.datepicker._defaults.dateFormat, selectedDate, instance.settings)) {
						this.value=defaultEmptyMessage;
						$('#pr_check-in_day').val('');
						$('#pr_check-out_date').val('');
						$(this).addClass('empty');
					} else {
						$(this).removeClass('empty');
					}
				} catch(e) {
	//				console.log('Invalid check-in date');
				}
			}
		});
	}

	var pr_nights = $('#pr_nights');
	if (pr_nights.length>0) {
		pr_nights.change(function(){
			var num=this.value;
			var date_in=$('#pr_check_in');
			try {
				var d=$.datepicker.parseDate($.datepicker._defaults.dateFormat, $(date_in).val());
				d.setDate(parseInt(d.getDate()) + parseInt(num));
				$('#pr_check-out_date').val($.datepicker.formatDate('DD d M yy', d));
			} catch(e) {
//				console.log('Invalid check-in date');
			}
		});
	}
	
	var gdate = $('#gdate');
	if (gdate.length>0) {
		gdate.datepicker({
			maxDate: +1,
			numberOfMonths: 1
		});
	}

	text_content = $('#main_text');
	if(text_content.length>0) {
		current_size = text_content.css('fontSize');
		target_size = parseFloat(current_size, 10);
		size_unit = current_size.slice(-2);

		$('#increase').click(function(e){
			if(target_size<15) {
				target_size *=1.1;
				text_content.css('fontSize', target_size + size_unit);
			}
			return false;
		});

		$('#decrease').click(function(e){
			if(target_size>11) {
				target_size /=1.1;
				text_content.css('fontSize', target_size + size_unit);
			}
			return false;
		});
	}

	$('a[href^="http:"], a[rel="external"]').attr('target','_blank');
	$('#subscribe_email').inputLabel(false, { color:'#b0b0b0' });
	$('#subscribe_mobile').inputLabel(false, { color:'#b0b0b0' });
	if ($('a[rel="lightbox"]').length>0){
		$('a[rel="lightbox"]').fancybox({ titlePosition: 'inside' });
	}

	var $targetfields=$("input[data-maxsize], textarea[data-maxsize]"); //get INPUTs and TEXTAREAs on page with "data-maxsize" attr defined
	setformfieldsize($targetfields);
});


$(window).load(function () {
	scrollPanes = $('.section_bottom_half .scrollable');
	if( scrollPanes.length>0 ) {
		var h=$('div.faux_columns').height();
		var t=$('.section_bottom_half .news h3').outerHeight(true);
		$('.section_bottom_half .news ul').css('height', h-50-t);
		scrollPanes.jScrollPane({dragMinHeight:30, dragMaxHeight:120, scrollbarWidth:12, scrollbarMargin:20});
	}
});

