function createMap(map) {
	map = new GMap2(document.getElementById("map_canvas"));	// Build a map
	map.setCenter(new google.maps.LatLng(37.4419, -122.1419), 2);	// Set to the default center
	map.setMapType(G_HYBRID_MAP);	// Set map type
	map.setUIToDefault();			// Set map UI
	map.mgr = new MarkerManager(map);	// New map manager
	
	return map;
}

// Get a date string like YYYY-MM-DD
function getFeedFormatDate(date) {
	var year = "" + date.getFullYear();
	var month = "" + (date.getMonth() + 1);		// Month is (0-11)
	if (month.length == 1) {
		month = "0" + month;
	}
	
	var day = "" + date.getDate();
	if (day.length == 1) {
		day = "0" + day;
	}
	
	return year + "-" + month + "-" + day;
}

// Parse the xsd date format, return the getTime() val of the date
function parseXsdDate (xsdDate) {
	var re = /(\d{4})\-(\d{2})-(\d{2})T(\d{2})\:(\d{2})\:(\d{2})Z/;
		//     2000   -  09   -  12   T  12    :  12    :  12   Z 
	var date = new Date(xsdDate.replace(re, "$2/$3/$1 $4:$5:$6 GMT"));
	return date;
}

function earthquakeAge (point) {
	now = new Date();
	gap = now - point.dateobj;
	if (gap < 3600000)
		return 0;
	if (gap < 86400000)
		return 1;
	return 2;
}


function createMarker(point) {
	var location = new GLatLng(point.lat, point.lon);
	var marker = new GMarker(location);
	
	// Create Marker Info Window
	GEvent.addListener(marker, "click", function() {
		infoWindow.load(point);
	});
	
	point.marker = marker;
	return marker;
}

function loadEarthquakeFeedOntoMap(map) {
	findInEntry = function(toFind, entry) {
		return $(entry).find(toFind).text()
	}
	
	$.getJSON("/eqfeed.json", function(data) {
		map.points = data
		map.mag = [[],[],[],[],[],[],[],[],[]]
		map.age = [[],[],[]]
		map.markers = []
		var maggroup;
		
		$(map.points).each(function(i, entry) {				
			// Make new marker for point and store to markers for mgr
			entry.dateobj = parseXsdDate(entry.updated);
			entry.date = getFeedFormatDate(entry.dateobj);
			map.markers.push(createMarker(entry));
			
			maggroup = Math.floor(entry.mag);
			if (maggroup < 3)
				maggroup = 3;
			
			map.mag[maggroup].push(entry);
			map.age[earthquakeAge(entry)].push(entry);
		});
		
		map.mgr.addMarkers(map.markers, 2);
		map.mgr.refresh();
		
		for (maggroup = 3; maggroup < 9; maggroup++)
			$("#mag"+maggroup+"amount").text(map.mag[maggroup].length);
		for (var age=0;age<3;age++)
			$("#age"+age+"amount").text(map.age[age].length);

	});
};

twitter = {
	"TWITTER_NOW" : 0,
	"TWITTER_THEN" : 1,
	"TWITTER_RPP" : 5	// Tweets per page
}

// Get URL for a single tweet
twitter.getTweetURL = function(tweet) {
	return "http://twitter.com/" + tweet.from_user + "/statuses/" + tweet.id;
}

// Get HTML for a single tweet
twitter.getTweetHTML = function(tweet) {
	return 	"<li><p class=\"twitter_cont\">" + 
			"<img class=\"twitter_image\" src=\""+ tweet.profile_image_url +"\" />" + 
			"<span class=\"twitter_user\">" + tweet.from_user + "</span><br />" + 
			"<span class=\"twitter_text\">" + tweet.text + "<a href=\"" + twitter.getTweetURL(tweet) +"\">&#8594;</a></span>" +
			"</p>"
			"</li>";
}

// Get HTML for twitter info
twitter.getTwitterInfoHTML = function(tweets) {
	// No tweets found
	if (tweets == "") {
		tweets = "<li>No tweets in this area.</li>";
	}
	
	return tweets;
}

twitter.fetchTwitterToDiv = function(point, time, page, divID) {
	//Generate Feed URL
	var twitterFeedURL = "http://search.twitter.com/search.json?geocode=" + point.lat + "," + point.lon + ",25km" + "&rpp=" + twitter.TWITTER_RPP + "&callback=?&page=" + page;
	if (time == twitter.TWITTER_THEN) {
		twitterFeedURL += "&since=" + point.date + "&until=" + point.date;
	}
	
	//Generate HTML and add to div
	$.getJSON(twitterFeedURL, function(data){
		var tweets = "";
		// Get the first 10 twitters
		$.each(data.results, function(i, result){
			tweets += twitter.getTweetHTML(result);
		});
			
		$(divID).html(twitter.getTwitterInfoHTML(tweets));
		$(divID+"-page_no").val(page);
	});
}

flickr = {
	"FLICKR_BEFORE": 0,
	"FLICKR_AFTER" : 1,
	"FLICKR_RPP" : 6	// flickr images per page
}

// Get URL for a single flickr photo
flickr.getFlickrPhotoURL = function(photoEntry) {
	return "http://farm" + photoEntry.farm + ".static.flickr.com/" + photoEntry.server + "/" + photoEntry.id + "_" + photoEntry.secret + "_s.jpg";
}

flickr.getFlickrPhotoInfoURL = function(photoEntry) {
	return "http://www.flickr.com/photos/" + photoEntry.owner + "/" + photoEntry.id;
}

// Get HTML for a single flickr photo
flickr.getFlickrPhotoHTML = function(photoEntry) {
	return "<li><a href=\"" + flickr.getFlickrPhotoInfoURL(photoEntry) + "\"><img class=\"flickr_photo\" src=\"" + flickr.getFlickrPhotoURL(photoEntry) + "\" /></a></li>\n"
}

// Get HTML for flickr info
flickr.getFlickrInfoHTML = function(photo) {
	if (photo == "")
		photo = "<li>No photo found in this area.</li>"
	
	return photo;
}

flickr.fetchFlickrToDiv = function(point, time, page, divID) {
	// Generate feed url
	var flickrFeedURL = "http://api.flickr.com/services/rest/?method=flickr.photos.search&api_key=fc1f8eb76117cde3cab14202802758f2&lat=" + point.lat + "&lon=" + point.lon + "&radius=25&radius_units=km&per_page=" + flickr.FLICKR_RPP + "&format=json&jsoncallback=?&page=" + page;
	if (time == flickr.FLICKR_BEFORE) {
		flickrFeedURL += "&max_taken_date=" + point.date;
	} else if (time == flickr.FLICKR_AFTER) {
		flickrFeedURL += "&min_taken_date=" + point.date + "&sort=date_taken_asc";
	}
		
	// Generate html and add to div
	$.getJSON(flickrFeedURL, function(data) {
		var flickrPhoto = "";
		
		$.each(data.photos.photo, function(i, photoEntry) {
			flickrPhoto += flickr.getFlickrPhotoHTML(photoEntry);
		});
		
		$(divID).html(flickr.getFlickrInfoHTML(flickrPhoto));
		$(divID+"-page_no").val(page);
	});
}

infoWindow = {
	"window": "#infowindow",
	"mag": "#info_magno",
	"title": "#info_title",
	"location": "#info_location",
	"date": "#info_date",
	"news": "#info_newslist",
	"twitter": "#info_twitterlist",
	"flickr_before": "#info_flickr_before_list",
	"flickr_after": "#info_flickr_after_list",
	"lat": "#info_lat",
	"lon": "#info_lon",
};

infoWindow.show = function() {
	$(infoWindow.window).show();
	load = "<li>Loading...</li>"
	$(infoWindow.news).html(load);
	$(infoWindow.twitter).html(load);
	$(infoWindow.flickr_before).html(load);
	$(infoWindow.flickr_after).html(load);
	
	$("#infowindow h4").next().hide();
	$("#info_news").slideDown();
}

infoWindow.hide = function() {
	$(infoWindow.window).hide();
}

infoWindow.setText = function(id, text) {
	if (id !== undefined)
		$(id).text(text);
}

infoWindow.loadBasic = function(point) {
	infoWindow.setText(infoWindow.mag, point.mag);
	infoWindow.setText(infoWindow.lat, point.lat);
	infoWindow.setText(infoWindow.lon, point.lon);
	infoWindow.setText(infoWindow.date, point.date);
	infoWindow.setText(infoWindow.title, point.title);
}

infoWindow.loadTwitter = function(point) {
	twitter.fetchTwitterToDiv(point, twitter.TWITTER_NOW, 1, infoWindow.twitter);
}

infoWindow.loadFlickr = function(point) {
	flickr.fetchFlickrToDiv(point, flickr.FLICKR_BEFORE, 1, infoWindow.flickr_before);
	flickr.fetchFlickrToDiv(point, flickr.FLICKR_AFTER, 1, infoWindow.flickr_after);
}

infoWindow.loadNews = function(point) {
	var title;
	if (point.address == null)
		title = point.title;
	else
		title = point.address;
	
	var feedURL = "/newsfeed.json?title="+title;

	$.getJSON(feedURL, function(data) {
		var newsHTML = "";
		var i;
		
		for (i=0;i<2;i++) {
			newsHTML += 
				"<li>" + data[i].description + "</li>";
		}
		
		$(infoWindow.news).html(newsHTML);
	})
}

infoWindow.load = function(point) {
	infoWindow.loadBasic(point);
	infoWindow.regPages(point);
	infoWindow.show();
	infoWindow.loadNews(point);
	infoWindow.loadTwitter(point);
	infoWindow.loadFlickr(point);

}

infoWindow.regPages = function(point) {
	$(".pages .page_arrow").click(function() {
		var arrowInfo = $(this).attr("id");		//Get the arrow info "target"_"direction"
		arrowInfo = arrowInfo.split("-");
		var targetID = "#" + arrowInfo[0];
		
		//page change
		var page = parseInt($(targetID + "-page_no").val());
		if (arrowInfo[1] == "prev" && page > 1) {
			page -= 1;
		} else if (arrowInfo[1] == "next") {
			page += 1;
		}
		
		//target
		if (targetID == infoWindow.twitter) {
			twitter.fetchTwitterToDiv(point, twitter.TWITTER_NOW, page, infoWindow.twitter);
		} else if (targetID == infoWindow.flickr_before) {
			flickr.fetchFlickrToDiv(point, flickr.FLICKR_BEFORE, page, infoWindow.flickr_before);
		} else if (targetID == infoWindow.flcikr_after) {
			flickr.fetchFlickrToDiv(point, flickr.FLICKR_AFTER, page, infoWindow.flickr_after);
		}		
	});
}

function loadPointsOntoMap(points, map) {
	var location, marker;

	$.each(points, function(key, point){
		location = new GLatLng(point.lat, point.lon);
		marker = new GMarker(location);
		
		map.mgr.addMarker(marker);
	});
	
	map.mgr.refresh();
}

filter = {
	"mag": [0,1,1,1,1,1,1,1,1],
	"age": [1,1,1]
}

filter.filterMag= function(map, mag) {
	$.each(map.mag[mag], function(i, point){
		if (filter.mag[mag])
			point.marker.hide()
		else
			point.marker.show()
	});
	
	filter.mag[mag] = Math.abs(filter.mag[mag]-1)
}

filter.filterAge= function(map, age) {
	$.each(map.age[age], function(i, point){
		if (filter.age[age])
			point.marker.hide()
		else
			point.marker.show()	
	});
	
	filter.age[age] = Math.abs(filter.age[age]-1);
}

$(document).ready(function() {
	infoWindow.hide();
	var map;
	map = createMap(map);
	loadEarthquakeFeedOntoMap(map);

	$("#infowindow h4").click(function() {
		$("#infowindow h4").next().hide();
		$(this).next().slideDown();
		return false;
	});
	
	$("#magul ul li").click(function() {
		if ($(this).hasClass("unselected"))
			$(this).removeClass("unselected")
		else
			$(this).addClass("unselected")
		id = $(this).attr("id")
		id = parseInt(id[id.length-1]);
		filter.filterMag(map, id);
	}).mouseenter(function() {
		$(this).addClass("hover")
	}).mouseleave(function() {
		$(this).removeClass("hover")
	});
	
	$("#ageul ul li").click(function() {
		if ($(this).hasClass("unselected"))
			$(this).removeClass("unselected")
		else
			$(this).addClass("unselected")
		id = $(this).attr("id")
		id = parseInt(id[id.length-1]);
		filter.filterAge(map, id);
	}).mouseenter(function() {
		$(this).addClass("hover")
	}).mouseleave(function() {
		$(this).removeClass("hover")
	});

});
