// declare a bunch of global variables up here.
var all = false;
var params = "";
var location_id = "0";

// gets new data about what to draw onto our map
function getnewdata() {
    //alert(params);
	
	//this.location = "map.php?" + params;
	
    jQuery.ajax({
		beforeSend : loading_show,
		data : params,
		dataType : "xml",
		error : function(XHR, errmsg) {
			loading_hide();
			alert("Error (1) getting new data!\nDetails: " + errmsg);
		},
		success : function(data) {
			all = data;
			
			map.clearOverlays();
			draw_postcodes();
			draw_districts();
			draw_location();
			draw_attractions();
			draw_tubelines();
			draw_hotels();
			draw_controls();
			setcenter();
			
			loading_hide();
			//$("#debug").html(all.documentURI);
		},
		type : "GET",
		url : "map_xml.php"
	});
	
}

// draws any postcode boundaries to the map.
function draw_postcodes() {
//alert($("search > postcodes > postcode", all));
	$("search > postcodes > postcode", all).each(function() {
		bounds = [];
		$("bound", this).each(function() {
			bounds.push(new GLatLng($(this).attr("lat"), $(this).attr("lng")));
		});
		map.addOverlay(new GPolygon(
			bounds,
			"#333333",	// line colour
			1,			// line width
			1,			// line opacity (0 - 1)
			"#0000ff",	// fill colour
			0.1		// fill opacity
		));
		if((map.getZoom() >= 12) && (map.getZoom() <= 17)) {
			title = $("title", this).text();
			map.addOverlay(new ELabel(new GLatLng($("lat", this).text(), $("lng", this).text()), title, "postcode_label", new GSize((Math.round((title.length * 15) / 2) * -1), 12), 80));
		}
	});
}

// draws in any district boundaries.
function draw_districts() {
	$("search > districts > district", all).each(function() {
		bounds = [];
		$("bound", this).each(function() {
			bounds.push(new GLatLng($(this).attr("lat"), $(this).attr("lng")));
		});
		map.addOverlay(new GPolygon(
			bounds,
			"#333333",	// line colour
			1,			// line width
			1,			// line opacity (0 - 1)
			"#0000ff",	// fill colour
			0.1		// fill opacity
		));
		
		//if((map.getZoom() >= 12) && (map.getZoom() <= 13)) {
		if((map.getZoom() >= 14)) {
			title = $("title", this).text();
			map.addOverlay(new ELabel(new GLatLng($("lat", this).text(), $("lng", this).text()), title, "location_label", new GSize((Math.round((title.length * 15) / 2) * -1), 12), 80));
		}
	});
}

// if their search was a location name, then draw that location in a little differently.
function draw_location() {
	if($("search > location_id", all).text() != "0") {
		bounds = [];
		$("search > location > bound", all).each(function() {
			bounds.push(new GLatLng($(this).attr("lat"), $(this).attr("lng")));
		});
		map.addOverlay(new GPolygon(
			bounds,
			"#000000",	// line colour
			2,			// line width
			1,			// line opacity (0 - 1)
			"#0000ff",	// fill colour
			0.2		// fill opacity
		));
		if((map.getZoom() >= 12) && (map.getZoom() <= 17)) {
			title = $("search > location > title", all).text();
			map.addOverlay(new ELabel(new GLatLng($("search > location > lat", all).text(), $("search > location > lng", all).text()), title, "location_label", new GSize((Math.round((title.length * 15) / 2) * -1), 12), 80));
		}
	}
}

// draws in any attractions.
function draw_attractions() {
	$("search > attractions > attraction", all).each(function() {
	  
        //Create the icon path
        mapIconImageName = $(this).attr('category').toLowerCase();
        mapIconImageName = mapIconImageName.replace("&amp;","&");
        mapIconImageName = mapIconImageName.replace(/\s/g,"_")+'.png'; 
                               
        //Create the icon
        var ibase = new GIcon();
        ibase.shadow = "images/google_shadow.png";
		ibase.iconSize = new GSize(25, 25);
		ibase.shadowSize = new GSize(0, 0);
		ibase.iconAnchor = new GPoint(9, 34);
		ibase.infoWindowAnchor = new GPoint(9, 2);
		ibase.infoShadowAnchor = new GPoint(18, 25);
		ibase.image = "/images/icons/map_icons/"+mapIconImageName;
			
		marker = new GMarker(new GLatLng($(this).attr("lat"), $(this).attr("lng")),ibase);
		marker.my_id = $(this).attr("id");
		marker.my_box = $(this).text();
		
		GEvent.addListener(marker, "click", function() {
			infobox_attraction(this.my_id);
		});
		GEvent.addListener(marker, "mouseover", function() {
			quickbox_load(this.getLatLng(), this.my_box);
		});
		GEvent.addListener(marker, "mouseout", quickbox_kill);
		
		map.addOverlay(marker);
	});
}

// draws in any tube lines we've been given.
function draw_tubelines() {
	$("search > tubes > tube", all).each(function() {
		points = [];
		$("point", this).each(function() {
			points.push(new GLatLng($(this).attr("lat"), $(this).attr("lng")));
		});
		
		map.addOverlay(new GPolyline(points, $("color", this).text(), 4, 1));
	});
}


function displayRadius(hotelLat, hotelLong){
			var degrad = Math.PI / 180;
            var R = 0;
            var dlon;
             var dlat;
             var lat1 = hotelLat;
             var lon1 = hotelLong;
             var lat2 = map.getCenter().lat();
             var lon2 = map.getCenter().lng();
             var units = 'miles';
            //convert the degree values to radians before calculation
            lat1 = lat1 * degrad;
            lon1 = lon1 * degrad;
            lat2 = lat2 * degrad;
            lon2 = lon2 * degrad;
            dlon = lon2 - lon1;
            dlat = lat2 - lat1;
            a = Math.pow(Math.sin(dlat / 2), 2) + Math.cos(lat1) * Math.cos(lat2) * Math.pow(Math.sin(dlon / 2), 2);
            c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
			
			
            // R (Earth Radius) = 3956.0 mi = 3437.7 nm = 6367.0 km
            switch (units){
                case 'miles': // STATUTE MILES
                    R = 3956.0;
                    break;
            }
			
			
			switch(map.getZoom()){
			
			
			case 10:
				radius = 20
			break;
			
			case 11:
				radius = 10
			break;
			
			case 12:
				radius = 5;
			break
			
			case 13:
				radius = 2;
			break;
			
			case 14:
				radius = 1.5
			break;
			
			case 15:
				radius = 1;
			break;
			
			case 16:
				radius = 0.5;
			break;
			case 17:
			case 18:
			case 19:
				radius = 0.25;
			break;
			
			default:
				radius = 30;
				break;
			}
			
            if((R * c) <=  radius){
			
			return true;
			
			}else{
			return false;
			}

}

// draws in the hotel markers.
function draw_hotels() {

	$("search > hotels > hotel", all).each(function() {
	
	if(displayRadius($("lat", this).text(), $("lng", this).text())){
		marker = new GMarker(new GLatLng($("lat", this).text(), $("lng", this).text()), hotel_icons[Math.min(5, Math.max(1, Math.floor($("stars", this).text())))]);
		marker.my_id = $("id", this).text();
		marker.my_lr_id = $("lr_id", this).text();
		marker.my_box = $("quick", this).text();
		
		GEvent.addListener(marker, "click", function() {
			infobox_hotel(this.my_lr_id,this.my_id);
		});
		GEvent.addListener(marker, "mouseover", function() {
            quickbox_load(this.getLatLng(), this.my_box);
		});
		GEvent.addListener(marker, "mouseout", quickbox_kill);
		
		map.addOverlay(marker);
	}
	});


}

// updates all our little bits of text with current info.
function draw_controls() {
	$("#hotels_count").html(($("search > filtered_hotel_count", all).text() == "1") ? "is <b>1</b> hotel" : "are <b>" + $("search > filtered_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_report_loading").hide();
	
	// hide/show the things depending on whether they have any hotels there.
	if($("search > filtered_hotel_count", all).text() == "0") {
		$("#hotels_report_count").hide();
		$("#hotels_report_none").show();
	}
	else {
		$("#hotels_report_count").show();
		$("#hotels_report_none").hide();
	}
	
	var pos = new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(100,10));
map.addControl(new GScaleControl(), pos); 
}

// displays a quickbox mouseover thingy.
function quickbox_load(latlng, str) {
	$("#quickbox_content").html(str);
    
	coords = map.fromLatLngToContainerPixel(latlng);
	
	x = (coords.x) + ($("#quickbox").width());
	y = (coords.y) - 60;

	$("#quickbox").css({
		"left" : x,
		"top" : y
	});
	
	$("#quickbox").show();
}

// hides the quickbox.
function quickbox_kill() {
	$("#quickbox").hide();
}

// loads the infobox up with some attraction's info.
function infobox_attraction(id) {

    jQuery.ajax({
		beforeSend : infobox_working,
		data : "attraction_id=" + id,
		dataType : "xml",
		error : function(XHR, errmsg) {
			infobox_kill();
			alert("Error (2) getting new data!\nDetails: " + errmsg);
		},
		success : function(data) {
			h = "<h2>" + $("attraction > title", data).text() + "</h2>";
			if($("attraction > image", data).text() != "") {
				h += "\n<img src=\"" + $("attraction > image", data).text() + "\" alt=\"" + $("attraction > title", data).text() + "\" />";
			}
			
			d = $("attraction > description", data).text();
			if(d.length > 80) {
				h += "\n<p>" + d.substring(0, 80) + "<span id=\"infobox_overflow\" style=\"display:none\">" + d.substring(80) + "</span><a href=\"javascript:toggleoverflow('#infobox_overflow')\" id=\"infobox_overflow_toggle\">More...</a></p>";
			}
			else {
				h += "\n<p>" + d + "</p>";
			}
			infobox_load(h);
		},
		type : "GET",
		url : "map_xml_attraction.php"
	});
}

// loads the infobox up with some hotel's info.
function infobox_hotel(lr_id,hl_id) {

    jQuery.ajax({
		beforeSend : infobox_working,
		data : "arriving=" + escape($("search > arriving", all).text()) + "&nights=" + $("search > nights", all).text() + "&lr_hotel_id=" + lr_id + "&hl_hotel_id=" + hl_id,
		dataType : "xml",
		error : function(XHR, errmsg) {
			infobox_kill();
			alert("Error (3) getting new data!\nDetails: " + errmsg);
		},
		success : function(data) {
		
            h = "<h2>" + $("hotel > title", data).text() + " <font color='red'>" + $("hotel > stars", data).text() + "</font></h2>";
			h += "\n" + $("hotel > address", data).text();
			if($("hotel > image", data).text() != "") {
				h += "\n<img width=\"136px\" src=\"" + $("hotel > image", data).text() + "\" alt=\"" + $("hotel > title", data).text() + "\" />";
			}
			
			d = $("hotel > description", data).text();
			if(d.length > 80) {
				h += "\n<p>" + d.substring(0, 80) + "<span id=\"infobox_overflow\" style=\"display:none\">" + d.substring(80) + "</span><a href=\"javascript:toggleoverflow('#infobox_overflow')\" id=\"infobox_overflow_toggle\">More...</a></p>";
			}
			else {
				h += "\n<p>" + d + "</p>";
			}
			
			if($("hotel > comments_count", data).text() != "0") {
				h += "\n<p><b><a href=\"" + $("hotel > comments_url", data).text() + "\">Guest Reviews [" + $("hotel > comments_count", data).text() + "]</a></b></p>";
			}
			
			h += "<p>" + $("hotel > room", data).text() + "</p>";
			h += "<p><b>" + $("hotel > price", data).text() + "</b></p>";

			h += "\n<a href=\"" + $("hotel > url", data).text() + "\" class=\"viewlink\">View Hotel Details</a>";
			
			infobox_load(h);
		
		},
		type : "GET",
		url : "map_xml_hotel.php"
	});
}

// update the info box contents
function infobox_load(str) {
	$("#infobox_content").html(str);
	$("#infobox").show();
}

// hides the infobox contents
function infobox_kill() {
	$("#infobox").hide();
}

// sets the infobox into a working mode
function infobox_working() {
    $("#infobox_content").html("<img src=\"images/jquery/loading.gif\" class=\"working\" />");
	$("#infobox").show();
}

// reads the form and updates what params we'll be handing to the xml thingy.
function readfilters() {
	f = document.filtering;
	f2 = document.mainsearch;
	
	stars = new Array();
	ranges = new Array();
	features = new Array();
	attcats = new Array();
	
    //minprice = 0;
	//maxprice = 0;
	
	postcodes = false;
	districts = false;
	if(f2.search.value == "District, Postcode, Attraction"){
	search = "";
	}else{
	search = f2.search.value;
	}
	
	//arriving = f2.arriving.value;
	//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 == "attcats") && f.elements[i].checked) {
			attcats.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.elements[i].name == "postcodes") && f.elements[i].checked) {
			postcodes = true;
		}
		else if((f.elements[i].name == "districts") && f.elements[i].checked) {
			districts = true;
		}
	}
	
	//params = "arriving=" + escape(arriving);
	//params += "&nights=" + escape(nights);
	
	params = "stars=" + escape(stars.join());
	params += "&ranges=" + escape(ranges.join());
	params += "&features=" + escape(features.join());
	//params += "&minprice=" + escape(minprice);
	//params += "&maxprice=" + escape(maxprice);
	params += "&postcodes=" + (postcodes ? "1" : "0");
	params += "&districts=" + (districts ? "1" : "0");
	params += "&attcats=" + escape(attcats.join());
	params += "&search=" + escape(search);
}

// little helper function that sets things going.
function refilter() {
	readfilters();
	getnewdata();
	return false;	// return false to stop the search box from submitting
}

// 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...");
	}
}

// dumps them over to the search page, keeping most filters along for the ride
function gotosearchpage(mode) {

    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(mode != "full") {
		u += "&mode=" + mode;
	}
	
	if(u != "") {
		u = u.replace(/^&/, "?");
	}
	
	u = "hotels.php" + u;
	self.location = u;
	return false;
}

// displays the loading overlay (only after the first load of the page though).
function loading_show() {
	//if(all) {
		$("#loading_overlay").show();
	//}
}

// hides the loading overlay
function loading_hide() {
	$("#loading_overlay").hide();
}

// just checks to see if they're newly searching for a location in which case tweak the position and slightly zoomier-in level.
function setcenter() {

	//if((location_id == "0") && ($("search > location_id", all).text() != "0")) {
	if(($("search > location_id", all).text() != "0") && $("search > location > lat", all).text() > 0) {
		map.setCenter(new GLatLng($("search > location > lat", all).text(), $("search > location > lng", all).text()), 14);
	}else if($("postcodes > pcode_searched", all).text() != "" && $("postcodes > pcode_searched > pcode_lat", all).text() > 0){
	map.setCenter(new GLatLng($("postcodes > pcode_searched > pcode_lat", all).text(), $("postcodes > pcode_searched > pcode_lon", all).text()), 14);
	}

	location_id = $("search > location_id", all).text();
	}

function moveclear(){
loading_show();
map.clearOverlays();
}

function newcentre(){

	
	draw_postcodes();
	draw_districts();
	draw_location();
	draw_attractions();
	draw_tubelines();
	//alert(map.getZoom());
	draw_hotels();
	draw_controls();
	loading_hide();
}

// handles what happens when they select a new zoom level
function newzoom(oldzoom, newzoom) {
	/*map.clearOverlays();
	draw_postcodes();
	draw_districts();
	draw_location();
	draw_attractions();
	draw_tubelines();
	alert("3");
	draw_hotels();
	draw_controls();
	//setcenter();*/
}