﻿/// <reference path="jquery.js" />

// This is a JSON class for the nokia maps.

var nokiaMap = {
	lat: 0,
	long: 0,
	radius: 0,
	lastLat: 0,
	lastLong: 0,
	lastRadius: 0,
	maxReturned: 100,
	zoomLevel: 0,
	days: 1,
	artistId: "",
	groupId: "",
	useLocalData: false,
	player: null,
	working: false,
	ticks: null,

	refreshMarkers: function() {
		if (this.radius != this.lastRadius || this.getMovement() > ((this.radius * 2) / 3)) {
			var tmpTicks;
			this.ticks = tmpTicks = (new Date()).getTime();
			if (!this.working) {
				nokiaMap.startWorking(tmpTicks, 2);
			}
		}
	},
	getMovement: function() {
		var mapCenter = player.map.getMapCenterPosition();
		var x = 69.1 * (mapCenter.latitude - this.lastLat);
		var y = 69.1 * (mapCenter.longitude - this.lastLong) * Math.cos(this.lastLat / 57.3);
		return Math.sqrt(x * x + y * y);
	},
	startWorking: function(tmpTicks, countdown) {
		if (tmpTicks == this.ticks) {
			if (countdown == 0) {
				$('#refresh').html("Refreshing...");
				this.working = true;
				this.refreshMap();
			} else {
				$('#refresh').html("Refreshing in " + countdown + "... <a href='#' onclick='nokiaMap.refreshMap(); return false;'>Refresh Now</a>");
				setTimeout('nokiaMap.startWorking(' + tmpTicks + ', ' + (countdown - 1) + ')', 1000);
			}
		}
	},
	refreshMap: function() {
		try {
			var mapCenter = player.map.getMapCenterPosition();
			this.lastLat = mapCenter.latitude;
			this.lastLong = mapCenter.longitude;

			this.lastRadius = this.radius;

			var mapBounds = player.map.getBoundingBox();
			var southWest = mapBounds[0];
			var northEast = mapBounds[1];
			RefreshMap(southWest.latitude, northEast.latitude, southWest.longitude, northEast.longitude);
		} catch (err) { }

		var url = "/handlers/webfetch.aspx?getUrl=" + encodeURIComponent('http://lyrics.tunewiki.com/tunewiki/services/getLocal?');
		url += encodeURIComponent("lat=" + this.lastLat + '&long=' + this.lastLong + '&max=' + this.maxReturned + '&radius=' + this.radius + '&device=6' + (this.groupId ? "&groupId=" + this.groupId : ""));
		// Send Request
		$.get(url, this.createLocalMarkers, "XML");
	},
	createLocalMarkers: function(xmlObj) {
		var mapObj = nokiaMap.layer.getMapObjects(true);
		nokiaMap.layer.removeMapObjects(mapObj);
		$(xmlObj).find("mapPoint").each(function() {
			var user = {
				lat: "",
				long: "",
				artistName: "",
				artistId: "",
				songTitle: "",
				groupId: "",
				user: "",
				thumbnail: "",
				city: "",
				region: "",
				country: ""
			};

			user.lat = $(this).find("lat").text();
			user.long = $(this).find("long").text();
			user.artistName = $(this).find("artist").text();
			user.artistId = $(this).find("artist").attr("id");
			user.songTitle = $(this).find("title").text();
			user.groupId = $(this).attr("groupId");
			user.city = $(this).find("city").text();
			user.region = $(this).find("region").text();
			user.country = $(this).find("country").text();
			user.handle = $(this).find("handle").text();
			user.thumbnail = $(this).find("thumbnail").text();
			if (user.handle == "") user.handle = "TuneWiki User"
			if (user.thumbnail == "") user.thumbnail = "http://www.tunewiki.com/wiki/wmp/wImages/avatar_default.png"
			nokiaMap.updateMarker(user);
		});
		$('#refresh').html("<a href='#' onclick='nokiaMap.refreshMap(); return false;'>Refresh Now</a>");
		nokiaMap.working = false;
	},
	updateMarker: function(user) {
		var myMarkers = [{
			type: "marker",
			longitude: user.long,
			latitude: user.lat,
			clickable: true,
			icon: "/images/icons/marker.png",
			infoTitle: "",
			infoDescription: ""
}];

			var markers = nokiaMap.layer.addMapObjects(myMarkers);
			markers[0].setHtmlContent("<table width='200' border='0' cellspacing='1' cellpadding='1'><tr>"
					+ "<td valign='top' align='center' rowspan='4'><img src='" + user.thumbnail + "'></td>"
					+ "<td width='100%' align='left' style='font-size:11px; color: #FF0000;'>" + user.handle + "<td>" +
					"</tr><tr>"
					+ "<td valign='top' style='font-size:11px; color: #000000; height: 30px; text-align:left;'>"
					+ "<b>" + user.songTitle + "</b> by <a href='/lyrics/" + toFriendlyUrl(user.artistName) + "-" + user.artistId + ".aspx' >" + user.artistName + "</a></td>" +
					"</tr><tr>"
					+ "<td valign='top' style='font-size:11px; color: #000000; height: 30px; text-align:left;'>"
					+ user.city + (user.city ? ", " : "") + user.region + (user.region ? ", " : "") + user.country + "</td>" +
					"</tr><tr>"
					+ "<td align='right'><a href='/lyrics/" + toFriendlyUrl(user.artistName) + "/" + toFriendlyUrl(user.songTitle) + "-" + user.groupId + ".aspx' >"
					+ "<img src='/images/ui/button_musicmap.png' border='0'></a>&nbsp;"
					+ "<a href='#' onclick='nokiaMap.showVideo(\"" + user.artistName.split('"').join('\"') + '","' + user.songTitle.split('"').join('\"') + "\"); return false;'>"
					+ "<img src='/images/ui/button_video.png' border='0'></a></td>" +
					"</tr></table>")
		},
		load: function() {
			player = nokiaMapLoader.getPlayer({ jsPlugin: "supported", uiLanguage: "en", token: "f7bad2d2048ff2eb28f473452501d2c6", playerDomId: "map_content", console: false, onInitDone: function() {

				twTopSongs.init({ listFrom: "local" });
				try {
					// Create layer
					nokiaMap.layer = player.map.createLayer({ name: "testLayer" });

					// Set zoom scale and center the map on the middle marker:
					player.map.moveTo({
						latitude: nokiaMap.lat,
						longitude: nokiaMap.long,
						animationMode: "teleport",
						scale: nokiaMap.zoomLevel
					});
					player.map.addEventHandler(nokia.maps.pfw.MapModel.EVENT_MOVE_DONE, function() {
						nokiaMap.setDistance();
						nokiaMap.refreshMarkers();
					});

					nokiaMap.setDistance();
					nokiaMap.refreshMap();
				}
				catch (err) {
					alert(err);
				}
			}
			});
		},
		setDistance: function() {
			var mapBounds = player.map.getBoundingBox();
			var southWest = mapBounds[0];
			var northEast = mapBounds[1];

			// vertical miles
			var y = 69.1 * Math.abs(northEast.latitude - southWest.latitude);
			this.radius = parseInt((y / 2) * 3);
		},
		showVideo: function(artist, title) {
			twVideoPlayer.play(artist, title);
		}
	}

$(function() {
	setTimeout("nokiaMap.load()", 500);
})

function refreshSearch(str) {
	if (str.length < 3) {
		$('#searchResults').html("");
		return true;
	}
	$.get("/handlers/webfetch.aspx?getUrl=" + encodeURIComponent("http://lyrics.tunewiki.com/tunewiki/services/getLocationsXML.php?location=" + str), function(xmlObj) {
		var content = "";
		$(xmlObj).find("location").each(function() {
			content += "<option value=\"";
			content += $(this).find("latitude").text() + "^" + $(this).find("longitude").text();
			content += "\">" + $(this).find("name").text() + "</content>";
		});

		if (content != "") {
			content = "<select style='width: 100%;' id='locations' size='4' onClick='updateLocationText();' onChange='updateLocationText();'>" + content + "</select>"
		}
		$('#searchResults').html(content);
	}, "xml");
	return true;
}
function updateLocationText(type) {
	try {
		if (type == 'search') {
			nokiaMaps.player.map.geoCode($('#txtSearchBar').val(), 1, function(location) {
				nokiaMaps.player.map.moveTo({ longitude: location[0].longitude,
					latitude: location[0].latitude,
					scale: 10000,
					orientation: "north"
				});
				$('#searchResults').html("");
			}, this);
		} else {
			tmpArray = $('#locations').val().split("^");
			nokiaMaps.player.map.moveTo({ longitude: tmpArray[1],
				latitude: tmpArray[0],
				scale: 10000,
				orientation: "north"
			});
			$('#searchResults').html("");
		}
	} catch (err) { }
}
