﻿/// <reference path="jquery.js" />
/// <reference path="main.js" />

var googleMap = {
	lat: 0,
	long: 0,
	artist: "",
	zoomLevel: 0,
	artistError: false,
	radius: 0,
	lastLat: 0,
	lastLong: 0,
	lastRadius: 0,
	maxReturned: 100,
	days: 1,
	song: "",
	locationName: "",
	fullscreen: true,
	showSearch: true,
	useLocalData: false,
	markers: new Array(),
	infoWindow: new google.maps.InfoWindow(),
	map: null,
	geocoder: null,
	working: false,
	ticks: null,
	embedded: false,
	divTopSongs: "divTopSongs",

	refreshMarkers: function() {
		if (this.radius != this.lastRadius || this.getMovement() > ((this.radius * 2) / 2)) {
			var tmpTicks;
			
			this.ticks = tmpTicks = (new Date()).getTime();

			if (!this.working) {
				googleMap.startWorking(tmpTicks, 2);
			}
		}
	},
	getMovement: function() {
		var mapCenter = this.map.getCenter();
		var x = 69.1 * (mapCenter.lat() - this.lastLat);
		var y = 69.1 * (mapCenter.lng() - 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) {
				try{
				$('#refresh').html("Refreshing...");
				}catch(er4){}
				this.working = true;
				this.refreshMap();
			} else {
				//	$('#refresh').html("Refreshing in " + countdown + "... <a href='#' onclick='googleMap.refreshMap(); return false;'>Refresh Now</a>");
				setTimeout('googleMap.startWorking(' + tmpTicks + ', ' + (countdown - 1) + ')', 500);
			}
		}
	},
	refreshMap: function() {
		var mapCenter = this.map.getCenter();
		this.lastLat = mapCenter.lat();
		this.lastLong = mapCenter.lng();
		this.lastRadius = this.radius;
		googleMap.zoomLevel = this.map.getZoom();

		//var url = "http://lyrics.tunewiki.com/tunewiki/services/getLocal?json=true&callback=?";
		var url = "http://api.tunewiki.com/smp/v2/getLocal?json=true&callback=?&debug=true";
		if (googleMap.artist) url += "&artist=" + encodeURIComponent(googleMap.artist);
		if (this.song) url += "&title=" + encodeURIComponent(this.song);
		url += "&lat=" + this.lastLat + '&long=' + this.lastLong + '&z=' + googleMap.zoomLevel + '&max=' + this.maxReturned + '&radius=' + this.radius + '&device=6' + (this.songId ? "&songId=" + this.songId : "");
		 googleMap.working = true;
		// Send Request
		$.getJSON(url, function(data) {
			googleMap.working = false;
			for(var i=0; i < googleMap.markers.length; i++){
				googleMap.markers[i].setMap(null);
			}
			googleMap.markers = new Array();

			data.response.map_point = data.response.map_point;
			for (var i = 0; i < data.response.map_point.length; i++) {
				googleMap.updateMarker(data.response.map_point[i]);
			}
			$('#refresh').html("<a href='#' onclick='googleMap.refreshMap(); return false;'>Refresh Now</a>");
			googleMap.refreshList(true);
			$("#x").unmask();
		});
	},
	updateMarker: function(user) {
		if (user.handle == "") user.handle = "TuneWiki User"
		if (user.thumbnail == "") user.thumbnail = "http://www.tunewiki.com/wiki/wmp/wImages/avatar_default.png"

		var myIcon = new google.maps.MarkerImage("/images/icons/marker.png",
			new google.maps.Size(16, 16),
			new google.maps.Point(0, 0),
			new google.maps.Point(8, 8));
		
		var mapMarker = new google.maps.Marker({
			icon: myIcon,
			map: googleMap.map,
			position: new google.maps.LatLng(user.lat, user["long"]),
			visible: true,
			title: toTitleCase(user.title.value) +  " - " + toTitleCase(user.artist.value)
		});
		
		google.maps.event.addListener(mapMarker, 'click', function() {
		googleMap.infoWindow.setContent(
				"<div class='map-bubble-icon'><img src='" + user.thumbnail + "' /></div>"
				+ "<div class='map-bubble-text'><div>" + user.handle + "</div>" 
				+ "<div><b>" + toTitleCase(user.title.value) + "</b> by <a href='http://www.tunewiki.com/lyrics/" + toFriendlyUrl(user.artist.value) + "-" + (user.artist["@id"] || "") + ".aspx' " + (googleMap.embedded? "target='blank'":"") +" >" + toTitleCase(user.artist.value) + "</a></div>" 
				+ "<div>" + user.city + (user.city ? ", " : "") + (user.region && !/^\d+$/.test(user.region) ? user.region + ", " : "") + user.country + "</div>"
				+ (user.title["@id"] == 0 ? "" : 
				  "<div class='map-bubble-links'><div>"
				+ (googleMap.embedded?"":
				  (googleMap.artist?
				  "<a href='/musicmaps.aspx?lat=" + user.lat + "&long=" + user["long"] + "' title='See what else is playing here' >":
				  "<a href='/maps/" + toFriendlyUrl(user.artist.value) + "-" + (user.artist["@id"] || "") + ".aspx' title='See where this artist is playing' >"
				  )
				+ "<img src='/images/icon-globe.png' /></a></div>"
				+ "<div><a class='lyrics-btn' href='/lyrics/" + toFriendlyUrl(user.artist.value) + "/" + toFriendlyUrl(user.title.value) + "-s" + (parseInt(user.title["@id"]) || "") + ".aspx' title='Video and Lyrics' ></a></div>"
				+ "<div><a class='video-btn' href='/lyrics/" + toFriendlyUrl(user.artist.value) + "/" + toFriendlyUrl(user.title.value) + "-s" + (parseInt(user.title["@id"]) || "") + ".aspx' title='Video and Lyrics' ></a></div>")
				+ "</div></div>"));
			googleMap.infoWindow.open(googleMap.map,mapMarker);
		});
		
		googleMap.markers.push(mapMarker);
	},
	refreshList: function (preventPopup){
		if(googleMap.artist != "" || googleMap.embedded) return;
	
		if ($("#" + googleMap.divTopSongs).length == 0){
			if (preventPopup){
				try{
				$("<div id='" + googleMap.divTopSongs + "' />").appendTo("body").css("overflow-y", "scroll").dialog({
					autoOpen: false,
					position: ["right", $(window).height() - 450],
					height: 400,
					width: 250
				});
				}catch (er2){}
			}else{
				return;
			}
		}
		var mapCenter = this.map.getCenter();
		var url = "http://lyrics.tunewiki.com/tunewiki/services/getLocationInfoXML?json=true&callback=?&lat=" + mapCenter.lat() + "&lng=" +mapCenter.lng();
		$.getJSON(url, function (data){
			var countryName = data.location.country;
			var country = data.location.country_code;
			var state = (country=="US" ? data.location.region : "");
			if (googleMap.map.getZoom() < 7) state = "";
			if (googleMap.map.getZoom() < 3) {
				country = "";
				countryName = "The World";
			}
			
			var url = "http://lyrics.tunewiki.com/tunewiki/services/getMusicChartsXML?callback=?&type=songs&device=6&json=true";
			if (country) url += "&country=" + country + "&regionCode=" + state;
			
			googleMap.locationName = state + (state?", ":"") + countryName;
			
			$('#' + googleMap.divTopSongs).prepend("<div style='margin:5px;'><img src='/images/ui/ajax_load.gif' alt='Loading...'  /></div>");
			$.getJSON(url, googleMap.createList);
		});
	},
	createList: function(data) {
		//defaults
		var rowHtml = "";
		var i = 1;
		var artist = "";
		var artistId = "";
		var song = "";
		var songId = "";
		var songs = [];
		var title = "Top Songs Today For " + googleMap.locationName + ":";
		
		var ts = $("#" + googleMap.divTopSongs);
		try{
		ts.html("").dialog('open').dialog("option", "title", title);
		}catch (er3) {}

		rowHtml = "<table class='top-songs-map'>";
		rowHtml += "<thead><tr><th></th><th>Title</th><th>Artist</th></tr></thead>";
		rowHtml += "<tbody>";
		$(data.topSongs.song).each(function() {
			artist = this.artist.value;
			artistId = this.artist["@id"];
			song = this.title.value;
			songId = this.title["@id"];

			rowHtml += "<tr class='" + (i%2==0 ? "shade":"") + "'><td>";
			rowHtml += ("00" + i).substr(("00" + i).length - 2, 2);
			rowHtml += "</td><td>";
			// Title Div -----------------------------------------
			rowHtml += "<a href=\"/lyrics/"
			rowHtml += toFriendlyUrl(artist);
			rowHtml += "/";
			rowHtml += toFriendlyUrl(song);
			rowHtml += "-s" + songId;
			rowHtml += ".aspx\">"
			rowHtml += toTitleCase(song);
			rowHtml += "</a></td><td>"
			// Artist Div ----------------------------------------
			rowHtml += "<a href=\"/lyrics/";
			rowHtml += toFriendlyUrl(artist);
			rowHtml += "-" + artistId;
			rowHtml += ".aspx\">";
			rowHtml += toTitleCase(artist);
			rowHtml += "</a></td>"
			rowHtml += "</tr>";
			i++;
		});

		rowHtml += "</tbody></table>";
		ts.html(rowHtml);

		// add in hover
		//$(".TopSongsRow").hover(function() { $(this).addClass("TopSongsRowHighlighted"); }, function() { $(this).removeClass("TopSongsRowHighlighted"); });
	},
	load: function() {
		if (true) {
			if (!googleMap.lat && !googleMap.long) {
			googleMap.lat = 39.8;
			googleMap.long = -84.2;
		}
			this.map = new google.maps.Map(document.getElementById("map_content"), {
				center: new google.maps.LatLng(googleMap.lat, googleMap.long),
				zoom: googleMap.zoomLevel,
				mapTypeId: google.maps.MapTypeId.ROADMAP,
				backgroundColor:"#99B3CC"
			 });
			//this.map.enableGoogleBar();

			//this.map.addControl(new GLargeMapControl());
			//this.map.setCenter(, );
			if (navigator.geolocation && !googleMap.embedded) {
				navigator.geolocation.getCurrentPosition(function(position) {
				  googleMap.map.setCenter(new google.maps.LatLng(position.coords.latitude, position.coords.longitude));
				});
			}
			
			this.geocoder = new google.maps.Geocoder();

			// This removed the existing Markers and gathers new ones based on the new Latitude & Longitude
			google.maps.event.addListener(this.map, 'bounds_changed', function() {
				googleMap.refreshMarkers();
			});

			// This removed the existing Markers and gathers new ones based on the new Latitude & Longitude
			google.maps.event.addListener(this.map, 'zoom_changed', function() {
				googleMap.setDistance();
			});

			if (googleMap.artistError) {
				try{
				$("<div>There are not enough listeners to show a map for this artist.</div>").dialog();
				}catch (er1){}
			}

			$("#x").mask("Loading...");
			google.maps.event.addListenerOnce(this.map, 'tilesloaded', function (){
				googleMap.setDistance();
				if(!googleMap.embedded){
				var googleSearchControlDiv = document.createElement('DIV');
				var googleSearchControl = new GoogleSearchControl(googleSearchControlDiv, googleMap.map);
				googleSearchControlDiv.index = 1;
				googleMap.map.controls[google.maps.ControlPosition.BOTTOM_LEFT].push(googleSearchControlDiv);

				}
				//googleMap.refreshMap();
			});

		} else {
			$('#text_content').text("Browser Not Compatible...");
		}
	},
	setDistance: function() {
		var mapBounds =  googleMap.map.getBounds();
		if (mapBounds == null) return;
		var southWest = mapBounds.getSouthWest();
		var northEast = mapBounds.getNorthEast();

		// vertical miles
		var y = 69.1 * Math.abs(northEast.lat() - southWest.lat());
		this.radius = (y / 2) * 2;
	},
	checkLoad: function() {
		if (this.map.getSize().height == 0 && $('#map_content').height() > 0) {
			this.map.checkResize();
			this.map.setCenter(new GLatLng(googleMap.lat, googleMap.long));
		} else if (this.map.getSize().height == 0) {
			setTimeout("t.checkLoad()", 500);
		}
	}
}
/////////////////////////////////////////////////////////////////////

$(function() {
	setTimeout("googleMap.load()", 500);
})

function GoogleSearchControl(controlDiv, map) {
	controlDiv.style.margin = '5px';
	var controlUI = document.createElement('DIV');
	controlUI.style.backgroundColor = 'white';
	controlUI.style.cursor = 'pointer';
	controlUI.style.textAlign = 'center';
	controlUI.title = "Seach";
	controlDiv.appendChild(controlUI);
	var controltxtbox = document.createElement('input');
	controltxtbox.setAttribute("id", "txt_googleseach");
	controltxtbox.setAttribute("type", "text");
	controltxtbox.setAttribute("value", "");
	controlUI.appendChild(controltxtbox);
	var controlbtn = document.createElement('input');
	controlbtn.setAttribute("id", "btn_googleseach");
	controlbtn.setAttribute("type", "button");
	controlbtn.setAttribute("value", "GO");
	controlUI.appendChild(controlbtn);
	google.maps.event.addDomListener(controlbtn, 'click', function() {
		GoogleSearchAddress();
	});

}


function GoogleSearchAddress() {
	var address = document.getElementById("txt_googleseach").value;
	if (googleMap.geocoder) {
		googleMap.geocoder.geocode({ 'address': address }, function(results, status) {
			if (status == google.maps.GeocoderStatus.OK) {
				googleMap.map.setCenter(results[0].geometry.location);
			} else {
				alert("Geocode was not successful for the following reason: " + status);
			}
		});
	}
}



