var page = 1;
var cache = "false";



currencies = new Array();
currencies['AUD'] = 1.113;
currencies['EUR'] = 0.735;
currencies['USD'] = 1.000;
currencies['GBP'] = 0.646;

function working() {
	// No map container to hide at the moment! 
	// May need to revisit this when we add the mapping bit
	// hide_map();
	// Hide searchResults div only if the results aren't being pulled from the cache
	if (cache == "true") {
		$('searchResults').hide();		
	} else {
		// and then show the searchLoader
		$('searchResults').hide();		
		$('searchLoader').show();		
	}

}


function done() {

}

function roomExtraPopup() {
	$$(".extra").each(function(s) {
		s.observe('mouseover', function() {
			this.down("span").show();
		});
		s.observe('mouseover', function() {
			this.setStyle({
				cursor:'pointer'
			});
		});
		s.down("span").observe('mouseout', function() {
			this.hide();
		});
	});
}

function failed () {
	//alert('Failed!');
}

function success () {
	//alert('Success');
}

// Function invoked on window.onload
function search() {
	if (cache == "true") {
	} else {
		// and then show the searchLoader
		$("#searchResults").hide();		
		$("#searchLoader").show();		
	}
	
	//var parameters = 'hotel_country=' + $('#select_country')[0].value + "&hotel_region=" + $('#hotel_region')[0].value + "&arrival=" + $('#datepicker')[0].value + "&duration=" + $('#stay_nights')[0].value + "&page=" + page + "&adults=" + $('#nr_adults')[0].value + "&cache=" + cache;
	
	if ($('#cacheStatus')[0].value == "true") {
		cache = "true";
	}
	var parameters = 'hotel_country=' + $('#select_country')[0].value + "&hotel_region=" + $('#hotel_region')[0].value + "&arrival=" + $('#datepicker')[0].value + "&duration=" + $('#stay_nights')[0].value + "&page=" + page + "&cache=" + cache;
	// Do ajax request		
	$.ajax({
		url: "/sandbox/index.cfm?action=search-hotels.searchResults",
		cache: false,
		data: parameters,
		success: function(html){
			// Hide the loader image
			$("#searchLoader").fadeOut(300).hide();
			// Show the search results
			var searchContainer = $("#searchResults");
			searchContainer.empty();
			searchContainer.append(html);
			searchContainer.show();
		 		
			// Add an onclick observer to each of the pagination links
			// which fires the search function, passing in the requested page number
			
			$('#pagination a').click(function(event){
				event.preventDefault();
				if ($('#select_country')[0].value !='') {
					page = event.target.href.match(/page=([0-9]+)/)[1];
					cache = "true";
					search();
				} else {
					alert('Please select a country to search within.');
					event.preventDefault();
				}
			});
			
			// Check to see what the currency is and set the currency button to active
			if($('.base-price').length) {
				var currency = $('.base-price').attr('currency') ;
				$('#currency-convertor span.currency').each(function(s){
					var currentCurr = $( this ).attr('title')
					if (currentCurr == currency) {
						$( this ).addClass("active");
					}
				});
			}
			

			// Hide all answers as default
			$("span.room_extra_detail").hide();
		
			$(".room_extra").hover(function() {
					$(this).next().fadeIn(250);
				},
					function() {
				    $(this).next().fadeOut(250);
				});
			
			
			// On currency convert change the buttons accoridinly
			$('#currency-convertor span.currency').click(function(event) {						
				// Remove the active class from the currency buttons
				$('#currency-convertor span.currency').removeClass('active');
				// Add the active class to the currency button
				$(event.target).addClass("active");
				// Call the currency convertor function 
				convert_currencies($(event.target).attr('title'));
				// Prevent the default link behaviour
				event.preventDefault();
			});
	    }
	});
} // EOF search();

function convert_currencies(currency) 
{
	$('span.base-price').each(function(s) {
		var converted = ($(this).attr('rate') / currencies[$(this).attr('currency')]) * currencies[currency];
		converted = Math.ceil(converted);
		$( this ).prev('span').empty().append(currency + ' ' + converted);
	});
	
	// If there is a discount it's nice to convert that as well.
	$("span.discounted-base-price").each(function(s) {
		var convertedDiscount = ($(this).attr('rate') / currencies[$(this ).attr('currency')]) * currencies[currency];
		convertedDiscount = Math.ceil( convertedDiscount );
		$( this ).prev().prev().prev( 'span' ).empty().append( currency + ' ' + convertedDiscount );
	});
}
$(document).ready(function(){				
 
	// Add an on change event handler to the country drop down
	if($('#select_country').length) {
    	$("select#select_country").change(function(){
    		var country = 'hotel_country=' + $('#select_country')[0].value 
    		$.ajax({
    			url: "/sandbox/index.cfm?action=home.getRegions",
    			cache: false,
    			data: country,

    			success: function(html){
    				var container = $(".region_list");
    				container.empty();
    				container.append(html);
    				
        			// Remove the classes that prevent the form script from updating the dropdowns
        			$('form#booking').removeClass('jqtransformdone');
        			$('select#hotel_region').removeClass('jqTransformHidden');
        			// Just run the jqTransform on form#booking
        			$('form#booking').jqTransform({imgPath:'/images_new/'});    				
    			}
    		});
    		
    
    	});
    }

	
    // Check to see if the Check availability button is present 
	if($('#checkAvailability').length) {
		$('#checkAvailability').click(function (event) {
			event.preventDefault();
			$("#checkAvailabilityForm").submit();
		})
	}

    // Initialise the date picker if present
    if($('#datepicker').length) {
    	$("#datepicker").datepicker({ showButtonPanel: true, currentText: '', closeText: 'x', dateFormat: 'dd-mm-yy', minDate: '+0m +0w', showOn: 'both', buttonImage: '/images_new/cal.gif', buttonImageOnly: true});
    }
    
    // Initialise the date picker if present
    if($('#enquiryDate').length) {
    	$("#enquiryDate").datepicker({ showButtonPanel: true, currentText: '', closeText: 'x', dateFormat: 'dd-mm-yy', minDate: '+0m +0w', showOn: 'both', buttonImage: '/images_new/cal.gif', buttonImageOnly: true});
    }  
    
    // Initialise the date picker if present
    if($('#roomSelectionDate').length) {
    	$("#roomSelectionDate").datepicker({ showButtonPanel: true, currentText: '', closeText: 'x', dateFormat: 'dd-mm-yy', minDate: '+0m +0w', showOn: 'both', buttonImage: '/images_new/cal.gif', buttonImageOnly: true});
    }  
    
       
    if($('#photos')) {
    	$('#photos').galleryView({
    		panel_width: 694,
    		panel_height: 300,
    		overlay_height: 0,
    		wrapper_width: 360,
    		frame_width: 36,
    		frame_height: 36,
    		transition_speed: 1200,
    		background_color: '',
    		overlay_color: '',
    		border: 'none',
    		pause_on_hover: false,
    		nav_theme: 'light',
    		filmstrip_position: 'bottom',
    		overlay_opacity: 0
    	});
    }
				
	if($('#thumbs').length) {
	   	// We only want these styles applied when javascript is enabled
	   	$('div.navigation').css({ 'width' : '694px' });
	   	//$('div.content').css('display', 'block');
		// Initially set opacity on thumbs and add
		// additional styling for hover effect on thumbs
		var onMouseOutOpacity = 0.67;
		$('#thumbs ul.thumbs li').opacityrollover({
			mouseOutOpacity:   onMouseOutOpacity,
			mouseOverOpacity:  1.0,
			fadeSpeed:         'fast',
			exemptionSelector: '.selected'
	});			
			
	// Initialize Advanced Galleriffic Gallery
	var gallery = $('#thumbs').galleriffic({
		delay:                     2500,
		numThumbs:                 8,
		preloadAhead:              8,
		enableTopPager:            false,
		enableBottomPager:         false,
		imageContainerSel:         '#slideshow',
		controlsContainerSel:      '#controls',
		captionContainerSel:       '#caption',
		loadingContainerSel:       '#loading',
		renderSSControls:          true,
		renderNavControls:         true,
		playLinkText:              'Play Slideshow',
		pauseLinkText:             'Pause Slideshow',
		prevLinkText:              '&lsaquo; Previous Photo',
		nextLinkText:              'Next Photo &rsaquo;',
		nextPageLinkText:          'Next &rsaquo;',
		prevPageLinkText:          '&lsaquo; Prev',
		enableHistory:             false,
		autoStart:                 false,
		syncTransitions:           true,
		defaultTransitionDuration: 900,
		onSlideChange:             function(prevIndex, nextIndex) {
		// 'this' refers to the gallery, which is an extension of $('#thumbs')
		this.find('ul.thumbs').children()
		.eq(prevIndex).fadeTo('fast', onMouseOutOpacity).end()
		.eq(nextIndex).fadeTo('fast', 1.0);
		// Update the photo index display
		this.$captionContainer.find('div.photo-index')
			.html('Photo '+ (nextIndex+1) +' of '+ this.data.length);
		},
		
		onPageTransitionOut:function(callback) {
			this.fadeTo('fast', 0.0, callback);
		},
		
		onPageTransitionIn:function() {
			var prevPageLink = this.find('a.prev').css('visibility', 'hidden');
			var nextPageLink = this.find('a.next').css('visibility', 'hidden');
			// Show appropriate next / prev page links
			if (this.displayedPage > 0)
				prevPageLink.css('visibility', 'visible');
				var lastPage = this.getNumPages() - 1;
				if (this.displayedPage < lastPage)
					nextPageLink.css('visibility', 'visible');
				this.fadeTo('fast', 1.0);
			}
		});

		/**************** Event handlers for custom next / prev page links **********************/
		gallery.find('a.prev').click(function(e) {
			gallery.previousPage();
			e.preventDefault();
		});

		gallery.find('a.next').click(function(e) {
			gallery.nextPage();
			e.preventDefault();
		});
	} // End of if thumbs!
	
	if ($('#searchResults').length) {
		search();
	}
	
	if($('#search')) {
		$('#search').click(function (event) {
			if ($('#select_country')[0].value !='') {
				//event.preventDefault();
				//$("#search").submit();		
			} else {
				alert('Please select a country to search within.');
				event.preventDefault();
			}		
		})
	}
	
	if($('#refineSearchButton').length) {
		$('#refineSearchButton').click(function (event) {
			if ($('#select_country')[0].value !='') {
				event.preventDefault();
				$("#refineSearch").submit();		
			} else {
				alert('Please select a country to search within.');
				event.preventDefault();
			}		
		})
	}

	if($('#updateRoomSelection').length) {
		$('#updateRoomSelection').click(function (event) {
			event.preventDefault();
			$("form#updateRoomSelectionForm").submit();		
		})
	}
	
	if($('form#booking').length) {
		
		$('form#booking').jqTransform({imgPath:'/images_new/'}); 
		$("#booking").validate();

	}
	
	if($('form#checkAvailabilityForm').length) {
		$('form#checkAvailabilityForm').jqTransform({imgPath:'/images_new/'});
	}
	
	if ( $.browser.msie ) {
		  // alert( $.browser.version );
	}
	
	//if($('form#updateRoomSelectionForm').length) {
		//$('form#updateRoomSelectionForm').jqTransform({imgPath:'/images_new/'});
	//}
	
	if($('form#roomSelection').length) {
		$('form#roomSelection').jqTransform({imgPath:'/images_new/'});
	}
	
	if($('form#nonStarEnquiry').length) {
		$('form#nonStarEnquiry .dates').jqTransform( {imgPath:'/images_new/'} ); 
		
		$('form#nonStarEnquiry').validate({
		onkeyup:true,
		errorPlacement: function(error, element) {
			if (element.hasClass('.enquiryDate')) {
				if ($('form#nonStarEnquiry span.error').length) { 
					
				} else {
					var el = $('form#nonStarEnquiry')
					error.fadeIn(500).insertBefore( el ); 
				}
			} else {
				error.fadeIn(500).insertAfter( element ); 
			}
        },
        errorElement:'span',
        rules: { 
            email: { 
                required: true, 
                email: true 
            },
            name: {
            	required:true,
            	minlength:2
            },
            phone: {
            	required:true,
            	minlength:11,
            	maxlength:25,
            	number:false
            },
            postcode: {
            	required:true,
            	minlength:5,
            	maxlength:8
            }, 
            arrival: {
            	required:true
            }, 
            roomList: {
            	required:true
            }
        },
        messages: {
			name: {
				required: "Please enter you full name.",
				minlength: "Please enter at least two characters for your name."
			},
			email: {
				required: "Please enter a valid email address.",
				email: "Please enter a valid email address."
			},
			phone: {
				required: "Please enter your contact phone number",
				minlength: "Phone number should be at least 11 digits - please include area code"
				// number: "Please enter only numbers for the telephone number"
			},
			postcode: {
				required: "Please enter your postcode.",
				minlength: "Postcode should be at least six characters.",
				maxlength: "Postcode should not be more than seven characters."
			},
			arrival: {
				required: "Please enter an arrival date."
			},
			roomList: {
				required: "Please select a room type."
			}
		}
		});
	}

	if($('form#subscribe').length) {
		$('form#subscribe').validate({
			onkeyup:false,
			errorPlacement: function(error, element) {
				error.fadeIn(500).insertAfter( element ); 
	        },
	        errorElement:'span',
	        rules: { 
	            email: { 
	                required: true, 
	                email: true 
	            }
	        },
	        messages: {
				email: {
					required: "Please enter a valid email address.",
					email: "Please enter a valid email address."
				}
	        }
		});
	}
	
	if($('form#contact').length) {
		$('form#contact').validate({
		onkeyup:false,
		errorPlacement: function(error, element) {
			error.fadeIn(500).insertAfter( element ); 
        },
        errorElement:'span',
        rules: { 
            email: { 
                required: true, 
                email: true 
            },
            name: {
            	required:true,
            	minlength:2
            },
            phone: {
            	required:true,
            	minlength:11,
            	maxlength:25,
            	number:false
            },
            message: {
            	required:true,
            	minlength:1,
            	maxlength:1500
            }
        },
        messages: {
			name: {
				required: "Please enter you full name - This is a required field.",
				minlength: "Please enter at least two characters for your name."
			},
			email: {
				required: "Please enter a valid email address.",
				email: "Please enter a valid email address."
			},
			phone: {
				required: "Please enter your contact phone number",
				minlength: "Phone number should be at least 11 digits - please include area code"
				// number: "Please enter only numbers for the telephone number"
			}
		}
		});
	}
	
	// Add the autocomplete jquery plugin to the hotelsearch input files
	if($('#hotelSearch').length) {	
		$("#hotelSearch").autocomplete(data, {	
			multiple: true,
			mustMatch: false,
			autoFill: false,
			width: 250,
			scroll: true,
			cacheLength: 50,
			dealy: 0,
			max:150,
			scrollHeight: 350,
			cacheLength:1,
			matchContains:true
		});		
	}
	
	// Add an on change event handler to the site search form
	if($('.hotel-search').length) {	
	
	$(".hotel-search").focus(function() {
		if( this.value == 'Hotel quick search...' ) {
			this.value = "";
		}
	}).blur(function() {
		if( !this.value.length ) {
			this.value = 'Hotel quick search...';
		}
	});
	}

	// Add the tool tips
	if($('.extra'))	{
		// Tooltips for room extras
		$("span.room_extra_detail").hide();
		$(".room_extra").hover(function() {
			$(this).next().fadeIn(250);
		},
			function() {
		    $(this).next().fadeOut(250);
		});
	}
	
	// Add handlers and what not to the rate guarantee 
	if($('.pop-up-guarantee').length) {
		$(".pop-up-guarantee .rateGuarantee").click(function(event) {
			event.preventDefault();
			$('.best-rate').fadeIn(500);
		});
		$("a.close").click(function(event) {
			event.preventDefault();
			$('.best-rate').fadeOut(500);	
		});
	}

	
	// Add handlers and what not to the privacy policy
	if($('.privacy-pop-up').length) {
		$(".privacy-pop-up .privacyStatement").click(function(event) {
			event.preventDefault();
			$('.privacy-policy').fadeIn(500);
		});
		$("a.close").click(function(event) {
			event.preventDefault();
			$('.privacy-policy').fadeOut(500);	
		});
	}
		
}); // End of document.ready

	
