// declare global variables

var ajax_call_file = '_include/map_rw_jq.php';
var t_base_ref;									// base URL for website
var map;										// map object for search map
var processing = 0;								// flag set to 1 if something is being processed
var search_active = 0;
var logged_in;
var ajax_in_progress = 0;

// handle page load

$(document).ready(function(){
	//
	var t_base_ref = (document.getElementsByTagName ('BASE')[0] && document.getElementsByTagName( 'BASE')[0].href) || location.href
});

// update map according to search options

function update_map_options()
{
	str_filter = build_filter_string();

	add_clustered_markers(str_filter);
}

// build filter string based on form components

function build_filter_string()
{	
	// site types
	
	var str_filter = "";
	var vCollection = document.getElementsByName('chk_req_site_type');
	for (var i = 0; i < vCollection.length; i++) {
		str_filter += vCollection[i].value + "=";
		if(vCollection[i].checked == true) {
			str_filter += "1;";
		} else {
			str_filter += "0;";
		}
	}
	
	// rating
	
	var this_rating = 0;
	for (var i = 1; i < 6; i++)
	{
		var img_id = 'rating_star_' + i;
		var img_src = $('#'+img_id).attr("src");
		if(img_src == "graphics/common/ratingstarred.jpg") this_rating = i;
	}
	str_filter += "rating=" + this_rating + ";";
	
	// facilities
	
	var vCollection = document.getElementsByName('chk_facilities');
	for (var i = 0; i < vCollection.length; i++) {
		str_filter += vCollection[i].value + "=";
		if(vCollection[i].checked == true) {
			str_filter += "1;";
		} else {
			str_filter += "0;";
		}
	}
	return str_filter;
}

// search settings

function search_option_changed(edit_key, this_setting, this_value)
{

	// run function to update map
	
	update_map_options();

	// check to see if settings are to be saved
	
	//if(logged_in == 1) {
		var save_settings = document.getElementById('chk_save_settings').checked;
		if(this_setting != "ss") {
			if(save_settings == false) {		// unless this is the 'save search' option, leave if settings not be saved
				return;
			}
		}
	//} else {
	//	return;
	//}
	
	if(ajax_in_progress == 1) return;
	ajax_in_progress = 1;
		
	// save search settings option
	
	if(this_setting == "ss") {
		if(document.getElementById('chk_save_settings').checked == true) {
			this_value = 1;
			var save_status = "Click to not save settings";
			
			// at this point the current settings need to be saved
			
			var str_filter = build_filter_string();
			
			// COMPLETE
		}
		if(document.getElementById('chk_save_settings').checked == false) {
			this_value = 0;
			var save_status = "Click to save settings";
		}
		$('#save_settings_status').html("<p class='tmtextg'>" + save_status + "</p>");
	}
	
	// facilities
	
	if(this_setting == "fc") {
		this_value = get_current_facilities();
	}
	
	// site types
	
	if(this_setting == "st") {
		this_value = get_current_site_types();
	}
	
	// use ajax to update user settings record
	
	$.get(
		ajax_call_file,
		{
			edit_key: edit_key ,
			s: this_setting ,
			f: 'css' ,
			value: this_value ,
			filter: str_filter
		}, 

		function(data){
			if(data.response == 'success') {
				//
			} else {
				alert("Something went wrong");
			}
			ajax_in_progress = 0;
		},
		'json'
	);
	//
}

// returns current checked site types

function get_current_site_types()
{
	var this_value = "";
	var vCollection = document.getElementsByName('chk_req_site_type');
	for (var i = 0; i < vCollection.length; i++) {						// loop through all the facilities checkboxes
		if(vCollection[i].checked == true) {
			this_value = this_value + vCollection[i].value + ";";
		}
	}
	if(this_value != "") {
		this_value = this_value.slice(0, -1);
	}
	return this_value;
}

// returns current checked facilities

function get_current_facilities()
{
	var this_value = "";
	var vCollection = document.getElementsByName('chk_facilities');
	for (var i = 0; i < vCollection.length; i++) {						// loop through all the facilities checkboxes
		if(vCollection[i].checked == true) {
			this_value = this_value + vCollection[i].value + ";";
		}
	}
	if(this_value != "") {
		this_value = this_value.slice(0, -1);
	}
	return this_value;
}

// click stars for minimum rating

function select_min_rating(rating, edit_key)
{
	if(ajax_in_progress == 1) return;		// don't allow changes whilst ajax call is in progress
	for(i = 1; i <= rating; i++)
	{
		img_name = "rating_star_" + i;		
		$('#' + img_name).attr("src", "graphics/common/ratingstarred.jpg");
	}
	for(i = (rating + 1); i <= 5; i++)
	{
		img_name = "rating_star_" + i;	
		if(i <= 5) {
			$('#' + img_name).attr("src", "graphics/common/ratingstaryellow.jpg");
		}
	}
	search_option_changed(edit_key, 'mr', rating);		// update saved setting where applicable
}

// returns current minimum rating

function get_current_min_rating()
{	
	var this_rating = 1;
	for (var i = 1; i < 6; i++)
	{
		var img_id = 'rating_star_' + i;
		var img_src = $('#'+img_id).attr("src");
		if(img_src == "graphics/common/ratingstarred.jpg") this_rating = i;
	}
	return this_rating;
}

// called by 'add site' link

function add_site()
{
	if(logged_in == 1) {					// user is not logged in, so display login box
		window.location = "newsite.php";
	
	} else {								// user is logged in, so navigate to required page
		show_login("newsite.php");
	}
}

// initialise search map - this is called by the body onload handler

function initialize_search_map(val_logged_in, easting, northing, zoom_level, set_t_base_ref, search_filter)
{
	t_base_ref = set_t_base_ref;
	logged_in = val_logged_in;

	map = new GMap2(document.getElementById("gmap"));				// create map object
	
	map.showControls();											// show controls on map
	map.setCenter(new GLatLng(northing, easting), zoom_level);		// set centre position and zoom
	map.setCenter(new GLatLng(52.980832, -3.379160), 6);			// default load position
	map.setMapType(G_PHYSICAL_MAP);
	add_clustered_markers(search_filter);

}

// navigates map according to submitted search string, using Google geocoding request

function execute_location_search()
{
	if(processing == 1) return;		// disable further requests until this one has been dealt with
	processing = 1;
	
	var this_address = $('#txt_search').val();		// get address from text field
	//this_address += ",United Kingdom";				// append country to limit search scope - poss change according to user prefs
	
	$('#map_loader').show();						// show loader box over map
	
	// see if this is a lat/lng
	
	var isLatLng = false;
	cPos = this_address.indexOf(',');
	if(cPos >= 0) {
		var arr_c = this_address.split(',');
		if(arr_c.length == 2) {
			var c1 = parseFloat(arr_c[0]);
			var c2 = parseFloat(arr_c[1]);
			if(isNaN(c1) == false && isNaN(c2) == false) {
				isLatLng = true
			}
		}
	}
	
	if(isLatLng == true) {
		var point = new GLatLng(c1, c2);
		map.setCenter(point, 13);
		processing = 0;	
		$('#map_loader').hide();						// hide loader box
	}
	
	if(isLatLng == false) {
		var geocoder = new GClientGeocoder();							// create geocoder object to convert address to lat/lng
		geocoder.getLocations(this_address, function(response) {
			
			var status = response.Status.code;
			if(status == 200) {		
			
				var place = response.Placemark[0];
				point = new GLatLng(place.Point.coordinates[1], place.Point.coordinates[0]);	// retrieve the latitude and longitude

				// calculate zoom level if available
				
				var zoom_level = map.getZoom();						// get current zoom from map
				var lat_lng_box = place.ExtendedData.LatLonBox;
				if(lat_lng_box) {
					var lat_lng_bound = new GLatLngBounds(new GLatLng(lat_lng_box.south, lat_lng_box.west), new GLatLng(lat_lng_box.north, lat_lng_box.east));
					zoom_level = map.getBoundsZoomLevel(lat_lng_bound);
				}

				// center map and zoom on this location
				
				map.setCenter(point, zoom_level);				// set map to point and zoom level
			
			} else {
			
				alert("Location not found!");
			}
			processing = 0;	
			$('#map_loader').hide();						// hide loader box
		});
	}
}

// fires when a layer is toggled on or off

function update_site_type_filter()
{
	var str_filter = build_filter_string();
	add_clustered_markers(str_filter);
}

// hides popup

function hide_map_popup()
{
	$('#map_disable').hide();
	$('#map_popup_mask').hide();
	$('#map_popup').hide();
	processing = 0;
}

// link to add site

function add_site()
{
	var map_zoom = map.getZoom();
	var map_center = map.getCenter();
	var lat = map_center.lat();
	var lng = map_center.lng();
	var topo = map.getCurrentMapType();
	topo = topo.getName();
	topo = topo.toLowerCase();
	
	map_params = lat + "/" + lng + "/" + map_zoom + "/" + topo;
	
	url = "add-my-site/" + map_params;
	
	open_private_url(url);
}

// function to handle user trying to navigate to site

function open_site(site_long_id)
{
	if(logged_in == 0) {		// user is not logged in, so display login box
	
		show_login("sites/" + site_long_id);
	
	} else {				// user is logged in, so navigate to required page

		window.location = "sites/" + site_long_id;
	}
}

// display popup on map for either general information or site details

function show_map_popup(popup_type, lat, lng)
{
	if(processing == 1) return;
	processing = 1;

	
	
	$('#map_disable').show();
	//$('#map_popup_mask').show();
	//$('#map_popup').show();
	
	
	if(popup_type == "geninf") {
	
	
	
	}
	
	if(popup_type == "site") {
	
		// fetch site details using ajax
		
		$.get(
			ajax_call_file,

			{
				f: 'findsite' ,
				latitude: lat ,
				longitude: lng
			}, 

			function(data){

				if(data.response == 'success') {
				
					var site_title = data.title;
					var long_id = data.longid;
					var rating_img = data.ratingimg;
					var rating_text = data.ratingtext;
					var facilities_img = data.facilities;
					if(facilities_img.length < 3 || facilities_img == null) facilities_img = "<p class='tmtextg'>This site has no features listed</p>";
					var description = data.description;
					var photos = data.photos;
					
					description = description.replace(/mpound/g, "£");
					
					var str_div_contents = "";
					
					// title
					
					str_div_contents += "<div style='width:502px;margin-left:20px;'>";
					str_div_contents += "    <div style='float:left;padding-top:10px;width:470px;height:40px;overflow:hidden;'>";
					str_div_contents += "        <p class='site_title'>" + site_title + "&nbsp;<a class='tmlinkg' style='display:inline' href='sites/" + long_id + "'>View this site</a></p>";
					str_div_contents += "    </div>";
					str_div_contents += "    <div style='float:right;padding-top:18px;'>";
					str_div_contents += "        <a class='tmlinkg' href='#' onclick='javascript:hide_map_popup();return false;'><img src='graphics/common/close_icon.png'></a>";
					str_div_contents += "    </div>";
					str_div_contents += "</div>";
		
					str_div_contents += "<div style='width:502px;margin-left:20px;margin-top:20px;overflow:auto;'>";
					str_div_contents += "    <div style='float:left;width:240px;overflow:hidden;padding:4px;padding-left:1px;'>";
					str_div_contents += "<div style='width:240px;'>";
					str_div_contents += rating_img;
					str_div_contents += "<br><p class='tmtextg'>&nbsp;" + rating_text + "</p>";
					str_div_contents += "    </div>";
					
					str_div_contents += "<div style='width:240px;padding-top:23px;'>";
					str_div_contents += facilities_img;
					str_div_contents += "</div>";
					str_div_contents += "</div>";				
					
					//str_div_contents += "<div style='facilities_img
					
					str_div_contents += "    <div style='float:right;width:240px;height:99px;overflow:hidden;padding-top:3px;'>";
					str_div_contents += "        <p class='tmtextgt'>" + description + "...&nbsp;<a href='sites/" + long_id + "' class='tmlinkg'>More</a></p>";
					str_div_contents += "    </div>";
					str_div_contents += "</div>";
					
					// photos
					
					str_div_contents += "<div style='width:502px;margin-left:20px;margin-top:26px;'>";
					str_div_contents += photos;
					str_div_contents += "</div>";

					if(photos == "") {
						$('#map_popup').css("background-image", "url('../graphics/map/popup_small.png')");
						$('#map_popup').css("margin-top", "105px");
					} else {
						$('#map_popup').css("background-image", "url('../graphics/map/popup.png')");
						$('#map_popup').css("margin-top", "40px");
					}

					$('#map_popup').html(str_div_contents);
					$('#map_popup').show();
					
				} else {
				
					// something went wrong
					
					hide_map_popup();
				}
				
			},
			'json'
		);
	}
}

// shows large area at appropriate zoom level

function zoom_to_large_area(lat, lng)
{
	if(processing == 1) return;
	processing = 1;
	
	$('#map_loader').show();
	var zoom_level = map.getZoom();

    $.get(
		ajax_call_file,

		{
			f: 'largeareabounds' ,
			latitude: lat ,
			longitude: lng ,
			zoom: zoom_level
		}, 

		function(data){

			if(data.response == 'success') {
			
				var lat_min = parseFloat(data.latmin);
				var lat_max = parseFloat(data.latmax);
				var lng_min = parseFloat(data.lngmin);
				var lng_max = parseFloat(data.lngmax);

				if(lat_min == lat_max && lng_min == lng_max) {		// if only one site then set default zoom level
					zoom_level = 14;
				} else {
					var lat_lng_bound = new GLatLngBounds(new GLatLng(lat_min, lng_min), new GLatLng(lat_max, lng_max));
					zoom_level = map.getBoundsZoomLevel(lat_lng_bound);
				}
				var point = new GLatLng(lat, lng);
				map.setCenter(point, zoom_level);
				
			} else {
			
				// something went wrong
			}
		
			processing = 0;
			$('#map_loader').hide();
		},
		'json'
    );
}

// adds all markers from xml file

// WE NEED SOME KIND OF KEY SYSTEM TO PREVENT PEOPLE STEALING THE XML FILE

function add_clustered_markers(filter)
{
	$('#map_loader').show();
	
	var point = map.getCenter();
	var zoom = map.getZoom();
	
	delete mc;
	delete map;
	map = new GMap2(document.getElementById("gmap"));				// create map object
	
	map.showControls();											// show controls on map
	map.setCenter(point, zoom);		// set centre position and zoom
	map.setMapType(G_PHYSICAL_MAP);
	
	//map.clearOverlays();												// clear existing markers

	// read filter settings

	var arr_filter = filter.split(";");
	
	var inc_camper = 0;
	var inc_tent = 0;
	var inc_bivvy = 0;
	var inc_paid = 0;
	
	if(arr_filter[0].charAt(arr_filter[0].length - 1)=="1") inc_camper = 1;			// show sites suitable for campervans
	if(arr_filter[1].charAt(arr_filter[1].length - 1)=="1") inc_tent = 1;			// show sites suitable for tents
	if(arr_filter[2].charAt(arr_filter[2].length - 1)=="1") inc_bivvy = 1;			// show sites suitable for bivvy bags
	if(arr_filter[3].charAt(arr_filter[3].length - 1)=="1") inc_paid = 1;			// also include paid sites

	// get required rating
	
	var req_rating = parseFloat(arr_filter[4].charAt(arr_filter[4].length - 1));
	if(req_rating == 1) req_rating = 0;
	
	// create list of required facilities
	
	var str_facilities = "";
	for(var i = 5; i < arr_filter.length; i++)
	{
		this_facility = arr_filter[i];
		if(this_facility.length > 2) {
			if(this_facility.charAt(this_facility.length - 1)=="1") {
				str_facilities += this_facility.substring(0, this_facility.length - 2) + ";";
			}
		}
	}
	str_facilities = str_facilities.substring(0, str_facilities.length - 1);
	if(str_facilities != "") {
		arr_facilities = str_facilities.split(";");
	//	alert(arr_facilities.length);
		var j = 0;
	}
	

		id_filter = "";
	
	// read xml file
	
	var myIdentifier = Math.round(Math.random()*10000);
	
	GDownloadUrl("xml/map.xml?uniq=" + myIdentifier, function(data, responseCode) {

		var xml = GXml.parse(data);
		var markers = xml.documentElement.getElementsByTagName("marker");

		// create custom markers for different site types

		var this_icon;
		var camper_icon = create_map_icon(0);
		var tent_icon = create_map_icon(1);
		var camper_tent_icon = create_map_icon(2);
		var bivvy_icon = create_map_icon(3);
		var camper_paid_icon = create_map_icon(4);
		var tent_paid_icon = create_map_icon(5);
		var camper_tent_paid_icon = create_map_icon(6);
		
		var arr_markers = [];
		
		var batch7 = [];	
		var batch8 = [];	
		var batch9 = [];	
		var batch10 = [];
		
		var batch_m7 = [];
		var batch_m8 = [];
		var batch_m9 = [];
		var batch_m10 = [];
		var batch_m11 = [];

		for (var i = 0; i < markers.length; i++) {
			
			var point = new GLatLng(parseFloat(markers[i].getAttribute("lat")), parseFloat(markers[i].getAttribute("lng")));
			
			// site marker

			// use logic of selected checkboxes to decide whether or not we should include this site
			
			var site_type = parseInt(markers[i].getAttribute("sitetype"));
			var inc_site = 0;
			switch(site_type)
			{
				case 0:										// sites suitable for campers
					if(inc_camper == 1) inc_site = 1;
					break;
				case 1:										// sites suitable for tents
					if(inc_tent == 1) inc_site = 1;
					break;
				case 2:														// sites suitable for campers and tents
					if(inc_camper == 1 || inc_tent == 1) inc_site = 1;
					break;
				case 3:										// sites suitable for bivvy bags
					if(inc_bivvy == 1) inc_site = 1;
					break;
				case 4:
					if(inc_camper == 1 && inc_paid == 1) inc_site = 1;
					break;
				case 5:
					if(inc_tent == 1 && inc_paid == 1) inc_site = 1;
					break;
				case 6:
					if((inc_camper == 1 || inc_tent == 1) && inc_paid == 1) inc_site = 1;
					break;
			}
			
			// check site rating if required
			
			var site_rating = parseFloat(markers[i].getAttribute("rating"));
			if(site_rating < req_rating) {
				inc_site = 0;
			}
			
			// check site facilities if user has specified any
			
			if(str_facilities != "") {
				var site_facilities = ";" + markers[i].getAttribute("facilities") + ";";

				// now check to see if each of the required facilities is included in this site
				
				for(var j = 0; j < arr_facilities.length; j++)
				{
					this_facility = arr_facilities[j];
					if(this_facility != "") {
					
						this_facility = ";" + this_facility + ";";
						
						if(site_facilities.search(this_facility) == -1) {
						
							// not found
							
							inc_site = 0;

						}
					}
				}
			}
			
			// if site to be included, show on map
			
			if(inc_site == 1) {
				if(id_filter != "") {
					
					if(site_type == '0') {
						var icon_width = 32;
						var icon_height = 32;
					}
					if(site_type == '1') {
						var icon_width = 25;
						var icon_height = 29;
					}
					if(site_type == '2') {
						var icon_width = 29;
						var icon_height = 29;
					}
					if(site_type == '3') {
						var icon_width = 36;
						var icon_height = 32;
					}
					
					var custIcon = new GIcon(G_DEFAULT_ICON);
					custIcon.iconSize = new GSize(icon_width, icon_height);
					custIcon.shadowSize = new GSize(0, 0);
					custIcon.iconAnchor = new GPoint(0, 0);
					
					var marker_icon = new GIcon(custIcon, "_include/icon_test.php?text=" + site_number + "&type=" + site_type);
				
				} else {
				
					if(site_type == 0) marker_icon = camper_icon;
					if(site_type == 1) marker_icon = tent_icon;
					if(site_type == 2) marker_icon = camper_tent_icon;
					if(site_type == 3) marker_icon = bivvy_icon;
					if(site_type == 4) marker_icon = camper_paid_icon;
					if(site_type == 5) marker_icon = tent_paid_icon;
					if(site_type == 6) marker_icon = camper_tent_paid_icon;
				}
			
				var marker = new GMarker(point, { icon:marker_icon });
				
				GEvent.addListener(marker, "click", function(latlng) {
					var this_lat = latlng.lat();
					var this_lng = latlng.lng();
					show_map_popup("site", this_lat, this_lng);
				});

				arr_markers.push(marker);
				
			}
		}
		
		//var mc_styles = {url: 'graphics/icons/cluster.png', width: 36, height: 32, opt_anchor: [16, 0], opt_textColor: '#FFFFFF'};
		
		var mc_styles = [{url: 'graphics/icons/cluster.png', width: 40, height: 34, opt_anchor: [14, 12], opt_textColor: '#FFFFFF'},{url: 'graphics/icons/cluster.png', width: 40, height: 34, opt_anchor: [14, 12], opt_textColor: '#FFFFFF'},{url: 'graphics/icons/cluster.png', width: 40, height: 34, opt_anchor: [14, 12], opt_textColor: '#FFFFFF'}];
		var mc_options = {gridSize: 40, maxZoom: 16, styles: mc_styles};
		
		//var mc_options = {gridSize: 100, maxZoom: 10};
		var mc = new MarkerClusterer(map, arr_markers, mc_options);

		map.setUIToDefault();
		
		if(id_filter == "") {
			$('#map_loader').hide();
		}
		
	});
}

