// The zoom control (dirty hax using default control and hiding was we don't want. )
var awm = {};
awm.maps = {
	generateMarker: function(product, baseIcon, infoPanelStyle) {
		var point = new GLatLng(
			parseFloat(product.childNodes[1].childNodes[0].data),
			parseFloat(product.childNodes[2].childNodes[0].data)
		);

		var marker = new google.maps.Marker(point,
			{
				"title": product.childNodes[0].childNodes[0].data,
				"icon": baseIcon
			}
		);

		marker.productId = product.getAttribute("id");

		google.maps.Event.addDomListener(marker, "click", function() {
			var panel = new awm.maps.MyInfoPanel(infoPanelStyle, this.productId);
			map.addControl(panel);
			return false;
		}
		);

		return marker;
	}
};

awm.maps.Data = new function()
{
	var groups = new Array();	
	var groupIds = new Array( 70, 1, 0, 150 );
	for ( var i = 0; i < groupIds.length; i++ )
	{
		$.ajax(
			{
				"async": false,
				"url": "/extraNav.xml.aspx?group=" + groupIds[i],
				"dataType": "xml",
				"success": function( xml, responseCode )
					{
						var xmlTypes = xml.documentElement.getElementsByTagName( "type" );
						
						var types = new Array();
						types["c:" + groupIds[i]] = "All " + xml.documentElement.getAttribute("name");
						for ( var j = 0; j < xmlTypes.length; j++ )
						{
							types[xmlTypes[j].getAttribute("id")] = xmlTypes[j].childNodes[0].childNodes[0].data;
						}
						
						groups[groupIds[i]] = {
							"id": groupIds[i],
							"name": xml.documentElement.getAttribute("name"),
							"types": types
						}
					}
				}
		);
	}
	this.groups = groups;
	
	this.counties = {
		1: "Birmingham",
		2: "Black Country",
		3: "Coventry & Warwickshire",
		4: "Herefordshire",
		8: "Shakespeare Country",
		5: "Ironbridge & Shropshire",
		6: "Staffordshire",
		7: "Worcestershire"
	};
	
	this.distances = Array( "0-5", "6-20", "21-40", "41+" );
};

awm.maps.ZoomTypeControl = function() {};
awm.maps.ZoomTypeControl.prototype = new google.maps.Control();

awm.maps.ZoomTypeControl.prototype.initialize = function( map )
{
	// Zoom
	var lc = new google.maps.LargeMapControl();
	var container = document.createElement( "div" );
	container.className = "navigator";
	
	var title = document.createElement( "p" );
	title.appendChild( document.createTextNode( "Zoom" ) );
	container.appendChild( title );
	
	var zoomControls = document.createElement( "div" )
	zoomControls.cssName = "navigatorControls";

	lcDom = lc.initialize( map );
	lcDom.style.position = "relative";

	zoomControls.appendChild( lcDom );
	zoomControls.style.overflow = "hidden";
	
	container.appendChild( zoomControls );
	
	// Map Types
	var mapTypes = document.createElement( "div" );
	mapTypes.cssName = "mapType";
	
	var mapButton = document.createElement( "div" );
	mapButton.className = "mapTypeButton selected";
	mapButton.appendChild( document.createTextNode( "Map" ) );
	mapTypes.appendChild( mapButton );

	var satelliteButton = document.createElement( "div" );
	satelliteButton.className = "mapTypeButton";
	satelliteButton.appendChild( document.createTextNode( "Satellite" ) );
	mapTypes.appendChild( satelliteButton );

	var terrainButton = document.createElement( "div" );
	terrainButton.className = "mapTypeButton";
	terrainButton.appendChild( document.createTextNode( "Terrain" ) );
	mapTypes.appendChild( terrainButton );

	google.maps.Event.addDomListener( mapButton, "click", function()
	{
		map.setMapType( G_NORMAL_MAP );
		mapButton.className = "mapTypeButton selected";
		satelliteButton.className = "mapTypeButton";
		terrainButton.className = "mapTypeButton";
	}
	);

	google.maps.Event.addDomListener( satelliteButton, "click", function()
	{
		map.setMapType( G_SATELLITE_MAP );
		mapButton.className = "mapTypeButton";
		satelliteButton.className = "mapTypeButton selected";
		terrainButton.className = "mapTypeButton";
	}
	);

	google.maps.Event.addDomListener( terrainButton, "click", function()
	{
		map.setMapType( G_PHYSICAL_MAP );
		mapButton.className = "mapTypeButton";
		satelliteButton.className = "mapTypeButton";
		terrainButton.className = "mapTypeButton selected";
	}
	);
	
	container.appendChild( mapTypes );

	map.getContainer().appendChild( container );
	return container;
}

awm.maps.ZoomTypeControl.prototype.getDefaultPosition = function()
{
	return new google.maps.ControlPosition( G_ANCHOR_TOP_RIGHT, new google.maps.Size( 10, 10 ) );
}


// The filter control to modify the pins on the map.
awm.maps.FilterControl = function() {};
awm.maps.FilterControl.prototype = new google.maps.Control();

awm.maps.FilterControl.prototype.initialize = function(map) {
	var container = document.createElement("div");
	container.id = "mapFilter";
	var form = document.createElement("form");

	// Add the categories
	var accordion = document.createElement("div");

	for (var i in awm.maps.Data.groups) {
		var data = awm.maps.Data.groups[i];
		var group = document.createElement("div");

		var header = document.createElement("a");
		header.setAttribute("href", "javascript:void(0);");
		header.appendChild(document.createTextNode(data.name));
		group.appendChild(header);

		cont = document.createElement("div");
		cont.className = "extraNav";
		cats = document.createElement("ul");

		for (var j in data.types) {
			var cat = document.createElement("li");

			if (document.all) {
				var radio = document.createElement("<input name=\"type\" />");
				var label = document.createElement("<label for=\"type_" + j + "\" />");
			}
			else {
				var radio = document.createElement("input");
				var label = document.createElement("label");
			}
			radio.id = "type_" + j
			radio.type = "radio";
			radio.name = "type";
			radio.value = j;

			label.setAttribute("for", "type_" + j);
			label.appendChild(document.createTextNode(" " + data.types[j]));

			cat.appendChild(radio);
			cat.appendChild(label);

			cats.appendChild(cat);
		}

		cont.appendChild(cats);
		group.appendChild(cont);
		accordion.appendChild(group);
	}

	form.appendChild(accordion);

	// Add the counties.
	var countyDiv = document.createElement("div");
	countyDiv.className = "extraNav2";
	var countyUl = document.createElement("ul");
	countyUl.id = "countyFilterList";

	var counties = awm.maps.Data.counties;
	for (i in counties) {
		var countyLi = document.createElement("li");
		radio = document.createElement("input");
		radio.type = "checkbox";
		radio.name = "county";
		radio.value = i;
		radio.id = "county_" + i;
		countyLi.appendChild(radio);

		if (document.all) {
			var countyLabel = document.createElement("<label for=\"county_" + i + "\" />");
		}
		else {
			var countyLabel = document.createElement("label");
		}
		countyLabel.setAttribute("for", "county_" + i);
		countyLabel.appendChild(document.createTextNode(" " + counties[i]))
		countyLi.appendChild(countyLabel);
		countyUl.appendChild(countyLi);
	}

	var countySelAll = document.createElement("a");
	countySelAll.setAttribute("href", "javascript:void(0);");
	countySelAll.className = "extraNav2Header";
	countySelAll.onclick = function() {
		$("#countyFilterList input[name=county]").attr("checked", true);
	}
	countySelAll.appendChild(document.createTextNode("All Counties"));
	countyDiv.appendChild(countySelAll);

	countyDiv.appendChild(countyUl);

	form.appendChild(countyDiv);

	// Add the keywords
	var keywordDiv = document.createElement("div");
	keywordDiv.className = "mapSearch";

	var keywordField = document.createElement("input");
	keywordField.id = "mapFilterKeyword";
	keywordField.type = "text";
	keywordField.name = "txtSearch";

	var keywordLabel = document.createElement("label");
	keywordLabel.id = "mapFilterKeywordLabel";
	keywordLabel.setAttribute("for", "mapFilterKeyword");
	keywordLabel.appendChild(document.createTextNode("Keywords"));

	keywordDiv.appendChild(keywordLabel);
	keywordDiv.appendChild(keywordField);
	form.appendChild(keywordDiv);

	// Add the submit button.
	var submitDiv = document.createElement("div");

	var submitButton = document.createElement("input");
	submitButton.type = "submit";
	submitButton.className = "mapButton";
	submitButton.setAttribute("value", "search the map ›");
	submitDiv.appendChild(submitButton);

	var spinner = document.createElement("img");
	spinner.id = "ajaxLoadSpinner";
	spinner.setAttribute("src", "/a/img/global/ajax-loader.gif");
	spinner.setAttribute("width", 16);
	spinner.setAttribute("height", 16);
	spinner.setAttribute("alt", "");
	spinner.style.display = "none";
	submitDiv.appendChild(spinner);

	form.appendChild(submitDiv);
	container.appendChild(form);

	// Wire up the form submit code
	$(form).submit(function() {
		$("#ajaxLoadSpinner").show();

		var type = $("#mapFilter input:radio:checked").attr("value");
		if (type) {
			if ("c" == type.substr(0, 1)) {
				type = "group=" + type.substr(2);
			}
			else {
				type = "category=" + type;
			}
		} else {
			type = "";
		}

		var counties = new Array();
		$("#countyFilterList input").each(function(i) {
			if ("county" == this.getAttribute("name")) {
				if (this.checked) {
					counties.push(this.getAttribute("value"));
				}
			}
		}
		);
		var txtSearch = $("#mapFilterKeyword").attr("value");

		google.maps.DownloadUrl("/productlist.xml.aspx?" + type + "&county=" + counties.toString() + "&txtSearch=" + txtSearch, function(data, responseCode) {
			var xml = google.maps.Xml.parse(data);
			var markers = xml.documentElement.getElementsByTagName("item");

			var icon = new google.maps.Icon(G_DEFAULT_ICON);
			icon.image = "/a/img/map/pin.gif";
			icon.iconSize = new google.maps.Size(24, 41);
			icon.imageMap = [9, 0, 15, 0, 24, 9, 24, 16, 15, 34, 15, 41, 8, 41, 8, 34, 0, 16, 0, 8];
			icon.iconAnchor = new google.maps.Point(12, 41);

			var soIcon = new google.maps.Icon(icon);
			soIcon.image = "/a/img/map/offer.gif";

			var tvIcon = new google.maps.Icon(G_DEFAULT_ICON);
			tvIcon.image = "/a/img/map/tvLarge.gif";
			tvIcon.iconSize = new google.maps.Size(42, 73);
			tvIcon.imageMap = [15, 0, 27, 0, 34, 5, 42, 15, 42, 25, 25, 60, 24, 73, 17, 73, 16, 60, 0, 25, 0, 15, 6, 5];
			tvIcon.iconAnchor = new google.maps.Point(21, 73);

			var marks = [];
			var markerBounds = new google.maps.LatLngBounds();
			for (var i = 0; i < markers.length; i++) {
				if ("true" == markers[i].getElementsByTagName("asseenontv")[0].childNodes[0].data) {
					var myIcon = tvIcon;
				} else if (0 < markers[i].getElementsByTagName("offer").length) {
					var myIcon = soIcon;
				} else {
					var myIcon = icon;
				}

				var marker = awm.maps.generateMarker(markers[i], myIcon, "long");
				markerBounds.extend(marker.getLatLng());
				marks.push(marker);
			}

			nbMgr.clearMarkers();
			mgr.clearMarkers();
			mgr.addMarkers(marks, 0);
			map.setCenter(markerBounds.getCenter(), map.getBoundsZoomLevel(markerBounds) - 1);
			mgr.refresh();

			$("#mapFilterKeywordLabel").html("Keywords - " + marks.length + " result(s)");

			$("#ajaxLoadSpinner").hide();
			$("#mapCurtain:visible").fadeOut("slow");
		}
		);

		return false;
	});

	// Add control to the map.
	map.getContainer().appendChild(container);

	// JQuery the accordian.
	$(accordion).accordion({ autoHeight: false });

	return container;
}

awm.maps.FilterControl.prototype.getDefaultPosition = function()
{
	return new google.maps.ControlPosition( G_ANCHOR_TOP_LEFT );
}


// Info Panel
awm.maps.MyInfoPanel = function( style, productId )
{
	this.style = style;
	this.productId = productId;
};

awm.maps.MyInfoPanel.prototype = new google.maps.Control();

awm.maps.MyInfoPanel.prototype.initialize = function(map) {
	awm.maps.MyInfoPanel.clear();

	var style = this.style;

	// Create container
	var container = document.createElement("div");
	container.id = "info";

	google.maps.DownloadUrl("/newdetail.xml.aspx?id=" + this.productId, function(data, responseCode) {
		var xml = google.maps.Xml.parse(data);
		var rootNode = xml.documentElement;
		var productId = rootNode.getAttribute("id");


		// Add the basic information
		var infoClose = document.createElement("div");
		infoClose.id = "infoClose";

		var infoCloseA = document.createElement("a");
		infoCloseA.setAttribute("href", "javascript:void(0)");
		infoCloseA.onclick = function() { awm.maps.MyInfoPanel.clear(); }

		var infoCloseImg = document.createElement("img");
		infoCloseImg.setAttribute("src", "/a/img/map/closeButton.gif");
		infoCloseImg.setAttribute("width", "21");
		infoCloseImg.setAttribute("height", "21");
		infoCloseImg.setAttribute("alt", "Close");
		infoCloseA.appendChild(infoCloseImg);

		infoClose.appendChild(infoCloseA);

		var infoDet = document.createElement("div");
		infoDet.id = "infoDetails";

		if (0 < rootNode.getElementsByTagName("offers").length) {
			var offersNode = document.createElement("div");
			offersNode.className = "offer clear";

			var offers = rootNode.getElementsByTagName("offers")[0].childNodes;
			for (var i = 0; i < offers.length; i++) {
				var offer = offers[i];
				var offerNode = document.createElement("p");

				var offerName = document.createElement("span");
				offerName.appendChild(document.createTextNode(offer.childNodes[0].childNodes[0].data));
				offerNode.appendChild(offerName);

				offersNode.appendChild(document.createTextNode(" "));

				var voucherLinkSpan = document.createElement("span");
				voucherLinkSpan.className = "voucherLink";

				var offScreenSpan = document.createElement("span");
				offScreenSpan.className = "offScreen";
				offScreenSpan.appendChild(document.createTextNode(" for " + offer.childNodes[0].childNodes[0].data));

				var offerLink = document.createElement("a");
				offerLink.setAttribute("href", "/newdetail.aspx?id=" + productId);
				offerLink.onclick = function() {
					window.open(this.href);
					return false;
				}
				offerLink.appendChild(document.createTextNode("voucher"));
				offerLink.appendChild(offScreenSpan);
				offerLink.appendChild(document.createTextNode(" ›"));

				voucherLinkSpan.appendChild(offerLink);
				offerNode.appendChild(voucherLinkSpan);
				offersNode.appendChild(offerNode);
			}

			infoDet.appendChild(offersNode);
		}

		var title = document.createElement("h3");
		title.className = "clear";
		title.appendChild(document.createTextNode(rootNode.getElementsByTagName("name")[0].childNodes[0].data));

		var img = document.createElement("img");
		img.setAttribute("src", rootNode.getElementsByTagName("image")[0].childNodes[0].data);
		img.setAttribute("width", "80");
		img.setAttribute("height", "80");

		var desc = document.createElement("p");
		desc.appendChild(document.createTextNode(rootNode.getElementsByTagName("description")[0].childNodes[0].data));

		var moreLinks = document.createElement("ul");
		moreLinks.className = "moreLinks clear";

		var moreInfoLi = document.createElement("li");
		var moreInfoA = document.createElement("a");
		moreInfoA.setAttribute("href", "/newdetail.aspx?id=" + productId);
		moreInfoA.onclick = function() {
			window.open(this.href);
			return false;
		}
		moreInfoA.appendChild(document.createTextNode("more info »"));

		moreInfoLi.appendChild(moreInfoA);
		moreLinks.appendChild(moreInfoLi);
		infoDet.appendChild(title);
		infoDet.appendChild(img);
		infoDet.appendChild(desc);
		infoDet.appendChild(moreLinks);
		container.appendChild(infoClose);
		container.appendChild(infoDet);

		// Add the nearby form
		if ("long" == style) {
			var form = document.createElement("form");
			form.className = "clear";

			var catSelDiv = document.createElement("div");
			catSelDiv.className = "clear";

			var catLabel = document.createElement("label");
			catLabel.setAttribute("for", "nearbyCat");
			catLabel.appendChild(document.createTextNode("Show:"))
			catSelDiv.appendChild(catLabel);

			var catInput = document.createElement("select");
			catInput.id = "nearbyCat";

			for (var i in awm.maps.Data.groups) {
				//var optGroup = document.createElement("optgroup");
				//optGroup.setAttribute("label", awm.maps.Data.groups[i].name);

				var opt = document.createElement("option");
				opt.setAttribute("value", "c:" + awm.maps.Data.groups[i].id);
				opt.appendChild(document.createTextNode(awm.maps.Data.groups[i].name));
				catInput.appendChild(opt);

				//types = awm.maps.Data.groups[i].types;
				//for (var j in types) {
				//	var opt = document.createElement("option");
				//	opt.setAttribute("value", j);
				//	opt.appendChild(document.createTextNode(types[j]));
				//	optGroup.appendChild(opt);
				//}

				//catInput.appendChild(optGroup);
			}

			catSelDiv.appendChild(catInput);
			form.appendChild(catSelDiv);

			/*distSelDiv = document.createElement("div");
			distSelDiv.className = "clear";

			var withinLabel = document.createElement("label");
			withinLabel.setAttribute("for", "nearbyDistance");
			withinLabel.appendChild(document.createTextNode("Within:"))
			distSelDiv.appendChild(withinLabel);

			var withinInput = document.createElement("select");
			withinInput.id = "nearbyDistance";

			for (var i in awm.maps.Data.distances) {
			var option = document.createElement("option");
			option.setAttribute("value", awm.maps.Data.distances[i]);
			option.appendChild(document.createTextNode(awm.maps.Data.distances[i] + " miles"));
			withinInput.appendChild(option);
			}

			distSelDiv.appendChild(withinInput);
			form.appendChild(distSelDiv);*/

			var submit = document.createElement("input");
			submit.className = "button";
			submit.setAttribute("type", "submit");
			submit.setAttribute("value", "go ›");
			form.appendChild(submit);

			var spinner = document.createElement("img");
			spinner.id = "nbLoadSpinner";
			spinner.setAttribute("src", "/a/img/global/ajax-loader.gif");
			spinner.setAttribute("width", 16);
			spinner.setAttribute("height", 16);
			spinner.setAttribute("alt", "");
			spinner.style.display = "none";
			form.appendChild(spinner);

			infoDet.appendChild(form);

			$(form).submit(function() {
				$("#nbLoadSpinner").show();
				var category = $("#nearbyCat option:selected").attr("value");
				if ("c" == category[0]) {
					category = "group=" + category.substr(2);
				}
				else {
					category = "category=" + category;
				}

				$.ajax(
							{
								"url": "/nearby.xml.aspx?" + category + "&id=" + productId,
								"dataType": "xml",
								"success": function(xml, responseCode) {
									var products = xml.documentElement.getElementsByTagName("product");

									var icon = new google.maps.Icon(G_DEFAULT_ICON);
									icon.image = "/a/img/map/nearby.gif";

									var marks = [];
									for (var i = 0; i < products.length; i++) {
										marks.push(awm.maps.generateMarker(products[i], icon, "short"));
									}

									nbMgr.clearMarkers();
									nbMgr.addMarkers(marks, 0);
									nbMgr.refresh();

									$("#nbLoadSpinner").hide();
								},
								"error": function(XMLHttpRequest, textStatus, errorThrown) {
									alert(textStatus + " : " + errorThrown);
								}
							}
						);

				return false;
			}
				);
		}

		// Add Control to map.
		map.getContainer().appendChild(container);

		// Update the nearbys below the area.
		var nearbyPanel = document.getElementById("nearbyContainer");
		var firstShow = (3 == nearbyPanel.childNodes.length || 1 == nearbyPanel.childNodes.length);

		var j = nearbyPanel.childNodes.length;
		for (var i = 2; i < j; i++) {
			nearbyPanel.removeChild(nearbyPanel.childNodes[2]);
		}

		var nearbys = xml.getElementsByTagName("nearby");
		for (var i = 0; i < nearbys.length; i++) {
			// Nearby and related results below map
			if (1 == i % 2) {
				var breakImg = document.createElement("img");
				breakImg.className = "mapRelatedDiv";
				breakImg.setAttribute("src", "/a/img/global/mapRelatedDiv.png");
				breakImg.setAttribute("width", 2);
				breakImg.setAttribute("height", 128);
				breakImg.setAttribute("alt", "");
				nearbyPanel.appendChild(breakImg);
			}

			var relItemDiv = document.createElement("div");
			relItemDiv.className = "mapRelatedItems clear";

			var relItemImg = document.createElement("img");
			relItemImg.setAttribute("width", 80);
			relItemImg.setAttribute("height", 80);
			relItemImg.style.width = "80px";
			relItemImg.style.height = "80px";

			relItemImg.setAttribute("alt", nearbys[i].getElementsByTagName("imageAlt")[0].childNodes[0].data);
			relItemImg.setAttribute("src", nearbys[i].getElementsByTagName("image")[0].childNodes[0].data);
			relItemDiv.appendChild(relItemImg);

			var relItemDescDiv = document.createElement("div");
			relItemDescDiv.className = "clear";

			var relItemDescH3 = document.createElement("h3");
			relItemDescH3.appendChild(document.createTextNode(nearbys[i].getElementsByTagName("name")[0].childNodes[0].data));
			relItemDescDiv.appendChild(relItemDescH3);

			var relItemDescP = document.createElement("p");
			nearbyDesc = nearbys[i].getElementsByTagName("description")[0].childNodes[0].data.toString();
			if (nearbyDesc.length > 180) {
				nearbyDesc = nearbyDesc.substr(0, 177) + '...';
			}
			relItemDescP.appendChild(document.createTextNode(nearbyDesc));
			relItemDescDiv.appendChild(relItemDescP);

			var relItemDescMoreLinks = document.createElement("ul");
			relItemDescMoreLinks.className = "moreLinks clear";

			var relItemDescMoreInfoLi = document.createElement("li");

			var relItemDescMoreInfoA = document.createElement("a");
			relItemDescMoreInfoA.appendChild(document.createTextNode("more info ›"));
			relItemDescMoreInfoLi.appendChild(relItemDescMoreInfoA);

			relItemDescMoreLinks.appendChild(relItemDescMoreInfoLi);
			relItemDescDiv.appendChild(relItemDescMoreLinks);
			relItemDiv.appendChild(relItemDescDiv);

			nearbyPanel.appendChild(relItemDiv);
		}

		if (firstShow) {
			$("#gettingToTheHeart").slideUp("slow");
			$("#gettingToToggle").text("show directions");
			$("#nearbyPanel").slideDown("slow");
		}

		return container;
	}
	);

	return container;
}

awm.maps.MyInfoPanel.prototype.getDefaultPosition = function()
{
	return new google.maps.ControlPosition( G_ANCHOR_TOP_RIGHT, new google.maps.Size( 100, 10 ) );
}

awm.maps.MyInfoPanel.clear = function()
{
	$("#info").remove();
}

awm.maps.Curtain = function() {};
awm.maps.Curtain.prototype = new google.maps.Control();

awm.maps.Curtain.prototype.initialize = function( map )
{
	var container = document.createElement( "div" );
	container.id = "mapCurtain";
	
	var img = document.createElement( "img" );
	img.setAttribute( "src", "/a/img/global/mapMedium.gif" );
	img.setAttribute( "width", "874" );
	img.setAttribute( "height", "600" );
	img.setAttribute( "alt", "Regional map visual" );
	container.appendChild( img );
	
	map.getContainer().appendChild( container );
	
	return container;
}

awm.maps.Curtain.prototype.getDefaultPosition = function()
{
	return new google.maps.ControlPosition( G_ANCHOR_TOP_LEFT, new google.maps.Size( 0, 0 ) )
}

