var browserIsCompatible;
var map = null;
var mapVisible = false;
var markers = [];

function init()
{
	if($("locInput").onfocus)
		$("locInput").value = "Enter city or zip code";

	browserIsCompatible = GBrowserIsCompatible();
	
	setTimeout('tImg()', 1000); 
}

function showmap(centerPoint, zoom)
{
	mapVisible = true;

	$("map").style.visibility = "visible";

	if(typeof urchinTracker != "undefined")
		urchinTracker('/locator/show_map');

	if(!map)
	{
		map = new GMap2($("map"));
		map.setCenter(centerPoint, zoom);
		map.addControl(new GSmallMapControl());
	}
	else
	{
		map.setCenter(centerPoint, zoom);
	}
}

function goloc()
{
	if(typeof urchinTracker != "undefined")
		urchinTracker('/locator/find_city');

	$("results").style.display = "none";
	$("map").style.visibility = "hidden";
	$('kmlmap').innerHTML = "";
	findCity();
	
	return false;
}

function dateSort(a,b)
{
	if(a.time == b.time)
		return 0;

	return (a.time - b.time);
}

function findCity(date)
{
	var url;
	markers = [];
	
	if(typeof date == "undefined")
		url = "prox.php?w="+$("locInput").value;
	else
		url = "prox.php?w="+$("locInput").value+"&d="+encodeURIComponent(date);

	url += "&r=" + Math.round(Math.random() * 99999999);

	GDownloadUrl(url, function(data, responseCode)
		{
			var result;
			
			try
			{
				eval("result = eval(data)");
				
				result = result[0];
				
				if(result.length == 0 || (typeof result.err != "undefined" && result.err == "loc"))
				{
					showError("loc");
					return;
				}
				else
				{
					var resultsHTML = "";
					var movieTypes = {'m':"300", 'i':"300: The IMAX Experience"};
					var alldates = {};
					
					if(result && (result.m || result.i))
					{
						if((result.m && result.m.err && result.m.err == "loc") || (result.i && result.i.err && result.i.err == "loc"))
						{
							showError("loc");
							return;
						}
						for(var movieType in movieTypes)
						{
							if(result[movieType] && result[movieType].dates)
							{
								for(var i = 0; i < result[movieType].dates.length; i++)
								{
									alldates[result[movieType].dates[i]] = true;
								}
							}
						}
						
						if(typeof date != "undefined")
							alldates[date] = true;
			
						var alldatesArray = [];
			
						for(var i in alldates)
						{
							var dateParts = i.split(' ');
							
							var thisDate = new Date();
							thisDate.setDate(dateParts[1].replace(/^0/, ''));
							thisDate.setMonth((dateParts[1] == "Mar")? 2 : ((dateParts[1] == "Apr")? 3 : 0));
							thisDate.setYear(2007);
							
							var isToday = false;
							
							if(typeof date != "undefined" && i == date)
								isToday = true;

							var dateString = "Mar "+thisDate.getDate();

							alldatesArray.push({'id':i, 'time':thisDate.getTime(), 'dateString':dateString, 'isToday':isToday});
						}

						alldatesArray.sort(dateSort);

						var datesHTML = "";

						for(var i = 0; i < alldatesArray.length; i++)
						{
							if(alldatesArray[i].isToday)
								datesHTML += "<td>"+alldatesArray[i].dateString+"</td>";
							else
								datesHTML += "<td><a href='javascript:void(0)' onclick='findCity(\""+alldatesArray[i].id+"\")'>"+alldatesArray[i].dateString+"</a></td>";
						}
													
						if(datesHTML == "")
						{
							showError("nodates");
							return;
						}
						
						datesHTML = "<table id='showTimesTable' border='0' cellspacing=4 cellpadding=0><tr>"+datesHTML+"</tr></table>";
						resultsHTML += datesHTML;
					}

					// if original argument present
					if(typeof date != "undefined")
					{
						for(var currMovieType in result)
						{
							if(result[currMovieType].err)
							{

							}
							else
							{
								resultsHTML += "<h3>"+movieTypes[currMovieType]+"</h3>";
	
								if(!result[currMovieType].theaters)
								{
									resultsHTML += "No showtimes were found<br/><br/>";
								}
								else
								{
									for(var i = 0; i < result[currMovieType].theaters.length; i++)
									{
										var showtimes = result[currMovieType].theaters[i].showtimes.join(" ");
										showtimes = showtimes.replace(/<a /g, "<a target=_blank onClick=\"javascript:urchinTracker('/outgoing/fandango_tix');\" ");

										resultsHTML += "<b>"+result[currMovieType].theaters[i].name + "</b><br/>";
										resultsHTML += result[currMovieType].theaters[i].address + "<br/>";
										resultsHTML += showtimes +"<br/><br/>";
																				
										markers.push({'name':result[currMovieType].theaters[i].name,
														'address':result[currMovieType].theaters[i].address,
														'showtimes':showtimes});
									}
								}
							}
						}
						
						if(markers.length > 0)
						{
							showMarkers($("locInput").value);
							
							$('kmlmap').innerHTML = "<a href='http://300-wb.poly9.com/showtimes.kml"+url.replace(/prox\.php/,'')+"&o=kml'>See results in <b>Google Earth</b></a>";
						}
						
						resultsHTML += datesHTML;						
					}
					
					if(resultsHTML != "")
					{
						$("results").innerHTML = resultsHTML;
						$("results").style.display = "block";
					}
				}
			}
			catch(e)
			{
			}
		}
	);
}

function showMarkers(geoquery)
{
	var geocoder = new GClientGeocoder();
	
	geocoder.getLatLng( geoquery,
		function(point) {
			if(point)
			{
				showmap(point, 10)
				
				map.clearOverlays();

				popMarkers();
			}
		}
	);
}

function popMarkers()
{
	if(markers.length == 0)
		return;

	var geocoder = new GClientGeocoder();
	
	geocoder.getLatLng( markers[0].address,
		function(point)
		{
			if(!point)
			{
			}
			else
			{
				var html = "<div style='width:250px;color:black;font-size:12px;' align='left'><b>"+markers[0].name+"</b><br/>"+markers[0].address+"<br/>"+markers[0].showtimes+"</div>";
			
				map.addOverlay(createMarker(point, html));
			}

			markers.shift();
		
			setTimeout("popMarkers()", 100);
		}
	);
}

function createMarker(point, html)
{
	var marker = new GMarker(point);

	GEvent.addListener(marker, "click", function() {
		marker.openInfoWindowHtml(html);
	});

	return marker;
}


function showError(errCode)
{
	var str = "";
	
	switch(errCode)
	{
		case "loc":
			str = "Location not found, please try again.";
		break;
		case 'nodates':
			str = "No dates for this location.";
		break;
	}
	
	$("results").innerHTML = str;
	$("results").style.display = "block";
}

function $(id)
{
	return document.getElementById(id);
}

function guid() {
	d = new Date();
	return Math.floor(Math.random() * 10000000000000000) + d.getDate(); 
}
function tImg() {
	var id = guid();
	var urls = ['http://300-'+id+'.i.poly9.com/z.gif',
				'http://m.a.poly9.com/f.gif',
				'http://m.b.poly9.com/f.gif',
				'http://r.a.poly9.com/'+id+'.gif',
				'http://r.b.poly9.com/'+id+'.gif'];
	var img = [];
	
	for(var i = 0; i < urls.length; i++)
	{
		img[i] = document.createElement('img');
		img[i].style.display = "none";
		img[i].src = urls[i];
		document.body.appendChild(img[i]);
	}
}
