var map = null;
var geocoderder = null;
var trans = null;
var listener = -1;
var toplists = [];
var countries = [];
var country_poly = [];
var country_poly_xy = [];
var norm_point;
var video_results = null;
var loaded_country_borders = false;
var top_list_names = ['topartists', 'topartists_local', 'toptracks'];
var top_list_labels = ['Top Artists', 'Local', 'Top Tracks'];
var toplist_tabs = [];
var savelatlng;
var savecountry;

Event.observe(window, 'load', loadPage);
Event.observe(window, 'resize', dynamicLayout);

function dynamicLayout() {
	var width = document.viewport.getWidth();
	var height = document.viewport.getHeight();
	if (height < 350)
	{
		height = 350;
	}
	var zoom;
	var center;
	document.getElementById("main").style.height = height - 59 + 'px';
	document.getElementById("sidebar").style.height = height - 59 + 'px';
	document.getElementById("main").style.width = width - 258 + 'px';
	document.getElementById("footer").style.width = width + 'px';
	document.getElementById("header").style.width = width + 'px';
	if (map)
	{
		zoom = map.getZoom();
		center = map.getCenter();		
		map.checkResize();
		map.setCenter(center, zoom);		
	}
}

function loadPage() {
	dynamicLayout();
	loadGMapScript();
}

function loadMap() {
	if (GBrowserIsCompatible()) {
		map = new GMap2(document.getElementById("map"), {draggableCursor: 'crosshair', draggingCursor: 'pointer'});
//		map.addMapType(G_PHYSICAL_MAP);
//		var topRight = new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(10,10));
//		map.addControl(new GMapTypeControl(), topRight);
//		map.disableDragging();
		map.setCenter(new GLatLng(41.086160, 29.043984), 4);
		geocoder = new GClientGeocoder();
		loadCountryBorders();
	}
}

//dynamic GMap loading
function loadGMapScript() {
	var script = document.createElement("script");
	script.setAttribute("src", 
"http://maps.google.com/maps?file=api&v=2.x&key=ABQIAAAAKJ9CJgOTRXTuSQDQtVRFJxS3keRxRrl2S-TA0KXaOlfaRuzAgxRIOAKpGwxk3cjIB8vowzToOPZL2g&c&async=2&callback=loadMap");
	script.setAttribute("type", "text/javascript");
	document.documentElement.firstChild.appendChild(script);
}

function loadCountryBorders() {
	var url = 'scripts/countries.xml';
	new Ajax.Request(url, {
			method: 'get',
			onSuccess: function(transport) {
				if (loaded_country_borders) {
					return;
				}				
				loaded_country_borders = true;
				var xmlDoc = transport.responseXML.documentElement;
				if (xmlDoc == null) {
					xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
					xmlDoc.loadXML(transport.responseText);
				}
				
				var elemcountries = xmlDoc.getElementsByTagName("c");
				var count = 0;
				var i;
				for (i = 0; i < elemcountries.length; ++i) {
					var elempolys = elemcountries[i].getElementsByTagName("p");
					var country = elemcountries[i].getAttribute("n");
					countries[i] = country;
					country_poly[i] = [];
					for (k = 0; k < elempolys.length; ++k)
					{
						country_poly[i][k] = [];
						var elempoints = elempolys[k].getElementsByTagName("o");
						var j;
						for (j = 0; j < elempoints.length; ++j) {
							var latlng = elempoints[j].firstChild.nodeValue.split(",");
							country_poly[i][k][2*j] = latlng[1];
							country_poly[i][k][2*j+1] = latlng[0];
							++count;
						}						
					}					
				}
				countryBordersToPixel();
				
				GEvent.addListener(map, "click", function(overlay,latlng) {
					if (typeof latlng == 'undefined')
					{
						return;
					}
					var point = latLngToXY(latlng.lat(), latlng.lng());
					var i;
					for (i = 0; i < countries.length; ++i)
					{
						for (j = 0; j < country_poly_xy[i].length; ++j)
						{
							var inside = inpoly(country_poly_xy[i][j], point[0], point[1]);
							if (inside)
							{
								map.clearOverlays();
								var n;
								for (n = 0; n < country_poly[i].length; ++n)
								{
									var points = [];
									var k;
									for (k = 0; k < country_poly[i][n].length/2; ++k)
									{
										points[k] = new GLatLng(country_poly[i][n][2*k], country_poly[i][n][2*k+1]);
									}
									var polygon = new GPolygon(points, "#FF4444", 1.0, 0.3, "#FF4444", 0.3);
									map.addOverlay(polygon);									
								}
								showTopList(countries[i], latlng);
								break;
							}							
						}
					}
				});
			}
		}
	);
}

function latLngToXY(lat, lng) {
	var x;
	x = Math.PI * lng / 360.0;
	var radlat = Math.PI * lat / 180.0;
	y = Math.log(Math.tan(radlat) + 1/Math.cos(radlat));
	return [x, y];
}

function countryBordersToPixel() {
	var i,j;
	
	for (i = 0; i < countries.length; ++i)
	{
		country_poly_xy[i] = [];
		for (k = 0; k < country_poly[i].length; ++k)
		{
			country_poly_xy[i][k] = [];
			for (j = 0; j < country_poly[i][k].length/2; ++j)
			{
				var point = latLngToXY(country_poly[i][k][2*j], country_poly[i][k][2*j+1]);
				country_poly_xy[i][k][2*j] = point[0];
				country_poly_xy[i][k][2*j+1] = point[1];
			}			
		}
	}		
}

function showTopList(country, latlng) {
	savelatlng = latlng;
	savecountry = country;
	if (typeof toplists[country] != 'undefined')
	{
		topList(0, 0, country);
		topList(0, 1, country);
		topList(0, 2, country);
		map.openInfoWindowTabsHtml(latlng, toplist_tabs[country], {maxWidth:300});	
	}
	else
	{
		toplists[country] = [];
		toplist_tabs[country] = [];
		downloadTopList(0, country, latlng);
		downloadTopList(1, country, latlng);
		downloadTopList(2, country, latlng);
	}
}

function updateTopList() {
	map.updateInfoWindow(toplist_tabs[savecountry]);
}

function downloadTopList(list, country, latlng) {
	var directory = "";
	if (list == 0 || list == 1) {
		directory = "artists/";
	} else {
		directory = "tracks/";
	}
	var url = 'scripts/' + directory + country + '_' + top_list_names[list] + '.xml';
	new Ajax.Request(url, {
			method: 'get',
			onSuccess: function(transport) {
				toplists[country][list] = transport.responseXML.documentElement;
				if (toplists[country][list] == null) {
					toplists[country][list] = new ActiveXObject("Microsoft.XMLDOM");
					toplists[country][list].loadXML(transport.responseText);
				}
				
				topList(0, list, country);
				map.openInfoWindowTabsHtml(latlng, toplist_tabs[country], {maxWidth:300});
			}
		}
	);
}

function topList(start, list, country) {
	var xmlDoc = toplists[country][list];
	if (xmlDoc == null) {
			return;
	}
	var feed = 'artist';
	if (list == 2)
	{
		feed = 'track';
	}
	var elems = xmlDoc.getElementsByTagName(feed);
	var html;
	if (elems.length == 0) {
		html = xmlDoc.textContent;
		toplist_tabs[country][list] = new GInfoWindowTab(top_list_labels[list], html);
		return;
	}
	var i;
	html = "<div style='width: 300px; min-height:180px;'><h4 style='text-align:center;'>" + country.toUpperCase() + "</h4><br/>";
	html += "<table style='border-spacing:0;'>";
	for (i=start; i < start+4 && i < elems.length; ++i)
	{
		var color = "inherit";
		if (i % 2 == 0)
		{
			html += "<tr style='background-color: #FEE'>";
		}
		var artist_track = elems[i].getAttribute("name");
		var searchkey = artist_track;
		var artist;
		var url;
		if (list == 2) {
			artist = elems[i].getElementsByTagName("artist")[0].getAttribute("name");						
			url = elems[i].getElementsByTagName("url")[1].firstChild.nodeValue;
			searchkey = artist + ' + ' + artist_track;
		}
		else {
			url = elems[i].getElementsByTagName("url")[0].firstChild.nodeValue;			
		}
		var thumbnail = elems[i].getElementsByTagName("thumbnail")[0].firstChild.nodeValue;

		html += "<td style='width:40px; text-align:center;'><h4>" + (i+1) + "</h4></td>";
		html += "<td style='width:60px'><a href='" + url + "'><img src='" + thumbnail + "' width='50'/></a></td>";
		html += "<td style='width:80px; padding-right: 10px; text-align:left;'><a href='javascript:void(0);' onclick='geoSearch(\"" + escape(searchkey) + "\"); return false;'>" + artist_track + "</a>";
		if (list == 2) {
			html += "<h5>(" + artist + ")</h5>";						
		}
		html += "<div style='width:" + (100*elems[i].getAttribute("count")/elems[0].getAttribute("count")) + "%; height:5px; background-color: #CCFF99; font-size:5px;'> </div>";
		html += "<span style='font-size:9px;'>" + elems[i].getAttribute("count") + " plays</span></td>";
		if (i % 2 != 0)
		{
			html += "</tr>";
		}
	}
	html += "</table></div>";
	html += "<div style='float:left;'><a href='http://www.last.fm'><img src='images/audioscrobbler.gif' width='110'/></a></div>";
	html += "<div style='float:right; text-align:right;'>";
	if (start-4 >= 0)
	{
		html += "<a href='javascript:void(0);' onclick='topList(" + (start-4) + "," + list + ",\"" + country + "\"); updateTopList();'>&lt;Prev </a>";		
	}
	if (start+4 < elems.length)
	{
		html += "<a href='javascript:void(0);' onclick='topList(" + (start+4) + "," + list + ",\"" + country + "\"); updateTopList();'>Next&gt;</a>";		
	}
	html += "</div>";
	toplist_tabs[country][list] = new GInfoWindowTab(top_list_labels[list], html);
}

function videoSearch(root) {
	video_results = root;
	var url = video_results.feed.entry[0]['media$group']['media$content'][0].url;
	var title = video_results.feed.entry[0]['media$group']['media$title']['$t'];
	title = title.truncate(35);
	loadVideo(title, url);
	showResults(0);
	document.getElementById("loadinggif").style.visibility = "hidden";	
}

function showResults(start) {
	var elem = document.getElementById("searchresults");
	var html = "";
	var i;
	for (i = start; i < video_results.feed.entry.length && i < start+5; ++i)
	{
		var title = video_results.feed.entry[i]['media$group']['media$title']['$t'];
		title = title.truncate(35);
		html += "<p><a href='javascript:void(0);' onclick='loadVideo(\"" + escape(title) + "\", " + "\"" + video_results.feed.entry[i]['media$group']['media$content'][0].url + "\"); return false;'>" + title + "</a></p>";
	}
	html += "<br/><p style='text-align:center'>";
	for (i = 0; i < video_results.feed.entry.length; i += 5)
	{
		if (i == start)
		{
			html += "<span style='font-size:11px; font-weight:bold; background-color:#99CC55; color:#CC0001'>" + (i/5+1) + "</span>";
		}
		else
		{
			html += "<a style='font-size:11px;' href='javascript:void(0);' onclick='showResults(" + i + ");'> " + (i/5+1) + " </a>";
		}
	}
	if (start+5 < video_results.feed.entry.length)
	{
		html += "<a style='font-size:11px;' href='javascript:void(0);' onclick='showResults(" + (start+5) + ");'> &gt; </a>";		
	}
	html += "</p>";
	elem.innerHTML = html;
}

function loadVideo(title, url) {
	var elem = document.getElementById("video");
	title = unescape(title);
	elem.innerHTML = '<h4 style="text-align:center">' + title + '</h4>' + '<object width="258" hspace="0" vspace="0" style="margin:0; padding:0; border:none;"><param name="movie" value="' + url + '"></param><param name="wmode" value="transparent"></param><embed src="' + url + '&autoplay=1&rel=1" type="application/x-shockwave-flash" wmode="transparent" width="258" height="200" hspace="0" vspace="0" style="margin:0; padding:0; border:none;"></embed></object>';
}

function geoSearch(query) {
	document.getElementById("searchtext").value = unescape(query);
	document.getElementById("loadinggif").style.visibility = "visible";
	var url = "http://gdata.youtube.com/feeds/api/videos?format=5&vq=" + unescape(query) + "&start-index=1&max-results=25&alt=json-in-script&callback=videoSearch";
	var script = document.createElement("script");
	script.setAttribute("src", url);
	script.setAttribute("type", "text/javascript");
	document.documentElement.firstChild.appendChild(script);

//search in amazon widget
	document.getElementById("amzn_search_textfield").value = unescape(query);
	window.nextCallBack["US"][8002][0].goOnClick("US",0);	
}

function inpoly(poly, x, y)
{	
	var i, j;
	var inside = false;
	var npoints = poly.length/2-1;
	for (i = 0, j = npoints-1; i < npoints; j = i++) {
		var xi = poly[2*i];
		var yi = poly[2*i+1];
		var xj = poly[2*j];
		var yj = poly[2*j+1];
		if ((((yi <= y) && (y < yj)) ||
			((yj <= y) && (y < yi))) &&
			(x < (xj - xi) * (y - yi) / (yj - yi) + xi))
		{
			inside = !inside;
		}
	}
	return inside;
}