// JavaScript Document


/* ----- Map Functions ------ */

var path = "mapTiles/";
var blankImagePath = "mapTiles/blue.png";
var tooltip = document.createElement("div");
var currentMarker;
var viewingLoc = false;

var map; 
var houseMarker;
var neighbourMarker;

var placeMarkers = [];
var placeMarkersAddresses = [];

function loadMap(){
	
	if (GBrowserIsCompatible()) {
		
		map = new GMap(document.getElementById("mapPanel"));
		map.addControl(new GScaleControl());
		
		var copyright = new GCopyright(1,
	          new GLatLngBounds(new GLatLng(4.168953967399562,73.50003719329834),new GLatLng(4.180585267939715,73.51962804794312) ),
      		    17, "&copy 2009 Alfisoft: Male' Maps ");

      	var copyrightCollection = new GCopyrightCollection('Map Data ');
      	copyrightCollection.addCopyright(copyright);
      
      	var tilelayers = [new GTileLayer(copyrightCollection,10,19)];
      	tilelayers[0].getTileUrl = CustomGetTileUrl;
      
     	// ============================================================
     	// === If we know the copyright, return it, otherwise look for the G_NORMAL_MAP copyright =====      
     	tilelayers[0].getCopyright = function(a,b) {
        var c= copyrightCollection.getCopyrightNotice(a,b);
        if (!c) {
          c = G_NORMAL_MAP.getTileLayers()[0].getCopyright(a,b);
        }
        	return c;
	    }
      
     
    	var custommap = new GMapType(tilelayers, G_SATELLITE_MAP.getProjection(), "Old OS");
		map.addMapType(custommap);

	    map.setCenter(new GLatLng(4.175288606914209, 73.50922107696533), 16, custommap);
	 	map.addControl(new GLargeMapControl());
		map.enableScrollWheelZoom();
		
		map.getPane(G_MAP_FLOAT_PANE).appendChild(tooltip);
		tooltip.style.visibility="hidden";	
		
		
																
	}
	
}

function parseLocationXML(xml) {
	$(xml).find('location').each(function(){
		Place = $(this).attr('Place');
		Road = $(this).attr('Road');
		Postcode = $(this).attr('Postcode');
		Category = $(this).attr('Category');
		CategoryImg = $(this).attr('CategoryImg');
		District = $(this).attr('District');
		Lat = $(this).attr('Lat');
		Lng = $(this).attr('Lng');
	});
	
	hideAllLocations();
	var Address = Road + ",<br />" + District + " " + Postcode;	
	
	showLocation (Place, Address, Lat, Lng);
	displayLocationInfo (Place, Address, Category, CategoryImg, true);
	
}


function displayLocationInfo (Place, Address, Category, CategoryImg, hidePanel1) {
	
	viewingLoc = true;	
	document.getElementById("resultsPanel2").style.visibility="visible";	
	var html = '<div class="shadedBox">' +  
					'<div class="shadedBoxContent">' + 
						'<div class="addressBoxIcon">' +
						'<img src="images/red-dot.png"  />' +
						'</div>'+ 
						'<div class="addressBoxText">' +  
						   '<b>' + Place + '</b><br />' + 
							'' + Address;
							
	if (Category != "" ) {
		html = html + '<br /><br />' + '<img src="images/' + CategoryImg + '"  align="absmiddle" /> ' + Category;
	}
								
	html = html + 	'</div><div class="clearBoth">&nbsp;</div> ' + 
					'</div>' + 
					'<div class="shadedBoxBottom"></div> ' + 
				'</div>' + 
				
				'<div class="clearBox">' + 
					'<div class="clearBoxContent">' + 
						'<a href="javascript:printMap()" ><img src="images/print.gif"  align="absmiddle" border="0" /> Print Location </a> &nbsp;&nbsp;&nbsp;' + 
						'<a id="address_link" href="popup_address_links.php?pl='+ escape(Place) +'" ><img src="images/link.gif"  align="absmiddle" border="0" /> Get Link of Location</a>' + 
					'</div>' + 
					'<div class="clearBoxBottom"></div>' + 
				'</div>' + 
				
				'<div class="shadedBox">' + 
		        	'<div class="shadedBoxContent" id="gallery_container"> </div>' + 
            		'<div class="shadedBoxBottom"></div>' + 
        		'</div>'; 
		
		if (hidePanel1) {
			document.getElementById("resultsPanel").style.visibility="hidden";
			document.getElementById("resultsPanel").style.height="0px";				
		} else {
			document.getElementById("resultsPanel").style.visibility="visible";
			document.getElementById("resultsPanel").style.height="240px";

		}
		

	$('#resultsPanel2').html(html);	
	
	$("a#address_link").fancybox({
		'padding': 20, 
		'hideOnContentClick': false,
		'overlayOpacity': 0.8,
		'zoomSpeedIn'			: 200,
		'zoomSpeedOut'			: 200,
		'easingIn'				: 'easeOutBack',
		'easingOut'				: 'easeInBack',
		'frameWidth': 320,
		'frameHeight': 520 
	});
	
	$.ajax({
	   type: "GET",
	   url: "ajax_address_photos.php",
	   data: "pl="+encodeURIComponent(Place), 
	   dataType: "html",
	   success: function(result){
			$('#gallery_container').html(result);
	   }
	 });	
	
}




function showLocation (Place, Address, Lat, Lng) {
	// ------------------------------------------------
	// Show Location Marker
	
	// Create custom red marker icon for marking places
	var icon = new GIcon();
	icon.image = "images/red-dot.png";
	icon.shadow = "images/marker-shadow.png";
	icon.iconSize = new GSize(32.0, 32.0);
	icon.shadowSize = new GSize(49.0, 32.0);
	icon.iconAnchor = new GPoint(16.0, 32.0);
	icon.infoWindowAnchor = new GPoint(16.0, 0.0);
	
	var infoWindowHtml = "<b>" + Place + "</b>" + Address;
	var markerOptions = { title:Place, icon:icon }; 
	
	var point = new GLatLng(Lat, Lng);
	
	currentMarker = createMarker(point, markerOptions, infoWindowHtml, Place);
	map.setCenter(currentMarker.getLatLng(), 18);
	map.addOverlay(currentMarker);
	
		
	// ------------------------------------------------
}

function mapCanvasResize() {
		var x,y;
		if (self.innerHeight) { // All browsers except Explorer
			x = self.innerWidth - 2;
			y = self.innerHeight - 2;
		}
		else if (document.documentElement && document.documentElement.clientHeight) {	// Strictly Explorer 6
			x = document.documentElement.clientWidth;
			y = (document.documentElement.clientHeight - 12);
		}
		else if (document.body) { // All others
			x = document.body.clientWidth;
			y = (document.body.clientHeight - 12);
		}
		e = document.getElementById("mapPanel");
		
		if(navigator.appName == "Microsoft Internet Explorer")
		{
			x = (x - 322);
			y = (y - 85); // increasing number decreases map size
		} else {	
			x = (x - 322);
			y = (y - 95); // increasing number decreases map size
		}
		
		e.style.width = x + 'px';
		e.style.height = y + 'px';
}

// ------ Our own getTileUrl function ---------
CustomGetTileUrl=function(a,b){
   		if (b==19) {
			if (a.x>=369185 && a.x<=369214 && a.y>=256049 && a.y<= 256067) {
				return path + b + "_" + (a.x) +"_"+(a.y)+".png";
			}	else { return blankImagePath; }
		}
		
		if (b==18) {
			if (a.x>=184592 && a.x<=184607 && a.y>=128024 && a.y<= 128033) {
				return path + b + "_" + (a.x) +"_"+(a.y)+".png";
			} else { return blankImagePath; }
		}
			
		if (b==17 && a.x>=92296 && a.x<=92303 && a.y>=64012 && a.y<= 64016) {
		   		return path + b + "_" + (a.x) +"_"+(a.y)+".png";
        } 
		else { return G_NORMAL_MAP.getTileLayers()[0].getTileUrl(a,b);
		}
}

function createMarker(point, markerOptions, infoWindowHtml, tooltip) {

	var marker = new GMarker(point, markerOptions);
		
	// === store the name so that the tooltip function can use it ===
	marker.tooltip = '<div class="tooltip"><nobr>'+tooltip+'</nobr></div>';
	GEvent.addListener(marker, "click", function() {
	  marker.openInfoWindowHtml(infoWindowHtml);
	});

	//  ======  The new marker "mouseover" and "mouseout" listeners  ======
	GEvent.addListener(marker,"mouseover", function() {
	  showTooltip(marker);
	});        
	GEvent.addListener(marker,"mouseout", function() {
		mouseout_place();	
	});       
		
    return marker;
}


// =====  TOOL TIPS AND INFOWINDOWS =============================
// ==============================================================

// ====== This function displays the tooltip ======
// it can be called from an icon mousover or a side_bar mouseover
function showTooltip(marker) {
    tooltip.innerHTML = marker.tooltip;
	var point=map.getCurrentMapType().getProjection().fromLatLngToPixel(map.fromDivPixelToLatLng(new GPoint(0,0),true),map.getZoom());
	var offset=map.getCurrentMapType().getProjection().fromLatLngToPixel(marker.getPoint(),map.getZoom());
	var anchor=marker.getIcon().iconAnchor;
	var width=marker.getIcon().iconSize.width;
	var height=tooltip.clientHeight - 20;
	var pos = new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(offset.x - point.x - anchor.x + width, offset.y - point.y -anchor.y -height)); 
	pos.apply(tooltip);
	tooltip.style.visibility="visible";
}

// ===== This function is invoked when the mouse goes over an entry in the side_bar =====
// It launches the tooltip on the icon      
function mouseover_place(i) {
    showTooltip(placeMarkers[i])
}
// ===== This function is invoked when the mouse leaves an entry in the side_bar =====
// It hides the tooltip      
function mouseout_place() {
	tooltip.style.visibility="hidden";
}

function show_infoWindow() {
	GEvent.trigger(currentMarker, "click");
}



/* ----- categories ---------- */

function hideAllLocations() {
	if (currentMarker != null) map.removeOverlay(currentMarker);
		
	for (var i=0;i<placeMarkers.length;i++) {
	 	  placeMarkers[i].closeInfoWindow();
		  map.removeOverlay(placeMarkers[i]);
    }
}

function displayAllCatLocations(cid, cname, cimage){
		var dataFile ='ajax_categorylocations.php?cid=' + cid;
		var thishttp = GXmlHttp.create();
		thishttp.open("GET", dataFile, true);
		thishttp.onreadystatechange = function() {
			
		document.getElementById("resultsPanel").innerHTML = " <img src='images/ajax-loader.gif'> Fetching data - one moment please... ";
		if (thishttp.readyState == 4) {
					
				hideAllLocations();
				
				currentMarker = null;
				placeMarkers = [];
				placeMarkersAddresses = [];
				
				var locations = thishttp.responseXML.documentElement.getElementsByTagName("location");
				locations_html ='<div style="padding:10px 0 2px 10px;">';
				locations_html += "<b>" + "<img src='images/"+ cimage +"' border='0' align='absmiddle' style='padding-right: 5px;' />"+ cname +"</b><br>";
				locations_html += "<i>Click on Place to view location</i></div><div id=\"category_results\"><table border=0 cellpadding=0 cellspacing=0 class=\"BorderAll\">";
				locations_html += "<tr><td class='Heading' width =140> Place </td><td class='Heading' width =132> Address </td></tr>";
				var alternateRow = true;
				
			
				// Create custom green marker icon for marking categories
				var icon = new GIcon();
				icon.image = "images/blue.png";
				icon.shadow = "images/marker-shadow.png";
				icon.iconSize = new GSize(32.0, 32.0);
				icon.shadowSize = new GSize(49.0, 32.0);
				icon.iconAnchor = new GPoint(16.0, 32.0);
				icon.infoWindowAnchor = new GPoint(16.0, 0.0);
				
				bounds = new GLatLngBounds();
				
				for (var j = 0; j < locations.length; j++) {
								// get any line attributes			
					var place = locations[j].getAttribute("Place");
					var address = locations[j].getAttribute("Road") + ",<br>" + locations[j].getAttribute("District") + " " + locations[j].getAttribute("Postcode");
					var category = locations[j].getAttribute("Category");
					var Lat = parseFloat(locations[j].getAttribute("Lat"));
					var Lng = parseFloat(locations[j].getAttribute("Lng"));
					var point = new GLatLng(Lat, Lng);
				
					locations_html += "<tr "; 
					if ((alternateRow = !alternateRow)) { locations_html += "class='alternate'"; }
					locations_html += ">";
					locations_html += "<td class='infoRows' align='left' valign='top'>";
					locations_html += '<a href="javascript:locate_place(' + j + ')">' + place + '</a><br>';
					locations_html += "&nbsp;</td>";
					locations_html += "<td class='infoRows' align='left' valign='top' id=" + j + ">" + address;
					locations_html += "&nbsp;</td>";
					locations_html += "</tr>";
			
				
					var infoWindowHtml = "<b>" + place + "</b><br>" + address;
					var markerOptions = { title:place, icon:icon }; 
					var marker = createMarker(point, markerOptions, infoWindowHtml, place);
					placeMarkers[j] = marker;
					placeMarkersAddresses[j] = address;
				
					map.addOverlay(marker);
					bounds.extend(marker.getLatLng());
				}
			
				locations_html += "</table></div>";
				
				map.setZoom(map.getBoundsZoomLevel(bounds));
				map.setCenter(bounds.getCenter());	
					
				document.getElementById("resultsPanel").innerHTML = locations_html;	
								
				if (viewingLoc) {
						document.getElementById("resultsPanel2").style.visibility="hidden";
						viewingLoc = false;
				}
				
				document.getElementById("resultsPanel").style.visibility="visible";
				document.getElementById("resultsPanel").style.height="240px";
			}
		}
		thishttp.send(null);
}

// This function picks up the side_bar click and opens the corresponding info window
function locate_place(i) {

	if (currentMarker != null) currentMarker.setImage("images/blue.png")	
	
	currentMarker = placeMarkers[i];
	currentMarker.setImage("images/red-dot.png")	
	displayLocationInfo (currentMarker.getTitle(), placeMarkersAddresses[i], "", "", false);
	show_infoWindow();

}


/* ----- other functions ------ */

function openHijakDialogue (lid, title, width, height, after_function_name) {
	var widthval = width; 
	var heightval = height; 
	if (typeof width === 'undefined') widthval = 500;
	if (typeof height === 'undefined') heightval = 300;
	
	$("#dialog").load($('#'+lid).attr('rel'), function() { // load remote content from its 'rel' attribute into hidden div
            $(this)
              .dialog('destroy') // destroy dialog widget (if exists)
              .dialog({ // and recreate it with following options
                title: title,
				height: heightval, 
				width: widthval, 
				zIndex: 10000, 
                open: function() { $(this).hijack() }, 
				close: function() {
					if (typeof after_function_name !== 'undefined') {
		   				eval(after_function_name); 
					} else { 
						// show_loading(); location.reload(); 
					}
				}
              });
	});
}

function newwindow(file,title, heightVal, widthVal) { //v2.0
	widthVal = widthVal || "520";
  window.open(file, title,'status=no, width='+widthVal+', height='+heightVal+', resizable=yes, scrollbars=yes');
}

function printMap(){
	var URL = "print.php?pl=" + encodeURIComponent(escape(currentMarker.getTitle())) + "&printLoc=1&zoom=" + map.getZoom() ;
	newwindow(URL, 'Print', 550, 620);
}


/* Ajax */
function createRequestObject(){
var request_o; 
var browser = navigator.appName; 
if(browser == "Microsoft Internet Explorer"){
/* Create the object using MSIE's method */
request_o = new ActiveXObject("Microsoft.XMLHTTP");
}else{
/* Create the object using other browser's method */
request_o = new XMLHttpRequest();
}
return request_o; //return the object
}
/* The variable http will hold our new XMLHttpRequest object. */
var http = createRequestObject(); //default
var subRequestDisplayArea;
/* Function called to handle the list that was returned from the file.. */
function handleSubRequest(){
/* Make sure that the transaction has finished. The XMLHttpRequest object
has a property called readyState with several states:
4: Finished */
var displayContainer = document.getElementById(subRequestDisplayArea);
displayContainer.className = "ajax_message";
displayContainer.innerHTML = " <img src='images/ajax-loader.gif'> Fetching data -- please wait... ";
if(http.readyState == 4){ //Finished loading the response
var response = http.responseText;
displayContainer.innerHTML = response;
displayContainer.className = "";
}
}