RPGGoogle = {
	mapID: "company-google",
	mapZoom: 12,
	closeZoom: 5,
	startCentre: {lon: -4.683523, lat:55.055784},
	htmlStyles: {
		width: "320px",
		height: "400px",
		right: "0"
	},
	fetchFunctions: {}
};

RPGGoogle.setHtmlStyles = function(mapE) {
	with (RPGGoogle) {
		var props = ['height','width','right','top'];
		for (var i = 0; i < props.length; i++) {
			if (typeof htmlStyles[props[i]] != "undefined") {
				mapE.style[props[i]] = htmlStyles[props[i]];
			}
		}
	}
}

RPGGoogle.fetchFunctions.pre = function(mapE) {
	Element.addClassName(mapE,"right-column home-column");

	RPGGoogle.setHtmlStyles(mapE);

	// Right column should look good on left
	l = document.getElementsByClassName("right-column");
	Element.addClassName(l[1],"left-column");
	Element.removeClassName(l[1],"right-column");

	// Holding notice
	mapE.innerHTML = "&nbsp;<br/>Fetching map from Google... ";

	// Google does something weird with the stylesheets,
	// So use script.aculo.us to move
	var left = -20;
	if (document.isIE) {
		//left = 230;
	}
	new Effect.MoveBy(mapE, 10, left, {duration: 0.3 });

	RPGGoogle.fetchFunctions.keepCorrecting(mapE);

	// WDDX packet
	document.RPGGoogleWDDX();

}

RPGGoogle.fetchFunctions.keepCorrecting = function(myMap) {

	// Either given a map - which we cache - or retrieve a map from the cache
	if (typeof myMap == "undefined") {
		if (typeof RPGGoogle.myMap == "undefined") {
			return false;
		}
		myMap = RPGGoogle.myMap;
	} else {
		RPGGoogle.myMap = myMap;
	}

	// Fix for IE's bug
	// Set a timeout to re-call this function
	// If you set an interval then interval overlays on interval until it all crashes
	Position.prepare();
	var a1 = Position.cumulativeOffset(myMap);
	var a2 = Position.cumulativeOffset($('return-to-home-img'));
	var xFix = a1[0] - a2[0];
	if (xFix < 200) {
		// Only fix once - don't set new timeouts if we fix
		new Effect.MoveBy(myMap, 0, 260, {duration: 0.1 });
	} else {
		// Distinguish between here, and fixed, and not here at all?
		// Can't: IE can load the whole page, and then break
		// So just detect IE: then, if page loaded, check but do it less frequently
		var windowHasLoaded = false;
		if ((typeof window.loaded != "undefined") && window.loaded) {
			windowHasLoaded = true;
		}
		if (RPGGoogle.fetchFunctions.quickSniffForIE()) {
			if (!windowHasLoaded) {
				RPGGoogle.myMapKeepCorrecting = window.setTimeout('RPGGoogle.fetchFunctions.keepCorrecting()', 200);
			} else {
				RPGGoogle.myMapKeepCorrecting = window.setTimeout('RPGGoogle.fetchFunctions.keepCorrecting()', 2000);
			}
		}
	}


	return false;
}

RPGGoogle.fetchFunctions.quickSniffForIE = function() {
	// Does not support KDE/KHTML browsers
	return (typeof document.all!="undefined");
}


RPGGoogle.fetchFunctions.post = function(mapE) {
	;
}

RPGGoogle.fetchFunctions.error = function(mapE) {
	// Holding notice
	mapE.innerHTML = mapE.innerHTML + " error.";
	// Put element where we can find it, then silently get rid
	document.mapElem = mapE;
	window.setTimeout("RPGGoogle.hideMap(); ", 2000);
}

RPGGoogle.bodyOnloadMap = function() {
	mapElem = $(RPGGoogle.mapID);
	try {
		// Pre-fetch
		RPGGoogle.fetchFunctions.pre(mapElem);
		// Fetch from Google
		RPGGoogle.makeMap(js_wddx,RPGGoogle.mapID);
		// Post-fetch
		RPGGoogle.fetchFunctions.post(mapElem);
	} catch (e) {
		RPGGoogle.fetchFunctions.error(mapElem,e);
	}
}

RPGGoogle.hideMap = function() {
	// Right column return to right
	l = document.getElementsByClassName("left-column");
	Element.addClassName(l[1],"right-column");
	Element.removeClassName(l[1],"left-column");

	document.mapElem.style.height = "";
	new Effect.Squish(document.mapElem);
	window.setTimeout("document.mapElem.parentNode.removeChild(document.mapElem);", 500);
}

RPGGoogle.makeMap = function(wddx, mapID) {

	// Company URL - append an ID
	var companyUrl = "http://www.recycledproducts.org.uk/search/results/companydetails/index.asp?id=";


	// Bind the map object to the div element with ID map
	var mapelem = $(mapID);
	if (mapelem == null) {
		return;
	}

	// Get map
	//var map = RPGInit(mapID,mapZoom, {lon: -2.5067661647745023, lat:53.762883443476013} );
	var map = RPGGoogle.init(mapID, RPGGoogle.mapZoom, RPGGoogle.startCentre );

	// Home, from postcode if exists
	var homemarker = null;
	if (typeof wddx.s_loc != "undefined") {
		homemarker = RPGGoogle.overlayHome(wddx.s_loc,map,wddx);
	}



	// All companies
	markers = new Array();
	points = new Array();
	for (var iMark =0; iMark < wddx.q_rest.getRowCount(); iMark++) {

		var point = new GPoint(wddx.q_rest["lon"][iMark],wddx.q_rest["lat"][iMark]);
		if (typeof wddx.q_rest["html"][iMark] == "undefined") {
			wddx.q_rest["html"][iMark] = "";
		}
		var marker = new RPGGoogle.markerFromData(map,point,wddx.q_rest["html"][iMark],wddx.q_rest["outlet_id"][iMark],wddx.q_rest["postcode"][iMark]);
	}
}

RPGGoogle.markerFromData = function(m,p,h,i,pc) {
	// Create marker from point p
	var marker = new RPGGoogle.smallMarker(p);
	marker.point = p;
	
	// Add marker postcode
	marker.postcode = pc;

	// Add marker HTML h
	marker.html = h;

	// Add outlet ID
	marker.outlet_id = i;

	// Overlay
	m.addOverlay(marker);

	// Events
	marker.clickListen = GEvent.addListener(marker, "click", function() {
		RPGGoogle.markerZoomIn(this); });
	GEvent.addListener(marker, "mouseout", function() {
		RPGGoogle.outletUnhighlight(this); });
	GEvent.addListener(marker, "mouseover", function() {
		RPGGoogle.outletHighlight(this); });
}

RPGGoogle.outletHighlight = function(marker) {
	Element.addClassName($('outlet-id-'+marker.outlet_id),'outlet-highlighted');
}
RPGGoogle.outletUnhighlight = function(marker) {
	Element.removeClassName($('outlet-id-'+marker.outlet_id),'outlet-highlighted');
}

RPGGoogle.mapPopup = function(m,p,h) {
	m.openInfoWindowHtml(p,h);
}
RPGGoogle.markerPopup = function(marker) {
	marker.openInfoWindowHtml(marker.html);
}

RPGGoogle.markerZoomIn = function(marker) {
	marker.map.centerAndZoom(marker.point, RPGGoogle.closeZoom);
	GEvent.removeListener(marker.clickListen);
	marker.clickListen = GEvent.addListener(marker, "click", function() {
		RPGGoogle.markerZoomOut(this); });
}

RPGGoogle.markerZoomOut = function(marker) {
	marker.map.centerAndZoom(new GPoint(RPGGoogle.startCentre.lon,RPGGoogle.startCentre.lat), RPGGoogle.mapZoom);
	GEvent.removeListener(marker.clickListen);
	marker.clickListen = GEvent.addListener(marker, "click", function() {
		RPGGoogle.markerZoomIn(this); });
}

RPGGoogle.init = function(divID,zoom,centreLL) {
	// Get map
	var m = new GMap($(divID));

	// Add some controls to the map object
	m.addControl(new GSmallMapControl());

	// Unleash the map object, centred on home
	m.centerAndZoom(new GPoint(centreLL.lon,centreLL.lat), zoom);

	return m;

}

RPGGoogle.smallMarker = function(point) {
	// Add a marker for home
	var smallicon = new GIcon();

	// Image
	smallicon.image="http://labs.google.com/ridefinder/images/mm_20_purple.png";
	smallicon.iconSize = new GSize(12,20);
	smallicon.shadow = "http://labs.google.com/ridefinder/images/mm_20_shadow.png";
	smallicon.shadowSize = new GSize(22, 20);

	// Anchor for icon relative to point, info window relative to icon?
	smallicon.iconAnchor = new GPoint(6,20);
	smallicon.infoWindowAnchor = new GPoint(5,1);

	// Make marker
	return 	new GMarker(point,smallicon);
}

RPGGoogle.overlayHome = function(ll,m,wddx) {
	// Create a point for home
	var GPointHome = new GPoint(ll.lon, ll.lat);

	// Make marker and overlay it
	var homemarker = new RPGGoogle.smallMarker(GPointHome);
	m.addOverlay(homemarker);

	// Put point as a property of the object so we can send it back
	homemarker.point = GPointHome;
	homemarker.html = "<i>Centre of catchment area<br/>" + wddx.postcode + "<br/>area radius = " + wddx.radius + " miles</i>";

	// Add popup listener
	GEvent.addListener(homemarker, "click", function() {
		popup(map,this.point,this.html); });

	return homemarker;
}
