// declare a bunch of global variables up here.
var all;
var params = "";
//var sortOrder = 'desc'; //stores the current sort order, which is altered by clicking multiple times
//hack allow asc desc transition for no jquery via jquery,  shoot me please!
var name= "sortorder";
var regexS = "[\\?&]"+name+"=([^&#]*)";
var regex = new RegExp( regexS );
var results = regex.exec( this.location.href );
if( results == null )
sortOrder =  "asc";
else
sortOrder =  results[1];


var name= "sort";
var regexS = "[\\?&]"+name+"=([^&#]*)";
var regex = new RegExp( regexS );
var results = regex.exec( this.location.href );
if( results == null )
var sort = null;
else
sort = results[1];
//var customSortArgs = array('rating');



$(document).ready(function() { 

	$("[id^=approved-hotel]").each(function(index) {
	   
	$(this).mouseover(function() {

				$("#approved-hotel-pop").fadeIn(200);
			})
			.mouseout(function(){
				$("#approved-hotel-pop").fadeOut(200);
			});
			
			
	});
});
// gets new hotel info and whatnot from the server
function getnewdata() {
	
	//alert(params);

	var loc = location.href ;

	var subdomain = new Array() ;
	subdomain = loc.split("?") ;
	subdomain = subdomain[0].split("hotels.php") ;

	this.location = subdomain[0] + "hotels.php?" + params;
	//this.location = "/hotels.php?" + params;
	

	//redraw_hotels();
	//		redraw_controls();
	//		redraw_location();
	//		repopulateform();
   /* jQuery.ajax({
		beforeSend : loading_show,
		data : params,
		dataType : "xml",
		error : function(XHR, errmsg) {
			loading_hide();
			alert("Sorry, we could not find any hotels which matched your search criteria");
		},
		success : function(data) {
			all = data;
			redraw_hotels();
			redraw_controls();
			redraw_location();
			repopulateform();
			loading_hide();
			window.scrollTo(0,0);
			//$("#debug").html(all.documentURI);
		},
		type : "GET",
		url : "hotels_xml.php"
	});*/
}

// little helper function that sets things going.
function refilter(sortBy) {
    readfilters(sortBy);
	getnewdata();
	return false;	// return false to stop the search box from submitting
}

// redraws the hotel info to the page
function redraw_hotels() {

	//Update the page h1 with the new ranges.
	title = ranges.join(', ');
    titleTemp = title;
    lastCommaPos = title.lastIndexOf(',');
    
    if(lastCommaPos!=-1) {
        titleTemp = title.substr(0,lastCommaPos);
        titleTemp += ' and ' + title.substr(lastCommaPos+2);
            
    }
     
    title = titleTemp + ' Hotels In London';
    
    $('h1').html(title);
       
    h = "";
	
	// list mode
	if($("search > mode", all).text() == "list") {
		//h += "\n<table id=\"hotels_list\">";
		h += "\n<tr>";
		h += "<th class=\"listtopleft\">Hotel Name</th>";
		h += "<th>Area</th>";
        if($("search > location_id", all).text() != 0) {
			h += "<th>Distance</th>";
			//h += "<th></th>";
		}
		h += "<th>Star Rating</th>";
		h += "<th>Guest Rating</th>";
		h += "<th>Total Price</th>";
		h += "<th class=\"listtopright\"></th>";
		h += "</tr>";
		
		$("search > hotels > hotel", all).each(function() {
			h += drawhotellist(this);
		});
		
		h += "\n<tr><td colspan=\"" + (($("search > location_id", all).text() != 0) ? 5: 4) + "\" class=\"listbottom\"></td></tr>";
		//h += "</table>";
		//alert(h);
		$("#list").html(h);
	}
	
	// full mode
	else {
	
		$("search > hotels > hotel", all).each(function() {
			h += drawhotelfull(this);
		});
	//alert(h);
		$("#list").html(h);
		
		/*
		jQuery(function($) {
			$("a[rel^='lightbox']").slimbox({}, null, function(el) {
				return (this == el) || ((this.rel.length > 8) && (this.rel == el.rel));
			});
		});*/
		
	}
	
}

// redraws all the other little bits that change, text displays, page number selectors and so on
function redraw_controls() {

	// update various little bits of reporting text.
	$("#hotels_count_all").html(($("search > unfiltered_hotel_count", all).text() == "1") ? "is <b>1</b> hotel" : "are <b>" + $("search > unfiltered_hotel_count", all).text() + "</b> hotels");
    $("#arriving_disp").html($("search > arriving", all).text());
	$("#departing_disp").html($("search > departing", all).text());
    $("#nights_disp").html("<b>" + $("search > nights", all).text() + "</b> night" + (($("search > nights", all).text() > 1) ? "s" : ""));
    $("#hotels_count_startrow").html(parseInt($("search > startrow", all).text()) + 1);
	$("#hotels_count_endrow").html(parseInt($("search > endrow", all).text()) + 1);
	$("#hotels_count_showing").html($("search > filtered_hotel_count", all).text());
	//$("#hotels_count_search").html(($("search > search", all).text() == "0" ? "London" : $("search > search", all)));
	$("#hotels_count_search").html('London');
	
	// hide/show the things depending on whether they have any hotels there.
	if($("search > hotel_count", all).text() == "0") {
		$("#hotels_count_displaying").hide();
		$("#hotels_sorting").hide();
		$("#hotels_count_none").show();
	}
	else {
		$("#hotels_count_displaying").show();
		$("#hotels_sorting").show();
		$("#hotels_count_none").hide();
	}
	
	// update the pages showing thing
	if($("search > pages", all).text() > 1) {
		h = '<div class="top"></div>';
		h += '<div class="mid">';
        h += "<b>Page:</b>";
		for(i=1;i<=$("search > pages", all).text();i++) {
			if(i == $("search > page", all).text()) {
				h += "<i>" + i + "</i>";
			}
			else {
				h += "<a href=\"javascript:viewpage(" + i + ")\">" + i + "</a>";
			}
		}
		h += '</div>';
        $("#hotels_pages").html(h);
		$("#hotels_pages").show();
	}
	else {
		$("#hotels_pages").hide();
	}
	
}

// draws out the little location info block at the bottom of the page.
function redraw_location() {

    if($("search > location_id", all).text() != "0") {
	
        h = "<h3><a href='" + $("location > url", all).text() + "' title='" + $("location > title", all).text() + "'>" + $("location > title", all).text() + "</a></h3>";
		h += $("location > description", all).text();
		$("#location_info").html(h);
		$("#location_info").show();
	}
	else {
		$("#location_info").hide();
	}
}

// returns the html for a given hotel index.
function drawhotelfull(x) {

    var h = "";
    
    //Begin hotel
	h += '\n<div class="result">';
    
    //Begin top section
    h += '\n<div class="top">';
	
	//Begin info section, contains name, address and stars(need adding)
	h += '\n<div class="info">';
	
    //Title
    h += '<div class="name"><a href="' + $("url", x).text() + '">' + $("title", x).text() + '</a></div>';
	
	//stars
	h += '<div class="star" style=" width:100px;" ><h1 class="s' + $("stars", x).text() + '">&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp</h1></div> ';
    
    //Address
	h += '<div class="addr">' + $("address", x).text() + ' <a href="javascript:showmap(\'map_' + $("hotel_id", x).text() + "', '" + $("latitude", x).text() + "', '" + $("longitude", x).text() + '\')" id="map_' + $("hotel_id", x).text() + '_link">Show on Map</a></div>';
    
    //Hotel distance from location
	//if($("search > location_id", all).text() != "0") {
		//h += "<div class=\"hotels_distance\"><b>" + $("location_distance", x).text() + "</b> miles from <b>" + $("search > location > title", all).text() + "</b></div>";
	//}
	
	//End info and top section
	h += '</div>';
	
	
    //Facilities
	h += '\<div class="fac-list">';
    h += '\<div class="fac-title">Facilites</div>';
    
    //Facilities list
    h += '\n<ul>';
    $("features > feature", x).each(function() {
		h += '\n<li>' + $(this).text() + '</li>';
	});               
    h += '\n</ul>';

    //End the facilities list
    h += '\n<div class="cl"></div></div>';

    //Hotel image
    h += '<div class="img"><a href="' + $("url", x).text() + '"><img src="' + $("image", x).text() + '" title="' + $("title", x).text() + '" height="100" width="100" alt="" /></a></div>';

    //Guest Rating
	var ratingsg = $("comments_average", x).text();
    h += '<div class="rate"><span>Guest Rating</span> <img src="images/' + Math.floor(ratingsg / 20) + '-5.gif" alt="" width="74" height="11" />'; 
    h += '<a href="' + $("comments_url", x).text() + '">' + $("comments_count", x).text() + ' review';
	if($("comments_count", x).text() != 1){
	h += 's';
	}
	
	
	h += '</a></div>';

    //End top
    h += '</div>';

    //Hotel map
	h += "\n<div id=\"map_" + $("hotel_id", x).text() + "\" class=\"hotels_map\" style=\"display:none\"><div id=\"map_" + $("hotel_id", x).text() + "_inner\" class=\"map\"></div></div>";
	
	//Start mid section
	h += '\n<div class="mid">';
	
	//Start room type
    h += '\n<div class="type"><p>';
	
	//Room title
	h += '\n<b>'+ $("room", x).text() +'</b>';
	h += '\n<br /><a href="' + $("url", x).text() + '">More room types</a>';
	
	//End room type
	h += '\n</p></div>';
	
    //Rates
    first = 1;
    h += '\n<div class="ratesContainer">';
    $("rates > rate", x).each(function() {
        h += '\n<div class="' + (($("relevant", this).text() == "true") ? "rr" : "pr") + ((first == 1) ? " first" : "") + '"><span>' + $("date", this).text() + '</span><b>' + $("price", this).text() + '</b></div>';
		first=0;
	});
	h += '\n</div>';
	
    	if($("total", x).text() != "&pound;0.00"){
	h += '\n<div class="total"><span>Total price inc taxes</span><b>' + $("total", x).text() + '</b></div>';
	}else{
	h += '\n<div class="total"><span>Total price inc taxes</span><b>On Request</b></div>';
	}
	//End mid section
	h += '\n</div>';
	
	//Bottom section	
	h += '<div class="bot"><a class="btn" href="' + $("url", x).text() + '"></a></div>';
    
    //End result    
    h += '</div>';

	return h;
}

// same as above, but for while in list mode.
function drawhotellist(x) {

    var h = "";
	
	h += "\t<tr class=\"listrow\">";
	h += "<td class=\"listrow_left\"><b><a href=\"" + $("url", x).text() + "\">" + $("title", x).text() + "</a></b>" + $("address", x).text() + "</td>";
	
	//Area
	h += '<td>'+$('area', x).text()+'</td>';
	
	if($("search > location_id", all).text() != 0) {
		h += "<td>" + $("hotelDistance", x).text() + " Mi.</td>";
		//h += "<td></td>"
	}
	
	
	
	h += "<td>" + Math.floor($("stars", x).text()) + "<img src=\"images/star.gif\" alt=\"star\" width=\"14\" height=\"12\" border=\"0\" /></td>";
	var ratingsg = $("comments_average", x).text();
	
	h += "<td><img src='images/" + Math.floor(ratingsg / 20) + "-5.gif' alt='' width='74' height='11' /><br /><a href=\"" + $("comments_url", x).text() + "\">" + $("comments_count", x).text() + " reviews</a></td>";
	
	if($("total", x).text() != "&pound;0.00"){
	h += "<td ><b>" + $("total", x).text() + "</b></td>";
	}else{
	h += "<td ><b>On Request</b></td>";
	}
	h +=  "<td class=\"listrow_right\"><a href=\"" +$("url", x).text() + "\"><img src=\"../images/buttons/btn-book.png\"></a></td>";
	h += "</tr>";
	
	return h;
}

// reads the form and updates what params we'll be handing to the xml thingy.
function readfilters(sortBy) {
	
    var f = document.filtering;
	var f2 = document.mainsearch;
	var stars = new Array();
	ranges = new Array();
	var features = new Array();
	var minprice = 0;
	var maxprice = 0;
	var attraction_id = 0;
	var tube_id = 0;	
	var train_id = 0;
	var mode = "full";
	
	

	//Check whether we're sorting and set
	if(sortBy) {
        sortArr = sortBy.split("_");
        //If we're sorting again by the same param, flip the sort order
        if(sortArr[1]==sort) {
            
            if(sortOrder == 'asc') {
                sortOrder = 'desc' 
            }
            else {
                sortOrder = 'asc' 
            }
            
        }    
        else if (sortArr[1]=="rating" || sortArr[1]=="stars") {
            sortOrder = 'desc';
        }else{
			sortOrder = 'asc';
		}
        
        sort = sortArr[1];

    }
	
	
	
	var search = f2.search.value;
	var arriving = f2.arriving.value;
	var adults = f2.occupancyAdults.value;
	var children = f2.occupancyChildren.value;
	
	var nights = f2.nights.options[f2.nights.selectedIndex].value;
	for(i=0;i<f.elements.length;i++) {
		if((f.elements[i].name == "stars") && f.elements[i].checked) {
			stars.push(f.elements[i].value);
		}
		else if((f.elements[i].name == "ranges") && f.elements[i].checked) {
			ranges.push(f.elements[i].value);
		}
		else if((f.elements[i].name == "features") && f.elements[i].checked) {
			features.push(f.elements[i].value);
		}
		else if(f.elements[i].name == "minprice") {
			minprice = f.elements[i].value;
		}
		else if(f.elements[i].name == "maxprice") {
			maxprice = f.elements[i].value;
		}
		else if((f.nearest_active.value == "attraction") && (f.elements[i].name == "attraction_id")) {
			attraction_id = f.elements[i].options[f.elements[i].selectedIndex].value;
		}
		else if((f.nearest_active.value == "tube") && (f.elements[i].name == "tube_id")) {
			tube_id = f.elements[i].options[f.elements[i].selectedIndex].value;
		}
		else if((f.nearest_active.value == "train") && (f.elements[i].name == "train_id")) {
			train_id = f.elements[i].options[f.elements[i].selectedIndex].value;
		}
		else if(f.elements[i].name == "mode") {
			mode = f.elements[i].value;
		}
	}



	params = "arriving=" + escape(arriving);
	
	if(nights != 1){
	params += "&nights=" + escape(nights);
	}
	
	
	
	if(stars.join() != ""){
	params += "&stars=" + escape(stars.join());
	}
	
	if(ranges.join() != ""){
	params += "&ranges=" + escape(ranges.join());
	}
	
	if(features.join() != ""){
	params += "&features=" + escape(features.join());
	}
	
	if(minprice != 0){
	params += "&minprice=" + escape(minprice);
	}
	
	if(maxprice != 700){
	params += "&maxprice=" + escape(maxprice);
	}
	
	if(adults != 1){
		params += "&adults=" + adults;
	}
	
	if(children != 0){
		params += "&children=" + children;
	}
	
	//params += "&attraction_id=" + escape(attraction_id);
	//params += "&tube_id=" + escape(tube_id);
	//params += "&train_id=" + escape(train_id);
	
	if(sort != null){
	params += "&sort=" + escape(sort);
	params += "&sortorder=" + escape(sortOrder);
	}
	
	//alert($('select[name=currency]').val());
	params += "&currency=" +  $('select[name=currency]').val();
	params += "&mode=" + escape(mode);
    
	params += "&search=" + escape(search.toLowerCase());
	
	//Set the arriving / nights cookies to be passed to the hotel details page
	setCookie('c_arriving',arriving);
	setCookie('c_nights',nights);
	
}

// toggles the display of one of our menus with fancy sliding effects
function togglediv(whichform) {
	whichform = "#" + whichform;
	titlediv = whichform + "_title";
	if($(whichform).css("display") == "none") {
		$(whichform).toggle("blind", {direction : "vertical"}, 200);
		$(titlediv).html($(titlediv).html().replace(/arrow_right/, "arrow_down"));
	}
	else {
		$(whichform).toggle("blind", {direction : "vertical"}, 200);
		$(titlediv).html($(titlediv).html().replace(/arrow_down/, "arrow_right"));
	}
}

// similar to the above but for the overflow bitties
function toggleoverflow(d) {
	if($(d).css("display") == "none") {
		$(d).toggle("blind", {direction : "vertical"}, 200);
		$(d + "_toggle").html("Less...");
	}
	else {
		$(d).toggle("blind", {direction : "vertical"}, 200);
		$(d + "_toggle").html("More...");
	}
}


function CTIsPlayback() {
   try { return parent && parent.WebPlayer; }
   catch(e) { return false; }
}

var map;
function showmap(div, lat, lon) {
  
  
  

    // write the map to the div bitty
	if(($('#' + div + '_inner').html()=='') && GBrowserIsCompatible()  && !CTIsPlayback()) {
        var map = new GMap2(document.getElementById(div + "_inner"));
		if (parseInt($("#"+div).css("height")) < 400) {
			map.addControl(new GSmallMapControl());
		} else {
			map.addControl(new GLargeMapControl());
		}
		map.addControl(new GMapTypeControl());
		var hotel_pt = new GLatLng(lat, lon);
		map.setCenter(hotel_pt, 16);
		var marker = new GMarker(hotel_pt);
		map.addOverlay(marker);
	}
	
	// slide it into view
	if($("#" + div).css("display") == "none") {
		$("#" + div).toggle("blind", {direction : "vertical"}, 200);
	}
	
	// google maps is a little funny about elements being resized so you have to check it after the slide and recentre it
	if(GBrowserIsCompatible()  && !CTIsPlayback() ) {
		setTimeout(function() {
			map.checkResize();
			map.setCenter(hotel_pt, 16);
		}, 210);
	}
	
	// rewrite the show/hide map thing
	linkdiv = div + "_link";
	$("#" + linkdiv).html("Hide Map");
	$("#" + linkdiv).attr("href", "javascript:hidemap('" + div + "', '" + lat + "', '" + lon + "')");
}

// hides the map of a selected hotel...
function hidemap(div, lat, lon) {
	// slide it out of view
	if($("#" + div).css("display") != "none") {
		$("#" + div).toggle("blind", {direction : "vertical"}, 200);
	}
	
	// rewrite the show/hide map thing
	linkdiv = div + "_link";
	$("#" + linkdiv).html("View On A Map");
	$("#" + linkdiv).attr("href", "javascript:showmap('" + div + "', '" + lat + "', '" + lon + "')");
}

// views page N of available hotels
function viewpage(n) {
	readfilters();
	params += "&page=" + n;
	getnewdata();
}

// switches us to a different display mode.
function remode(m) {
	f = document.filtering;
	if(m != f.mode.value) {
		f.mode.value = m;
		refilter();
	}
}

// pipes as many of the search variables over to the map page as we can.
function searchonmap() {
	f2 = document.mainsearch;
	f = document.filtering;
	u = "&arriving=" + escape(f2.arriving.value);
	
	if(f2.nights.options[f2.nights.selectedIndex].value != "1") {
		u += "&nights=" + f2.nights.options[f2.nights.selectedIndex].value;
	}
	if(f2.search.value != "") {
		u += "&search=" + escape(f2.search.value);
	}
	if(f.minprice.value != $("#price_slider").slider("option", "min")) {
		u += "&minprice=" + f.minprice.value;
	}
	if(f.maxprice.value != $("#price_slider").slider("option", "max")) {
		u += "&maxprice=" + maxprice;
	}
	
	stars = [];
	ranges = [];
	features = [];
	for(i=0;i<f.elements.length;i++) {
		if((f.elements[i].name == "stars") && f.elements[i].checked) {
			stars.push(f.elements[i].value);
		}
		else if((f.elements[i].name == "ranges") && f.elements[i].checked) {
			ranges.push(escape(f.elements[i].value));
		}
		else if((f.elements[i].name == "features") && f.elements[i].checked) {
			features.push(escape(f.elements[i].value));
		}
	}
	if(stars.length > 0) {
		u += "&stars=" + stars.join();
	}
	if(ranges.length > 0) {
		u += "&ranges=" + ranges.join();
	}
	if(features.length > 0) {
		u += "&features=" + features.join();
	}
	
	if(u != "") {
		u = u.replace(/^&/, "?");
	}
	u = "/map.php" + u;
	self.location = u;
	return false;
}

// because of their... questionable... stuff dealing with attractions and the displaying thereof, we need separate functions for when they try to refilter by attractions/etc.
function refilter_nearest(section) {
	f = document.forms.filtering;
	
	//Clear the search field.
    document.forms.mainsearch.search.value = "";
	
	//Set the nearest active thingy to our section and reset the other 2 dropdowns to blank to show they aren't being filtered on
	f.nearest_active.value = section;

	// now just yer basic refiltering.
	refilter();
}

// once we've got new data we have to update a bunch of the form fields with our data.
function repopulateform() {

    f = document.forms.filtering;
	
	f.nearest_active.value = $("search > nearest_active", all).text();
	f.location_id.value = $("search > location_id", all).text();
	
    /*	
	for(i=0;i<f.attraction_id.options.length;i++) {
		if(f.attraction_id.options[i].value == $("search > attraction_id", all).text()) {
			f.attraction_id.options[i].selected = true;
			break;
		}
	}

	for(i=0;i<f.train_id.options.length;i++) {
		if(f.train_id.options[i].value == $("search > train_id", all).text()) {
			f.train_id.options[i].selected = true;
			break;
		}
	}
	
	for(i=0;i<f.tube_id.options.length;i++) {
		if(f.tube_id.options[i].value == $("search > tube_id", all).text()) {
			f.tube_id.options[i].selected = true;
			break;
		}
	}
	*/	
}

// displays the loading overlay
function loading_show() {
	$("#loading_overlay").show();
}

// hides the loading overlay
function loading_hide() {
	$("#loading_overlay").hide();
}

$(function(){
	$(".enquiry [name=when]:input").focus(function(){
		if (!$(this).data("firstFocus")) {
			$(this).data("firstFocus", $(this).val());
			$(this).val("");
		}
	}).blur(function(){
		$(this).val() || $(this).val($(this).data("firstFocus"));
	});
});

