var map;
var myMarkers;
var icon;

// Create the marker icon
var icon = new GIcon();
icon.image = "/static/dot.gif";
icon.iconSize = new GSize(11, 11);
icon.iconAnchor = new GPoint(5, 5);
icon.infoWindowAnchor = new GPoint(5, 5);

if (window.attachEvent) {
  window.attachEvent("onresize",
    function() {this.map.checkResize()});
} else { 
  window.addEventListener("resize",
    function() {this.map.checkResize()},
    false);
}

function onLoad() {
	resizeMapElement();
	initialise(-4.15283203125, 53.99485396562768, 6);
	if (location.pathname != '/') {
		getPages();
	}
}

function makeHttpRequest(url, callback_function, return_xml)
{
	var request = GXmlHttp.create();
	request.open('GET', url, true);

	request.onreadystatechange = function() {
       if (request.readyState == 4) {
           if (request.status == 200) {
               eval(callback_function + '(request.responseXML)');
           } else {
               alert('There was a problem with the request.(Code: ' + request.status + ')');
           }
       }
   }
   request.send(null);
}

function initialise(lat, lon, zoom) {
	map = new GMap2(document.getElementById("map"));
	map.addControl(new GLargeMapControl());
	map.addControl(new GOverviewMapControl());
	map.addControl(new GMapTypeControl());
	map.setCenter(new GLatLng(lon, lat), zoom);
}

function setLocation(lat, lon, level) {
	map.setCenter(new GLatLng(lon, lat), level);
}

function gotoMyMarker(mkid) {
	var theMarker = myMarkers[mkid];
	map.setCenter(new GLatLng(theMarker.getPoint().lat(), theMarker.getPoint().lng()), 17);
	GEvent.trigger(theMarker,'click');
}

function showMarker(mkid) {
	var theMarker = myMarkers[mkid];
	//map.setCenter(new GLatLng(theMarker.getPoint().lat(), theMarker.getPoint().lng()), 17);
	GEvent.trigger(theMarker,'click');
}

function createMarker(lat, lon, name, address, town, locale, postcode, telephone, url) {
  var point = new GPoint(lat, lon);
  var marker = new GMarker(point, {title:name, icon:icon});
  var theurl = '';
  var theaddress = '';
  var thelocale = '';
  var thetown = '';
  var tab_website = '<b>No website registered</b>';
  var tab_blog = '<b>No blog registered</b>';
  map.addOverlay(marker);
  
  // Show this marker's index in the info window when it is clicked
  GEvent.addListener(marker, "click", function() {
  	// Website?
	if (url != '') {
		theurl = "<a href='" + unescape(url) + "' target='_blank'>" + name + "</a>";
		tab_website = '<div><a href="' + unescape(url) + '" target="_blank"><img border="0" src="http://pthumbnails.alexa.com/image_server.cgi?id=www.knowcal.co.uk&size=small&url='+ unescape(url) + '" border="0"/></a></div>';
	} else {
		theurl = '<b>' + name + '</b>';
		//tab_website =  tab_website + '<script type="text/javascript"><![CDATA[google_ad_client = "pub-6022733869870304";google_ad_width = 200;google_ad_height = 90;google_ad_format = "200x90_0ads_al";google_ad_channel ="";google_color_border = "FF66FF";google_color_link = "660066";google_color_bg = "FFCCFF";google_color_text = "000000";google_color_url = "660066";]]></script><script type="text/javascript" src="http://pagead2.googlesyndication.com/pagead/show_ads.js"></script>';
	}
	if (town != '') {
		thetown = town + "<br/>";
	}
	if (locale != '') {
		thelocale = locale + "<br/>";
	}
	if (address != '') {
		theaddress = address + "<br/>";
	}
	var skype_phone = "+44" + replaceAll(telephone.substring(1, telephone.length), " ", "");
	var tab_address = '<b>' + theurl + '</b><br/>' + theaddress + thelocale + thetown + postcode + '<br/>Tel. <b>' + telephone + '</b><br/><a href="skype:' + skype_phone + '" onclick="return skypeCheck();"><img src="http://goodies.skype.com/graphics/skypeme_btn_small_red.gif" border="0"></a><br/>';
	//var tab_website = '<div style="height: 150px;"><img src="http://pthumbnails.alexa.com/image_server.cgi?id=www.knowcal.co.uk&size=medium&url='+ unescape(url) + '" border="0"/></div>';

	var infoTabs = [
		new GInfoWindowTab("Address", tab_address)
		//new GInfoWindowTab("Web", tab_website)
		//new GInfoWindowTab("Blog", tab_blog)
	];
    marker.openInfoWindowTabsHtml(infoTabs);
    //showInfo(marker);
  });
  return marker;
}

function whatwhereEvent(event) {
	// Get what and where
	var where = document.getElementById('i_where').value;
	where = replaceAll(where, "-", "_");
	where = replaceAll(where, " ", "-");
	
	var what = document.getElementById('i_what').value;
	what = replaceAll(what, " ", "-");
	what = replaceAll(what, "&", "and");
	
	var who = document.getElementById('i_who').value;
	who = replaceAll(who, " ", "-");
	who = replaceAll(who, "&", "and");
	
	var q = document.getElementById('i_qual').value;
	
	// Add the qualifier, if necessary
	if (q != '') {
		q = q + "/"
	}
	
	// Redirect appropriately
	if (what && where && who) {
		window.location = "/" + what + "/" + where + "/" + q + "?who=" + who;
	} else
	if (what && where) {
		if (q == "-") {
			window.location = "/" + what + "/" + where + "/";
		} else {
			window.location = "/" + what + "/" + where + "/" + q;
		}
	} else
	if (who && where) {
		window.location = "/-/" + where + "/" + q + "?who=" + who;
	}
}

function getPages() {
	// Get what and where
	var where = document.getElementById('i_where').value;
	var what = document.getElementById('i_what').value;
	var who = document.getElementById('i_who').value;
	
	// Use Postcode for more accurate results (if available)
	var pcd = document.getElementById('i_pcd');
	if (pcd != null && pcd.value !='' && who == '') {
		where = pcd.value;
	}
	var q = document.getElementById('i_qual').value;
	
	if ((what && where) || (who && where)) {
		// Reset meter and turn on egg timer
		document.body.style.cursor = "wait";
		
		// Build url
		var the_url = '/services/directory.xml?page=1&location=' + escape(where) + '&heading='+ escape(what) + '&phrase=' + escape(who) + '&qualifier='+ escape(q);
		makeHttpRequest(the_url, 'whatwhereResult');
	}
}

function whatwhereResult(xmlDoc) {
	// Get what and where
	var where = document.getElementById('i_where').value;
	var what = document.getElementById('i_what').value;
	var who = document.getElementById('i_who').value;
	var q = document.getElementById('i_qual').value;
	
	// Use Postcode for more accurate results (if available)
	var pcd = document.getElementById('i_pcd');
	if (pcd != null && pcd.value !='') {
		where = pcd.value;
	}
	
	// Get result node
	var result_node = document.getElementById('results');
	
	// Get results from document
	var places = xmlDoc.documentElement.getElementsByTagName("result");
	
	// Get results tag from document
	var result_div = document.createElement('div');
	result_div.setAttribute('id','tmp2');
	
	// Get metadata from document
	var meta = xmlDoc.documentElement.getElementsByTagName("meta");
	var page = meta[0].getAttribute("page");
	var pages = meta[0].getAttribute("pages");
	var cnt = parseInt(meta[0].getAttribute("count"));
	
	if (places.length == 0 && page == 1) {
		var li = document.createElement('li');
		txt = document.createTextNode('No places of interest found');
		li.appendChild(txt);
		result_div.appendChild(li);
	}
	
	// If first page, clear everything before adding new
	if (page == 1) {
		// Reset points array
		myMarkers = new Array();
		
		// Remove current overlays
		map.clearOverlays();
	
		// Get result node and remove results
		var result_node = document.getElementById('results');
		while(result_node.hasChildNodes() == true)
		{
			result_node.removeChild(result_node.childNodes[0]);
		}
	}

	// Loop through results
	var lastinrange = true;
	for (var i = 0; i != places.length; i++) {
		var name = places[i].getAttribute("name");
		var lname = places[i].getAttribute("longname");
		var address = places[i].getAttribute("address");
		var town = places[i].getAttribute("town");
		var locale = places[i].getAttribute("locality");
		var postcode = places[i].getAttribute("postcode");
		var telephone = places[i].getAttribute("telephone");
		var url = places[i].getAttribute("url");
		var lat = parseFloat(places[i].getAttribute("lat"));
		var lon = parseFloat(places[i].getAttribute("lon"));
		var distance = places[i].getAttribute("distance");;
		
		if ((distance != '' && parseFloat(distance) <= 3.0) || distance == '') {
			var marker = createMarker(lon, lat, name, address, town, locale, postcode, telephone, url);
			myMarkers.push( marker );
		
			// Add to search results
			var li = document.createElement('li');
			var anchor = document.createElement('a');
			//anchor.setAttribute('onClick','gotoMyMarker(' + (myMarkers.length-1) + ')');
			anchor.setAttribute('href','javascript:gotoMyMarker(' + (myMarkers.length-1) + ');');
			txt = document.createTextNode(lname);
			li.appendChild(anchor);
			if (distance != '') {
				li.appendChild(document.createTextNode(' (' + distance + ' miles)'));
			}
			anchor.appendChild(txt);
			result_div.appendChild(li);
			// set lastinrange for next page logic
			lastinrange = true;
		} else {
			lastinrange = false;
		}
	}
	result_node.appendChild(result_div);
	
	// Now get the other results
	if ((lastinrange && page < pages && page < 5) && who == '') {
		page++;
		var the_url = '/services/directory.xml?page=' + page + '&location=' + escape(where) + '&phrase=' + escape(who) + '&heading='+ escape(what) + '&qualifier='+ escape(q);
		makeHttpRequest(the_url, 'whatwhereResult');
	}
	if (myMarkers.length > 0) {
		resizeMap(map, myMarkers);
	}
	// Complete loading (after rounding errors)
	document.body.style.cursor = "default";
	showMarker(0);
}

function clearQualifier() {
	document.getElementById('i_qual').value = '';
}

function resizeMap( map, markers ) {
	var bounds = new GLatLngBounds();
	for (var i=0; i<markers.length; i++) {
        bounds.extend(markers[i].getPoint());
	}
	var lat = bounds.getSouthWest().lat() + ((bounds.getNorthEast().lat() - bounds.getSouthWest().lat()) / 2);
	var lon = bounds.getSouthWest().lng() + ((bounds.getNorthEast().lng() - bounds.getSouthWest().lng()) / 2);
	var zoom = map.getBoundsZoomLevel(bounds);
	setLocation(lon, lat, zoom);
	map.savePosition();
}

function resizeMapElement() {
	var offset = 0;
	for (var elem = e("map"); elem != null; elem = elem.offsetParent) {
		offset += elem.offsetTop;
	}
	var windowHeight = getWindowHeight();
	var windowWidth = getWindowWidth();
	
	var height = windowHeight - offset - 10;
	var width = windowWidth - offset - 12;
	if (height >= 0) {
		e("map").style.height = height + "px";
		e("menus").style.height = (height-260) + "px";
		e("google").style.top = (height-250) + "px";
		e("top").style.width = (width+80) + "px";
	}
}

function e(id) {
	return document.getElementById(id);
}

function getWindowHeight() {
	return document.body.clientHeight;
}

function getWindowWidth() {
	return document.body.clientWidth;
}

function replaceAll(str, old, nw) {
	while (str.indexOf(old) > 0) {
		str = str.replace(old, nw);
	}
	return str;
}
