/********************* SEARCH CALENDAR FUNCTIONS **********************/
initCalendar = function(){
	if($("showcal")){
		//Popup event handler function calls
		!document.all ? document.addEventListener("click",resetPopups,true) : document.attachEvent("onclick",resetPopups);
		//Set onchange and onclick events
		$("showcal").onclick = function(event){
			buildCalendar("calCon",1); 
			$("calCon").toggleClass('hidden');
			return false;
		};
		//Load Date Calendar
		buildCalendar("calCon",1);
	}
}

addOptn = function(eleTarget,text,value,valid,storedVal){
	var optn = document.createElement("OPTION");
	this.text = text;
	if((value != "???") && (eleTarget.id == "from1" || eleTarget.id == "to1")){this.text += " (" + value + ")";}
	optn.text = this.text;
	optn.value = value;
	if(value == storedVal){
		optn.selected = true;
	}
	eleTarget.options.add(optn);
}
removeAllOptns = function(ele){for(var optn=ele.options.length-1;optn>=0;optn--){ele.remove(optn);}}
assocSort = function(oAssoc){
	var idx; var key; var arVal = []; var arValKey = []; var oRes = {};
	for (key in oAssoc) {
		arVal[arVal.length] = oAssoc[key];
		arValKey[oAssoc[key]] = key;
	}
	arVal.sort();
	for (idx in arVal){
		oRes[arValKey[arVal[idx]]] = arVal[idx];
	}
	return oRes;
}
getMonthName = function(idx){
	var m_names = new Array("Jan", "Feb", "Mar","Apr", "May", "Jun", "Jul", "Aug", "Sep","Oct", "Nov", "Dec");
	return m_names[idx];
}
getIsLeapYear =function(year){
	if((year % 4) == 0){if((year % 100) == 0){Result = ((year % 400) == 0);}else{Result = 1;}}else{Result = 0;}
	return(Result);
}
addZeros = function(val){
	if(val < 10){val = "0" + val}
	return val;
}
getMaxDaysInMonth = function(month,year,date){
	this.month = month;
	this.year = year;
	if(date){
		this.month = date.getMonth()+1;
		this.year = date.getFullYear();
	}
	var maxDays = 31;
	switch(this.month){
		case 1: maxDays = 31;break;
		case 3: maxDays = 31;break;
		case 5: maxDays = 31;break;
		case 7: maxDays = 31;break;
		case 8: maxDays = 31;break;
		case 10: maxDays = 31;break;
		case 12: maxDays = 31;break;
		case 4: maxDays = 30;break;
		case 6: maxDays = 30;break;
		case 9: maxDays = 30;break;
		case 11: maxDays = 30;break;
		case 2:	maxDays = (this.year%4 == 0) ? 29:28;break;
	}
	return maxDays;
}
getToday = function(incDay,incMonth,incYear,returnType){
	var today = new Date();
	today.setDate(today.getDate() + incDay);	
	today.setMonth(today.getMonth() + incMonth);
	today.setFullYear(today.getFullYear() + incYear);
	switch(returnType){
		case "obj" : return today; 
		case "str" : return today.getFullYear().toString() + addZeros(today.getMonth()+1) + addZeros(today.getDate());
		case "date" : return addZeros(today.getDate());
		case "month" : return addZeros(today.getMonth()+1);
		case "year" : return today.getFullYear();
		case "yearmonth" : return today.getFullYear() + addZeros(today.getMonth()+1);
	}
}
concatEles = function(a,b){
	var c = new Array();
	for(var i=0;i<a.length+b.length;i++){
	    var e = ( i < a.length ) ? a[i] : b[i-a.length];
	    c.push(e);
	}
	return c;
}
getEleY = function(ele){
	var val = 0;
	while(ele!=null){
		val += ele.offsetTop;
		ele=ele.offsetParent;
	}
	return val;
}
getEleX = function(ele){
	var val = 0;
	while(ele!=null){
		val += ele.offsetLeft;
		ele=ele.offsetParent;
	}
	return val;
}
buildCalendar = function(calContainer,mrkNo,dateArg,monthYearArg){
	if($(calContainer)){
		var calCon = $(calContainer);
		this.minMonthToDisplayYear1 = 0;
		this.maxMonthToDisplayYear1 = 0;
		this.minMonthToDisplayYear2 = 0;
		this.maxMonthToDisplayYear2 = 0;
		var mrkNo = mrkNo;
		//Important variable handlers - decides on the start month of the season calendar
		if($("departureDay")){
			var DayField = $("departureDay");
			var MonthField = $("departureMonthYear");
			var currYear = MonthField.options[0].value.substring((MonthField.options[0].value.indexOf("-")+1),MonthField.options[0].value.length);
			var yearCount = 1;
			minMonthToDisplayYear1 = (MonthField.options[0].value.substring(0,MonthField.options[0].value.indexOf("-"))-0);
			// Rotate through YearMonth Field to determine start and end dates for year 1 and 2	
			for(opt=0;opt<MonthField.options.length;opt++){				
				if(MonthField.options[opt].value.substring((MonthField.options[opt].value.indexOf("-")+1),MonthField.options[opt].value.length) == currYear){
					//Set maxMonths
					this['maxMonthToDisplayYear' + yearCount] = (MonthField.options[opt].value.substring(0,MonthField.options[opt].value.indexOf("-"))-0);
				}else{
					//Set minMonths 
					yearCount+=1;
					this['minMonthToDisplayYear' + yearCount] = (MonthField.options[opt].value.substring(0,MonthField.options[opt].value.indexOf("-"))-0);
					currYear = MonthField.options[opt].value.substring((MonthField.options[opt].value.indexOf("-")+1),MonthField.options[opt].value.length);	
				}
			}
			//alert("minMonthToDisplayYear1 = " + this.minMonthToDisplayYear1);
			//alert("maxMonthToDisplayYear1 = " + this.maxMonthToDisplayYear1);
			//alert("minMonthToDisplayYear2 = " + this.minMonthToDisplayYear2);
			//alert("maxMonthToDisplayYear2 = " + this.maxMonthToDisplayYear2);
		}else{
			this.minMonthToDisplayYear1 = 1;
			this.maxMonthToDisplayYear1 = 12;
			this.minMonthToDisplayYear2 = 1;
			this.maxMonthToDisplayYear2 = 12;	
		}
		//Clear out existing calendar table
		if($("calendar")){
			var calTable = $("calendar");
			calCon.removeChild(calTable);
		}
		//Capture Engine dates if no arguments are passed to this function
		if(arguments.length == 2 && $("departureDay")){
			//var Engine_date = (DayField.value-0); This needs to be set lower down I think :-)) MUST ALWAYS BE 01
			var Engine_date = 1;
			var Engine_month = parseInt((MonthField.value.substring(0,MonthField.value.indexOf("-"))-0))-1;
			var Engine_year = MonthField.value.substring((MonthField.value.indexOf("-")+1),MonthField.value.length);
			//alert("Search engine= " + Engine_year + ":" + Engine_month + ":" + Engine_date);
		}
		else if(arguments.length == 2 && !$("departureDay")){
			//Exception caught - no information is provided to build calendar
			alert("buildCalendar Function Error:\n Insufficient information provided. Form elements Date and Month or parameters required! Please refer to documentation within js file.");
			return false;
		}else{
			//Function is being passed arguments so used these instead of the engine fields
			var Engine_date = (dateArg-0);
			var Engine_month = parseInt(monthYearArg.substring(4)-0)-1;
			var Engine_year = monthYearArg.substring(0,4);
			//alert("Passed args= " + Engine_year + ":" + Engine_month + ":" + Engine_date);
		}
		var Engine_dateObj = new Date(Engine_year,Engine_month,Engine_date);
		
		var DaysInMonth = getMaxDaysInMonth("","", Engine_dateObj);
		//Set this for onclick dates
		var onclickMonthYear = Engine_dateObj.getFullYear().toString() + addZeros(Engine_dateObj.getMonth()+1).toString();
		//Calculate number of table rows needed
		var emptyStartCels = Engine_dateObj.getDay()-1;
		var emptyStartCelsToAdd = Engine_dateObj.getDay();
		var tableCels = DaysInMonth + emptyStartCelsToAdd;
		var tableRows = Math.floor(tableCels / 7);
		if((tableCels % 7) != 0){tableRows += 1;}
		//Add an extra 2 rows for month and day displays
		tableRows += 2;
		//Build calendar table
		var tableEle = document.createElement("TABLE");
		tableEle.className = "tbl_default tbl_cal";
		tableEle.setAttribute("id","calendar");
		var tablebodyEle = document.createElement("TBODY");
		tableEle.appendChild(tablebodyEle);
		calCon.appendChild(tableEle);
		var dayCount = 1;
		for(var tableRowsCount = 0; tableRowsCount<tableRows; tableRowsCount++){
			if(tableRowsCount == 0){ //Month display row
				var prevMonth = Engine_dateObj.getMonth()+1;
				var prevYear = Engine_dateObj.getFullYear();
				var nextMonth = Engine_dateObj.getMonth()+1;
				var nextYear = Engine_dateObj.getFullYear();
				var rowEle = document.createElement("tr");
				for(var tableColsCount = 0; tableColsCount<3; tableColsCount++){
					if(tableColsCount == 0){ 
					// Insert prev button in row 1 cell 1
						var colEle = document.createElement("th");
						colEle.setAttribute("id","prevth");
						//Create prev button
						var prevMonthLinkEle = document.createElement("a");
						var prevMonthLinkTextEle = document.createTextNode(" ");
						prevMonthLinkEle.setAttribute("href","Javascript:void(0)");
						prevMonthLinkEle.className = "linkbutton_sml";
						if( (prevMonth > minMonthToDisplayYear1) && (prevYear == new Date().getFullYear()) ){ 
						//Stops prev button when April is reached if the engine year is the same as current year
							prevMonth = addZeros(prevMonth - 1);
						}
						else if( (prevYear > new Date().getFullYear()) && (prevMonth == minMonthToDisplayYear2) ){ 
						//If year is greater than current year and the month is March then allow prev button to go back to October in prev year
							prevMonth = maxMonthToDisplayYear1;
							prevYear = parseInt(prevYear)-1;
						}
						else if( (prevYear > new Date().getFullYear()) && (prevMonth > minMonthToDisplayYear2) ){ 
						//If year is greater than current year and the month is greater than March then allow prev button to go back a month in that year					
							prevMonth = addZeros(prevMonth - 1);
						}
						var prevMonthYear =  prevYear.toString() + prevMonth;
						prevMonthLinkEle.onclick = function(){buildCalendar('calCon',mrkNo,'01',prevMonthYear)};
						//prevMonthLinkEle.setAttribute("class", "calLink");
						prevMonthLinkEle.appendChild(prevMonthLinkTextEle)
						colEle.appendChild(prevMonthLinkEle);
						rowEle.appendChild(colEle);
					}
					else if(tableColsCount == 1){ 
					// Insert name of month in row 1 cell 2
						var colEle = document.createElement("th");
						colEle.setAttribute("id","dateth");
						colEle.setAttribute("colSpan","5");
						var colTextEle = document.createTextNode(getMonthName(Engine_dateObj.getMonth()) + " " + Engine_dateObj.getFullYear());
						colEle.appendChild(colTextEle);
						rowEle.appendChild(colEle);
					}
					else if(tableColsCount == 2){ 
					// Insert next button in row 1 cell3
						var colEle = document.createElement("th");
						colEle.setAttribute("id","nextth");
						//Create next button
						var nextMonthLinkEle = document.createElement("a");
						var nextMonthLinkTextEle = document.createTextNode(" ");
						nextMonthLinkEle.setAttribute("href","Javascript:void(0)");
						nextMonthLinkEle.className = "linkbutton_sml";
						if( (nextMonth == maxMonthToDisplayYear1) && (nextYear < parseInt(new Date().getFullYear())+1) && (minMonthToDisplayYear2 != 0)){
							nextMonth = addZeros(minMonthToDisplayYear2); /*##### Retains the seasonal month in YEAR 2 display minMonthToDisplayYear2! Set this to minMonthToDisplay if you need to mimic YEAR 1#####*/
							nextYear = parseInt(nextYear)+1;
						}
						else if( (nextMonth < maxMonthToDisplayYear1) && (nextYear <= parseInt(new Date().getFullYear())+1) ){
							if( (nextYear == parseInt(new Date().getFullYear())+1) && (nextMonth < maxMonthToDisplayYear2) ){
								nextMonth = addZeros(nextMonth + 1);
							}
							else if(nextYear != parseInt(new Date().getFullYear())+1){
								nextMonth = addZeros(nextMonth + 1);
							}
						}
						var nextMonthYear = nextYear.toString() + nextMonth;
						nextMonthLinkEle.onclick = function(){buildCalendar('calCon', mrkNo,'01',nextMonthYear)};
						//nextMonthLinkEle.setAttribute("class", "calLink");
						nextMonthLinkEle.appendChild(nextMonthLinkTextEle);
						colEle.appendChild(nextMonthLinkEle);
						rowEle.appendChild(colEle);
					}
				}
			}
			else if(tableRowsCount == 1){ //Day display row
				var rowEle = document.createElement("tr");
				for(var tableColsCount = 0; tableColsCount<7; tableColsCount++){
					var colEle = document.createElement("th");
					colEle.setAttribute("class", "datesth");
					colEle.appendChild(document.createTextNode("SMTWTFS".substring(tableColsCount,tableColsCount+1)));
					rowEle.appendChild(colEle);
				}
			}else{
				var rowEle = document.createElement("tr");
				//Handle 1st row which possibly contains empty starting cels
				if(tableRowsCount==2){
					var rowEle = document.createElement("tr");
					for(var tableColsCount = 0; tableColsCount<7; tableColsCount++){ 
						if(tableColsCount>emptyStartCels){ 
						//Create date populated cells in row 2
							var colEle = document.createElement("td");
							// Colour code TODAY and SELECTED DATE columns
							if( (dayCount == $("departureDay").value) && (parseInt($("departureMonthYear").value.substring(0,$("departureMonthYear").value.indexOf("-"))-0) == (Engine_dateObj.getMonth()+1)) && (parseInt($("departureMonthYear").value.substring($("departureMonthYear").value.indexOf("-")+1,$("departureMonthYear").value.length)) == Engine_dateObj.getFullYear()) ){
								colEle.className = "cal_currday";
							}
							else if( (dayCount == new Date().getDate()) && (parseInt($("departureMonthYear").value.substring(0,$("departureMonthYear").value.indexOf("-"))-0) == (Engine_dateObj.getMonth()+1)) && (new Date().getFullYear() == Engine_dateObj.getFullYear()) ){
								colEle.className = "cal_today";
							}
							rowEle.appendChild(colEle);
							/********************* Start build date links ********************/
							var dateLink = buildDateLink(calCon,dayCount,onclickMonthYear,mrkNo)
							if(dateLink.nodeName == "A"){
								if(!colEle.className){
									colEle.className = "cal_active";
								}
							}
							colEle.appendChild(dateLink);
							/*********************  End build date links  ********************/
							dayCount += 1;
						}else{
						//Create start empty cels if required
							var colEle = document.createElement("td");
							rowEle.appendChild(colEle);
							var colTextEle = document.createTextNode(" ");
							colEle.appendChild(colTextEle);
						}
					}
				}else{ 
				//middle rows of dates that do not require empty cells
					var rowEle = document.createElement("tr");
					for(var tableColsCount = 0; tableColsCount<7; tableColsCount++){
						var colEle = document.createElement("td");
						if(dayCount <= DaysInMonth){
							// Colour code TODAY and SELECTED DATE columns
							if( (dayCount == $("departureDay").value) && (parseInt($("departureMonthYear").value.substring(0,$("departureMonthYear").value.indexOf("-"))-0) == (Engine_dateObj.getMonth()+1)) && (parseInt($("departureMonthYear").value.substring($("departureMonthYear").value.indexOf("-")+1,$("departureMonthYear").value.length)) == Engine_dateObj.getFullYear()) ){
								colEle.className = "cal_currday";
							}
							else if( (dayCount == new Date().getDate()) && (parseInt($("departureMonthYear").value.substring(0,$("departureMonthYear").value.indexOf("-"))-0) == (Engine_dateObj.getMonth()+1)) && (new Date().getFullYear() == Engine_dateObj.getFullYear()) ){
								colEle.className = "cal_today";
							}
							/********************* Start build date links ********************/
							var dateLink = buildDateLink(calCon,dayCount,onclickMonthYear,mrkNo)
							if(dateLink.nodeName == "A"){
								if(!colEle.className){
									colEle.className = "cal_active";
								}
							}
							colEle.appendChild(dateLink);
							/*********************  End build date links  ********************/
							dayCount += 1;
						}else{ 
						// Create end empty cels
							var colTextEle = document.createTextNode(" ");
							colEle.appendChild(colTextEle);
						}
						rowEle.appendChild(colEle);
					}
				}
			} /*##### END of build dates in month block ######*/
			tablebodyEle.appendChild(rowEle); //Add the resulting row to the table!
		}/*##### END of build table rows block ######*/
	}else{ //End of calCon DIV existance
		alert("buildCalendar Function Error:\n calCon Div is not present on the page!");
		return false;
	}
}
buildDateLink = function(calDIVtoClose,dayCount, yearMonth, mrkNo){
	//Builds date links and return element to be appended to each column
	var dateLinkText = document.createTextNode(dayCount);
	var dateLink = document.createElement("a");
	dateLink.setAttribute("href","Javascript:void(0)");
	dateLink.onclick = function(){
		SetDates(addZeros(dayCount), yearMonth, mrkNo);
	}		
	dateLink.appendChild(dateLinkText);
	return dateLink;
}
SetDates = function(day, yearMonth, mrkNo){
	var MonthField = $("departureMonthYear");
	var DayField = $("departureDay");
	var yearMonth = yearMonth.substring(4,yearMonth.length) + "-" + yearMonth.substring(0,4);
	MonthField.value = yearMonth;
	DayField.value = day;
}
resetPopups = function(evt){
	var elem = (evt.target) ? evt.target : evt.srcElement;
	if( (elem.className != "calLink" 
	&& elem.className != "linkbutton_sml") 
	&& (elem.id != "showcal" 
	&& elem.id != "CalImg2"
	&& elem.id != "nextth" 
	&& elem.id != "signup_header" 
	&& elem.id != "submitbtn_paxLayer" 
	&& elem.id != "paxPopupDIV" 
	&& elem.id != "AdultPaxDIV_paxLayer" 
	&& elem.id != "ChildPaxDIV_paxLayer" 
	&& elem.id != "InfantPaxDIV_paxLayer" 
	&& elem.id != "AdultPax_paxLayer" 
	&& elem.id != "ChildPax_paxLayer" 
	&& elem.id != "InfantPax_paxLayer" 
	&& elem.id != "paxLayer_body" 
	&& elem.id != "paxLayer_container" 
	&& elem.className != "opt" 
	&& elem.className != "smllabel") ){
		$("calCon").addClass("hidden");
	}
}
window.addEvent('domready', function() {
	initCalendar();
});

/* LightBox Slider classes start */
var SlideItMoo = new Class({
Implements: [Options],
options: {
	overallContainer: 'carousel',
	elementScrolled: 'inner',
	thumbsContainer: 'items',		
	itemsVisible:3,
	elemsSlide: 3,
	itemsSelector: '.slide-element',
	itemWidth: 240,
	showControls:1,
	transition: Fx.Transitions.linear,
	duration: 300,
	direction: 1,
	autoSlide: false,
	mouseWheelNav: false
},
initialize: function(options){
	this.setOptions(options);
	/* all elements are identified on CSS selector (itemsSelector) */
	this.elements = $(this.options.thumbsContainer).getElements(this.options.itemsSelector);
	this.totalElements = this.elements.length;
	if( this.totalElements <= this.options.itemsVisible ) return;
	// width of thumbsContainer children
	this.elementWidth = this.options.itemWidth || this.elements[0].getSize().x;
	this.currentElement = 0;
	this.direction = this.options.direction;
	this.autoSlideTotal = this.options.autoSlide + this.options.duration;
	this.begin();
},
begin: function(){	
	// resizes the container div's according to the number of itemsVisible thumbnails
	this.setContainersSize();
	
	this.myFx = new Fx.Morph(this.options.thumbsContainer, { 
		wait: true, 
		transition: this.options.transition,
		duration: this.options.duration
	});		
			
	/* if navigation is needed and enabled, add it */
	this.addControls();
	/* if autoSlide is not set, scoll on mouse wheel */
	if( this.options.mouseWheelNav && !this.options.autoSlide ){
		$(this.options.thumbsContainer).addEvent('mousewheel', function(ev){
			new Event(ev).stop();
			this.slide(-ev.wheel);								
		}.bind(this));
	}
	
	if( this.options.autoSlide )
		this.startAutoSlide();		
},
setContainersSize: function(){
	$(this.options.overallContainer).set({
		styles:{
			'width': '70em'
		}
	});
	$(this.options.elementScrolled).set({
		styles:{
			'width': '72em'
		}
	});
	$(this.options.thumbsContainer).set({
		styles:{
			'width': this.totalElements * (this.elementWidth + 10)	
		}
	});
},
addControls: function(){
	if( !this.options.showControls ) return;
	
	this.fwd = new Element('div', {
		'class': 'SlideItMoo_forward mr',
		'events':{
			'click':this.slide.pass(1, this)
		}
	});
	this.bkwd = new Element('div', {
		'class': 'SlideItMoo_back ml',
		'events':{
			'click': this.slide.pass(-1, this)
		}
	});
	$(this.options.overallContainer).adopt(this.fwd, this.bkwd);		
},
slide: function( direction ){
	if(this.started) return;
	this.direction = direction;
	var currentIndex = this.currentIndex();
	if( this.options.elemsSlide && this.options.elemsSlide>1 && this.endingElem==null ){
		this.endingElem = this.currentElement;			
		for(var i = 0; i < this.options.elemsSlide; i++ ){
			this.endingElem += direction;
			if( this.endingElem >= this.totalElements ) this.endingElem = 0;
			if( this.endingElem < 0 ) this.endingElem = this.totalElements-1;
		}
	}	
	if( this.direction == -1 ){
		this.rearange();
		$(this.options.thumbsContainer).setStyle('margin-left', -this.elementWidth);			
	}
	this.started = true;
	this.myFx.start({ 
		'margin-left': this.direction == 1 ? -this.elementWidth : 0 
	}).chain( function(){			
		this.rearange(true);			
		if(this.options.elemsSlide){
			if( this.endingElem !== this.currentElement ) this.slide(this.direction);
			else this.endingElem=null;	
		}
	}.bind(this)  );
},
rearange: function( rerun ){
	if(rerun) this.started = false;
	if( rerun && this.direction == -1 ) {
		return;
	}
	this.currentElement = this.currentIndex( this.direction );
	$(this.options.thumbsContainer).setStyle('margin-left',0);
	if( this.currentElement == 1 && this.direction == 1 ){
		this.elements[0].injectAfter(this.elements[this.totalElements-1]);
		return;
	}
	if( (this.currentElement == 0 && this.direction ==1) || (this.direction==-1 && this.currentElement == this.totalElements-1) ){
		this.rearrangeElement( this.elements.getLast(), this.direction == 1 ? this.elements[this.totalElements-2] : this.elements[0]);
		return;
	}
	if( this.direction == 1 ){
		this.rearrangeElement( this.elements[this.currentElement-1], this.elements[this.currentElement-2]);
	}
	else{
		this.rearrangeElement( this.elements[this.currentElement], this.elements[this.currentElement+1]);
	}		
},
rearrangeElement: function( element , indicator ){
	this.direction == 1 ? element.injectAfter(indicator) : element.injectBefore(indicator);
},
currentIndex: function(){
	var elemIndex = null;
	switch( this.direction ){
		/* forward */
		case 1:
			elemIndex = this.currentElement >= this.totalElements-1 ? 0 : this.currentElement + this.direction;				
		break;
		/* backwards */
		case -1:
			elemIndex = this.currentElement == 0 ? this.totalElements - 1 : this.currentElement + this.direction;
		break;
	}
	return elemIndex;
},
startAutoSlide: function(){
	this.startIt = this.slide.bind(this).pass(this.direction||1);
	this.autoSlide = this.startIt.periodical(this.autoSlideTotal, this);
	this.elements.addEvents({
		'mouseover':function(){
			$clear(this.autoSlide);						
		}.bind(this),
		'mouseout':function(){
			this.autoSlide = this.startIt.periodical(this.autoSlideTotal, this);
		}.bind(this)
	});
}
});
/* Lightbox Slider classes end */ 


/*
Author:
	luistar15, <leo020588 [at] gmail.com>
License:
	MIT License

Class
	viewer v0.9 (rev.08-12-08)

Arguments:
	items: dom collection | required
	parameters - see Parameters below

Parameters:
	sizes: obj | item sizes (px) | default: {w:480,h:240}
	mode: string OR array | 'rand','top','right','bottom','left','alpha' | default: 'rand'
	modes: array | default: ['top','right','bottom','left','alpha']
	fxOptions: object | Fx.Tween options | default: {duration:500}
	interval: int | for periodical | default: 5000

Methods:
	previous(manual): walk to previous item
		manual: bolean | default:false
	next(manual): walk to next item
		manual: bolean | default:false
	play(wait): auto walk items
		wait: boolean | required
	stop(): stop auto walk
	walk(item,manual): walk to item
		item: int | required
		manual: bolean | default:false

Requires:
	mootools 1.2 core
*/
var viewer = new Class({
	mode: 'rand',
	modes: ['top','right','bottom','left','alpha'],
	sizes: {w:480,h:240},
	fxOptions: {duration:500},
	interval: 5000,
	initialize: function(items,options){
		if(options) for(var o in options) this[o]=options[o];
		//
		if(this.buttons){
			this.buttons.previous.addEvent('click',this.previous.bind(this,[true]));
			this.buttons.next.addEvent('click',this.next.bind(this,[true]));
		}
		this.__current = 0;
		this.__previous = null;
		this.items = items.setStyle('display','none');
		this.items[this.__current].setStyle('display','block');
		this.disabled = false;
		this.attrs = {
			left: ['left',-this.sizes.w,0,'px'],
			top: ['top',-this.sizes.h,0,'px'],
			right: ['left',this.sizes.w,0,'px'],
			bottom: ['top',this.sizes.h,0,'px'],
			alpha: ['opacity',0,1,'']
		};
		this.rand = this.mode=='rand';
		this.sequence = typeof(this.mode)=='object' ? this.mode : false;
		this.curseq = 0;
		this.timer = null;
	},
	walk: function(n,manual){
		if(this.__current!==n && !this.disabled){
			this.disabled = true;
			if(manual){
				this.stop();
			}
			if(this.rand){
				this.mode = this.modes.getRandom();
			}else if(this.sequence){
				this.mode = this.sequence[this.curseq];
				this.curseq += this.curseq+1<this.sequence.length ? 1 : -this.curseq;
			}
			this.__previous = this.__current;
			this.__current = n;
			var a = this.attrs[this.mode].associate(['p','f','t','u']);
			for(var i=0;i<this.items.length;i++){
				if(this.__current===i){
					this.items[i].setStyles($extend({'display':'block','z-index':'2'},JSON.decode('{"'+a.p+'":"'+a.f+a.u+'"}')));
				}else if(this.__previous===i){
					this.items[i].setStyles({'z-index':'1'});
				}else{
					this.items[i].setStyles({'display':'none','z-index':'0'});
				}
			}
			this.items[n].set('tween',$merge(this.fxOptions,{onComplete:this.onComplete.bind(this)})).tween(a.p,a.f,a.t);
		}
	},
	play: function(wait){
		this.stop();
		if(!wait){
			this.next();
		}
		this.timer = this.next.periodical(this.interval,this,[false]);
	},
	stop: function(){
		$clear(this.timer);
	},
	next: function(manual){
		this.walk(this.__current+1<this.items.length ? this.__current+1 : 0,manual);
	},
	previous: function(manual){
		this.walk(this.__current>0 ? this.__current-1 : this.items.length-1,manual);
	},
	onComplete: function(){
		this.disabled = false;
		this.items[this.__previous].setStyle('display','none');
		if(this.onWalk) this.onWalk(this.__current);
	}
});
//
//
//
// <script type="text/javascript" src="#jsUrl('global.js')"></script>
//
//
//
var applyHover = new Class({
	initialize: function(selector, classname){
		$$(selector).addEvents({
			'mouseover': function(){
				this.addClass(classname);
			},
			'mouseout': function(){
				this.removeClass(classname);
			}
		});
	}
});

window.addEvent('domready', function() {
	new applyHover('.menu li', 'hover');
	new applyHover('#headlogo','hover');
	new applyHover('.large','largehover');
	new applyHover('.small','smallhover');
	new applyHover('.long','longhover');
	new applyHover('#holidaydestinations dl','hover');
});

window.addEvent('domready', function() {
	if($('vslider') && $('vtoggle')){
	  var status = {
	    'true': 'Hide more',
	    'false': 'Read more...'
	  };
	  var vslider = new Fx.Slide('vslider').hide();
	  $('vtoggle').addEvent('click', function(event){
	    event.stop();
	    vslider.toggle();
	  });
	  // When Vertical Slide ends its transition, we check for its status
	  // note that complete will not affect 'hide' and 'show' methods
	  vslider.addEvent('complete', function() {
	    $('vtoggle').set('text', status[vslider.open]);
	  });
	}
});

window.addEvent('domready', function() {
	if($$('.toggler')){
	   $$('.toggler').each(function(toggler){
		   toggler.addEvent('click', function(e){
			   e.stop();
			   toggler.getParent("thead").getNext("tbody").toggleClass("hidden");
			   var togglerText = (toggler.getParent("thead").getNext("tbody").hasClass("hidden"))?"show":"hide";
			   toggler.set('text', togglerText);
	       });
	   });	
	}
	if($$('.loading')){
		$$('.loading').addClass('hidden');
	}
});
//
//
//
// <script type="text/javascript" src="#jsUrl('site-tracker.js')"></script>
//
//
//
/*
SiteTracker 6.5.311
Copyright (C) 2009 Site Intelligence Ltd.
*/
//Namespace for SI javascript
var SITEINTEL = {};

SITEINTEL.config = {
	baseDirectory: "/flythomascook",
	taggingServer: "secure.si-tag.co.uk", // Send tags to same server as document comes from
	cookieName: "SIVISITOR",
	tracerCookieName: "SITRACER",
	linkAttribute: "id",  // This must either be "si:link" or "id"
 searchTracerPath: "/search",
 cookieQPName: "simigvis",
	cookiePath: "/",
	cookieTimeout: 315360000000,
	tracerTimeout: 1000, // ms to wait maximum for tracer to be sent
	domainList: [".co.uk",".com",".org",".net",".org.uk"],
	centralCookie: false,
	centralReqName: "req",
	centralRefName: "refer",
	centralURL: "",
	trackerUrl: "/flythomascook/track.gif"
};

/* Compressed javascript code follows */
eval(function(p,a,c,k,e,r){e=function(c){return(c<a?'':e(parseInt(c/a)))+((c=c%a)>35?String.fromCharCode(c+29):c.toString(36))};if(!''.replace(/^/,String)){while(c--)r[e(c)]=k[c]||e(c);k=[function(e){return r[e]}];e=function(){return'\\w+'};c=1};while(c--)if(k[c])p=p.replace(new RegExp('\\b'+e(c)+'\\b','g'),k[c]);return p}('7 1I;1g{1b.2n=4n;1b.2n("1W")}1f(e){1b.2n=4T}1g{1b.2p=4m;1b.2p("1W")}1f(4d){1b.2p=42}1b.1x=13(d){7 b=[];7 c=0;15.19=13(a){b[b.1a]=a;c+=a.1a;14 15};15.1s=13(){14 b.46("")};15.1a=13(){14 c};11(d){15.19(d)}};1b.2r=13(2V){7 2u="N";7 1J=1e;7 2L="t"+(1i 1D()).1T()+"h"+1k.2A.1a;7 1B="";7 s=0;7 u=[];7 x=17.3a;7 z=17.2a;7 A="4c:49";7 B=1e;7 M=1;7 P=1b.1E;7 Q=1j;7 S=1j;7 V=1j;7 X=1j;7 Z=1j;7 3K=5I;7 2O=0;7 1y=1e;7 o="5t+/";7 r=1b.2n;7 t=1b.2p;7 w=13(b){7 c=b.1K;7 a=b.1V("5f");11(!a||a=="5a"){14 13(){1c.1K=c}}1d{11(a.1a>0&&a.1m(0,1)=="2C"){14 13(){1k.3A(c,a)}}1d{7 d=4L.4J[a];11(d){14 13(){d.1c.1K=c}}1d{14 13(){1k.3A(c,a)}}}}};7 3k=13(b,c){14 13(){7 a=1e;11(c&&c.1l){a=17.2i("1H");a.1z("1l",c.1l);a.1z("1A",c.1A);b.2z(a)}b.2h();11(a){1k.3d(13(){b.4q(a)},4o)}}};7 3c=13(c){11(!c){14""}7 d=1i 1b.1x();1n(7 i=0;i<c.1a;i+=3){7 a=c.1a-i;7 b=0;b=(c.2g(i)<<16)&4f;b|=(a>1)?(c.2g(i+1)<<8)&4e:0;b|=(a>2)?c.2g(i+2)&4b:0;d.19(o.26((b&48)>>18));d.19(o.26((b&45)>>12));d.19((a>1)?o.26((b&43)>>6):"2C");d.19((a>2)?o.26((b&40)):"2C")}14 d.1s()};7 K=13(a,b){7 c=1i 1b.1x();1n(7 i=0;i<a.1a;i++){7 d;3Y(a.26(i)){1t"r":d=x;1r;1t"p":d=z;1r;1t"d":d=1M.3V+"x"+1M.3T+"x"+1M.2U+"."+1X.2T();11(1X.2R){d+="."+1X.2R.1a}1r;1t"c":d=1J;1r;1t"u":d=1k.2A.1a+"."+(3P.3N()*5K)+"."+(1i 1D()).1T();1r;1t"t":11(27 b.2Q!="1I"){d=b.2Q}1d{d=2L}1r;1t"f":d=b.1u;1r;1t"q":d=b.1O;1r;1t"g":d=D(b);1r;1t"w":d=2u;1r;1t"y":d=b.1q;1r;1t"o":d=(M++).1s();1r}c.19(3c(d)+"*")}14 c.1s()};7 D=13(d){7 a=1i 1b.1x();a.19("5w=").19(1k.1M.2U);a.19("&5s=").19(1k.1M.5r).19("x").19(1k.1M.5q);a.19("&5o="+E(1i 1D()));11(1X.2T()){a.19("&3w=1")}1d{a.19("&3w=0")}11(1e!==B){a.19("&5k=").19(B)}a.19(F());11(17.2k){7 b=17.2k.1V(A);11(!b){7 c=A.1o(":");11(c>-1){b=17.2k.1V(A.1m(c+1))}}11(b){a.19("&5e="+b)}}11(d.1Q){a.19("&59="+d.1Q)}11(d.2F){a.19("&54="+d.2F)}14 a.1s()};7 F=13(){7 a="";11(Q){a+="&1L:51"}11(S){a+="&1L:4Y"}11(V){a+="&1L:x-4W"}11(X){a+="&1L:4U"}11(Z){a+="&1L:4S"}14 a};7 E=13(a){7 b=1i 1b.1x();b.19(a.4P());b.19("-");b.19(1S(a.4M()+1));b.19("-");b.19(1S(a.4K()));b.19("T");b.19(1S(a.4I()));b.19(":");b.19(1S(a.4H()));b.19(":");b.19(1S(a.4G()));14 b.1s()};7 1S=13(n){11(n<1){14"20"}14(n>9?"":"0")+n};7 28=13(c){7 a;11(/4z/.1W(27(c))){a=c}1d{a=c.1V(P.2M);11(!a){7 b=P.2M.1o(":");11(b>-1){a=c.1V(P.2M.1m(b+1))}}}14 a};7 N=13(a){R(U,a)};7 W=13(a){R(1Z,a)};7 3e=13(a){R(m,a)};7 p=13(a){R(v,a)};7 y=13(a,b,c){11(!c){7 d=b.1R.1N();11(d=="a"){c=w(b)}1d{11((d=="1H"||d=="2y")&&(b.1p=="2h"||b.1p=="2x")){c=13(){b.4p();b.2w=1j};11(b.2w){14 1h}1d{b.2w=1h}}1d{3b 1i 3g("4l 4k 4j 4i 4h 4g 39");}}}R(1Z,a,c,P.2j);14 1j};7 R=13(a,b,c,d){b.2F=2L;b.1u="1G://"+17.1c.1v+P.23+"/39";a("38","37",b,c,d)};7 36=13(){7 b=H(P.24,17.2a,"&");11(b!==1e){B=I(P.1F);J(P.1F,b,P.35);11(P.2t){7 a=H(P.34,17.2a,"&");11(a!==1e){x=t(a)}a=H(P.2t,17.2a,"&");11(a!==1e){z=t(a)}}}1d{b=I(P.1F);11(b===1e){b=K("u");2u="Y";J(P.1F,b,P.35);11(P.2t){b=I(P.1F);11(b!==1e){7 c=P.47;7 d;11(c.1m(0,4)!="1G"){c=17.1c.1C+"//"+c;d=1h}1d{d=(c.1m(0,c.1o(":")+1)==17.1c.1C)}11(d){11(c.1o("?")==-1){c+="?"}1d{c+="&"}c+=P.44+"="+r(17.2a)+"&"+P.34+"="+r(17.3a);11(27 1k.3E!="1I"){1k.3E=1j}17.1c=c;14{2N:1h}}}}}}b=I(P.1F);14 b};7 I=13(a){14 H(a,17.29,";")};7 H=13(a,b,c){7 d=a+"=";7 e=1e;7 f=b.1o(d);11((f!=-1)&&(a.1a>0)){7 g=b.1o(c,f);11(g==-1){g=b.1a}e=b.1m(f+d.1a,g)}14 e};7 G=13(g,c,d,e){7 f=(1J===1e)?c:g;7 h="f="+f+"&d="+K(f,d);7 a="&c="+L(h);7 b=P.1P+P.41+"?"+h+a;e(b)};7 L=13(c){7 a=1;7 b=0;1n(7 i=0;i<c.1a;i++){a+=c.2g(i);b+=a}a%=30;b%=30;7 d=(b*3Z)+a;14 d.1s(16)};7 T=13(c,d,a){7 b=17.2i("1H");b.1z("1l",d);b.1z("1A",a);c.2z(b);14 b};7 m=13(c,d,e){7 f=13(b){7 a=1i 2P();a.1Y=b;u[u.1a]=a};G(c,d,e,f)};7 v=13(c,a,b){m(c,a,b);2Z(P.2j)};7 1Z=13(i,j,k,l,g){7 h=13(b){7 c=1i 2P();11(l){1y=l;11(g){7 d=13(){11(1y){7 a=1y;1y=1e;a()}};d.1s=13(){14"7 2Y = 2X; 2X = 1e; 2Y();"};7 e=1k.3d(d,g)}}7 f=13(){11(c.2q&&--2O===0&&1y){11(e){1k.3X(e)}7 a=1y;1y=1e;a()}};1g{11(c.2d){c.2d("3W",f,1j)}1d{c.3U("31",f)}}1f(3S){}++2O;c.1Y=b;u[u.1a]=c};G(i,j,k,h)};7 2Z=13(a){7 b=1i 1D().1T();2W(1i 1D().1T()-b<a){}};7 U=13(c,d,e){11(s<25){7 f=13(a){11(s>0){11(I(P.2e+(s-1))===1e){s=0}}7 b=P.2e+s++;J(b,a,3R)};G(c,d,e,f)}};7 2v=13(){11(15.1l&&((15.1p=="2S"||15.1p=="33")?(15.2s!=15.3Q):(15.1A!=15.3O))){7 a=15.1U.32;1n(7 i=0;i<a.1a;i++){11(15.1l==a[i]){14}}7 b="4a:"+15.1l;7 c={1u:"1G://"+17.1c.1v+P.23+"/3L",1O:r(b)+"=Y",1q:"3L"};m("2c","2b",c);a[a.1a]=15.1l}};7 C=13(a,b,c,d){11(a.1w&&(a.1w.1a>0)){7 f=1j;7 g=1i 1b.1x();1n(7 i=0;i<a.1w.1a;i++){7 k=a.1w[i];11(k.1l){7 h=(!d);11(d){1n(7 j=0;!h&&(j<d.1a);j++){11(k.1l==d[j]){h=1h}}}11(k.1p=="5J"){h=1j}1d{11((k.1R.1N()=="1H"||k.1R.1N()=="2y")&&(k.1p=="2h"||k.1p=="2x")){h=(k==a.2f)}1d{11(h&&(k.1p=="2S")){h=k.2s}}}11(h){7 e=r(k.1l)+"="+3J(k);11(g.1a()+e.1a>3K){b.1O=g.1s();c();g=1i 1b.1x();f=1j}11(f){g.19("&")}g.19(e);f=1h}}}b.1O=g.1s();c()}};7 3J=13(b){11(b.1p=="33"){14(b.2s)?"1h":"1j"}1d{11(b.2o&&b.5H){7 a=1h;7 c=1i 1b.1x();1n(7 i=0;i<b.2o.1a;i++){11(b.2o[i].5G){11(a){a=1j}1d{c.19("&").19(r(b.1l)).19("=")}c.19(r(b.2o[i].1A))}}14 c.1s()}1d{14 r(b.1A)}}};7 O=13(a,b,c){11(a.1m(0,1)=="/"){a=17.1c.1C+"//"+17.1c.1v+a}7 d={1u:a,1O:b,1q:c};m("2c","2b",d)};7 Y=13(){7 i=0;7 b=P.2e+i++;7 c=I(b);2W(c){11(c.1m(0,c.1o(":")+1)==17.1c.1C){7 a=1i 2P();a.1Y=c;u[u.1a]=a}1b.3I(b);b=P.2e+i++;c=I(b)}};7 q=13(e){14 1h};11(P.5F){15.5E=13(){7 a=[];1n(7 i=0;i<u.1a;i++){a[i]=u[i].1Y}14 a}}15.5D=13(){S=1h};15.5C=13(){Q=1h};15.5B=13(){V=1h};15.5A=13(){X=1h};15.5y=13(){Z=1h};1b.2r.3H.5x=13(a){17.2k.1z(A,a)};15.3F=13(f,a,b){7 c=1i 1D();c.5v(c.1T()+b);7 d=1b.2K();7 e=f+"="+a+((1b.1E.2B)?"; 1u="+1b.1E.2B:"")+((d)?"; 3D="+d:"");17.29=e+"; 2J="+c.5p();11(I(f)!=a){17.29=e;11(I(f)!=a){17.29=e+"; 2J=3C, 1 3h 3j 20:20:3y 3x"}}};7 J=15.3F;15.5m=13(a){1g{7 b={1Q:28(a),1q:"21"};N(b);14 1h}1f(e){14 q(e)}};15.5j=13(a){1g{7 b={1Q:28(a),1q:"21"};3e(b)}1f(e){q(e)}};15.5i=13(a,b){1g{7 c={1Q:28(a),1q:"21"};14 y(c,a,b)}1f(e){14 q(e)}};15.5h=13(b){1g{7 c={1Q:28(b),1q:"21"};W(c);7 f=b.1K;11(f.1o("://")==-1){11(f.1m(0,1)!="/"){7 d=17.1c.3v.2I("/");7 g=17.1c.3v.1m(0,d+1);f=g+f}11(f.1m(0,2)!="//"){f="//"+17.1c.1v+f}f=17.1c.1C+f}7 h=w(b);7 a={1q:"1L",1u:f,2Q:"t"+(1i 1D()).1T()+"h"+1k.2A.1a};1Z("38","37",a,h,P.2j);14 1j}1f(e){14 q(e)}};15.3t=13(a){7 b={1u:"1G://"+17.1c.1v+P.23+"/5g",1O:a,1q:"2H"};m("2c","2b",b)};15.5d=13(b,a){1g{11(1B!==""){1B+="&"}1B+=r(b)+"="+r(a);11(1B.1a>=5c){15.3r()}}1f(e){q(e)}};15.3r=13(){1g{11(1B!==""){15.3t(1B);1B=""}}1f(e){q(e)}};15.5b=13(a){1g{7 b=I(P.1F);11(b!==1e){11(a.1R.1N()=="a"){a.1K=a.1K+((a.1K.1o("?")>0)?"&":"?")+P.24+"="+b}1d{11(a.1R.1N()=="1U"){11(a.58.56()=="55"){1g{7 c=17.2i("<1H 1l=\\""+P.24+"\\" 1p=\\"3p\\" 1A=\\""+b+"\\" />")}1f(3n){c=17.2i("1H");c.1z("1l",P.24);c.1z("1p","3p");c.1z("1A",b)}a.2z(c)}1d{a.2E=a.2E+((a.2E.1o("?")>0)?"&":"?")+P.24+"="+b}}1d{3b 1i 3g("53 52");}}}14 1h}1f(e){14 q(e)}};15.50=13(a,b,c){1g{7 d={1u:"1G://"+17.1c.1v+P.23+"/1U",1q:"2H"};11(!c){c=3k(a,a.2f)}7 f=13(){1Z("2c","2b",d,c,P.2j)};C(a,d,f,b);14 1j}1f(e){14 q(e)}};15.4Z=13(a,b,c){1g{7 d={1u:"1G://"+17.1c.1v+(c?c:P.23+"/1U"),1q:"2H"};C(a,d,13(){U("2c","2b",d)},b);14 1h}1f(e){14 q(e)}};15.4X=13(d,f){1g{11(d.1w&&(d.1w.1a>0)){d.32=[];1n(7 i=0;i<d.1w.1a;i++){7 g=d.1w[i];11(g.1l){7 h=(27(f)=="1I"||f===1e);11(!h){1n(7 j=0;!h&&(j<f.1a);j++){11(g.1l==f[j]){h=1h}}}11(h){7 c=g.2D;11(c){(13(){7 b=c;7 a=g;g.2D=13(e){2v();14 b.3m(a,e)}})()}1d{g.2D=2v}}}g=1e}}}1f(e){q(e)}};15.4V=13(b,d,c){7 a=1i 1b.1x();a.19("q=").19(b);11(d!==1I){a.19("&n=").19(d)}11(c){1n(7 e 57 c){11(e.1o(".")!=-1){a.19("&").19(e).19("=").19(c[e])}}}7 f=a.1s();15.3o(1b.1E.4R,f)};15.4Q=13(b,a){1g{O(b,a,1e)}1f(e){q(e)}};15.3o=13(a,b){1g{O(a,b,"21")}1f(e){q(e)}};15.3l=13(a){1g{11(a!==1I){11(a.1o("://")==-1){11(a.1m(0,1)!="/"){a="/"+a}a=17.1c.1C+"//"+17.1c.1v+a}z=a.1o("?")==-1?a+1k.1c.3q:a+"&"+1k.1c.3q.1m(1)}m("4O","4N",{1q:"1L"})}1f(e){q(e)}};15.3u=13(){11(2l.2m.22){14}2l.2m.22=1h;7 g=13(){15.1U.2f=15};1n(7 i=0;i<17.3s.1a;i++){7 c=17.3s[i];1n(7 j=0;j<c.1w.1a;j++){7 h=c.1w[j];7 d=h.1R.1N();11((d=="1H"||d=="2y")&&(h.1p=="2h"||h.1p=="2x")){7 f=h.2G;11(f){(13(){7 b=f;7 a=h;h.2G=13(e){15.1U.2f=15;14 b.3m(a,e)}})()}1d{h.2G=g}}}}};1g{11(!P.1P){P.1P=17.1c.1C+"//"+17.1c.1v+":"+17.1c.5l}1d{11(P.1P.1m(0,4)!="1G"){P.1P=17.1c.1C+"//"+P.1P}}1J=36();11(1J&&27 1J.2N!="1I!"&&1J.2N){14}Y();1b.3z(15.3u);11(2V){15.3l()}}1f(e){q(e)}};1b.2r.3H.5n="6.5.4F";(13(){7 j=[];7 k=13(){1g{11(2l.2m.22){14}2l.2m.22=1h;11(l){4E(l)}1n(7 i=0;i<j.1a;i++){1g{j[i]()}1f(3n){}}}1f(e){}};1b.2K=13(){7 e=1e;7 g;7 h;7 a;7 b=17.1c.1v;11(b){7 c;1n(c=0;(c<1b.1E.3M.1a)&&(e===1e);c++){7 d=b.2I(1b.1E.3M[c]);11(d>0){7 f=b.2I(".",d-1);11(f>=0){e=b.1m(f)}1d{e="."+b}}}}14 e};1b.3I=13(d,a,b){11(!a){a=1b.1E.2B}11(!b){b=1b.2K()}7 c=d+"=1e"+((a)?"; 1u="+a:"")+((b)?"; 3D="+b:"");17.29=c+"; 2J=3C, 1 3h 3j 20:20:3y 3x"};1b.3z=13(a){1g{11(k.22){a()}1d{j[j.1a]=a}}1f(e){}};11(17.2d){17.2d("4D",k,1j)}/*@4C@*//*@11(@4B)17.5u("<3B 4A=3i 4y 1Y=//5z:4x></3B>");7 m=17.4w("3i");m.31=13(){11(15.3G=="2q"){k()}};@4v;@*/11(/4u/i.1W(1X.4t)){7 l=4s(13(){11(/4r|2q/.1W(17.3G)){k()}},10)}7 n=1k.3f;1k.3f=13(){11(n){n()}k()}})();',62,357,'|||||||var||||||||||||||||||||||||||||||||||||||||||||||||||||||||if||function|return|this||document||append|length|SITEINTEL|location|else|null|catch|try|true|new|false|window|name|substring|for|indexOf|type|tagType|break|toString|case|path|hostname|elements|StringBuilder|bh|setAttribute|value|bj|protocol|Date|config|cookieName|http|input|undefined|bg|href|page|screen|toLowerCase|query|taggingServer|clickedLinkID|nodeName|bl|getTime|form|getAttribute|test|navigator|src|bb|00|trace|done|baseDirectory|cookieQPName||charAt|typeof|bn|cookie|URL|fqdtyuo|fqctyuo|addEventListener|tracerCookieName|siActivatedSubmit|charCodeAt|submit|createElement|tracerTimeout|body|arguments|callee|encode|options|decode|complete|SiteTracker|checked|centralCookie|bd|bk|siOutstandingTracer|image|button|appendChild|history|cookiePath|_|onblur|action|refClickID|onclick|extra|lastIndexOf|expires|getDomain|bi|linkAttribute|redirecting|bf|Image|extClickID|plugins|radio|javaEnabled|colorDepth|ba|while|m_syncFinishedAction|exec|bo|65521|onreadystatechange|siFilledFields|checkbox|centralRefName|cookieTimeout|br|fdtgyuo|fctgyuo|link|referrer|throw|bq|setTimeout|be|onload|Error|Jan|__si_ie_onload|1970|bp|trackPage|call|exception|sendAdditionalTracer|hidden|search|sendTrackParams|forms|trackData|registerForms|pathname|jv|GMT|01|runWhenDOMLoaded|open|script|Thu|domain|siAutoTracer|setCookie|readyState|prototype|deleteCookie|bm|bc|formfield|domainList|random|defaultValue|Math|defaultChecked|1800000|ignore|availHeight|attachEvent|availWidth|load|clearTimeout|switch|65536|63|trackerUrl|unescape|4032|centralReqName|258048|join|centralURL|16515072|pageID|siform|255|si|err|65280|16711680|track|internal|to|supplied|element|Unknown|decodeURIComponent|encodeURIComponent|100|click|removeChild|loaded|setInterval|userAgent|WebKit|end|getElementById|blank|defer|string|id|_win32|cc_on|DOMContentLoaded|clearInterval|311|getSeconds|getMinutes|getHours|frames|getDate|top|getMonth|pdrtgyuo|pcrtgyuo|getFullYear|trackTracer|searchTracerPath|popup|escape|redir|trackInternalSearch|frame|activeTrackForm|menu|trackFormData|trackExternalFormData|fset|argument|Illegal|rcid|GET|toUpperCase|in|method|rl|_self|migrateCookie|512|addTrackParam|req|target|data|trackLinkToUntagged|trackExternalLink|trackEvent|mc|port|trackLink|version|lt|toGMTString|height|width|sr|ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789|write|setTime|co|setPageID|markAsPopup|about|markAsRedirection|markAsExtraFrame|markAsFrameset|markAsMenu|getQueuedTracers|visibleTracers|selected|multiple|1200|file|1000'.split('|'),0,{}))

//
//
//
// <script type="text/javascript" src="#jsUrl('si_impl.js')"></script>
//
//
//

/* APPLIES SI TRACKING PAGE HREFS */
si_impl = function(){
	var siLnx = document.getElementsByTagName("a"); 
	var siID = ""; // Site Intelligence link id
	for(siLnc=0;siLnc<siLnx.length;siLnc++){
		// Skip skipper links
		if(siLnx[siLnc].className != "skipper"){
			//Clear the siID
			siID = "";
			siID = getPID() + getCID(siLnx[siLnc]) + getLID(siLnx[siLnc]);	
			if(siID != "" && !siLnx[siLnc].id){
				siLnx[siLnc].id = siID;
				siLnx[siLnc].onclick = function(){
					if(typeof sitracker != 'undefined'){
						sitracker.trackExternalLink(this);
					}
				}				
			}
		}
	}
}
// Get Link ID
getLID = function(ele){
	var txtNodeIdx = -1;
	var imgNodeIdx = -1;
	var lid = "";
	if(ele.hasChildNodes()){
		for(i=0;i<ele.childNodes.length;i++){
			if( (ele.childNodes[i].nodeName == "#text") && ((ele.childNodes[i].nodeValue != " ") && (ele.childNodes[i].nodeValue != "")) ){txtNodeIdx = i;}
			if(ele.childNodes[i].nodeName == "IMG"){imgNodeIdx = i;}
		}
		if(txtNodeIdx != -1){
			lid = ele.childNodes[txtNodeIdx].nodeValue.toLowerCase().replace(/(^\s)|(\s$)/g,'');
		}else if(imgNodeIdx != -1){
			lid = ele.title.toLowerCase().replace(/(^\s)|(\s$)/g,'');
		}
		lid = lid.replace(/\s/g,'-');
	}
	return (lid != "") ? "." + lid : lid; 
}
// Get Container ID
getCID = function(ele){
	while(!ele.parentNode.id){
		ele = ele.parentNode;
	}
	return "." + ele.parentNode.id;
}
//Get Page ID
getPID = function(){
	var re = /\.com|\.co\.uk|C\:/g;
	var us = unescape(document.location.toString()).toLowerCase().replace(/\s/g,'-').split("/");
	var idx = 0;
	for(i=0;i<us.length;i++){
		if(re.test(us[i])){
			idx = i+1;
			break;
		}
	}
	var siPID = us.slice(idx, us.length).join(".");
	siPID = siPID.substring(0,siPID.lastIndexOf("."));
	return escape(siPID);
}
//Call si_impl function
window.addEvent('domready', function() {
	si_impl();
});

//
//
//
// <script type="text/javascript" src="#jsUrl('cookiefunc.js')"></script>
//
//
//

/* Start Cookie functions */

function GetCookie(name){
	var result = null;
	var ftcCookie = " " + document.cookie + ";";
	var searchName = " " + name + "=";
	var startOfCookie = ftcCookie.indexOf(searchName); // find pos of name
	var endOfCookie;
	if (startOfCookie != -1){
		startOfCookie += searchName.length; // Skip passed name to retrieve value
		endOfCookie = ftcCookie.indexOf(";", startOfCookie);
		result = unescape(ftcCookie.substring(startOfCookie,endOfCookie));
	}
	return result;
}

function SetCookie(name, value, expires, path, domain, secure){
	var expString = ((expires == null) ? "" : ("; expires="+ expires.toGMTString()));
	var pathString = ((path == null) ? "" : ("; path=" + path));
	var domainString = ((domain == null) ? "" : ("; domain=" + domain));
	var secureString = ((secure == true) ? "; secure=" : "");
	document.cookie = name + "=" + escape(value) +
	expString + pathString + domainString + secureString;
}

//
//
//
// <script type="text/javascript" src="#jsUrl('tts.js')"></script>
//
//
//

function MM_findObj(n, d) { var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) { d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);} if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n]; for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document); if(!x && d.getElementById) x=d.getElementById(n); return x;}
function MM_showHideLayers() { var i,p,v,obj,args=MM_showHideLayers.arguments; for (i=0; i<(args.length-2); i+=3) if ((obj=MM_findObj(args[i]))!=null) { v=args[i+2]; if (obj.style) { obj=obj.style; v=(v=='show')?'block':(v=='hide')?'none':v; } obj.display=v; }}

function showHide(id,show) {
  MM_showHideLayers(id,'',show ? 'show' : 'hide');
}

function swapText(id){
    document.getElementById('sds_' + id).style.display='none';
    document.getElementById('sdf_' + id).style.display='inline';
}

function convertToPounds(price) {
	return "\u00A3" + (price/100).toFixed(2);
}

function clearList(selectBox) {
    var i;

    if (selectBox.options) {

	    for(i=selectBox.options.length-1;i>=0;i--)
	        selectBox.remove(i);

	    while (selectBox.hasChildNodes())
	        selectBox.removeChild(selectBox.firstChild);
    }
}

function replaceList(selectBox,newOptionsArray,selected) {
	clearList(selectBox);
	
	//if((selectBox.id=="duration")||(selected=="")){
	//	selected=newOptionsArray[0][0];
	//}

    var optGroup=null;
    
    for(i=0;i<newOptionsArray.length;i++) {

        if (newOptionsArray[i][0]=="dash") {

            var optn = document.createElement("option");
            optn.text = "--------------------";
            optn.disabled=true;

            selectBox.options.add(optn);

        } else if (newOptionsArray[i][0].substring(0,13)=="optGroupStart") {

            optGroup = document.createElement("optgroup");
            optGroup.label=newOptionsArray[i][1];

        } else if (newOptionsArray[i][0].substring(0,11)=="optGroupEnd") {

            selectBox.appendChild(optGroup)
            optGroup=null;

        } else {

            if (optGroup == null) {

                var optn = document.createElement("option");
                    optn.text = newOptionsArray[i][1];
                    optn.value = newOptionsArray[i][0];

                selectBox.options.add(optn);

            } else {

                var optn = document.createElement("option");
                    optn.text = newOptionsArray[i][1];
                    optn.value = newOptionsArray[i][0];
                optGroup.appendChild(optn);

            }
        }
    }

    for(var i = 0; i < selectBox.length; i++) {
    	if(selectBox.options[i].value == selected) {
    		selectBox.options[i].selected = true;
    	} else {
    		selectBox.options[i].selected = false;
    	}
    }
}

Number.implement({

	/*
	Property: numberFormat
		Format a number with grouped thousands.

	Arguments:
		decimals, optional - integer, number of decimal percision; default, 2
		dec_point, optional - string, decimal point notation; default, '.'
		thousands_sep, optional - string, grouped thousands notation; default, ','

	Returns:
		a formatted version of number.

	Example:
		>(36432.556).numberFormat()  // returns 36,432.56
		>(36432.556).numberFormat(2, '.', ',')  // returns 36,432.56
	*/

	numberFormat : function(decimals, dec_point, thousands_sep) {
		decimals = Math.abs(decimals) + 1 ? decimals : 2;
		dec_point = dec_point || '.';
		thousands_sep = thousands_sep || ',';

		var matches = /(-)?(\d+)(\.\d+)?/.exec((isNaN(this) ? 0 : this) + ''); // returns matches[1] as sign, matches[2] as numbers and matches[3] as decimals
		var remainder = matches[2].length > 3 ? matches[2].length % 3 : 0;
		return (matches[1] ? matches[1] : '') + (remainder ? matches[2].substr(0, remainder) + thousands_sep : '') + matches[2].substr(remainder).replace(/(\d{3})(?=\d)/g, "$1" + thousands_sep) +
				(decimals ? dec_point + (+matches[3] || 0).toFixed(decimals).substr(2) : '');
	}


});

//
//
//
// <script type="text/javascript" src="#jsUrl('extras.js')"></script>
//
//
//

/*
 * $Id: style-collections.js,v 1.15 2011/12/20 12:06:29 nic Exp $
 */

var extras      = null;
var guestCounts = null;

function Criteria(dateRequired, stockControlledInd, minimumAge, maximumAge, minimumDuration, maximumDuration) {
	this.dateRequired       = dateRequired;
	this.stockControlledInd = stockControlledInd;
	this.minimumAge         = minimumAge;
	this.maximumAge         = maximumAge;
	this.minimumDuration    = minimumDuration;
	this.maximumDuration    = maximumDuration;
}

function DateRange(start,end,duration) {
	this.start    = start;
	this.end      = end;
	this.duration = duration;
}

function Extra(rph,code,name,type,quantity,applyTo,selectionType) {
	this.rph                    = rph;
	this.code                   = code;
	this.name                   = name;
	this.type                   = type;
	this.quantity               = quantity;
	this.applyTo                = applyTo;
	this.selectionType          = selectionType;
	this.listOfPassengerRPH     = new Array();
	this.listOfSubTypes         = null;
	this.subCategory            = null;
	this.subCategories          = null;
	this.date                   = null;
	this.criteria               = null;
	this.periods                = null;
	this.additionalInfoPrompt   = null;
	this.additionalInfoResponse = null;
	this.reversalCode           = null;
	this.show                   = true;

	/*
	 * This prices an individual extra, it relies on the set of guestCounts for passengers
	 */
	this.priceExtra = function priceExtra(guests) {

		if (this.applyTo==null) {

			if (this.periods!= null) {
				for (var x=0;x<this.periods.length;x++) {
					if (this.periods[x].prices!=null) {
						for (var y=0;y<this.periods[x].prices.length;y++) {

							var lAmount = this.periods[x].prices[y].amount;
							return lAmount;
						}
					}
				}
			}

		} else if(this.applyTo=="AllPax") {

			var lTotalPrice = null;

			if (guests != null) {
				for (var paxNo=0;paxNo<guests.length;paxNo++) {

					var paxPrice = this.pricePax(guests[paxNo]);

					if (paxPrice != null) {

						if (lTotalPrice == null)
							lTotalPrice=0;

						lTotalPrice += paxPrice;

					}
				}
			}

			if (lTotalPrice != null)
				return lTotalPrice;

		} else if(this.applyTo=="SelectedPax") {

			var lTotalPrice = 0;

			for (var paxNo=0;paxNo<this.listOfPassengerRPH.length;paxNo++) {

				var rph      = this.listOfPassengerRPH[paxNo];
				var paxPrice = this.pricePax(guests[(rph - 1)]);

				if (paxPrice != null) {
					lTotalPrice += paxPrice;
				}

			}

			return lTotalPrice;

		}

		return 0;
	}

	/*
	 * This prices an individual passenger
	 */

	this.pricePax = function pricePax(guestCount) {

		if (guestCount.code==7) // Infant
			return null;

		if (this.periods!= null) {
			for (var x=0;x<this.periods.length;x++) {
				if (this.periods[x].prices!=null) {

					var lPrice = null;

					for (var y=0;y<this.periods[x].prices.length;y++) {

						if(this.periods[x].prices[y].code!= null) {

							if (guestCount.code!=this.periods[x].prices[y].code)
								continue;

							if (guestCount.code!=10 &&
								 guestCount.age!=null &&
								  this.periods[x].prices[y].age != null &&
								   guestCount.age>this.periods[x].prices[y].age)
								continue;
						}

						lPrice = this.periods[x].prices[y];
						break;

					}

					if (lPrice == null) {

						window.console && console.log("Failed to find price for guest type:" + guestCount.code + " age " +  guestCount.age);

						return null;

					} else {
						var lAmount     = lPrice.amount;
						var lQty        = guestCount.count;
						var lTotalPrice = (lQty * lAmount);

						trace && window.console && console.log("got here qty [" + lQty + "] price [" + lAmount + "] total [" + lTotalPrice + "]");

						return lTotalPrice;
					}
				}
			}
		}
		return null;
	}
}

function ExtraGroup(listOfExtrasRPH, ruleCode) {
	this.listOfExtrasRPH = listOfExtrasRPH;
	this.ruleCode = ruleCode;
}

function GuestCount(code, birthdate, age, count) {
	this.code      = code;
	this.birthdate = birthdate;
	this.count     = count;
	this.age       = age;
}

function Period(start, duration, prices) {
	this.start    = start;
	this.duration = duration;
	this.prices   = prices;
}

function Price(age, code, amount) {
	this.age    = age;
	this.code   = code;
	this.amount = amount;
}

function SubCategory(name) {
	this.name = name;
}

/*
 * current noPax of specified type
 */
function firstPaxOfType(type) {
	for (var x=0;x<guestCounts.length;x++)
		if (guestCounts[x].code==type)
			return x;

	return null;
}

/*
 * current nopax of specified type
 */
function noPaxOfType(type) {
	var total = 0;

	for (var x=0;x<guestCounts.length;x++)
		if (guestCounts[x].code==type)
			total += guestCounts[x].count;

	return total;
}

function currentBasePrice(currentTotal) {

	if (extras == null)
		extras = loadExtras();

	if (guestCounts == null)
		guestCounts = loadGuests();

	var price = 0

	for (key in extras) {
		extra = extras[key];

        if (extra.code==undefined)
            continue;

		if (!reverseMandatoryOptionals && extra.type=="MND" && extra.reversalCode != null) {
			debug && window.console && console.log("I would remove this from the total " + extra.code + " price " + extra.priceExtra(guestCounts));
			price += extra.priceExtra(guestCounts);
		}
	}

	price = currentTotal - price;

	debug && window.console && console.log("Current price adjustment is " + convertToPounds(price));

	return price;

}


/*
 * General function to cost all extras
 */
function priceAllExtras() {

	var totalExtras = 0;

	for (key in extras) {

		extra=extras[key];

		if (!extra.show)
			continue;

		var itemPrice = 0;

		if (extra.applyTo==null && extra.quantity != null && extra.quantity >0)
			itemPrice = extra.priceExtra(guestCounts);

		else if (extra.applyTo=="AllPax" && extra.quantity != null && extra.quantity >0)
			itemPrice = extra.priceExtra(guestCounts);

		else if (extra.applyTo=="SelectedPax" && extra.listOfPassengerRPH.length > 0)
			itemPrice = extra.priceExtra(guestCounts);

		if (itemPrice != 0)
			debug && window.console && console.log('Extra price [' + extra.code + '] cost ' + itemPrice + ' pence');

	    totalExtras += itemPrice;

	}

    debug && window.console && console.log('Total extras ' + totalExtras + ' pence');

    return totalExtras;
}

//
//
//
// <script type="text/javascript" src="#jsUrl('TabbedPanel.js')"></script>
//
//
//

var TabbedPanel = function(container,toptab,subtab){
	var container = $(container);
	var tabs = container.getElements('li.tab');	
	tabs.each(function(tab){
		tab.addEvent('click',function(){
			var panelParent = tab.getParent().getNext();
			var tabsPanels = panelParent.getChildren();
			var currTabs = tab.getParent().getChildren();
			var ctabindex = 0;
			currTabs.removeClass('active');
			currTabs.each(function(currtab, currindex){
				if(tab == currtab){
					ctabindex = currindex;
					currtab.addClass('active');
				}
				else{
					currtab.removeClass('active');
				}
			});
			tabsPanels.addClass('hidden');	
			tabsPanels[ctabindex].removeClass('hidden');	
			//Handle subtabs
			if( (tabsPanels[ctabindex].getFirst()) && (tabsPanels[ctabindex].getFirst().className.indexOf('tabs')!=-1) ){
				tabsPanels[ctabindex].getFirst().getChildren()[0].fireEvent('click');	
				// Set subtab to passed subtab label			
				if(($arguments(3)!=null) && (tabsPanels[ctabindex].getFirst().getChildren()[0].get('tag') == 'li')){
					tabsPanels[ctabindex].getFirst().getChildren().each(function(tab){
						if(tab.getFirst().get('text').toLowerCase().replace(/ /g,'-') == subtab){
							tab.fireEvent('click');
						}
					});
				}
			}
			return false;
		});
	}, this);
	
	// Intial parent tabs
	tabs[0].fireEvent('click');
	// Set product tab to passed product
	if($arguments(2)!=null){
		tabs.each(function(tab){
			if(tab.getFirst().get('text').toLowerCase().replace(/ /g,'-') == toptab){
				tab.fireEvent('click');
			}
		});
	}	
}


//
//
//
// <script type="text/javascript" src="#jsUrl('tooltips.js')"></script>
//
//
//

function addTips(lnk, cls) {
    var tips = new Tips(lnk, {
        className: cls,
        fixed: false,
        hideDelay: 50,
        showDelay: 50
    });
   $$(lnk).each(function(infolink){
       infolink.addEvent('click', function(e){
       e.stop();
       });
   });
}

window.addEvent('domready', function(){addTips('a.infolink','infolink');});


//
//
//
// <script type="text/javascript" src="#jsUrl('avail-search.js')"></script>
//
//
//

/*
 * $Id: style-collections.js,v 1.15 2011/12/20 12:06:29 nic Exp $
 */
function holidayTypeChoice() {

	if($('holtype').value == hotelFlight){

		replaceList($('destination'), hotelFlightArrivals,arrPointSelect);
        replaceList($('airport'), hotelFlightDepartures,depPointSelect);
        replaceList($('boardtype'), hotelBoardList,hotelBoardSelect);
        $('airportWrapper').removeClass('hidden');
        $('boardWrapper').removeClass('hidden');
        $('roomtable').addClass('hidden');
        $('roomchoicetable').removeClass('hidden');
        $('ratingChoice').removeClass('hidden');
        $('boardWrapper').removeClass('hidden');
        $('freeChildren').addClass('hidden');
        $('hrImInterestedIn').removeClass('hidden');
        $('imInterestedIn').removeClass('hidden');
        $('searchByRoom').value='true';

	} else if($('holtype').value == villaFlight){

		replaceList($('destination'), villaFlightArrivals,arrPointSelect);
		replaceList($('airport'), villaFlightDepartures,depPointSelect);
		replaceList($('boardtype'), villaBoardList,villaBoardSelect);
		$('airportWrapper').removeClass('hidden');
		$('boardWrapper').addClass('hidden');
		$('roomtable').removeClass('hidden');
		$('roomchoicetable').addClass('hidden');
		$('ratingChoice').getElements('input').setProperty('checked',false);
		$('ratingChoice').addClass('hidden');
        $('freeChildren').getElements('input').setProperty('checked',false);
        $('freeChildren').addClass('hidden');
        $('hrImInterestedIn').addClass('hidden');
        $('imInterestedIn').addClass('hidden');
        $('boardWrapper').addClass('hidden');
		$('searchByRoom').value='false';

	} else if($('holtype').value == villaOnly){

		replaceList($('destination'), villaOnlyArrivals,arrPointSelect);
		replaceList($('boardtype'), villaBoardList,villaBoardSelect);
		clearList($('airport'));
		$('airportWrapper').addClass('hidden');
		$('boardWrapper').addClass('hidden');
		$('roomtable').removeClass('hidden');
		$('roomchoicetable').addClass('hidden');
		$('ratingChoice').getElements('input').setProperty('checked',false);
		$('ratingChoice').addClass('hidden');
        $('freeChildren').getElements('input').setProperty('checked',false);
        $('freeChildren').addClass('hidden');
        $('hrImInterestedIn').addClass('hidden');
        $('imInterestedIn').addClass('hidden');
        $('boardWrapper').addClass('hidden');
		$('searchByRoom').value='false';

	}
}

var duration = new Array( new Array("7","7 nights"),new Array("10","10 nights"),new Array("11","11 nights"),new Array("14","14 nights") );
var durationKTT = new Array( new Array("3","3 nights"),new Array("4","4 nights") );
var durationRVN = new Array( new Array("1","1 night") );
var datesKTT = new Array( new Array("12-2011","Dec 11") );
var datesRVN = new Array( new Array("12-2011","Dec 11") );

function destinationChoice(ele){
	var currMonthYear = $("departureMonthYear").value;
	var currDuration = $("duration").value;
	var durationArr = (window["duration"+ele.value])?window["duration"+ele.value]:window["duration"];
	var datesArr = (window["dates"+ele.value])?window["dates"+ele.value]:window["allMonthYear"];
	replaceList($('duration'),durationArr,currDuration);
	if(datesArr){
		replaceList($('departureMonthYear'),datesArr,currMonthYear);
	}
}

function availRoomChoice() {
	var x;
	for (x=0;x<4;x++) {
		if (x>=$('roomcount').value){
			$('roomchoicerow' + x).getElements('select').each(function(item, index){item.value=0;});
			$('roomchoicerow' + x).addClass('hidden');
		} else {
			$('roomchoicerow' + x).removeClass('hidden');
		}
	}
}

function getNoAdults() {
	return parseInt(noAdults=$('noAdults').value, 10);
}

function getNoChildren() {
	return parseInt(noChildren=$('noChildren').value, 10);
}

function getNoInfants() {
	return parseInt(noInfants=$('noInfants').value, 10);
}

function setNoAdults(val) {
	$('noAdults').value=val;
}

function setNoChildren(val) {
	$('noChildren').value=val;
}

function setNoInfants(val) {
	$('noInfants').value=val;
}

function showPax() {
	alert("pax change ad [" + getNoAdults() + "] ch [" + getNoChildren() + "] in [" + getNoInfants() + "]" );
}

function getAllPax() {
	return getNoAdults() + getNoChildren() + getNoInfants();
}

function validatePax(ad,ch,inf) {

	if ((ad + ch + inf) > 9) {
		alert("The total number of passengers must not exceed 9");
		return false;
	}

	if (inf > ad) {
		alert("The total infants may not exceede the number of adults");
		return false;
	}

	return true;
}

function availRoomPaxChange(calledByRoomChange) {
	var lNoAdults   = 0;
	var lNoChildren = 0;
	var lNoInfants  = 0;
	var roomObjects = null;

	for (x=0;x<$('roomcount').value;x++) {

		roomObjects = $('roomchoicerow' + x).getElements('select');

		for (y=0;y<roomObjects.length;y++) {

			if (roomObjects[y].name.search('Adult') != -1)
				lNoAdults += parseInt(roomObjects[y].value, 10);

			else if (roomObjects[y].name.search('Child') != -1)
				lNoChildren += parseInt(roomObjects[y].value, 10);

			else if (roomObjects[y].name.search('Infant') != -1)
				lNoInfants += parseInt(roomObjects[y].value, 10);

		}
	}

	if (!validatePax(lNoAdults, lNoChildren, lNoInfants))
		return false;

	setNoAdults(lNoAdults);
	setNoChildren(lNoChildren);
	setNoInfants(lNoInfants);

	for (x=0;x<$('roomcount').value;x++) {

		lNoAdults   = 0;
		lNoChildren = 0;
		lNoInfants  = 0;
		roomObjects = $('roomchoicerow' + x).getElements('select');

		for (y=0;y<roomObjects.length;y++) {

			if (roomObjects[y].name.search('Adult') != -1)
				lNoAdults += parseInt(roomObjects[y].value, 10);

			else if (roomObjects[y].name.search('Child') != -1)
				lNoChildren += parseInt(roomObjects[y].value, 10);

			else if (roomObjects[y].name.search('Infant') != -1)
				lNoInfants += parseInt(roomObjects[y].value, 10);
		}

		if (!calledByRoomChange && lNoAdults == 0) {
			alert("No room may have zero adults");
			return false;
		}
		if ((lNoAdults + lNoChildren)>5) {
			alert("No room may have greater than 5 passengers");
			return false;
		}
	}

	return true;
}

function searchDateValid() {
	currentMonth = $('departureMonthYear').value.substring(0,2);
	currentYear  = $('departureMonthYear').value.substring(3);
	currentDay   = $('departureDay').value;
	currentDate  = currentMonth + "/" + currentDay + "/" + currentYear;
	first        = Date.parse('05/01/2010');
	current      = Date.parse(currentDate);
	if (first.diff(current)<0) {
		//alert('We do sell holidays on this site before ');
		return false;
	}
	return true;
}

window.addEvent('domready', function(){

	if($("showcal")){
		holidayTypeChoice();
	    availRoomChoice();
	
	     var s = function(){
	         if($('searchform').getParent('div') != $('search')){
	             var div = $('searchform').getParent('div');
	             div.setStyle('height','100%');
	             div.setStyle('overflow','visible');
	         }
	     };
	
	    $$('#showcal, #holtype').each(function(el){
			el.addEvent('click', function(){
	        	s();
	    	});
		});
	
	     var formslide = new Fx.Slide('searchform');
	     var theclicker = $('searchclick');
	
	     theclicker.getElement('h2 a').addEvent('click', function(e) {
	
	    	 if ($defined(e)) {
	    		 e.preventDefault();
	    	 };
	
	    	 $('searchform').getParent('div').setStyle('overflow','hidden');
	    	 formslide.toggle();
	    	 theclicker.toggleClass('open');
	     });
	
	     if (slideout = null || !slideOut)
	    	 formslide.slideOut();
	
	     $('holtype').addEvent('change', function(){
	         holidayTypeChoice();
	     });
	     
	     $('destination').addEvent('change', function(){
	         destinationChoice(this);
	     });
	
	     $('roomcount').addEvent('change', function(){
	         availRoomChoice();
	     });
	          
		$$('select[name^=rooms-]').addEvent('change', function(){
	         availRoomChoiceMyStyle(this.name.match(/\d+/));
	     });     
	
	     $('availgo').addEvent('click', function(event){
	
	    	 if($('holtype').value == hotelFlight){
	
	    		 if (!availRoomPaxChange(false))
	    			 event.preventDefault();
	
	    	 } else {
	
	    		 if (!validatePax(getNoAdults(), getNoChildren(), getNoInfants()))
	    			 event.preventDefault();
	
	    	 }
	
	    	 if (!searchDateValid())
				 event.preventDefault();
	
	     });
	
	     $$('.roomChg').addEvent('change', function(event){
	         if(!availRoomPaxChange(true))
	    		 event.preventDefault();
	     });
	
	    $$('select[class^=roomChg-]').addEvent('change', function(event){	 
	         if(!availRoomPaxChangeMyStyle(true,this.className.match(/\d+/)))
	    		 event.preventDefault();
	     });
	     
	     $$('.paxChange').addEvent('change', function(event){
	
			 if (!validatePax(getNoAdults(), getNoChildren(), getNoInfants())) {
	    		 event.preventDefault();
	    	 }
	
	     });
	     
	     destinationChoice($('destination'));
	}
});

function replaceCalendar(targeturl, date, dep, arr, duration, accom){
 var calendarParams = "monthYear=" + date + "&depPoint=" + dep + "&arrPoint=" + arr + "&duration=" + duration + "&hotelCode=" + accom;
 new Request({
       method: "get",
       url: targeturl,
       onRequest: function(response) { $$('#availabilityCalendar').setProperty('text', 'Loading calendar'); },
       onFailure: function(response) { $$('#availabilityCalendar').setProperty('text', 'failed to load calendar'); },
       onComplete: function(response) { $$('#availabilityCalendar').setProperty('html', response); addTips('a.tips','tips'); }
    }).send(calendarParams);
}

function calendarSelect(
		startDate, 
		outDepAirport, outDepDate, outArrAirport, outArrDate, outAirline, outFlightNo, 
		rtnDepAirport, rtnDepDate, rtnArrAirport, rtnArrDate, rtnAirline, rtnFlightNo, 
		todaysOffer, packagePrice) {
 $$('.calReplaceStartDate').setProperty('html',startDate);
 $$('.calReplaceOutDeparts').setProperty('html', outDepAirport + "<br />" + outDepDate);
 $$('.calReplaceOutArrives').setProperty('html', outArrAirport + "<br />" + outArrDate);
 $$('.calReplaceOutCarrier').setProperty('html', outAirline + "<br />" + outFlightNo);
 $$('.calReplaceRtnDeparts').setProperty('html', rtnDepAirport + "<br />" + rtnDepDate);
 $$('.calReplaceRtnArrives').setProperty('html', rtnArrAirport + "<br />" + rtnArrDate);
 $$('.calReplaceRtnCarrier').setProperty('html', rtnAirline + "<br />" + rtnFlightNo);
 $$('.brochurelabel').dispose();
 $$('.brochureprice').dispose();
 $$('.yousavelabel').dispose();
 $$('.yousaveprice').dispose();
 $$('.offerprice').setProperty('html', todaysOffer + "<span class='text_size_05'>pp</span>");
 $$('.calRemoveDiscount').dispose();
 $$('.calReplacePrice').setProperty('html', "<span class='margin_left_05 text_weight_bold'>Holiday Price:</span><br/><span class='margin_left_01 text_size_25 text_line_height_12'>" + packagePrice + "</span>");
 return false;
}



/**
 * @package		CeraBox
 * 
 * @copyright 	Copyright (c) 2011-2012 Ceramedia
 * @author 		Sven
 * @since 		13-01-2011
 * @version 	1.2.6-r
 * 
 * This package requires Mootools 1.3
 */

var CeraBox = new Class({
	
	Implements: [Options],
	
	loaderTimer: null,
	timeOuter: null,
	
	vars : {
		items: new Array(),
		cerabox: null,
		windowOpen: false,
		busy: false
	},
	
	options: {
		group:					true,
		errorLoadingMessage:	'The requested content cannot be loaded. Please try again later.'
	},
	
	//initialization
	initialize: function(options) {
		//set options
		this.setOptions(options);
		
		this.initHTML();
		
		if (Browser.ie6)
			$('cerabox-loading').addClass('ceraboxbox-ie6');
		
		window.addEvent('resize', this._resize.bind(this));
		
		$('cerabox-loading').addEvent('click', function(event){
			event.stop();
			this.close();
		}.bind(this));
		
		document.addEvent('keyup', function(event) {
			if (event.key == 'esc')
				this.close();
			if (event.target.get('tag')=='input' || event.target.get('tag')=='select' || event.target.get('tag')=='textarea')
				return;
			if (event.key == 'left')
				this.vars.cerabox.getElement('.cerabox-left').fireEvent('click', event);
			if (event.key == 'right')
				this.vars.cerabox.getElement('.cerabox-right').fireEvent('click', event);
		}.bind(this));
	},
	
	/**
	 * Add items to the box
	 * 
	 * @param mixed container
	 * @param object options {ajax:{}, group:bool, width:int, height:int, displayTitle:bool, fullSize:bool, displayOverlay:bool, clickToClose:bool, animation:'fade'|'ease'}
	 */
	addItems: function(container, options) {
		items = $$(container);
		if (items.length<1)
			throw 'Empty container';
		
		itemsIndex = this.vars.items.length;
		this.vars.items[itemsIndex] = [];
		
		options = options ? options : {};
		
		Array.each(items, function(item, index) {
			
			// Dont group selection
			if (options.group===false) {
				this.vars.items[itemsIndex] = [];
				this.vars.items[itemsIndex][0] = item;
				index 		= [itemsIndex,0];
				itemsIndex	= itemsIndex+1;
			}
			else {
				this.vars.items[itemsIndex][index] = item;
				index = [itemsIndex,index];
			}
			//this.vars.cerabox.getElement('.cerabox-left').removeEvents('click').setStyle('display','none');
			if (typeof options.ajax != 'undefined') {
				item.addEvent('click', function(event){
					event.stop();
					this.vars.cerabox.setStyle('cursor','auto').removeEvents('click');
					if (true===options.clickToClose)
						this.vars.cerabox.setStyle('cursor','pointer').addEvent('click', function(event){event.stop(); this.close();}.bind(this));
					this._showInit();
					this.showAjax(index, options);
				}.bind(this));
			}
			else if (item.get('href').test(/\.jpg|jpeg|png|gif$/i)) {
				item.addEvent('click', function(event){
					event.stop();
					this.vars.cerabox.setStyle('cursor','auto').removeEvents('click');
					if (true===options.clickToClose)
						this.vars.cerabox.setStyle('cursor','pointer').addEvent('click', function(event){event.stop(); this.close();}.bind(this));
					this._showInit();
					this.showImage(index, options);
				}.bind(this));
			}
			else if (item.get('href').test(/\.swf$/i)) {
				item.addEvent('click', function(event){
					event.stop();
					this.vars.cerabox.setStyle('cursor','auto').removeEvents('click');
					if (true===options.clickToClose)
						this.vars.cerabox.setStyle('cursor','pointer').addEvent('click', function(event){event.stop(); this.close();}.bind(this));
					this._showInit();
					this.showSwf(index, options);
				}.bind(this));
			}
			else {
				item.addEvent('click', function(event){
					event.stop();
					this.vars.cerabox.setStyle('cursor','auto').removeEvents('click');
					if (true===options.clickToClose)
						this.vars.cerabox.setStyle('cursor','pointer').addEvent('click', function(event){event.stop(); this.close();}.bind(this));
					this._showInit();
					this.showIframe(index, options);
				}.bind(this));
			}
		}.bind(this));
	},
	
	/**
	 * Display AJAX item
	 * 
	 * @param array index
	 * @param object options
	 */
	showAjax: function(index, options) {
		if (this.vars.busy)
			return;
		
		ceraBox = this;
		
		items		= this.vars.items[index[0]];
		currentItem	= items[index[1]];
		
		this.loaderTimer = this._displayLoader.delay(200, this);
		
		requestEr = new Request.HTML({
			url: currentItem.get('href'),
			method: options.ajax.method?options.ajax.method:'post',
			data: options.ajax.data?options.ajax.data:'',
			
			onSuccess: function(responseTree) {
				ceraBox.vars.busy = true;
				
				clearInterval(ceraBox.loaderTimer);
				$('cerabox-loading').setStyle('display', 'none');
				
				if (false!==options.displayOverlay)
					ceraBox._displayOverlay();
				
				ajaxEle = ceraBox.vars.cerabox.getElement('#cerabox-ajaxPreLoader').empty().adopt(responseTree);
				// Needed to know its size
				ceraBox.vars.cerabox.setStyle('display','block');
				
				ajaxEle.setStyle('width', options.width?options.width:ajaxEle.getScrollSize().x + 'px');
				ajaxEle.setStyle('height', options.height?options.height:ajaxEle.getScrollSize().y + 'px');
				
				dimension = ceraBox._getSizeElement(ajaxEle, (true===options.fullSize?true:false));
				
				ajaxEle = ajaxEle.get('html');
				ceraBox.vars.cerabox.getElement('#cerabox-ajaxPreLoader').empty().setStyles({'width':0,'height':0});
				
				// Hide title
				ceraBox.vars.cerabox.getElement('.cerabox-title span')
					.setStyle('display','none')
					.empty();
				
				// If window open morph to new size
				if (ceraBox.vars.windowOpen==true) {
					ceraBox._transformItem(dimension.width, dimension.height);
				}	
				
				ceraBox.vars.cerabox.getElement('.cerabox-content').set('tween', {duration: 300}).tween('opacity','0')
					.get('tween')
					.addEvent('complete', complFnc=function(){
						this.removeEvent('complete',complFnc);
						
						if (false!==options.displayTitle)
							ceraBox.vars.cerabox.getElement('.cerabox-title span')
								.setStyle('display','block')
								.set('text',(items.length>1?'Item ' + (index[1]+1) + ' / ' + items.length + ' ':'') + (currentItem.get('title')?currentItem.get('title'):''));
						
						ceraBox.vars.cerabox.getElement('.cerabox-content')
							.empty()
							.set('opacity',0)
							.set('html', ajaxEle)
							.set('tween', {duration: 100}).tween('opacity','1');
						
						if (items.length>1)
							ceraBox._addNavButtons(index);
						
						ceraBox._openWindow(dimension.width, dimension.height, options.animation?options.animation:'fade', index);
						
						if (true===options.fullSize)
							ceraBox._resize();
						
						ceraBox.vars.busy = false;
					});
			},
			onTimeout: function() { ceraBox._timedOut(index, options); },
			onFailure: function() { ceraBox._timedOut(index, options); },
			onException: function() { ceraBox._timedOut(index, options); }
		}).send();
	},
	
	/**
	 * Display image item
	 * 
	 * @param array index
	 * @param object options
	 */
	showImage: function(index, options) {
		if (this.vars.busy)
			return;
		
		ceraBox = this;
		
		items		= this.vars.items[index[0]];
		currentItem	= items[index[1]];
		
		this.loaderTimer = this._displayLoader.delay(200, this);
		
		image = new Asset.image(currentItem.get('href'), {
			onload: function() {
				ceraBox.vars.busy = true;
				
				clearInterval(ceraBox.loaderTimer);
				$('cerabox-loading').setStyle('display', 'none');
				
				if (false!==options.displayOverlay)
					ceraBox._displayOverlay();
				
				this.set('width', options.width?options.width:this.get('width'));
				this.set('height', options.height?options.height:this.get('height'));
				
				dimension = ceraBox._getSizeElement(this, (true===options.fullSize?true:false));
				
				// Hide title
				ceraBox.vars.cerabox.getElement('.cerabox-title span')
					.setStyle('display','none')
					.empty();
				
				// If window open morph to new size
				if (ceraBox.vars.windowOpen==true) {
					ceraBox._transformItem(dimension.width, dimension.height);
				}
				
				ceraBox.vars.cerabox.getElement('.cerabox-content').set('tween', {duration: 300}).tween('opacity','0')
					.get('tween')
					.addEvent('complete', complFnc=function(){
						this.removeEvent('complete',complFnc);
						
						if (false!==options.displayTitle)
							ceraBox.vars.cerabox.getElement('.cerabox-title span')
								.setStyle('display','block')
								.set('text',(items.length>1?'Item ' + (index[1]+1) + ' / ' + items.length + ' ':'') + (currentItem.get('title')?currentItem.get('title'):''));
						
						ceraBox.vars.cerabox.getElement('.cerabox-content')
							.empty()
							.set('opacity',0)
							.adopt(image)
							.set('tween', {duration: 100}).tween('opacity','1');
						
						if (items.length>1)
							ceraBox._addNavButtons(index);
						
						ceraBox._openWindow(dimension.width, dimension.height, options.animation?options.animation:'fade', index);
						
						if (true===options.fullSize)
							ceraBox._resize();
						
						ceraBox.vars.busy = false;
					});
			},
			onerror: function() {
				ceraBox._timedOut(index, options);
			}
		});
	},
	
	/**
	 * Display swf item
	 * 
	 * @param array index
	 * @param object options
	 */
	showSwf: function(index, options) {
		if (this.vars.busy)
			return;
		
		this.vars.busy = true;
		
		ceraBox = this;
		
		items		= this.vars.items[index[0]];
		currentItem	= items[index[1]];
		
		// Hide title
		ceraBox.vars.cerabox.getElement('.cerabox-title span')
			.setStyle('display','none')
			.empty();
		
		dimension = {width:options.width?options.width:500, height:options.height?options.height:400};
		
		swfEr = new Swiff(currentItem.get('href'), {
			width: dimension.width,
		    height: dimension.height,
			params: {
				wMode: 'opaque'
		    }
		});
		
		if (false!==options.displayOverlay)
			ceraBox._displayOverlay();
		
		// If window open morph to new size
		if (ceraBox.vars.windowOpen==true) {
			ceraBox._transformItem(dimension.width, dimension.height);
		}
		
		ceraBox.vars.cerabox.getElement('.cerabox-content').set('tween', {duration: 300}).tween('opacity','0')
			.get('tween')
			.addEvent('complete', complFnc=function(){
				this.removeEvent('complete',complFnc);
				
				if (false!==options.displayTitle)
					ceraBox.vars.cerabox.getElement('.cerabox-title span')
						.setStyle('display','block')
						.set('text',(items.length>1?'Item ' + (index[1]+1) + ' / ' + items.length + ' ':'') + (currentItem.get('title')?currentItem.get('title'):''));
				
				ceraBox.vars.cerabox.getElement('.cerabox-content')
					.empty()
					.set('opacity',0)
					.adopt(swfEr)
					.set('tween', {duration: 100}).tween('opacity','1');
				
				if (items.length>1)
					ceraBox._addNavButtons(index);
				
				ceraBox._openWindow(dimension.width, dimension.height, options.animation?options.animation:'fade', index);
				
				if (true===options.fullSize)
					ceraBox._resize();
				
				ceraBox.vars.busy = false;
			});
	},
	
	/**
	 * Display iframe item
	 * 
	 * @param array index
	 * @param object options
	 */
	showIframe: function(index, options) {
		if (this.vars.busy)
			return;
		
		ceraBox = this;
		
		items		= this.vars.items[index[0]];
		currentItem	= items[index[1]];
		
		this.loaderTimer = this._displayLoader.delay(200, this);
		// Set timeout timer incase request cannot be done
		this.timeOuter = this._timedOut.delay(10000, this, [index, options]);
		
		ceraIframe = new IFrame({
			src: currentItem.get('href'),
			
			events: {
				load: function() {
					ceraBox.vars.busy = true;
					
					clearInterval(ceraBox.timeOuter);
					clearInterval(ceraBox.loaderTimer);
					$('cerabox-loading').setStyle('display', 'none');
					
					if (false!==options.displayOverlay)
						ceraBox._displayOverlay();
					
					this.setStyles({
						width: options.width?options.width:'1px',
						height: options.height?options.height:'1px',
						border: '0'
					});
					
					dimension = ceraBox._getSizeElement(this, (true===options.fullSize?true:false));
					
					if (items.length>1)
						ceraBox._addNavButtons(index);
					
					// Hide title
					ceraBox.vars.cerabox.getElement('.cerabox-title span')
						.setStyle('display','none')
						.empty();
					
					// If window open morph to new size
					if (ceraBox.vars.windowOpen==true) {
						ceraBox._transformItem(dimension.width, dimension.height);
					}
					
					ceraBox._openWindow(dimension.width, dimension.height, options.animation?options.animation:'fade', index);
					
					if (true===options.fullSize)
						ceraBox._resize();
					
					ceraBox.vars.cerabox.getElement('.cerabox-content').set('tween', {duration: 100}).tween('opacity','1');
					
					ceraBox.vars.busy = false;
				}
			}
		});
		
		ceraIframe.set('border','0');
		ceraIframe.set('frameborder','0');
		
		// Open it so onload fires
		this.vars.cerabox.setStyle('display','block').getElement('.cerabox-content')
			.empty()
			.set('opacity',0)
			.adopt(ceraIframe);
	},
	
	/**
	 * Close box
	 */
	close: function() {
		if (this.vars.busy)
			return;
		
		this.vars.busy = true;

		clearInterval(this.timeOuter);
		clearInterval(this.loaderTimer);
		$('cerabox-loading').setStyle('display', 'none');
		
		ceraBox = this;
		
		ceraBox.vars.cerabox.set('tween', {duration: 50}).tween('opacity', '0').get('tween')
			.addEvent('complete', complFnc=function() {
				this.element.setStyle('display','none');
				$('cerabox-background').set('tween', {duration: 150,link:'chain'}).tween('opacity','0').tween('display','none');
				
				ceraBox.vars.cerabox.getElement('.cerabox-content').empty();
				ceraBox.vars.cerabox.getElement('.cerabox-left').removeEvents('click').setStyle('display','none');
				ceraBox.vars.cerabox.getElement('.cerabox-right').removeEvents('click').setStyle('display','none');
				ceraBox.vars.windowOpen = false;
				
				this.removeEvent('complete',complFnc);
				ceraBox.vars.busy = false;
			});
	},
	
	/**
	 * Inject needed HTML to the body
	 */
	initHTML: function() {
		wrapper = $(document.body);
		
		wrapper.adopt([
				new Element('div',{'id':'cerabox-loading'}).adopt(new Element('div')),
				new Element('div',{'id':'cerabox-background', 'styles':{'height':wrapper.getScrollSize().y+'px'}, 'events':{'click':function(event){event.stop();this.close()}.bind(this)}}),
				this.vars.cerabox = new Element('div',{'id':'cerabox'}).adopt([
				                                    new Element('div', {'class':'cerabox-content'}),
				                                    new Element('div', {'class':'cerabox-title'}).adopt(new Element('span')),
				                                    new Element('a', {'class':'cerabox-close','events':{'click':function(event){event.stop();this.close()}.bind(this)}}),
				                                    new Element('a', {'class':'cerabox-left'}).adopt(new Element('span')),
				                                    new Element('a', {'class':'cerabox-right'}).adopt(new Element('span')),
				                                    new Element('div', {'id':'cerabox-ajaxPreLoader', 'styles':{'float':'left','overflow':'hidden','display':'block'}})
				])
		]);
	},
	
	/**
	 * Has timed out display error
	 * 
	 * @param array index
	 */
	_timedOut: function(index, options) {
		if (this.vars.busy)
			return;
		
		this.vars.busy = true;
		
		clearInterval(this.loaderTimer);
		$('cerabox-loading').setStyle('display', 'none');
		
		this._displayOverlay();
		
		this.vars.cerabox.getElement('.cerabox-title span')
			.setStyle('display','none')
			.empty();
		
		ceraBox = this;
		
		items = this.vars.items[index[0]];
		
		this.vars.cerabox.getElement('.cerabox-content').set('tween', {duration: 300}).tween('opacity','0')
			.get('tween')
			.addEvent('complete', complFnc=function(){
				this.removeEvent('complete',complFnc);
				
				ceraBox.vars.cerabox.getElement('.cerabox-content')
					.empty()
					.set('opacity',0)
					.adopt(new Element('span',{'text':ceraBox.options.errorLoadingMessage}))
					.set('tween', {duration: 100}).tween('opacity','1');
				
				if (items.length>1)
					ceraBox._addNavButtons(index);
				
				ceraBox._openWindow(250, 50, options.animation?options.animation:'fade', index);
				
				/*if (true===options.fullSize)
					ceraBox._resize();*/
				
				ceraBox.vars.busy = false;
			});
		
		
		// If window open morph to new size
		if (ceraBox.vars.windowOpen==true) {
			ceraBox._transformItem(250, 50);
		}
	},
	
	/**
	 * Add navigation buttons for group items
	 * 
	 * @param array index
	 */
	_addNavButtons: function(index) {
		ceraBox = this;
		this.vars.cerabox.getElement('.cerabox-left').removeEvents('click').setStyle('display','none');
		this.vars.cerabox.getElement('.cerabox-right').removeEvents('click').setStyle('display','none');
		
		if (this.vars.items[index[0]][(index[1]-1)]) {
			this.vars.cerabox.getElement('.cerabox-left').setStyle('display','block').addEvent('click', function(event){
				
				event.stopPropagation();
				this.setStyle('display','none');
				ceraBox.vars.items[index[0]][(index[1]-1)].fireEvent('click', event);
			});
		}
		if (this.vars.items[index[0]][(index[1]+1)]) {
			this.vars.cerabox.getElement('.cerabox-right').setStyle('display','block').addEvent('click', clickFnc=function(event){
				
				event.stopPropagation();
				this.setStyle('display','none');
				ceraBox.vars.items[index[0]][(index[1]+1)].fireEvent('click', event);
			});
		}
	},
	
	/**
	 * Transform item to an other size
	 * 
	 * @param int width
	 * @param int height
	 * @return morph
	 */
	_transformItem: function(width, height) {
		morphObject = {
			'display':'block',
			'width':width,
			'height':height,
			'opacity':1
		};
		if (window.getSize().x > this.vars.cerabox.getSize().x+40 && window.getSize().x > width+40) {
			this.vars.cerabox.setStyles({
				'left':'50%',
				'right':'auto'
			});
			morphObject['margin-left'] = ((-width/2)+$(document.body).getScroll().x) + 'px';
		}
		else {
			this.vars.cerabox.setStyles({
				'margin-left':'0',
				'left':'auto',
				'right':'20px'
			});
		}
		if (window.getSize().y > this.vars.cerabox.getSize().y+40 && window.getSize().y > height+40) {
			this.vars.cerabox.setStyles({
				'top':'50%'
			});
			morphObject['margin-top'] = ((-height/2)+$(document.body).getScroll().y) + 'px';
		}
		else {
			if (height+40 > ($(document.body).getScrollSize().y-$(document.body).getScroll().y)) {
				this.vars.cerabox.setStyles({
					'margin-top':'0',
					'top':($(document.body).getScrollSize().y-(height+60)>20?$(document.body).getScrollSize().y-(height+60):20) + 'px'
				});
			}
			else {
				this.vars.cerabox.setStyles({
					'margin-top':'0',
					'top':$(document.body).getScroll().y + 20 + 'px'
				});
			}
		}
		return this.vars.cerabox.set('morph', {duration: 150})
			.morph(morphObject).get('morph');
	},
	
	/**
	 * Initialize show function
	 */
	_showInit: function() {
		if (this.vars.busy)
			return;
		
		// Make sure it doesnt time out when started a new request and prev loader is gone
		clearInterval(this.timeOuter);
		clearInterval(this.loaderTimer);
		$('cerabox-loading').setStyle('display', 'none');
	},
	
	/**
	 * Open cerabox window
	 * 
	 * @param int width
	 * @param int height
	 * @param string[optional] animation 'ease'|'fade'
	 * @param array[optional] index item
	 */
	_openWindow: function(width, height, animation, index) {
		if (this.vars.cerabox.getElement('.cerabox-content iframe'))
			this.vars.cerabox.getElement('.cerabox-content iframe').setStyles({'width':width,'height':height});
		
		if (this.vars.windowOpen==true)
			return;
		
		switch (animation) {
		case 'ease':
			currentItem	= this.vars.items[index[0]][index[1]];
			
			this.vars.cerabox.setStyles({
				'display':'block',
				'left':currentItem.getPosition().x + 'px',
				'top':currentItem.getPosition().y + 'px',
				'width':currentItem.getSize().x + 'px',
				'height':currentItem.getSize().y + 'px',
				'margin':0,
				'opacity':0
			}).set('morph', {duration: 200}).morph({
				'left':((window.getSize().x/2)) + 'px',
				'top':((window.getSize().y/2)) + 'px',
				'width':width,
				'height':height,
				'margin-left':((-width/2)+$(document.body).getScroll().x) + 'px',
				'margin-top':((-height/2)+$(document.body).getScroll().y) + 'px',
				'opacity':'1'
			});
			break;
		case 'fade':
		default:
			this.vars.cerabox.setStyles({
				'display':'block',
				'left':'50%',
				'top':'50%',
				'width':width,
				'height':height,
				'opacity':0,
				'margin-left':((-width/2)+$(document.body).getScroll().x) + 'px',
				'margin-top':((-height/2)+$(document.body).getScroll().y) + 'px'
			}).set('tween', {duration: 150}).tween('opacity', '1');
			break;
		}
		
		this.vars.windowOpen = true;
	},
	
	/**
	 * Display transparen overlay
	 */
	_displayOverlay: function() {
		$('cerabox-background').setStyles({'display':'block','opacity':'.5','height':$(document.body).getScrollSize().y + 'px','width':$(document.body).getScrollSize().x + 'px'});
	},
	
	/**
	 * Display loading spinner
	 */
	_displayLoader: function() {
		$('cerabox-loading').setStyle('display','block');
		this._loaderAnimation();
	},
	
	/**
	 * Loader animation
	 * 
	 * @param int frame
	 */
	_loaderAnimation: function(frame) {
		if (!frame)
			frame=0;
		$('cerabox-loading').getElement('div').setStyle('top', (frame * -40) + 'px');
		frame = (frame + 1) % 12;
		
		if ($('cerabox-loading').getStyle('display')!='none')
			this._loaderAnimation.delay(60, this, frame);
	},
	
	/**
	 * Get size element object
	 * 
	 * @param object element
	 * @return object
	 */
	_getSizeElement: function(element, fullSize) {
		if (element.tagName == 'IFRAME') {
			try {
				eleWidth = (element.get('width')?this._sizeStringToInt(element.get('width'),'x'):(element.getStyle('width').toInt()>1?this._sizeStringToInt(element.getStyle('width'),'x'):
					(element.contentWindow.document.getScrollWidth()?element.contentWindow.document.getScrollWidth():window.getSize().x * 0.75)));
				eleHeight = (element.get('height')?this._sizeStringToInt(element.get('height'),'y'):(element.getStyle('height').toInt()>1?this._sizeStringToInt(element.getStyle('height'),'y'):
					(element.contentWindow.document.getScrollHeight()?element.contentWindow.document.getScrollHeight():window.getSize().y * 0.75)));
			}
			catch(err) {
				eleWidth = window.getSize().x * 0.75;
				eleHeight = window.getSize().y * 0.75;
				this._log(err); // IE6 fix
			}
			
			if (Browser.ie) {
				eleHeight = eleHeight + 20;
			}
			
			if (false===fullSize) {	
				if ((window.getSize().y - 100)<eleHeight) {
					eleWidth = eleWidth + (Browser.Platform.mac?15:17);
				}
				return {width: (window.getSize().x - 50)<eleWidth?(window.getSize().x - 50):eleWidth, height: (window.getSize().y - 100)<eleHeight?(window.getSize().y - 100):eleHeight};
			} else
				return {width: eleWidth, height: eleHeight};	
		}
		
		eleWidth = (element.get('width')?this._sizeStringToInt(element.get('width'),'x'):(element.getStyle('width')&&element.getStyle('width')!='auto'?this._sizeStringToInt(element.getStyle('width'),'x'):window.getSize().x - 50));
		eleHeight = (element.get('height')?this._sizeStringToInt(element.get('height'),'y'):(element.getStyle('height')&&element.getStyle('height')!='auto'?this._sizeStringToInt(element.getStyle('height'),'y'):window.getSize().y - 100));
		
		if (false===fullSize) {
			var r = Math.min(Math.min(window.getSize().x - 50, eleWidth) / eleWidth, Math.min(window.getSize().y - 100, eleHeight) / eleHeight);
			return {width: Math.round(r * eleWidth), height: Math.round(r * eleHeight)};
		}
		else
			return {width: eleWidth, height: eleHeight};
	},
	
	/**
	 * Get the pixels of given element size
	 * 
	 * @param string size
	 * @param string dimension 'x'|'y'
	 */
	_sizeStringToInt: function(size, dimension) {
		return (typeof size == 'string' && size.test('%')?window.getSize()[dimension]*(size.toInt()/100):size.toInt());
	},
	
	_resize: function() {
		if(this.vars.windowOpen==true) {
			if (window.getSize().x > this.vars.cerabox.getSize().x+40) {
				this.vars.cerabox.setStyles({
					'margin-left':(this.vars.cerabox.getSize().x>0?((-this.vars.cerabox.getSize().x/2)+$(document.body).getScroll().x):0) + 'px',
					'left':'50%',
					'right':'auto'
				});
			}
			else {
				this.vars.cerabox.setStyles({
					'margin-left':'0',
					'left':'auto',
					'right':'20px'
				});
			}
			if (window.getSize().y > this.vars.cerabox.getSize().y+40) {
				this.vars.cerabox.setStyles({
					'margin-top':(this.vars.cerabox.getSize().y>0?((-this.vars.cerabox.getSize().y/2)+$(document.body).getScroll().y):0) + 'px',
					'top':'50%',
					'bottom':'auto'
				});
			}
			else {
				if (this.vars.cerabox.getSize().y+40 > ($(document.body).getScrollSize().y-$(document.body).getScroll().y)) {
					this.vars.cerabox.setStyles({
						'margin-top':'0',
						'top':($(document.body).getScrollSize().y-(this.vars.cerabox.getSize().y+60)>20?$(document.body).getScrollSize().y-(this.vars.cerabox.getSize().y+60):20) + 'px'
					});
				}
				else {
					this.vars.cerabox.setStyles({
						'margin-top':'0',
						'top':$(document.body).getScroll().y + 20 + 'px'
					});
				}
			}
			$('cerabox-background').setStyles({'height':$(document.body).getScrollSize().y + 'px','width':$(document.body).getScrollSize().x + 'px'});
		}
	},
	
	/**
	 * Simple logging function
	 */
	_log: function(log, alertIt) {
		try {
			console.log(log);
		}
		catch(err) {
			if (alertIt)
				alert(log);
		}
	}
});
