/* IE6 flicker fix
-------------------------------------------------- */
try { document.execCommand("BackgroundImageCache", false, true); } catch(err){}
jQuery.fn.hasClass = function(c) { return this.is('.'+c) };
function g(r){ return document.getElementById(r); }

var now = new Date();
var time = new Date(now.getFullYear(), now.getMonth(), now.getDate()); 

$.fn.tagName = function(){
	if(1 === this.length){
		return this[0].tagName.toLowerCase();
	} else{
		var tagNames = [];
		this.each(function(i, el){
			tagNames[i] = el.tagName.toLowerCase();
		});
		return tagNames;
	}
};
var bookingSearchBox = {
	'calendarColouring': {
		'timeFrame': {
			'start': undefined,
			'end': undefined
		},
		'cachedColourings': new Array()
	},
	'selectedHotelID': undefined
};



/* Init */

$(document).ready(function() {
	if($('#contentslider').length>0){
		$('#contentslider').slideshow();
	}
	if($('.accordion').length>0){
		$( ".accordion" ).accordion({
			autoHeight: false,
			collapsible: true
		});
	}; 
	/*$('INPUT.wdate').each(function(a, b) {
	$(this).datePicker({
		startDate : '01/01/2008',
		ico:js_site_url+'img/ico_calendar.png'
	}).dpSetOffset(0,-330).dpSetRenderCallback(
		function(d, currentDate, month, year)
		{
			if (currentDate.valueOf() < time.valueOf())
			{
				$(d).addClass('disabled na');
			}
		}
		);
	});*/
	if($('#banners').length>0){
		initScroller();
	}
	$("#kubijaGallery").Gallery({});
	initTooltip(); 
	
	/* eDream Booking begin */
	
	Date.format = 'dd.mm.yyyy';
	setBookingCalendarTimeFrame();

	$('INPUT.forms_pickdate').each(function() {
		$(this).datePicker({hideLegend: true, startDate: '01.01.1000', showYearNavigation: false, ico:js_site_url+'img/ico_calendar.png'}).dpSetOffset(0,24);
	});

	$('INPUT.pickdate').each(function() {
		$(this).datePicker({ clickInput: true, hideLegend: true, showYearNavigation: false, ico:js_site_url+'img/ico_calendar.png'}).dpSetOffset(20,-100);
	});

	if ($('#checkin').length > 0 && $('#checkin').val().length == 0)
	{
		var defaultStartDate = new Date();
		defaultStartDate.addDays(1);
		var defaultStartDateString = defaultStartDate.asString();
		$('#checkin').val(defaultStartDateString);
		var defaultEndDateString = defaultStartDate.addDays(1).asString();
		$('#checkout').val(defaultEndDateString);
	}

	$('#rooms_search_button').click(function(){
	
		$('.error').hide();

		hotelID = 41;
		clientName = 'kubijahotell';
		
		var checkIn		= Date.fromString($('#checkin').val());
		var checkOut	= Date.fromString($('#checkout').val());
		
		var nights = 2;

		var currentDate = new Date().zeroTime();

		if (checkIn < currentDate) {
			alert('Check in date is invalid or in the past!');
			return false;
		}

		var rooms = 1;

		var errors = [];
		var error = false;

		if(error) {
			return false;
		}

		var promocode = $.trim($('#promocode').val());

		var url = 'https://bookings.edreamhotels.com/' + js_site_lang + '/Booking/available-rooms/client/' + clientName + '/hotels/' + hotelID + '/checkin/' + checkIn.asString() + '/checkout/' + checkOut.asString() + '/rooms/' + rooms;

		var adults = parseInt($('#adults').val());
		var children = parseInt($('#children').val());
		url += '/adults/' + adults;
		url += '/children/' + children;

		if (promocode.length > 0) {
			url += '/code/' + promocode.toUpperCase();
		}

		if (typeof(_var) != 'undefined' && typeof(_var.search_parameters) != 'undefined' && _var.search_parameters.pguid && _var.search_parameters.pdomain) {
			url += '/pguid/'+_var.search_parameters.pguid+'/pdomain/'+_var.search_parameters.pdomain;
		}

		window.open(url);

		return true;
	});

	$('#room_plus').click(function(){handleRoomsCount(+1);});
	$('#room_minus').click(function(){handleRoomsCount(-1);});
	$('#rooms').change(function(){handleRoomsCount(0);});
	$('#rooms').blur(function(){handleRoomsCount(0);});

	$('#rooms').change();

	/* eDream Booking end */
});

var newslength;
var newswidth;
function initScroller(){
	newslength = $("#banners .container > UL > LI").length;
	newswidth = $("#banners .container > UL > LI").outerWidth();
	if(newslength<=3){
		$("#banners").addClass("disabled");
	}
	else{
		$("#banners .container > UL").css("width",(newslength*newswidth*3)+"px");
		var slides = $("#banners .container > UL").contents().clone();
		$("#banners .container > UL").prepend(slides);
		$("#banners .container > UL").append(slides.clone());
		$("#banners .container > UL").css("left",-(newslength*newswidth)+"px");
		$("#banners .btnLeft").click(function(){
			if(!$(this).hasClass("animating")&&!$(this).hasClass("disabled")){
				$("#banners .btnLeft").addClass("animating");
				$("#banners .btnRight").addClass("animating");
				$("#banners .container > UL").animate({
				left: '+='+newswidth
				}, 1000,
				function() { updateScroller() });
			}
			return false;
	
		});
	}
	$("#banners .btnRight").click(function(){
		if(!$(this).hasClass("animating")&&!$(this).hasClass("disabled")){
			$("#banners .btnRight").addClass("animating");
			$("#banners .btnLeft").addClass("animating");
			$("#banners .container > UL").animate({
			left: '-='+newswidth
			}, 1000,
			function() { updateScroller() });
		}
		return false;

	});
	updateScroller();
}

function updateScroller(){
	$("#banners .btnLeft").removeClass("animating");
	$("#banners .btnRight").removeClass("animating");
	if(parseInt($("#banners .container > UL").css("left"))>=0){
		$("#banners .container > UL").css("left",-(newslength*newswidth)+"px");
	}
	else{
		$("#banners .btnLeft").removeClass("disabled");
	}
	if(parseInt($("#banners .container > UL").css("left"))<=-((newslength*3)-3)*newswidth){
		$("#banners .container > UL").css("left",-((newslength-3)*newswidth)+"px");
	}
}


/* function to fix the -10000 pixel limit of jquery.animate */
$.fx.prototype.cur = function(){
	if ( this.elem[this.prop] != null && (!this.elem.style || this.elem.style[this.prop] == null) ) {
	  return this.elem[ this.prop ];
	}
	var r = parseFloat( jQuery.css( this.elem, this.prop ) );
	return typeof r == 'undefined' ? 0 : r;
}


var rotateInterval;
var mouseWithin=false;
   
(function($) {
  $.fn.slideshow = function(customOptions) {
	 var options = {
      action: "init",
	  pos: -1
    };
    $.extend(options, customOptions);
    $targ = $(this);
	
	if(options.action=="init"){
		$('.images li',$targ).css({opacity: 0.0});
		$('.imagedata li',$targ).css({display:'none'});
		
		var imagecount = $('.images li',$targ).length;
		$('ul.bullets',$targ).empty();
		var i = 1;
		$('.images li',$targ).each(function(){
			$(this).css("z-index",i*10);
			$('ul.bullets',$targ).append('<li><a href="#"></a></li>');
			i++;
		});
		$('ul.bullets LI',$targ).first().addClass("first");
		$('ul.bullets LI',$targ).last().addClass("last");
		$('ul.bullets',$targ).css("margin-left",-$('ul.bullets',$targ).width()/2);
		//Get the first image and display it (gets set to full opacity)
		$('.images li:first',$targ).css({opacity: 1.0});
		$('.imagedata li:first',$targ).css({display:'block'})
		.addClass("show");
		
		$('ul.bullets li:first',$targ).addClass("active");
		if(imagecount>1){
			$targ.mouseover(function(){
				clearInterval(rotateInterval);
				mouseWithin = true;
			})
			.mouseout(function(){
				clearInterval(rotateInterval);
				mouseWithin = false;
			})
			$('ul.bullets li a',$targ).click(function(){
				$('ul.bullets li',$targ).removeClass("active");
				$(this).parent().addClass("active");
				var newpos = $('ul.bullets li',$targ).index($(this).parent());	
				clearInterval(rotateInterval);
				$("#"+$targ.attr("id")).slideshow({action:"rotate",pos:newpos});	
				$targ.mouseover();
				return false;
			});
			$('#contentslider .btnLeft').click(function(){
				clearInterval(rotateInterval);
				var current = ($('.images li.show',$targ)?  $('.images li.show',$targ) : $('.images li:first',$targ));
				if ( current.length == 0 ) current = $('.images li:first',$targ);
				var newpos = $('.images li',$targ).index(current);
				if(newpos>0){
					$targ.slideshow({action:"rotate",pos:newpos-1});					
				}
				else{
					$targ.slideshow({action:"rotate",pos:$('.images li',$targ).length-1});
				}
				$targ.mouseover()
				return false;
			})
			$('.btnRight',$targ).click(function(){
				clearInterval(rotateInterval);
				var current = ($('.images li.show',$targ)?  $('.images li.show',$targ) : $('.images li:first',$targ));
				if ( current.length == 0 ) current = $('.images li:first',$targ);
				var newpos = $('.images li',$targ).index(current);
				if(newpos<$('.images li',$targ).length-1){
					$targ.slideshow({action:"rotate",pos:newpos+1});
				}
				else{
					$targ.slideshow({action:"rotate",pos:0});
				}
				$targ.mouseover()
				return false;
			})
			//Call the rotator function to run the slideshow, 6000 = change to next image after 6 seconds
			
			//rotateInterval = setInterval('$("#'+$targ.attr("id")+'").slideshow({action:"rotate",pos:-1})',6000);
		}
	}
	else if(options.action=="rotate"){		
		clearInterval(rotateInterval);			
		//Get the first image
		var current = ($('.images li.show',$targ)?  $('.images li.show',$targ) : $('.images li:first',$targ));
		var currenttext = ($('.imagedata li.show',$targ)?  $('.imagedata li.show',$targ) : $('.imagedata li:first',$targ));
		var currentdot = ($('ul.bullets li.active',$targ)?  $('ul.bullets li.active',$targ) : $('ul.bullets li:first',$targ));
		
		if ( current.length == 0 ) current = $('.images li:first',$targ);
		if ( currentdot.length == 0 ) currentdot = $('ul.bullets li:first',$targ);
		var pos = options.pos;
		//Get next image, when it reaches the end, rotate it back to the first image
		if(pos>=0){
			var next = $('.images li',$targ).eq(pos);
			var nextdot = $('ul.bullets li',$targ).eq(options.pos);
		}
		else{
			var next = ((current.next().length) ? ((current.next().hasClass('show')) ? $('.images li:first',$targ) :current.next()) : $('.images li:first',$targ));
			var nextdot = ((currentdot.next().length) ? ((currentdot.next().hasClass('active')) ? $('ul.bullets li:first',$targ) :currentdot.next()) : $('ul.bullets li:first',$targ));
		}
		if ( currenttext.length != 0 ) {
			if(pos>=0){
				var nexttext = $('.imagedata li',$targ).eq(pos);
			}
			else{
				var nexttext = ((currenttext.next().length) ? ((currenttext.next().hasClass('show')) ? $('.imagedata li:first',$targ) :currenttext.next()) : $('.imagedata li:first',$targ));
			}
			nexttext.addClass('show')
			.show();
		
			//Hide the current image
			currenttext.hide()
			.removeClass('show');
		}
		
		//Set the fade in effect for the next image, the show class has higher z-index
		next.css({opacity: 0.0})
		.addClass('show')
		.animate({opacity: 1.0}, 1000);
	
		//Hide the current image
		current.animate({opacity: 0.0}, 1000)
		.removeClass('show');
		
		currentdot.removeClass("active");
		nextdot.addClass("active");
	};    
  };
})(jQuery);

/* Tooltip */

function initTooltip(){
	$tooltip ='<div id="tooltip">';
	$tooltip +='	<div id="tooltip-start"><span class="a"></span><span class="c"></span><span class="b"></span><span class="d"></span></div>';
	$tooltip +='	<div id="tooltip-body">';
	$tooltip +='		<span class="content-a"></span>';
	$tooltip +='		<div class="content-b"><div id="tooltip-inner" class="w100p content"></div></div>';
	$tooltip +='		<span class="content-c"></span>';
	$tooltip +='	</div>';
	$tooltip +='	<div id="tooltip-ending"><span class="a"></span><span class="c"></span><span class="b"></span><span class="d"></span></div>';
	$tooltip +='</div>';
	$("body").append($tooltip);
}

function showTooltip(txt,opt){
	if(opt.title){
		title = "<p class='title'>"+opt.title+"</p>";
	} 
	else {
		title = ""; 
	}
	if(opt.logo){
		$('#tooltip').find('#tooltip-inner').html('<div class="clear">'+title+'<div class="col-a"><img src="'+opt.logo+'" alt="" /></div><div class="col-b">'+txt+'</div></div>');
	} else {
		$('#tooltip').find('#tooltip-inner').html('<div class="clear">'+title+'<p>'+txt+'</p></div>');
	}
	var offset = $(opt.ref).offset();
	var twidth = $('#tooltip').outerWidth();
	// if the tooltip would go outside pages edge try and fix
	if(offset.left - twidth<0 && opt.align!='right'){
		opt.align='right';
	}
	// position tooltip based on alignment. default is left
	if(opt.align=="right"){
		$('#tooltip-start span.d').hide();
		$('#tooltip-start span.e').show();
		$('#tooltip').css({
				left: offset.left +$(opt.ref).width() + 28 + 'px',
				top: offset.top + 'px'
			})
		;
	}
	else{
		$('#tooltip-start span.e').hide();
		$('#tooltip-start span.d').show();
		$('#tooltip').css({
				left: offset.left - twidth + 'px',
				top: offset.top + 'px'
			})
		;
	}
}
function hideTooltip(){
	$('#tooltip').css({
		left: '-1000px',
		top: '-1000px'
	});
}


/* Tabs switcher */

function showTab(ref,set){
	$('#'+set+' > LI > A').each(function(i,a){
		$(a).removeClass('active');
		$($(a).attr('href')).addClass('hidden');
	});
	$(ref).addClass('active');
	$($(ref).attr('href')).fadeIn(500).removeClass('hidden').css({display: ''});
	return false;
}

/* eDream Booking form functions */
/* Booking calendar */

function setBookingCalendarTimeFrame()
{
	var startDate = new Date();
	var endDate = new Date();

	startDate.setDate(1);

	endDate.setDate(0);
	endDate.setMonth(endDate.getMonth()+1);
	endDate.setYear(endDate.getFullYear()+1);

	timeFrame = {'start': startDate.asString(), 'end': endDate.asString()};

	bookingSearchBox.calendarColouring.timeFrame.start = startDate.asString();
	bookingSearchBox.calendarColouring.timeFrame.end = endDate.asString();
}

function getNewDate(date, days, id) {

	var checkIn = Date.fromString(date);
	var currentDate = new Date().zeroTime();

	if (checkIn < currentDate)
	{
		date = currentDate.asString();
		$('#checkin').val(date);
	}

	if((date != '') && (days != '')) {
		var olddate = new Date(date.substring(6, 10), date.substring(3, 5) - 1, date.substring(0, 2));
		olddate.setDate(olddate.getDate() + eval(days));
		var day = (olddate.getDate() + '').length == 1 ? ("0" + olddate.getDate()) : olddate.getDate();
		var month = olddate.getMonth() + 1;
		month = (month + '').length == 1 ? ("0" + month) : month;
		$('#' + id)[0].value = day + '.' + month + '.' + olddate.getFullYear();
		$('#' + id).change();
	}
}

function getDateDif(date1, date2, id) {
	if((date1 != '') && (date2 != '')) {
		var d1 = new Date(date1.substring(6, 10), date1.substring(3, 5) - 1, date1.substring(0, 2));
		var d2 = new Date(date2.substring(6, 10), date2.substring(3, 5) - 1, date2.substring(0, 2));
		d11 = d1.getTime();
		d12 = d2.getTime();
		var one_day = 1000 * 60 * 60 * 24;
		var dif = d12 - d11;
		var result = Math.round(dif / one_day);
		if (result >= 0) $('#' + id)[0].value = result;
		else $('#' + id)[0].value = 0;
	}
}

function checkDates(date1, date2, id1, id2) {
	if((date1 != '') && (date2 != '')) {
		var d1 = new Date(date1.substring(6, 10), date1.substring(3, 5) - 1, date1.substring(0, 2));
		var d2 = new Date(date2.substring(6, 10), date2.substring(3, 5) - 1, date2.substring(0, 2));
		var next = new Date();
		next.setDate(d1.getDate() + 1);
		var month = next.getMonth() + 1;
		var nextdate = _zeroPad(next.getDate()) + '.' + _zeroPad(month) + '.' + next.getFullYear();
		d11 = d1.getTime();
		d12 = d2.getTime();
		var one_day = 1000 * 60 * 60 * 24;
		var dif = d12 - d11;
		var result = Math.ceil(dif / one_day);
		if (result <= 0) {
			$('#' + id1)[0].value = nextdate;
			$('#' + id2)[0].value = '1';
		}
	}
}

function form_minus(ref) {
	if (ref.value > 1) {ref.value = ref.value - 1;}
}

function form_plus(ref) {
	if (ref.value < 1) {ref.value = 0;}
	ref.value = eval(ref.value) + 1;
}

function handleRoomsCount (increment)
{
	var inputValue = parseInt($('#rooms').val(), 10) + increment;

	var roomsNow = Math.min(4, Math.max(1, inputValue));
	var roomsVisible = $('div.room:visible').length;

	$('#rooms').val(roomsNow);

	if (roomsVisible < roomsNow)
	{
		for (var i = 1; i <= roomsNow; i++)
		{
			if ($('div.room#room'+i+':visible').length == 0) $('div.room#room'+i).show();
		}
	}
	else if (roomsVisible > roomsNow)
	{
		for (var i = 4; i > roomsNow; i--)
		{
			if ($('div.room#room'+i+':visible').length == 1)
			{
				$('div.room#room'+i).hide();
				$('div.room#room'+i+' select:eq(0)').val(1);
				$('div.room#room'+i+' select:eq(1)').val(0);
			}
		}
	}
	if($('div.room:visible').length==1){
		$('div.room#room1 P.bold').hide();
	}
	else{
		$('div.room#room1 P.bold').show();
	}
}
