// global.js using Google's map

// Retrieves and then displays points for an area of the map.
function addPoint(item) {
	// Add each item returned to the points array. The array is sorted by the item's MySQL id field to prevent duplicate entries.
	points[item.id] = item;
	
	// Now add the point to the map.
	// This conditional is here to make sure that the array entry contains something. Mostly, it just stops the thing from trying to render a point from points[0] .
	if (item && !pointtracker[item.id]) {
		// Are we admin-side?
		if (admin) {
			// Add a new draggable marker and its overlay.
			currentmarker = new GMarker(new GLatLng(item.y, item.x), {draggable: true});
			map.addOverlay(currentmarker);
			// Add the marker to the pointtracker array so the marker can be accessed later by its ID in the database.
			pointtracker[item.id] = currentmarker;
			// Add a listener so the point's position gets updated when it's moved.
			GEvent.addListener(currentmarker, 'dragend', function(){
				slng = this.getPoint().lng();
				slat = this.getPoint().lat();
				$.get('/maps/changePoint.aro?act=updatexy&lo=' + slng + '&la=' + slat + '&id=' + item.id);
			});
			// Add another listener so that, when clicked, the user is given the option of modifying the information relating to the point.
			GEvent.addListener(currentmarker, "click", function() {
				getData(item.id);
			});
		}
		else {
			// Add the marker and overlay.
			currentmarker = new GMarker(new GLatLng(item.y, item.x));
			map.addOverlay(currentmarker);
			// Throw the marker into the array.
			pointtracker[item.id] = currentmarker;
			// Add a click event so the information associated with the marker is brought up when the marker is clicked.
			GEvent.addListener(currentmarker, 'click', function() {
				getData(item.id);
			});
		}
		return true;
	}
}

function clearSearch() {
	$('#search').val('');
	$('#searchcategory').val('All Categories');
	map.setCenter(new GLatLng(44.90105, -76.02065), 14);
	refreshpoints();
}

// Clears all the markers on the map and reloads the ones for the current area.
function refreshpoints() {
	$('#businesslist').html('<li>Please select a category or search for a business.</li>');
	points = new Array();
	pointtracker = new Array();
	map.clearOverlays();
	if (admin) {
		window.bigmarker = new GMarker(new GLatLng(map.getCenter().lat(), map.getCenter().lng()), {icon: new GIcon(G_DEFAULT_ICON, "bigmarker.png")});
		GEvent.addListener(bigmarker, "dragend", function() {
			$('#y').val(bigmarker.getPoint().lat());
			$('#x').val(bigmarker.getPoint().lng());
		});
		map.addOverlay(bigmarker);
	}
	//getJSONMarkers();
}

// Returns business data for the information area.
function getData(id) {
	if(!admin){
		// If the info is already visible, hide it.
		if ($('#infocontainer').is(':visible')) {
			$('#infocontainer').slideUp();
		}
	}

	// Get the information.
	var url = 'maps/map-go.xml.aro?id=' + id;
	if (admin) { url = '../../' + url; }
	$.getJSON(url,function(data) {
		$.each(data.items, function(i, item) {
			// Move the map to the location of the point that was just requested.
			map.panTo(new GLatLng(item.y, item.x));
			if (!admin) {
				$('#infocontainer').html('<div id="close"><a href="javascript:;" onclick="$(\'#infocontainer\').slideUp();">Back to Member List<\/a><\/div>');
            
				// Initialize the InfoWindow content.
				infowindowcontent = '<strong>' + item.name + '</strong><br />' + item.address + '<br />' + item.town + '<br />' + item.postcode;
				// Update the content of the information container.
				// Business name
				$('#infocontainer').html($('#infocontainer').html() +'<h2>' + item.name + '<\/h2>');
				// Contact
				$('#infocontainer').html($('#infocontainer').html() + '<p><strong>Contact:<\/strong> ' + item.contact + '<\/p>');
				// Address
				$('#infocontainer').html($('#infocontainer').html() + '<p><strong>Address:<\/strong><br \/>' + item.address + '<br \/>' + item.town + '<br />' + item.postcode + '<\/p>');
				// Phone and fax
				if (item.phone && item.fax) {
					$('#infocontainer').html($('#infocontainer').html() + '<p><strong>Phone:<\/strong> ' + item.phone + '<br/> <strong>Fax:<\/strong> ' + item.fax + '<\/p>');
					infowindowcontent += '<br />' + item.phone;
				}
				else if (item.phone && !item.fax) {
					$('#infocontainer').html($('#infocontainer').html() + '<p><strong>Phone:<\/strong> ' + item.phone + '<\/p>');
					infowindowcontent += '<br />' + item.phone;
				}
				else if (item.fax && !item.phone) {
					$('#infocontainer').html($('#infocontainer').html() + '<p><strong>Fax:<\/strong> ' + item.fax + '<\/p>');
				}
				// E-mail
				if (item.email) {
					$('#infocontainer').html($('#infocontainer').html() + '<p><strong>E-mail:</strong> <a href="mailto:' + item.email + '">' + item.email + '</a></p>');
				}
				// Web Site
				if (item.website) {
					$('#infocontainer').html($('#infocontainer').html() + '<p><strong>Web Site:<\/strong><br/> <a href="' + item.website + '" target="_blank">' + item.website + '</a><\/p>');
				}
				// Description
				if (item.description) {
					$('#infocontainer').html($('#infocontainer').html() + '<p>' + item.description + '</p>');
				}
				// Picture
				if (item.picture) {
					$('#infocontainer').html($('#infocontainer').html() + '<p><img src="' + item.picture + '" alt="" \/><\/p>');
				}
				// Panoramic
				if (item.panoramic) {
					$('#infocontainer').html($('#infocontainer').html() + '<p><a href="pano.php?id=' + item.id + '" onclick="showPopup(this.href);return false;">View Panoramic<\/a><\/p>');
				}
				/*//
				if (item.) {
					$('#infocontainer').html($('#infocontainer').html() + '<p><strong>:</strong> ' + item. + '</p>');
				}*/
				// Show the container.
				$('#infocontainer').slideDown();
				// Throw up the InfoWindow.
				pointtracker[item.id].openInfoWindowHtml(infowindowcontent);
			}
			else {
				// Blank edit form fields.
				$('#ename').val(item.name);
				$('#econtact').val('');
				$('#eaddress').val('');
				$('#etown').val('');
				$('#epost').val('');
				$('#ephone').val('');
				$('#eemail').val('');
				$('#efax').val('');
				$('#ewsite').val('');
				$('#eusername').val('');
				$('#epassword').val('');
				$('#eid').val('');
				$('#epicturewindow').attr('src', '');
				// Populate fields.
				$('#ename').val(item.name);
				$('#econtact').val(item.contact);
				$('#eaddress').val(item.address);
				$('#etown').val(item.town);
				$('#epost').val(item.postcode);
				$('#ephone').val(item.phone);
				$('#eemail').val(item.email);
				$('#efax').val(item.fax);
				if (item.website != '') {
					$('#ewsite').val(item.website.substr(7, item.website.length - 7));
				}
				$('#eusername').val(item.username);
				$('#epassword').val(item.password);
				$('#edescription').val(item.description);
            //console.log(item.category);
				$('#ecategory').val(item.category);
				$('#eid').val(item.id);
				$('#epicturewindow').attr('src', '' + item.picture);
				whichdel = item.id;
				pointtracker[item.id].openInfoWindowHtml('<strong>' + item.name + '</strong><br \/><a href="javascript:;" onclick="$(\'#edit\').jqmShow();">Edit Point<\/a><br \/><a href="javascript:;" onclick="$(\'#del\').jqmShow();">Delete Point Permanently<\/a>');
				centerMarker(window.bigmarker);
			}
		});
	});
}

// Get a page for the popup.
function getPage(url) {
	$('.dialog').load(url);
}

// GMap2 initialization.
function load() {
	if(GBrowserIsCompatible) {
		// Create the map.
		map = new GMap2(document.getElementById('map'));
		map.setCenter(new GLatLng(44.90105, -76.02065), 14);
		map.addControl(new GSmallMapControl());
		
		// Add a point on the middle of the screen to show where the middle is (for adding new points).
		if (admin) {
			window.bigmarker = new GMarker(new GLatLng(44.90105, -76.02065), {icon: new GIcon(G_DEFAULT_ICON, "bigmarker.png")});
			GEvent.addListener(bigmarker, "dragend", function() {
				$('#y').val(marker.getPoint().lat());
				$('#x').val(marker.getPoint().lng());
			});
			map.addOverlay(bigmarker);
		}
		
		// Create the points array for the dynamic point retrieval. pointtracker tracks which points are already on the map.
		points = new Array();
		pointtracker = new Array();
		
		if (admin) {
			// Center the add marker point.
			GEvent.addListener(map, 'move', function() {
				centerMarker(window.bigmarker);
			});
			
			// Close any open info windows when the map starts moving.
			GEvent.addListener(map, 'dragstart', function() {
				map.closeInfoWindow();
			});
		}
		
		if (!admin) {
			GEvent.addListener(map, 'dragstart', function() {
				if ($('#infocontainer').is(':visible')) {
					$('#infocontainer').slideUp();
				}
			});
		}
	}
}

$(document).ready(function() {
	// Set up the AJAX search form.
	$('#searchform').ajaxForm({
		dataType: 'json',
		success: function(data) {
			refreshpoints();
			if ($('#infocontainer').is(':visible')) {
				$('#infocontainer').slideUp();
			}
			$('#businesslist').html('');
			$('#listlabel').html('Search Results');
			// Add each item returned to the points array. The array is sorted by the item's MySQL id field to prevent duplicate entries.
			$.each(data.items, function(i, item) {
				points[item.id] = item;
				$('#businesslist').html($('#businesslist').html() + '<li><a href="javascript:getData(' + item.id + ');">' + item.name + '<\/a><\/li>');
				addPoint(item);
			});
			// Check if nothing was returned.
			if (data.length == 0) {
				$('#businesslist').html('<li>No results.<\/li>');
			}
		}
	});
	
	// Set up the JS dialog thing.
	$('#dialog').jqm({ajax: '@href', modal: true, target: 'div.dialog', onShow: function(hash) {
		hash.w.fadeIn('500');
	}, onHide: function(hash) {
		hash.w.fadeOut('500', function() { hash.o.remove(); });
	}});
	if (admin) {
		$('.dialogwrapper').jqm({modal: true, onShow: function(hash) {
			hash.w.fadeIn('500');
		}, onHide: function(hash) {
			hash.w.fadeOut('500', function() { hash.o.remove(); });
		}});
	}
	
	// For the category-based search.
	$('#searchcategory').change(function() {
		refreshpoints();
		if ($('#infocontainer').is(':visible')) {
			$('#infocontainer').slideUp();
		}
		category = $('#searchcategory').val();
		if (category != "") {
			$('#businesslist').html('<li>Loading...</li>');
			var url = 'maps/map-go.xml.aro?searchcategory=' + category;
			if (admin) { url = '../../' + url; }
			$.getJSON(url, function(data) {
				$('#businesslist').html('');
				$('#listlabel').html('Category Listing');
				$.each(data.items, function(i, item) {
					points[item.id] = item;
					$('#businesslist').html($('#businesslist').html() + '<li><a href="javascript:getData(' + item.id + ');">' + item.name + '<\/a><\/li>');
					addPoint(item);
				});
				// Check if nothing was returned.
				if (data.length == 0) {
					$('#businesslist').html('<li>No results.<\/li>');
				}
			});
		}
	});
	
	load();
});

$(document).unload(function() {
	GUnload();
});

var map;

