// -- for Internet Explorer - stops background flickering --//
   /*@cc_on 
	@if (@_win32)
	try {
	  document.execCommand('BackgroundImageCache', false, true);
	} catch(e) {}
	@end
@*/
// -- addLoadEvent function from http://simonwillison.net --//
function addLoadEvent(func) {
  var oldonload = window.onload;
  if (typeof window.onload != 'function') {
    window.onload = func;
  } else {
    window.onload = function() {
      if (oldonload) {
        oldonload();
      }
      func();
    }
  }
}



//---- DROPDOWN LIST SYNC ----//
addLoadEvent(filterDestinations);
function hideOpt(opt,select){
  //var opt = document.getElementById(id);
  var sel = select;
  opt && sel && sel.appendChild(opt.cloneNode(true));
}

function showOpt(opt,select){ 
  var dest = select;//document.getElementById('ctl00_FindHotel1_fDestinationselect');
  if (opt) {
    if (dest) {
      dest.appendChild(opt.cloneNode(true));
    }
  }
} 

function moveSelectOption(select,selectcopy,start1,start2) {
    selectcopy.options.length=start2;
    for(i=start1;i<select.length;i++)
	{  //ignore the first please select
       hideOpt(select.options[i],selectcopy);
	}
	select.options.length=start1;
}
function findByValue(select,value){
    var valueToSelect = value;
    var mySelect = select;
    for (var index = 0, roof = mySelect.options.length; index < roof; index++) {
       if (valueToSelect == mySelect.options[index].value) {
          return mySelect.options[index];
       }
    }
}
function filterDestinations(){
    
        if (typeof cIdTempSelectArrayId != 'undefined') 
            {for (var index = 0, roof = cIdTempSelectArrayId.length; index < roof; index++)
                {subFilterDestinations(cIdTempSelectArrayId[index][0],cIdTempSelectArrayId[index][1],cIdTempSelectArrayId[index][2]);}
        } 
    
}

function subFilterDestinations(tempId,mainSelect,subSelect){
  var temp = document.getElementById(tempId);
  var country,dest,selectedValue,mainS,subS;
  
  if (temp) if (mainSelect) country = document.getElementById(mainSelect);
  if (temp) if (mainSelect) dest = document.getElementById(subSelect);
  
  if (temp && country && dest) {
      selectedValue=dest.options[dest.selectedIndex].value;
      if (temp.length == 0 ) moveSelectOption(dest,temp,1,0);
      dest.options.length=1;
      if (country) {
        for (var currObj in CountrySlhDest){
           if (CountrySlhDest[currObj][country.value]) {showOpt(findByValue(temp,CountrySlhDest[currObj][country.value]),dest);}
        }
        if (country.selectedIndex==0) {moveSelectOption(temp,dest,0,1);}
        if (dest.options.length == 1 && (dest.options[0].text=='Please Choose' || dest.options[0].text=='-- Not Applicable --')) dest.options[0].text = '-- Not Applicable --'; else if (dest.options[0].text=='Please Choose' || dest.options[0].text=='-- Not Applicable --') dest.options[0].text='Please Choose';
      }
      var obj=findByValue(dest, selectedValue)
      if (obj) obj.setAttribute('selected',true);  
   }   
}

function setCookie(c_name,value,expiredays,path)
{
    var exdate=new Date();
    exdate.setDate(exdate.getDate()+expiredays);
    document.cookie=c_name+ "=" +escape(value)+
    ((expiredays==null) ? "" : ";expires="+exdate.toUTCString()) +
    (path ? ";path=" + path : "");
}

function getCookie(c_name)
{
    if (document.cookie.length>0)
      {
      c_start=document.cookie.indexOf(c_name + "=");
      if (c_start!=-1)
        {
        c_start=c_start + c_name.length+1;
        c_end=document.cookie.indexOf(";",c_start);
        if (c_end==-1) c_end=document.cookie.length;
        return unescape(document.cookie.substring(c_start,c_end));
        }
      }
    return "";
}



//---- RESERVATION DROPDOWNS ----//  
function unSelect(dropdownId)
{
    //selects the first element of a dropdown list
    if (document.getElementById(dropdownId)){document.getElementById(dropdownId).selectedIndex =0;}
}

//---- DATEPICKER/Calendar ----//
var _$bookingForm = $("#booking_form");
var _$hotelNightsContainer = _$bookingForm.find(".findAHotelNights")
var _$hotelGuestsContainer = _$bookingForm.find(".findAHotelGuests")
var _$arrivingTextInput = _$bookingForm.find(".arriving")
var _$departingTextInput = _$bookingForm.find(".departing")
var _$nightsSelectInput = _$bookingForm.find(".no-of-nights")
var _$guestsSelectInput = _$hotelGuestsContainer.find(".guests")

var _$calendarContainer = $("#calendar-control");
var _$emptyCalendarContainer = _$calendarContainer.find("#cal")
var _$calendarTable = _$calendarContainer.find("table");
	

// ----------- top destinations
var locationSelector = $("#locations-selector");
var monthList = locationSelector.find("#months a");
var resultsPanel = locationSelector.find("#locations-selector-results");
var monthListItem = locationSelector.find("#months li");

$(function (){

    if(typeof(monthList) != 'undefined')
    {
		monthList.bind("click", function() {
			$.ajax({
				 url: this.href,
			       success: function(html){
				        resultsPanel.empty().append(html);
						monthListItem.removeClass("selected");
						$(this).parent().addClass("selected")
			        }
			})
		return false;
		})  
    }

	if(_$calendarContainer.length > 0){
		
		//call ajax request to get unavailable dates
		AJAXCalendar();
		
		if(unavailableDates.length > 0){
			for(i=0; i<unavailableDates.length; i++){
				unavailableDates[i] = new Date(unavailableDates[i]+" 00:00:00")
			}
		}
		//get today's date
		var todaysDate = new Date();
		todaysDate.getDate()
		
		//get prepopulated dates for pre-selection
		var preSelected = new Array();
		var sd;
		var ed; 
		var numberOfNights; 
		
		sd = _$arrivingTextInput.val();
		numberOfNights = _$nightsSelectInput.val();
		//have to swap the date string into yy,mm,dd to create a date object
		var yearStr = sd.substring(6, 10)
		var monStr = sd.substring(3, 5)
		var dayStr = sd.substring(0, 2)
		//initialise date object

		var startDate = new Date();
		//startDate.setDate(yearStr+","+monStr+","+dayStr)
		var startDate = new Date(yearStr+","+monStr+","+dayStr)
		
		var nextDate = new Date();
		nextDate.setDate(startDate.getDate()+1);
	
		//calculate new date object from sd + 1da
		for(i=0; i<numberOfNights; i++){
			preSelected.push(nextDate.setDate(nextDate.getDate()+1) )
			//console.log(preSelected[i])
		}
		
		var clickFlag = 1;
		
		
		//initialise Date/time functions
		Date.prototype.msPERDAY = 1000 * 60 * 60 * 24;
		Date.prototype.getDaysBetween = function(d){
			d = d.copy();
			d.setHours(this.getHours(), this.getMinutes(), this.getSeconds(), this.getMilliseconds());
			var diff = d.getTime() - this.getTime();
			return (diff) / this.msPERDAY;
		};
		Date.prototype.copy = function(){
			return new Date(this.getTime());
		};

		//render new calendar
		_$calendarTable.hide();

		_$emptyCalendarContainer.availabilitycalendar({
			flat: true,
			date: '24/06/2010', //controls initial selected item - can use multiple selections
			current: '01/07/2010', //controls calendar month layout
			calendars: 2,
			format: 'd/m/Y',
			mode: 'range',
			starts: 1,
			prev: 'previous',
			next: 'next',
			onChange: function(formated, dates){
				if (clickFlag == 1) {
					_$arrivingTextInput.val(formated[0]);
					clickFlag = 2;
				}
				else 
					if (clickFlag == 2) {
						_$departingTextInput.val(formated[1]);
						sd = dates[0]
						ed = dates[1]
						var days = sd.getDaysBetween(ed);
						clickFlag = 1
						_$nightsSelectInput.hide()
						//reusing variable name instead of redeclaring doesn't seem to work here
						//do I need a live command for dynamically inserted element?
						if ($(".new-nights").length > 0) {
							$(".new-nights").val(days)
						}
						else {
							_$hotelNightsContainer.append("<input type='text' value='" + days + "' class='new-nights text'/>")
						}
					}
			},
			onRender: function(date){
				var disabledBoolean = false;
				var classNameVal = false;
				
				if (date.valueOf() < todaysDate.valueOf()) {
					disabledBoolean = true;
				}
				else {
					for (i = 0; i < unavailableDates.length; i++) {
						if ((date.valueOf() == unavailableDates[i].valueOf())) {
							disabledBoolean = true;
							classNameVal = 'availabilitycalendarSpecial'
						}
					}
				}
				return {
					disabled: disabledBoolean,
					className: classNameVal
				}
			}
		})	
	}//end of calendar 	

	if (_$bookingForm.length > 0) {
		if (_$arrivingTextInput.val() == "" || _$arrivingTextInput.val() == "dd/mm/yyyy") {
			_$arrivingTextInput.val("dd/mm/yyyy");
			if ($("#find_a_hotel").length > 0) {
				showHideNightsAndGuests(false);
			}
			else {
				showHideNightsAndGuests(true);
			}
		}else{
			showHideNightsAndGuests(true);
		}
		
		//this change not working on datepicker change
		_$arrivingTextInput.bind('focus', function(){
			var show = $(this).val() != "" && $(this).val() != "dd/mm/yyyy";
			showHideNightsAndGuests(show);
		})
		_$arrivingTextInput.bind('keyup', function(){
			showHideNightsAndGuests($(this).val().length > 0);
		})
		
		_$arrivingTextInput.bind('click', function(){
			_$arrivingTextInput.val("")
		})
	}
})
function showHideNightsAndGuests(show) {
    if (show){
       _$hotelNightsContainer.show();
       _$hotelGuestsContainer.show();
       _$hotelNightsContainer.css({ "display": "block" });
       _$hotelGuestsContainer.css({ "display": "block" });

    }else{
        _$hotelNightsContainer.hide();
        _$hotelGuestsContainer.hide();

    }
}

function makeTwoChars(inp) {
        return String(inp).length < 2 ? "0" + inp : inp;
}

//not sure what this function is for?
function setLowRangeToBeSixWeeksAfterToday() {
        if(!("sd" in datePickerController.datePickers)) {
                setTimeout("setLowRangeToBeSixWeeksAfterToday()", 50);
                return;
        }
        
        var dt = new Date();
        dt.setDate(dt.getDate() +  (6 * 7));
        
        var stringDt = dt.getFullYear() + String(makeTwoChars(dt.getMonth())) + makeTwoChars(dt.getDate());

        datePickerController.datePickers["sd"].setRangeLow(stringDt);
        datePickerController.datePickers["ed"].setRangeLow(stringDt);
    }


//AJAX availability calendar
var AJAXCalendar = function(){
	var __next = $("#next-month");
	var __previous = $("#previous-month");
	//_$calendar.append(__container)

	var __temp = document.createElement("div");
	__temp.id = "temp";
	
	//Click event on the next button
	__next.bind("click", function(){
		var __url = createUrl(_$next.attr("href"));
		$.ajax({
			url: __url,
			success: function(html){
				update(html);
			}
		})
		return false;
	});

	__previous.bind("click", function(){
	var __url = createUrl(_$previous.attr("href"));
		
		$.ajax({
			url: __url,
			success: function(html){
				//__ajaxLoader.hide()
				update(html);
			}
		})
		return false;
	});

	function createUrl(url){
		var __chkIn = _$arrivingTextInput.val();
		var __chkOut = _$departingTextInput.val();
		var __guests =_$guestsSelectInput.val();
		
		__chkIn = __chkIn.replace(/\//g, "-");
		__chkOut = __chkOut.replace(/\//g, "-");
		
		__chkIn = "&checkin=" + __chkIn;
		__chkOut = "&checkout=" + __chkOut;
		__guests = "&guests=" + __guests;
		var __currentLanguage = "&lang=" + currentLanguage;
		var __trustId = "";
		
		if (typeof(currentHotelTrustId) != "undefined") {
			__trustId = "&hid=" + currentHotelTrustId;
		}
		
		var __urlString = url + __chkIn + __chkOut + __guests + __currentLanguage + __trustId;
		return __urlString;
	}
	
	function update(html){
		//replace the temp div contents with the new HTML
		$(__temp).empty();
		$(__temp).append(html);
		//replace the tbody with the new tbody
		__calendar = _$calendar;
		__calendar.replaceWith($(__temp).find("tbody"));
		//replace the date with the new date
		__date = $(".availability-calendar table #date");
		__date.replaceWith($(__temp).find("#date"));
		//update the HREF on the buttons
		__next.attr("href", $(__temp).find("#next-month").attr("href"));
		__previous.attr("href", $(__temp).find("#previous-month").attr("href"));

	}
}

var AJAXBooking = function() {

    var results = $(".book-now-results");

    results.bind("click", function() {
        var __url = createUrl(results.attr("href"));

        //results.c

        $.ajax({
            url: __url,
            success: function(html) {
                update(html);
            }
        });

        return false;
    });

    function createUrl(url) {
        var __chkIn = _$arrivingTextInput.val();
        __chkIn = "&checkin=" + __chkIn;

        var __urlString = url + __chkIn;
        return __urlString;
    }
};


function setReservationDates(e) {


    // Check the associated datePicker object is available (be safe)
    if (!("sd" in datePickerController.datePickers)) {
        document.getElementById("noOfNightsSpan").innerHTML = "--";
        return;
    }

    // Check the value of the input is a date of the correct format
    var dt = datePickerController.dateFormat(this.value, datePickerController.datePickers["sd"].format.charAt(0) == "m");

    // If the input's value cannot be parsed as a valid date then return
    if (dt == 0) {
        document.getElementById("noOfNightsSpan").innerHTML = "--";
        setDateDiff(e);
        return;
    }

    // Grab the value set within the endDate input and parse it using the dateFormat method
    // N.B: The second parameter to the dateFormat function, if TRUE, tells the function to favour the m-d-y date format
    var edv = datePickerController.dateFormat(document.getElementById("ed").value, datePickerController.datePickers["ed"].format.charAt(0) == "m");

    // Grab the end date datePicker Objects
    var ed = datePickerController.datePickers["ed"];

    //Set low range to be alway connected to the start date
    var lr = datePickerController.dateFormat(document.getElementById("sd").value, datePickerController.datePickers["sd"].format.charAt(0) == "m");
    var sdd;
    if (lr.length == 8) {
        sdd = new Date(lr.substring(0, 4), lr.substring(4, 6) - 1, lr.substring(6, 8));
        sdd.setTime(sdd.getTime() + (1000 * 24 * 60 * 60)); //add a day
        lr = sdd.getFullYear().toString() + LZ((sdd.getMonth() + 1).toString()) + LZ(sdd.getDate().toString());
        if (dt != 0) { ed.setRangeLow(lr); }
    }
    // If theres a value already present within the end date input and it's smaller than the start date
    // then clear the end date value
    if (edv < dt) {
        document.getElementById("ed").value = "";
        document.getElementById("noOfNightsSpan").innerHTML = "--";
    }

    var sdv = datePickerController.dateFormat(document.getElementById("sd").value, datePickerController.datePickers["sd"].format.charAt(0) == "m");

    //if date is ok, try to count the days and fill the span
    //if(document.getElementById("noOfNightsSpan")) {
    //        document.getElementById("noOfNightsSpan").innerHTML = (edv-sdv);
    //}
    setDateDiff(e);
}

function LZ(x) { return (x < 0 || x > 9 ? "" : "0") + x }

function setDateDiff(e) {

    var sdv = datePickerController.dateFormat(document.getElementById("sd").value, datePickerController.datePickers["sd"].format.charAt(0) == "m");
    var edv = datePickerController.dateFormat(document.getElementById("ed").value, datePickerController.datePickers["ed"].format.charAt(0) == "m");

    // Check the associated datePicker object is available (be safe)
    if (!("sd" in datePickerController.datePickers || sdv == 0)) {
        document.getElementById("noOfNightsSpan").innerHTML = "--";
        return;
    }
    if (!("ed" in datePickerController.datePickers || edv == 0)) {
        document.getElementById("noOfNightsSpan").innerHTML = "--";
        return;
    }
    var sdd, edd;
    if (sdv == edv) {
        document.getElementById("ed").value = "";
        document.getElementById("noOfNightsSpan").innerHTML = "--";
        return;
    }

    if (sdv.length == 8) { sdd = new Date(sdv.substring(0, 4), sdv.substring(4, 6) - 1, sdv.substring(6, 8)); }
    if (edv.length == 8) { edd = new Date(edv.substring(0, 4), edv.substring(4, 6) - 1, edv.substring(6, 8)); }

    //if date is ok, try to count the days and fill the span
    if (document.getElementById("noOfNightsSpan")) {
        //document.getElementById("noOfNightsSpan").innerHTML = (edv-sdv);
        var one_day = 1000 * 60 * 60 * 24;

        //Calculate difference btw the two dates, and convert to days
        var daysspan = Math.ceil((edd - sdd) / one_day);
        if (daysspan > 0) { document.getElementById("noOfNightsSpan").innerHTML = daysspan; } else { document.getElementById("noOfNightsSpan").innerHTML = "--"; }

    }
}

addLoadEvent(dropdownRedirect);
function dropdownRedirect() {
		
		var dropdown = document.getElementById('footer').getElementsByTagName('select')[0];
		var button = document.getElementById('footer').getElementsByTagName('input')[0];

}






$(function() {
	//$('body').addClass('js');
    if ($("#masthead-gallery").length > 0) {hotelGallery();};
    if ($("ol.reasons").length) {clubReasons();};

	if ($('.gallery-inner .thumb a').length){
		showImage();
		scroller();
		prevNext();
		gallerySlideShow();
		//var $imageURLs = getURLs();	
	};
	if ($('.club-member').length){showLogin();};
	if($('#panel-recommended-destinations').length){showRecommendedDestinations();}
	if($('.tabs-bigger-js').length){tabs();}
	if($('.login-link').length){logInSlideDown();}
	if($('#worldmap').length){worldmap();}
	if($('div.logged-home li.selected').length){clubHomeLoggedIn();}
	if($('.special-offer-summary-details').length){specialOfferDescription()};
})



/* GALLERY SHOW/HIDE */
var galleryPLImages = [];

var hotelGallery = function() {

    var __intro = $("#masthead-hotel");
    var __gallery = $("#masthead-gallery");
    var __galleryInner = $(".gallery-inner");
    var __open = $(".masthead-gallery-link");
    var __close = $("#masthead-gallery a.close");
    var __content = $("#content");
	
	// Preload images. This makes correctImageDimensions work more reliably
	var imageUrlsForPreloading = getURLs();
	for(var i=0; i<imageUrlsForPreloading.length; i++) {
		var image = new Image();
		image.src = imageUrlsForPreloading[i];
		galleryPLImages.push(image);
	}
	
	var openGallery = function() {
        __intro.fadeOut(500, function() {

            __gallery.css({ display: "block" });
            __content.animate({ paddingTop: 483 }, 500);
            __gallery.animate({ height: 465 }, 500, function() {
                __galleryInner.fadeIn(500);
				correctImageDimensions();
            });

        });

        return false;
	}

    __open.bind("click", openGallery);


    __close.bind("click", function() {
        // stop the slideshow
        gallerySlideShowStop();
        __galleryInner.fadeOut(500, function() {

            __content.animate({ paddingTop: 254 }, 500);
            __gallery.animate({ height: 236 }, 500, function() {

                __gallery.css({ display: "none" });
                __intro.fadeIn(500);

            });

        });

        return false;

    });

	if($('body.opengallery').length > 0) {
		openGallery();
	}

}




// GALLERY - Self contained 
var showImage = function(){
	$('.gallery-inner .thumb a').bind("click",function(){
		gallerySlideShowStop();	
		var __imgPath = $(this).attr('href');
		gallerySlideShowMainImage.fadeOut(250,function(){
			gallerySlideShowMainImage.attr('src',__imgPath);
			correctImageDimensions();
			gallerySlideShowMainImage.fadeIn(250);
			//gallerySlideShowMainImage.attr('display','inline-block');	
		});
		return false;
	});			
}


//Slideshow
var gallerySlideShowButton = $(".buttons .view");
var gallerySlideShowButtonImage = gallerySlideShowButton.find('img');
var gallerySlideShowMainImage = $('.main-image img');

var gallerySlideShow = function(){
	gallerySlideShowButton.bind("click", function(){
		if(window.slideshowRunning) {
			gallerySlideShowStop();
		}
		else {
			gallerySlideShowStart();
		}
		return false;
	});
	gallerySlideShowMainImage.bind("click", function(){
		if(window.slideshowRunning) {
			gallerySlideShowStop();
		}
		return false;
	})
}

var gallerySlideShowStart = function() {
	changeImage(0);
	window.slideshowInterval = setInterval("cycle()",4000);
	window.slideshowRunning = true;
	gallerySlideShowButtonImage.attr('src', function(){
		return this.src.replace('-view-', '-stop-');
	});
}
var gallerySlideShowStop = function() {
	window.clearInterval(window.slideshowInterval);
	window.slideshowRunning = false;
	gallerySlideShowButtonImage.attr('src', function(){
		return this.src.replace('-stop-', '-view-');
	});
}

var cycle = function(){
	var $imageURLs = getURLs();	
	__counter = getCurrentImage($imageURLs);
	__counter++;
	if(__counter==$imageURLs.length){__counter=0;}
	changeImage(__counter);
}



// CHANGE THE IMAGE 
var changeImage = function(__counter){
	var $imageURLs = getURLs();	

	gallerySlideShowMainImage.fadeOut(300,function(){
		gallerySlideShowMainImage.attr('src',$imageURLs[__counter]);
		gallerySlideShowMainImage.fadeIn(300);
		correctImageDimensions();
	});
}

var correctImageDimensions = function() {
	var MAXWIDTH = 473;
	var MAXHEIGHT = 360;
	
	var currentImageIndex = getCurrentImage(getURLs());
	gallerySlideShowMainImage.removeAttr('width');
	gallerySlideShowMainImage.removeAttr('height');

	var width = galleryPLImages[currentImageIndex].width;
	var height = galleryPLImages[currentImageIndex].height;
	
	if(width > MAXWIDTH || height > MAXHEIGHT) {
		var widthRatio = MAXWIDTH/width;
		var heightRatio = MAXHEIGHT/height;
		
		if(widthRatio < heightRatio) {
			var ratio = widthRatio;
		}
		else {
			var ratio = heightRatio;
		}

		var newWidth = Math.round(width*ratio);
		var newHeight = Math.round(height*ratio);
		
		//alert('Width: ' + width + '\nHeight: ' + height + '\n\nwidthRatio: ' + widthRatio + '\nheightRatio: ' + heightRatio + '\n\nnewWidth: ' + newWidth + '\nnewHeight: ' + newHeight);
		
		gallerySlideShowMainImage.attr('width', newWidth);
		gallerySlideShowMainImage.attr('height', newHeight);
	}
}



//Previous and Next buttons
var prevNext = function(){

	var $imageURLs = getURLs();
		
	$('.main-image .previous').bind("click", function(){
		gallerySlideShowStop();
		__counter = getCurrentImage($imageURLs);	
		__counter--;

		if (__counter < 0){
			__counter = ($imageURLs.length-1);
		} 
		changeImage(__counter);
		return false;
		
	});
	$('.main-image .next').bind("click", function(){
		gallerySlideShowStop();
		__counter = getCurrentImage($imageURLs);	
		__counter++;
		// ensure it's not going past the length of the array
		if (__counter > ($imageURLs.length - 1)){
			__counter = 0;
		}
		changeImage(__counter);
		return false;
	});
}

// get all the images into an array
var getURLs = function(){
	var $imageURLs = [];
	
	var __counter = 0;
	$(".gallery-inner .thumbCol li a").each(function() { 
		$imageURLs[__counter] = $(this).attr('href'); 
		__counter++;
	});
	return $imageURLs;
}

// find the current image and made the array number match it - that way we can figure out which image to show next/previous
var getCurrentImage = function($imageURLs){
	var __arrayCounter = 0;
	for( var i = 0; i < $imageURLs.length; i++ ){
		 if (gallerySlideShowMainImage.attr('src') == ($imageURLs[i])){
			 __arrayCounter = i;	
		}
	}
	return __arrayCounter;
}

// scroller function for IMAGE GALLERY */
var scroller = function(){
	$(".buttons .next").show();
	$(".buttons .previous").show();
	$(".thumbnailContainer").css('overflow-x','hidden');

	var __right = $(".buttons .next a");
	var __left = $(".buttons .previous a");
	var __container = $(".thumbnailContainer");
	var __scrollAmount = 1;
	var __current = 0;
	var __contentBoxes = $(".thumbnailContainer .thumbnailWrapper .thumbCol");
	var __max = Math.floor(__contentBoxes.length/__scrollAmount);
	__max = __max*__scrollAmount;
	
	//Activate both rollovers
	//rollover(__right,"FormatsRight",0);
	//rollover(__left,"FormatsLeft",0);
	
	//Make sure the scroller is at the start
	__container.scrollTo( '.thumbCol:eq('+0+')', 500, {axis:'x'});
	
	
	if(__max==__contentBoxes.length){
		__max=__max-__scrollAmount;
	}


	//Left scroller button
	__left.bind("click", function(){

		if(__current>0){
		
			//rollover(__right,"FormatsRight",0);
			//__right.find("img").attr("src","../images/slh/country/colour5/buttons/products-right-off.gif");
			
			__current = __current-__scrollAmount;
			__container.scrollTo( '.thumbCol:eq('+__current+')', 500, {axis:'x'});	
		}
		//if(__current==0){
		//	rollover(__left,"FormatsLeft",1);
		//	__left.find("img").attr("src","../images/slh/country/colour5/buttons/products-left-inactive.gif");
		//}
		return false;
	});
	
	
	
	
	
	//Right scroller button
	__right.bind("click", function(){

		if(__current<__max){
			
			//if(__current==(__max-__scrollAmount)){
			//	rollover(__right,"FormatsRight",1);
			//	__right.find("img").attr("src","../images/slh/country/colour5/buttons/products-right-inactive.gif");
			//}
			
			//rollover(__left,"FormatsLeft",0);
			//__left.find("img").attr("src","../images/slh/country/colour5/buttons/products-left-off.gif");
			
			__current = __current+__scrollAmount;
			__container.scrollTo( '.thumbCol:eq('+__current+')', 500, {axis:'x'});
			
			
		}
		
		return false;
	});

}


var showLogin = function(){

	var checkbox = $('.club-member input');
	var clubLoginBox = $('.clubLogin');
	var checkAvailabilityButton = $('input.check-availability');
	
	var bottomBorder = $('.bottom-border');
	
	// Pre-load images: DDK need to translate the images below, but need to move it to c#
	var imagePaths = [		
		'/images/slh/button_sign-in-and-check-availability.gif'
	];
	for(var i=0; i<imagePaths.length;i++) {
		var a = new Image();
		a.src = imagePaths[i];
	}
	// Images should be pre-loaded now
	
	var hideClubLoginBox = function() {
		//checkAvailabilityButton.attr('src', imagePaths[0]);
		clubLoginBox.hide();
		bottomBorder.hide()
	}
	
	var showClubLoginBox = function() {
		checkAvailabilityButton.attr('src', imagePaths[1]);
		clubLoginBox.show();
		bottomBorder.show();
		
	}
	
	if(!checkbox.get(0).checked && $('.panel-club.club-login-reservation').length == 0) {
		hideClubLoginBox();// Hide the Make Reservations login box, but only if the "I am a Club member" checkbox isn't checked, and the class indicating a log-in error isn't present
	}
	else {
		showClubLoginBox();// It's shown by default anyway, but this sorts out the button stuff too
	}
	
	checkbox.bind("click", function(){
		//if it's selected, then show the div
		if(this.checked){
			showClubLoginBox();
		}else{
		//hide the div
			hideClubLoginBox();
		}
										 
	});

}

var showRecommendedDestinations = function() {
	var heading = $('#panel-recommended-destinations h2');
	var spanToReceiveClickElement = $('#panel-recommended-destinations h2 .ie-js');
	var headingAndSIFR = $('#panel-recommended-destinations h2, #panel-recommended-destinations h2 object, #panel-recommended-destinations h2 embed');
	var content = $('#panel-recommended-destinations ul');

	//set default to collapsed
	heading.addClass('collapsed');
	content.hide();
	
	headingAndSIFR.toggle(
		function() {
			content.show();
			heading.removeClass('collapsed');
			return false;
		},							   
		function() {
			content.hide();
			heading.addClass('collapsed');
			return false;
		}
	);
	spanToReceiveClickElement.css({
		'cursor': 'pointer'
	});
}



var clubHomeLoggedIn = function(){

    $('div.logged-home li').click( 
								   
		function() {
			
			if(!$(this).hasClass('selected') && $('#tab-offer-data').hasClass('hideThis'))
			{
				$(this).addClass('selected');
				$('#tab-hotel-nav').removeClass('selected');
				
				$('#tab-hotel-data').addClass('hideThis');
				$('#tab-hotel-data').removeClass('showThis');
				
				$('#tab-offer-data').addClass('showThis');
				$('#tab-offer-data').removeClass('hideThis');
				
				return false;
				
			}
			else if(!$(this).hasClass('selected') && $('#tab-offer-data').hasClass('showThis'))
			{
				$(this).addClass('selected');
				$('#tab-offer-nav').removeClass('selected');
				
				$('#tab-hotel-data').addClass('showThis');
				$('#tab-hotel-data').removeClass('hideThis');
				
				$('#tab-offer-data').addClass('hideThis');
				$('#tab-offer-data').removeClass('showThis');
				
				return false
				
			}

		}

	);
}


var clubReasons = function() {
    //console.log("club reasons");
    $("ol.reasons li").find(".text").css("margin-top", "10px");
    $("ol.reasons li .text-collapse").each(function() {
        $(this).addClass("collapsed").hide().after($("<a></a>").addClass("collapse-link").addClass("large-link").attr("href", "#").text("Tell me more"));
        $(this).parents(".text").siblings(".image-collapse").css("height", "76px");
    });
    //alert($(".collapse-link").length);
    $(".collapse-link").bind("click", function() {
        if ($(this).siblings(".collapsed").length) {
            $(this).text("Close");
            $(this).siblings(".collapsed").removeClass("collapsed").addClass("expanded").slideDown(500);
            $(this).parents(".text").siblings(".image-collapse").animate({ height: 150 }, 500);
            $(this).parents(".text").animate({ marginTop: 0 }, 500);
            $(this).parents(".text").addClass("alt");
        } else {
            $(this).text("Tell me more");
            $(this).siblings(".expanded").removeClass("expanded").addClass("collapsed").slideUp(500);
            $(this).parents(".text").siblings(".image-collapse").animate({ height: 76 }, 500);
            $(this).parents(".text").animate({ marginTop: 10 }, 500);
            $(this).parents(".text").removeClass("alt");
        }
        return false;
    });
}

var tabs = function() {
	var tabsContainers = $(".tabs-bigger-js");
	var SELECTEDCLASS = 'selected';

	tabsContainers.each(function(){
		var tabContainer = $(this);
		var tabLinks = tabContainer.find('.tabs li a');
			
		tabLinks.bind('click', function(){
			var oldTab = tabContainer.find('.' + SELECTEDCLASS);
			var oldContent = $(oldTab.find('a').attr('href'));
			
			var newTab = $(this.parentNode);
			var newContent = $($(this).attr('href'));
			
			if(oldTab.get(0) !== newTab.get(0)) {
				oldTab.removeClass(SELECTEDCLASS);
				newTab.addClass(SELECTEDCLASS);
				
				tabContainer.get(0).className = tabContainer.get(0).className.replace('tabs-bigger_' + oldContent.attr('id'), 'tabs-bigger_' + newContent.attr('id'));// Set a class on the tab container indicating which tab content should be shown. You'll need to add a selector to the following rule in the stylesheet to actually make the content visible:

				// body.js .tabs-bigger_destination-map .tab-content#destination-map,
				// body.js .tabs-bigger_destination-list .tab-content#destination-list {
				//     position: static;
				//}
				
				// This was the only way I could find to make the transition smooth.
			}

			
			return false;
		});
	});
}

var logInSlideDown = function() {
	var logInLink = $('.login-link');
	var logInBox = $('#navigation .panel-club');
	logInBox.addClass('club-login-topmenu-closed');
	
	var logInBoxCloseLink = $('<a href="#" title="Close login window" class="login-close-link">x</a>');
	
	var openLogInBox = function(){
		logInBox.slideDown();
		logInBox.removeClass('club-login-topmenu-closed');
		logInBox.addClass('club-login-topmenu-open');
	}
	
	var closeLogInBox = function(){
		logInBox.slideUp();
		logInBox.removeClass('club-login-topmenu-open');
		logInBox.addClass('club-login-topmenu-closed');
	}
	
	$(logInBoxCloseLink).bind('click', function(){
		closeLogInBox();
		return false;
	});
	logInBox.append(logInBoxCloseLink);
	
	$(logInLink).bind("click", function(){
		if(logInBox.is('.club-login-topmenu-closed')) {
			openLogInBox();
		}
		else {
			closeLogInBox();
		}
		return false;
	});
	
	if($('.panel-club.club-login-topmenu').length) {
		openLogInBox(); // Open the log-in box if the server says we should (i.e. because there's a sign-in error the user needs to see).
	}
}

var worldmap = function() {
	var worldmap = $('#worldmap');
	var areas = $(worldmap.attr('usemap') + ' area')
	
	//alert(areas.length);
	
	areas.each(function(){
		var i = new Image();// Good old image pre-loading trick
		i.src = '/images/slh/map-' + this.id.replace('worldmap-', '') + '.jpg';
		//alert(i.src);
	});
	
	areas.each(function(){
		$(this).bind('mouseover', function(){
			worldmap.get(0).src = '/images/slh/map-' + this.id.replace('worldmap-', '') + '.jpg';
		});
		$(this).bind('focus', function(){
			worldmap.get(0).src = '/images/slh/map-' + this.id.replace('worldmap-', '') + '.jpg';
		});
		$(this).bind('mouseout', function(){
			worldmap.get(0).src = '/images/slh/map-placeholder.jpg';
		});
	});
}

function specialOfferDescription() {
	function init() {		
		var specialOfferDetails = $(this);
		
		var description = specialOfferDetails.find('.special-offer-description');
		var image = specialOfferDetails.find('img');
		var additionalLinks = specialOfferDetails.find('.additional-links');
		var truncateTextAt = 200; // Rough guess as to how many characters the paragraph can hold at its maximum height. It's dependent on font size, but the font would have to get pretty big to stop this working.
		
		if (image.length) {
			var imageHeight = image.height();
		}
		else {
			var imageHeight = 119;
		}

		// Max description height is:
		// - height of image (currently 119px)
		// - minus height of .additional-links
		// - minus .onecol top and bottom padding (currently 5px + 5px)
		var maxDescriptionHeight = imageHeight - additionalLinks.height() - 10;
		
		// Remove stylesheet's min-height declaration from description
		description.css({
			'min-height': '0'
		});

		var fullText = description.text();
		var truncateAt = fullText.lastIndexOf(' ', truncateTextAt);

		description.fcSpecialOfferFullText = fullText;
		description.fcSpecialOfferTruncatedText = fullText.slice(0, truncateAt) + ' ... ';

		var collapse = function() {
			description.addClass('special-offer-description-collapsed');
			description.removeClass('special-offer-description-expanded');
			
			description.text(description.fcSpecialOfferTruncatedText);
			
			description.css({
				'height': maxDescriptionHeight
			});

			description.append(moreHideLink);
		}
		
		var expand = function() {
			description.addClass('special-offer-description-expanded');
			description.removeClass('special-offer-description-collapsed');
			
			description.text(description.fcSpecialOfferFullText);
			
			description.css({
				'height': 'auto'
			});
			
			description.append(moreHideLink);
		}
		
		var moreHideLink = $('<a href="#" class="more-hide-link">More &gt;</a>');
		moreHideLink.bind ('click', function(){
			var self = $(this);
			if(description.attr('class').indexOf('special-offer-description-collapsed') > -1) {
				expand();
				self.text('Close >');
			}

			else {
				collapse();
				self.text('More >');
			}
			return false;
		});

		if(description.height() > maxDescriptionHeight) {
			collapse();
		}
	}

	$('.special-offer-summary-details').each(init);
}

		$(function (){
			if($("#sm").length > 0){
			
				$.submenu.init($("#sm"))
				
			}
		});
		
		$.submenu = function() {}
		
		$.submenu.init = function(target){

			//initialise jquery objects
			var __$menuLink = target.find("a");
			var __$pointer = target.find(".pointer"); 
			var __$selected = target.find(".selected a");
			var __$first = target.find(".first a");
			var __$startPoint = "";
		
		__$selected.length > 0 ? __$startPoint = __$selected : __$startPoint = __$first

		__$menuLink.bind("mouseenter",function(){
			$.submenu.animateBG(target,$(this))	
			__$pointer.show()
		})
		
		__$menuLink.bind("mouseleave",function(){
			$.submenu.animateBG(target, __$startPoint)
			__$selected.length > 0 ? __$pointer.show(): __$pointer.hide()	
				
		})

	$.submenu.animateBG = function(target, childElement){
		var x = ((childElement.position().left - target.position().left) + childElement.width() / 2) + 13
		__$pointer.stop();
		__$pointer.animate({
			"left": x
		})
	}
		
		$.submenu.animateBG(target,__$startPoint)
		__$selected.length > 0 ? __$pointer.show(): __$pointer.hide()
	}

		
$(function(){
	if($("#destinations_hero").length) {
		$.destSwitcher.initialize($("#destinations_hero"));
		$("#destinations_hero").css("background","#000");
		$("#destinations_hero .back").click(function(e){
			$.destSwitcher.showSlide("dest_world");
		})
	}
});

jQuery.fn.initAccordion = function() {

					this.each(function(){
				
					$('.accordionInner',this).hide();
					$('.accordionInner:first',this).show();
					$('.accordionItem:first',this).addClass('on');
					
					$('.accordionItem h3 a',this).click(function() {
						if( $(this).parent().parent().hasClass('on') ) {
							$(this).parent().parent().removeClass('on');
							$(this).parent().parent().find(".accordionInner").slideUp('normal');
						} else {
							$(this).parent().parent().siblings().removeClass('on');
							$(this).parent().parent().addClass('on');
						
							var checkElement = $(this).parents(".accordionItem").find(".accordionInner");
							$(this).parents(".accordion").find(".accordionInner:visible").slideUp('normal');
							checkElement.slideDown('normal');
						}
						return false;
					});
					
					});
					return this;
				  };

	$(document).ready( function(){
					$(".accordion").initAccordion();
					
					if($("#destinations_hero").length > 0){
						var __lozenge = $("#destinations_hero .lozenge");
						
						__lozenge.bind("mouseenter",function(e){
							$(this).addClass('iehov');
					});
					
						__lozenge.bind("mouseleave",function(e){
							$(this).removeClass('iehov');
					});
					}

					
				})
				
		$(function (){	
		
		var _$carousel = $("#carousel")
		
			if(_$carousel.length > 0 && typeof data != "undefined"){
				
					$.car.init(_$carousel, data);
				
			} 
		});
		
		
		$.car = function() {}
		
		$.car.globals = {
			target: $("#carousel"),
			currentSlide: 1,
			timer: "",
			data: {}
		}
		
		$.car.init = function(target, data) {
			if(!target.length || !data.length ) {return false;}
			
			this.globals.target = target;
			this.globals.data = data;
			
			this.buildHTML();
						
			//button events
			target.find("#carousel-control li").click(function(){$.car.showSlide(this.innerHTML)});
			
			//?what was this one for?
			//target.find("#carousel-control span").click(this.autoAdvance);
			
			//Slide events
		
			target.click(function(e) {
				if(e.target.className == "slide") {
					window.location = $.car.globals.data[$.car.globals.currentSlide-1].hotelLink;
				}
			});
			
			//target events
			target.mouseout(this.startTimer);
			target.mouseover(this.stopTimer);
			
			
				//Let's go!, hide all slide hard, show slide 1, remove backup img and start auto advance.
			
				if (!$.support.opacity) {
					$("#carousel-slides > div").hide();
				}else{
					$("#carousel-slides > div").css("opacity", 0);
				}
				
				
				this.showSlide(this.globals.currentSlide);
				this.globals.target.css("background", "#fff");
				this.startTimer();
			
		}
		
		$.car.buildHTML = function() {
			var slideHTML = "";
			var buttonHTML = "";
			for (var i in this.globals.data) {
				slideHTML += buildSlide(data[i],i);
				if (data.length > 1) {
					buttonHTML += buildButton(i);
				}
			}
			
			this.globals.target.html('<div id="carousel-slides">' + slideHTML + '</div><ul id="carousel-control">'  + buttonHTML +  '</ul>');
			
			
	
			function buildSlide(d,i) {
			
				var slideHTML = '<div class="slide" style="background-image:url('+ d.img +');">';				
				slideHTML += '<div class="slide-info">';
				
				if (d.hotelLink != "") {
					slideHTML += '<p class="title"><a href="'+ d.hotelLink +'">'+ d.hotelName +'</a></p>';
				}else{
					slideHTML += '<p class="title">'+ d.hotelName +'</p>';
				}
				slideHTML += '<p>'+ d.strapline +'</p>';
				
				/*if (d.viewMoreLink != ""){
					slideHTML += '<a href="'+ d.viewMoreLink +'" title="'+ d.viewMoreTitleText +'" class="view-more">'+ d.viewMoreLinkText +'</a>'; 
				}*/
				if (d.hotelLink != ""){
					slideHTML += '<a href="'+ d.hotelLink +'" title="'+ d.hotelTitleText +'" class="view-this-hotel">'+  d.hotelLinkText +'</a>'; 
				}
				slideHTML += '</div></div>';	
				return slideHTML;	
			}
			
			function buildButton(i) {
				i++;			
				return '<li>'+ i +'</li>';
			}
		}
		
		$.car.startTimer = function() {
			$.car.globals.timer = window.setInterval($.car.autoAdvance,5000)
		}
		
		$.car.stopTimer = function() {
			window.clearInterval($.car.globals.timer)
		}
		
		$.car.autoAdvance = function() {
			$.car.showSlide($.car.globals.currentSlide += 1)
		}
		
		$.car.showSlide = function showSlide(i) {
			if(i > this.globals.data.length) {i = 1}
			
			if(!$.support.opacity){
				$("#carousel-slides > div").hide();
				$("#carousel-slides > div:eq(" + (i - 1) + ")").show();
		
			}else{
				$("#carousel-slides > div").stop().animate({ "opacity": 0 }, "slow");
				$("#carousel-slides > div:eq(" + (i - 1) + ")").stop().animate({ "opacity": 1 }, 1000);
			}
			
			this.globals.currentSlide = i;
		}
