/*
 tourmappr (Written by Greg Avola (Something More Human))
(C) 2010 Something More Human

*/

$(document).ready(function(){
	
	// hide info headers on load	
	$(".infoHeader").hide();
	
	// Set the Enter Artist Name to Display on Load
	$("#searchTerm").val("Enter artist name...");
	
	// when the button with the id of sumbit is clicked
	$("#submit").click(function (){
		// trigger event of Display Points
		$("#submit").hide();
		if ($("#searchTerm").val() == "" || $("#searchTerm").length == 0 || $("#searchTerm").val() == "Enter artist name...")
		{
			jQuery.facybox("You must enter an Artist!");
		}
		else
		{
			
			displayPoints($("#searchTerm").val());
		}

		return false;
	});
	
});

function addslashes(str) 
{
	str=str.replace(/\\/g,'\\\\');
	str=str.replace(/\'/g,'\\\'');
	str=str.replace(/\"/g,'\\"');
	str=str.replace(/\0/g,'\\0');
	return str;
}

function stripslashes(str) 
{
	str=str.replace(/\\'/g,'\'');
	str=str.replace(/\\"/g,'"');
	str=str.replace(/\\0/g,'\0');
	str=str.replace(/\\\\/g,'\\');
	return str;
}

function createMarker(point, message, map, link, location) 
{
	// create the marker based on the point
	var baseIcon = new GIcon(G_DEFAULT_ICON);
	baseIcon.shadow = "images/markerShadow.png";
	baseIcon.iconSize = new GSize(20, 34);
	baseIcon.shadowSize = new GSize(40, 40);
	baseIcon.iconAnchor = new GPoint(12, 34);
	baseIcon.infoWindowAnchor = new GPoint(9, 2);

	var letter = location + 1;
	
	var letteredIcon = new GIcon(baseIcon);
	letteredIcon.image = "data/dynimg.php?id=" + letter;
	
	markerOptions = { icon:letteredIcon };
	var marker = new GMarker(point, markerOptions);
	GEvent.addListener(marker, "click", function() {
		var myHtml = message;
		// add popup window html text
		
		
		marker.openExtInfoWindow(
		      map,
		      "concertInfoBox",
		      myHtml,
		      {beakOffset: 3}
		    ); 
		
		//map.openInfoWindowHtml(point, myHtml);
		//getTheImage(link, location);
	});

	// return the marker object
	return marker;
}

function getTheImage(link, location)
{
	var args = "url="+link;
	$.ajax({
		url: "data/getbandImage.php",
		type: "GET",
		data: args,
		error: function(html)
		{
			alert("Oops! Something went wrong. Please refer the page and try again.");
		},
		success: function(html)
		{
			$("#band_"+location).html("<img height='49' width='49' src='"+html+"'>");
		}
	});
}


function displayPoints(artist)
{
	
	var map = new GMap2(document.getElementById('map'));
	map.setUIToDefault();	
	directions = new GDirections(map);
	destination_array = new Array();
	content_html = new Array();
	artist_link = new Array();
	artist_location = new Array();
	cities_array = new Array();
	var first_date = new Date();
	var last_date = new Date();
	var country_array = new Array();
	var state_array = new Array();
	var event_date = new Array();
	var google_link = new Array();
	var venue_array = new Array();
	var event_date_raw = new Array();
	var artist_names_array = new Array();
	var event_names_array = new Array();
	var event_id_array = new Array();
	var event_upcoming = new Array();
	var items_array = new Array();
	var destination_array = new Array();
	var dis = "";
	var sho = "";
	var longest_city = "";
	var shortest_city = "";
	var coolness = 0;
	
	$("#locationContents").html("");
	$("#statsContent").html("");
	
	$("#bodyContainer").mask("Searching Concerts");
	
	$.getJSON("data/data.php?id="+escape(artist), function(data)
	{
		if (data.httpCode != 200)
		{
			$("#bodyContainer").unmask();
			$("#submit").show();
			$(".infoHeader").hide();
			map.setCenter(new GLatLng(38, -97), 4);
			if (data.httpCode == 404)
			{
				jQuery.facybox("<div style='padding: 10px; text-align:center; color: #fff;'><p><strong>" + artist + "</strong> is not not currently on tour.</p><br /><p>Please try a different artist.</p></div>");
			}
			else
			{
				jQuery.facybox("<div style='padding: 10px; text-align: center; color: #fff;'><p>An unknown error occured.</p><br /><p>Please refresh the page and try again.</p></div>");			
			}
		}
		else
		{
			if (data.length == 0)
			{
				jQuery.facybox("Nothing was found for the artist you selected. Please try again");
			}
			else
			{
				// for each event loop through the results
				$.each(data.result, function(i, items)
				{
				
				
					if (items.event_name == "" || items.event_name.length == 0)
					{
					
					}
					else
					{
						if (i == 0)
						{
							first_date.setFullYear(items.year, (items.month - 1), items.day);
						}
						var old_lat = $("#lastLatitude").val();
						var old_lon = $("#lastLongitude").val();
						var date_of_event = $("#dateOfEvent").val();
		
						// get the latitude and longitude
						var lat = items.latitude;
						var lon = items.longitude;
						var doc = items.event_date;
						var qin = 3;
						//old_lat == lat || old_lon == lon || doc == date_of_event
						if (qin == 4)
						{
							//alert("In " + i + ' we have a duplicate');
						}
						else
						{
						
							// get the html that will be displayed in the pop-up box on the map.
						
							var id_for_div = "band_"+i;
							var google_maps = "http://maps.google.com" + items.location_link;
							var html = "<div><p id='"+id_for_div+"'><img src='"+items.artist_image+"' height='"+items.image_height+"' width='"+items.image_width+"'></p><ul><li><strong><a href='"+google_maps+"' target='_blank'>" + items.event_name + "</a></strong></li><li>" + items.city + ", " + items.region + "</li><li>" + items.event_date + "</li>";

							if (items.ticket_status == "available")
							{
								html = html + "<li><a href='"+items.ticket_url+"' target='_blank'>Buy Tickets to This Concert!</a></li></div>";
							}
							else
							{
								html = html + "</ul><div style='clear: both;'></div></div>";
							}
							
							
							
							venue_array[coolness] = items.event_name;
							content_html[coolness] = html;
							artist_location[coolness] = i;
							artist_link[coolness] = items.artist_url;
							google_link[coolness] = google_maps;
							event_date[coolness] = items.short_date;
							event_date_raw[coolness] = items.raw_date;
							artist_names_array[coolness] = items.artist_name;
							event_names_array[coolness] = items.event_name;
							event_id_array[coolness] = items.event_id;
							event_upcoming[coolness] = items.upcoming;
						
							var last_lat = $("#lastLatitude").val(lat);
							var last_lon = $("#lastLongitude").val(lon);

							// create the point
							
		
							//alert(items.event_name + " " + i);
							
							point = new GLatLng(lat, lon);
			
							// create the marker, and add it to the map
							map.addOverlay(createMarker(point, html, map, items.artist_url, i));
				
							// store cities and destination
							cities_array[coolness] = items.city + ", " + items.region;
				
							destination_array[coolness] = lat + "," + lon;
						
							// loop the coolness. why? because its cool.
							coolness++;
					
							$("#lastLatitude").val(lat);
							$("#lastLongitude").val(lon);
							$("#dateOfEvent").val(items.event_date);
							last_date.setFullYear(items.year, (items.month - 1), items.day);
						
							if (data.start == "non-us" && (i == data.result.length - 1))
							{
								map.setCenter(point, 4)
							}
						}
					
				
					}
				});
		
				// Used for debugging the CSS
				//qalert("s");
			
				// testing to make sure country and state do not have empty value
				if (data.country == "undefined")
				{
				
				}
				else
				{
					$.each(data.country, function(m, items)
					{
						country_array[m] = items.name;
					});
				}
			
				if (data.state == "undefined")	
				{
				
				}
				else
				{
					$.each(data.state, function(m, items)
					{
						state_array[m] = items.name;
					});
				}
			
				var total_miles = 0;

		
				var size;
				var expand = true;
				
				if (destination_array.length < 5)
				{
					size = destination_array.length;
					expand = false;
				}
				else
				{
					size = 5;
				}

				
				for (var u = 0; u < size; u++)
				{
					if (u == (destination_array.length -1))
					{
						var letter = u+1;
						var coords1 = destination_array[u].split(",");
						var alt_content = addslashes(content_html[u]) + "/~/" + artist_location[u] + "/~/" + artist_link[u];
						var html = '<li><p alt="'+alt_content+'" "><span class="listNumber">' + letter + '</span><a href="#" alt="'+ coords1 + '" class="concertClick"><strong>'+cities_array[u] + '</strong></a><span class="listDate">'+ event_date[u]+'</span></p></li>';
	
						$("#locationContents").append(html);
					
					}
					else
					{
						var coords1 = destination_array[u].split(",");
						var coords2 = destination_array[u+1].split(",");
						var polyline = new GPolyline([
							  new GLatLng(coords1[0], coords1[1]),
							  new GLatLng(coords2[0], coords2[1])
							], "#618451", 5);
							map.addOverlay(polyline);
					
						var point = new GLatLng(coords1[0], coords1[1]);
						var other_point = new GLatLng(coords2[0], coords2[1]);
						var meter = point.distanceFrom(other_point);
						var miles = parseInt(meter) * 0.000621371192;
						var other_u = u+1;
						if (sho == "")
						{
							sho = miles;
						}
						else
						{
							if (miles < sho)
							{
								sho = miles;
								shortest_city = cities_array[u] + ' to ' + cities_array[other_u];
							}
						}
					
						if (dis == "")
						{
							dis = miles;
						}
						else
						{
							if (miles > dis)
							{
								dis = miles;
								longest_city = cities_array[u] + ' to ' + cities_array[other_u];
							}
						}
					
				
					
						var coord1 = coords1[0] + "," + coords1[1];
						var coord2 = coords2[0] + "," + coords2[1];
						total_miles = parseInt(total_miles) + parseInt(miles);
						
				
						
						var letter = u+1;
						var alt_content = addslashes(content_html[u]) + "/~/" + artist_location[u] + "/~/" + artist_link[u];
						var html = '<li><p alt="'+alt_content+'" "><span class="listNumber">' + letter + '</span><a href="#" alt="'+ coords1 + '" class="concertClick"><strong>'+cities_array[u] + '</strong></a><span class="listDate">'+ event_date[u]+'</span></p></li>';
						$("#locationContents").append(html);
					
					}
				
				}
				
				if (destination_array.length >= 8)
				{
					$("#locationContents").append("<div id='locationList' style='display: none;'></div>");
					$("#locationContents").append("<li><a href='#' class='expandList'><span class='seeMore'>See More...</span></a></li>");
					
					for (var u = 5; u < destination_array.length; u++)
					{
						if (u == (destination_array.length -1))
						{
							var letter = u+1;
							var coords1 = destination_array[u].split(",");
							var alt_content = addslashes(content_html[u]) + "/~/" + artist_location[u] + "/~/" + artist_link[u];
							var html = '<li><p alt="'+alt_content+'" "><span class="listNumber">' + letter + '</span><a href="#" alt="'+ coords1 + '" class="concertClick"><strong>'+cities_array[u] + '</strong></a><span class="listDate">'+ event_date[u]+'</span></p></li>';

							$("#locationList").append(html);

						}
						else
						{
							var coords1 = destination_array[u].split(",");
							var coords2 = destination_array[u+1].split(",");
							var polyline = new GPolyline([
								  new GLatLng(coords1[0], coords1[1]),
								  new GLatLng(coords2[0], coords2[1])
								], "#618451", 5);
								map.addOverlay(polyline);

							var point = new GLatLng(coords1[0], coords1[1]);
							var other_point = new GLatLng(coords2[0], coords2[1]);
							var meter = point.distanceFrom(other_point);
							var miles = parseInt(meter) * 0.000621371192;
							var other_u = u+1;
							if (sho == "")
							{
								sho = miles;
							}
							else
							{
								if (miles < sho)
								{
									sho = miles;
									shortest_city = cities_array[u] + ' to ' + cities_array[other_u];
								}
							}

							if (dis == "")
							{
								dis = miles;
							}
							else
							{
								if (miles > dis)
								{
									dis = miles;
									longest_city = cities_array[u] + ' to ' + cities_array[other_u];
								}
							}



							var coord1 = coords1[0] + "," + coords1[1];
							var coord2 = coords2[0] + "," + coords2[1];
							total_miles = parseInt(total_miles) + parseInt(miles);



							var letter = u+1;
							var alt_content = addslashes(content_html[u]) + "/~/" + artist_location[u] + "/~/" + artist_link[u];
							var html = '<li><p alt="'+alt_content+'" "><span class="listNumber">' + letter + '</span><a href="#" alt="'+ coords1 + '" class="concertClick"><strong>'+cities_array[u] + '</strong></a><span class="listDate">'+ event_date[u]+'</span></p></li>';
							$("#locationList").append(html);

						}

					}
				
				}
			
			
				$("#statsContent").append("<li><span><strong>Longest Distance:</strong></span>" + longest_city + " (" + Math.round(dis) + " miles)</li>")
		
					
				$("#statsContent").append("<li><span><strong>Shorest Distance:</strong></span> " + shortest_city + " (" + Math.round(sho) + " miles)</li>")
			
					
				$("#statsContent").append("<li><span><strong>Total Miles:</strong></span> " + Math.round(total_miles) + " miles</li>");
			
				var ny_la = (total_miles) / 2462;
	
				$("#statsContent").append("<li><span><strong>Total trips from NY to LA:</strong></span> " + Math.round(ny_la*1000)/1000 + " x  2462 miles</li>");
			
				var around_the_world = (total_miles) / 24901.55;
			
				$("#statsContent").append("<li><span><strong>Total trips around the world:</strong></span>  " + Math.round(around_the_world*1000)/1000 + " x 24901.55 miles</li>");
			
				var one_day=1000*60*60*24;
			
				$("#statsContent").append("<li><span><strong>First Day on Tour:</strong></span> " + (first_date.getMonth()+1) + "/" + first_date.getDate() + "/" + first_date.getFullYear() + "</li>");
			
				$("#statsContent").append("<li><span></strong>Last Day on Tour: </strong></span>" + (last_date.getMonth()+1) + "/" + last_date.getDate() + "/" + last_date.getFullYear() + "</li>");
			
				var days_total = Math.ceil((last_date.getTime()-first_date.getTime())/(one_day));
			
				$("#statsContent").append("<li><span><strong>Total Days on Tour:</strong></span> " + days_total + " days</li>");
			
				$("#statsContent").append("<li><span><strong>Total Meals Eaten:</strong></span> " + (days_total*3) + " meals </li>");
			
				//$("#statsContent").append("(" + state_array.length + ")");
			
				var stateLine = "";
			
				var length_of_state = state_array.length;
				
				for(var o = 0; o < state_array.length; o++)
				{
					if (o == (state_array.length -1))
					{
						stateLine = stateLine + " " + state_array[o];
					}
					else if (o == 0)
					{
						stateLine = state_array[o] + ", ";
					}
					else
					{
						stateLine = stateLine + " " + state_array[o] + ",";
					}
				
				}
			
				var splural = "";
			
				if (state_array.length > 1)
				{
					splural = "<strong>States";
				}
				else
				{
					splural = "<strong>State";
				}
				
				if (state_array.length =! 0)
				{
					$("#statsContent").append(splural + " Traveled: </strong>(" + length_of_state + ")<li>" + stateLine + "</li>");
				}
			
				var plural = ""
			
				if (country_array.length > 1)
				{
					plural = "<strong>Countries";
				}
				else
				{
					plural = "<strong>Country";
				}
			
				$("#statsContent").append(plural + " Traveled: </strong>(" + country_array.length + ")<br />")
						
				for(var o = 0; o < country_array.length; o++)
				{
					$("#statsContent").append(country_array[o] + "<br />");
				}
			
				$(".concertClick").click(function (){
						$(".concertClick").each(function (){
							$(this).removeClass("active");
						})
						var coord = $(this).attr("alt");
						var coords = coord.split(",");
						$(this).addClass("active");
						var text = stripslashes($(this).parent().attr("alt"));
						var real_items = text.split("/~/");
						point = new GLatLng(coords[0], coords[1]);
						var marker = new GMarker(point);
						map.panTo(point);
					
						marker.openExtInfoWindow(
						      map,
						      "concertInfoBox",
						      real_items[0],
						      {beakOffset: 3}
						    );
						//map.openInfoWindowHtml(point, real_items[0]);
						//getTheImage(real_items[2], real_items[1]);
					
						return false;
				
				});
				
				$(".expandList").click(function(){
					var display = $("#locationList").attr("style");
				
					if (display == "display: block;")
					{
						$(".expandList").html("<span class='seeMore'>See More...</span>");
					}
					else
					{
						$(".expandList").html("<span class='seeLess'>Hide List...</span>");
					}
					
					$("#locationList").slideToggle("slow");	
					
					return false;
				});
				
				if (data.start == "us")
				{
					point = new GLatLng(38, -97);
					map.setCenter(point, 4)
				}
				
				$("#statsContent").append("<p><br /><a href='http://twitter.com?status=I have a cool stat idea for @tourmappr' target='_blank'>Idea for more fun stats?<br />Send us a tweet.</a></p>");
			
				var html = "http://twitter.com?status=I just tracked " + $("#searchTerm").val() + "'s tour on @tourmappr. You can too! http://tourmappr.com/" + data.niceArtist + "&source=tourmappr";
				
				var url = "http://tourmappr.com/" + data.niceArtist;
				var title = "tourmappr | " + $("#searchTerm").val() + " | find out where your favorite artist is going.";
				var body_text = "Now you can track where your favorite artist goes around the world!";
				
				var facebook_url = "http://www.facebook.com/sharer.php?u="+url+"&t="+title;
				
				var digg_url = "http://digg.com/submit?phase=2&url="+url+"&title="+title+"&bodytext="+body_text;
				
				
				//$("#facebookShare").show();
				$("#facebookURL").attr("href", facebook_url);
			
				//$("#diggShare").show();
				$("#diggURL").attr("href", digg_url);
				
				//$("#twitterShare").show();
				$("#twitterURL").attr("href", html);
			
				$("#sharingPane").show();
			
				$("#bodyContainer").unmask();
				$("#submit").show();
				$(".infoHeader").show();
			
			}
		}
	});
	
}
