
//var serverBase = "http://inaugreport.twittervision.com";
var serverBase = "http://inaugurationreport.com";

	//serverBase = "http://inaugurationreport.com/reports/state/DC/page/1.json";

var count = 20;

var jsonURL = "/reports.json?count=" + count + "&state=" + state;


var reports;

var updateInterval = 7000;

var mapkey = "ABQIAAAAYfI_xw3MwUbmAScWsa72VBS3brufayud0K-TNhSZwZ84qkX6QxSEfo58_lVfuS48qB8ez6cDsXmFEw";


function boot (version, width, height, mapWidth, mapHeight)
{
	_width = width;
	_height = height;
	
	if (mapWidth)
		_mapWidth = mapWidth;
		
	if (mapHeight)
		_mapHeight = mapHeight;


	$("#reportBox").load("widget" +version + ".html");

	$("#reportMap").css("width",_mapWidth+"");
	$("#reportMap").css("height",_mapHeight+"");
getReports('');

//setTimeout("refreshReports()",refreshTimer);

//setTimeout("scrollReports()",5000);

setTimeout("displayReports()",updateInterval);
}

function refreshReports()
{
getReports();
setTimeout("refreshReports()",refreshTimer);

}

var offsetTop = 0;

function scrollReports ()
{

if (viewMode == "list")
{

	offsetTop -= 64;


     $("#reportListEntry0").animate({marginTop: offsetTop + "px"}, 1000);
 
 }
 else if (viewMode == "grid")
 {
 	
	document.getElementById("reportListEntry" + offsetTop).style.display = "none";
	
	offsetTop++;
 }
      
setTimeout("scrollReports()",updateInterval);
}

function getReports (newReportType)
{
	//alert("getting reports: " + jsonURL);
	
	
	if (newReportType)
	{
		reportType = newReportType;
		//$("#reportList").html("");
		offsetTop = 0;
	}
			
	var thisJsonUrl = jsonURL;
	
	if (reportType)
	{
		if (reportType == "all")
			reportType = "";
			
		thisJsonUrl += "&type=" + reportType;
	}
	
	
	//console.log("fetching report: " + thisJsonUrl);
	
	 $.getJSON(thisJsonUrl, function(jsonstr) {
	 
	 	reports = eval(jsonstr);
	 	
	 	var markers = "";
	 	
	 	
	 	for (i = 0; i < reports.length; i++)
	 	{
	 		//$("#reportList").append(renderReport(reports[i],i));
	 		
	 		markers += renderLatLon(reports[i]) + ",smallblue%7C";
	 		
	 	}
	 	
	 	currReportIdx = reports.length-1;

		
	
	 	showMapPoints(markers);
	 	
	 });

	
}

var currReportIdx;

function displayReports ()
{
		//alert("displaying report: " + currReportIdx);
		
		if (currReportIdx >= 0)
		{
			
		//console.log("report: " + currReportIdx);
		
		if (viewMode == "list")
		{
		$(".reportDisplayList:first").before(renderReport(reports[currReportIdx],currReportIdx));
		}
		else if (viewMode == "grid")
		{
		$(".reportDisplayIcon:first").before(renderReport(reports[currReportIdx],currReportIdx));
		
		}
		currReportIdx = currReportIdx - 1;
	
	//	$("#reportListEntry0").animate({marginTop: offsetTop + "px"}, 1000);
		
		}
		else
		{
		
			getReports();
		}
		
		setTimeout("displayReports()",5000);
}

function renderLatLon (report)
{
	return report.location.location.point.coordinates[1]
	 + "," + report.location.location.point.coordinates[0];
	 		
	 		
}

function renderReport (report, reportIdx)
{

	if (viewMode == "list")
		return renderReportList (report, reportIdx);
	else
		return renderReportIcon (report, reportIdx);
}

function showReportFull (reportIdx)
{
	report = reports[reportIdx];
	
	$("#reportMapImg").css("display","none");
	
	var display = "<div>";
	
	if (report['class'] == "TextReport")
	{
	display += "<div class=\"hugeText\">" + "<img src=\"" + report.reporter.icon + "\" class=\"reporterIcon\" title=\"click for full info\"/> \"" + report.display_text + "\"</div>";
	
		
	}
	else if (report['class'] == "PhotoReport")
	{
		var imgLink = report.media_url;
		
		if ((!imgLink) || imgLink.length == 0)
			return;
			
		if (imgLink.indexOf("http:\/\/inaugurationreport.comhttp:")==0)
		{
			imgLink = imgLink.substring("http:\/\/inaugurationreport.com".length);
		}
		else if (imgLink.indexOf("http")==-1)
                {
                        imgLink = serverBase + imgLink;
                }

	
		display += "<a href=\"" + imgLink + "\" target=_blank ><img src=\"" + imgLink + "\" class=\"reportPhotoFull\" title=\"" + report.display_text + "\"/></a>";
		
	}
	else if (report['class'] == "AudioReport")
	{
		var audioLink = report.media_url;
		audioLink = serverBase + audioLink.substring(29);
		
		display += "<embed src=\"" + audioLink + "\" height=\"20\" width=\"100\" autostart=\"true\"></embed>";
	}
	else if (report['class'] == "VideoReport")
	{
		
		//var audioLink = report.media_url;
		//display += "<embed src=\"" + audioLink + "\" height=\"" + _mapHeight + "\" width=\"" + _mapWidth + "\" autostart=\"true\"></embed>";
		display += report.display_html;
	}
	
		
	
	display += "<div class=\"reportDisplayName\">" + report.reporter.name + "</div>";
	
	
var datestr = "January " + report.created_at.substring(8,10) + ", 2009 " + report.created_at.substring(11,19) + " GMT";
	//console.log(datestr);
	var thisdate = Date.parse(datestr);
	
	
	display += "<div class=\"reportDisplayTime\">" + dateFormat(thisdate, "dddd, h:MM TT") + "</div>";
	
	display += "<div class=\"reportDisplayAddress\">" + report.location.location.address + "</div>";
	
	display += "</div>";
	
	$("#reportMapContent").html(display);
}

function renderReportIcon (report, reportIdx)
{
	var display;
	
	display =  "<div class=\"reportDisplayIcon\" id=\"reportListEntry" + reportIdx + "\" onclick=\"showMapPoint('" + renderLatLon(report) + "')\" onmouseover=\"showReportFull(" + reportIdx + ")\">";
	
	
	  if (report.reporter.icon.indexOf("http")!=0)
	    	report.reporter.icon = "http://inaugurationreport.com" + report.reporter.icon;
	    	
	var reporterName = report.reporter.name;
	
	if (reporterName && reporterName.length > 8)
		reporterName = reporterName.substring(0,8) + "...";
	else
		reporerName = "unknown";
		
	var thisdate = "today";
	
	if (report.created_at)
		thisdate = Date.parse(report.created_at);
	


	if (report['class'] == "PhotoReport")
	{
		var imgLink = report.media_url;
		
if ((!imgLink) || imgLink.length == 0)
			return;
			
		if (imgLink.indexOf("http:\/\/inaugurationreport.comhttp:")==0)
		{
			imgLink = imgLink.substring("http:\/\/inaugurationreport.com".length);
		}
		else if (imgLink.indexOf("http")==-1)
		{
			imgLink = serverBase + imgLink;
		}

		//display =  "<div class=\"reportDisplayIcon\" style=\"background-image:url('" + imgLink + "')\" onmouseover=\"showMapPoint('" + renderLatLon(report) + "')\" onclick=\"showReportFull(" + reportIdx + ")\">";
	//	display =  "<div class=\"reportDisplayIconSmall\" onmouseover=\"showMapPoint('" + renderLatLon(report) + "')\" onclick=\"showReportFull(" + reportIdx + ")\">";
	
		display += "<img src=\"" + imgLink + "\" title=\"click for full info\"/>";
	
		
	}
	else
	{
	
		display += "<img src=\"" + report.reporter.icon + "\" title=\"click for full info\"/>";
	
	
	
	}

var datestr = "January " + report.created_at.substring(8,10) + ", 2009 " + report.created_at.substring(11,19) + " GMT";
//	console.log(datestr);
	var thisdate = Date.parse(datestr);
	
display += "<div class=\"reportDisplayName\">" + reporterName + "</div>";
	display += "<div class=\"reportDisplayTime\">" + dateFormat(thisdate, "h:MM TT") + "</div>";
	display += "<div class=\"reportDisplayAddress\">(" + report.location.location.administrative_area + ")</div>";
	
	 
	display += "</div>";
	
	return display;
}

function renderReportList (report, reportIdx)
{
	var display;
	display =  "<div class=\"reportDisplayList\" id=\"reportListEntry" + reportIdx + "\" onclick=\"showReportFull(" + reportIdx + ")\">";

	var displayText = report.display_text;
	
	
	  if (report.reporter.icon.indexOf("http")!=0)
	    	report.reporter.icon = "http://inaugurationreport.com" + report.reporter.icon;
	    	
	if (displayText && displayText.length > maxText)
		displayText = displayText.substring(0,maxText) + "...";
		
	if (report['class'] == "TextReport")
	{
		display += "<img src=\"" + report.reporter.icon + "\" title=\"click for full info\" class=\"reporterIcon\"/>";
		display += report.reporter.name + ": ";
		display +=  displayText;
		 
	}
	else if (report['class'] == "PhotoReport")
	{
		var imgLink = report.media_url;
		
		if ((!imgLink) || imgLink.length == 0)
			return;
			
		if (imgLink.indexOf("http:\/\/inaugurationreport.comhttp:")==0)
		{
			imgLink = imgLink.substring("http:\/\/inaugurationreport.com".length);
		}
		else if (imgLink.indexOf("http")==-1)
                {
                        imgLink = serverBase + imgLink;
                }

		
		
		display += "<img src=\"" + imgLink + "\" title=\"click for full info\" class=\"reporterIcon\"/>";
		
		if (report.reporter.name)
		{
		display += "<div class=\"reportDisplayName\">" + report.reporter.name + ": </div>";
		}
		
		display += displayText;
		
	}
	else if (report['class'] == "AudioReport")
	{
	
		display += "<img src=\"" + report.reporter.icon + "\" title=\"click for full info\" class=\"reporterIcon\"/>";
		display += "<div class=\"reportDisplayName\">" + report.reporter.name + ": </div>";
		var audioLink = report.media_url;
	
		
		display += "<a href=\"#\">[ play audio ]</a>";
	}
	else if (report['class'] == "VideoReport")
	{
	
		display += "<img src=\"" + report.reporter.icon + "\" title=\"click for full info\" class=\"reporterIcon\"/>";
		display += "<div class=\"reportDisplayName\">" + report.reporter.name + ": </div>";
		var audioLink = report.media_url;
	
		
		display += "<a href=\"#\">[ play video ]</a>";
	}
	
	display += "<div class=\"reportDisplayMeta\">";
	//report.created_at.substring(0,10) + "
	var datestr = "January " + report.created_at.substring(8,10) + ", 2009 " + report.created_at.substring(11,19) + " GMT";
//	console.log(datestr);
	var thisdate = Date.parse(datestr);
	
	display += "<div class=\"reportDisplayTime\">" + dateFormat(thisdate, "ddd, h:MM TT") + "</div>";
	
	display += "<div class=\"reportDisplayAddress\">" + report.location.location.address + " <a href=\"javascript:return;\" onmouseover=\"showMapPoint('" + renderLatLon(report) + "')\" >[map]</a></div>";
	 
	display += "</div>";
	display += "</div>";
	
	return display;
}

function parseReportsJSON () {
    $.getJSON("http://inaugreport.twittervision.com/reports.json", function(json) {

        /* Parse JSON objects */

        jJSON["isPermaLink"] = (function() {
            response = {
                values: [],
                count: 0
            };
            $.each(json.channel.items,function(i,item) {
                if (item.guid.isPermaLink != "undefined") {
                    response.count++;
                    response.values[i] = item.guid.isPermaLink;
                }
            });
            return response;
        })();

        jJSON["title"] = (function() {
            response = {
                values: [],
                count: 0
            };
            $.each(json.channel.items,function(i,item) {
                if (item.title != "undefined") {
                    response.count++;
                    response.values[i] = item.title;
                }
            });
            return response;
        })();

        /* Return a number of values for a given object */

        alert( jJSON.getValues("title",null) );

        /* Return a count for a given object */

        alert( jJSON.getCount("isPermaLink") );

        /* Return a number of randomized values for a given object */

        alert( jJSON.getRandomValues("title",null) );

    });
}

var lastlatlon;


function showMapPoint(latlon,width,height,zoom)
{


if (!width)
	width = _mapWidth;
	
if (!height)
	height = _mapHeight;

if (!zoom)
	zoom = 15;
	
var newmapurl="http://maps.google.com/staticmap?zoom=" + zoom + "&markers=" + latlon + ",smallblue&size=" + width + "x" + height +"&key=" + mapkey;

$("#reportMapContent").html("");

	$("#reportMapImg").css("display","block");

	$("#reportMapImg").attr('src',newmapurl);

	lastlatlon = latlon;
}

var lastPointList;

function showMapPoints (pointList,width,height)
{


if (!pointList)
	pointList= lastPointList;
	
if (!width)
	width = _mapWidth;
	
if (!height)
	height = _mapHeight;


var mainmapurl = "http://maps.google.com/staticmap?markers=" + pointList + "&size=" + width + "x" + height +"&key=" + mapkey;

$("#reportMapContent").html("");

	$("#reportMapImg").css("display","block");

	$("#reportMapImg").attr('src',mainmapurl);

lastPointList = pointList;


}



/*
 * Date Format 1.2.2
 * (c) 2007-2008 Steven Levithan <stevenlevithan.com>
 * MIT license
 * Includes enhancements by Scott Trenda <scott.trenda.net> and Kris Kowal <cixar.com/~kris.kowal/>
 *
 * Accepts a date, a mask, or a date and a mask.
 * Returns a formatted version of the given date.
 * The date defaults to the current date/time.
 * The mask defaults to dateFormat.masks.default.
 */
var dateFormat = function () {
	var	token = /d{1,4}|m{1,4}|yy(?:yy)?|([HhMsTt])\1?|[LloSZ]|"[^"]*"|'[^']*'/g,
		timezone = /\b(?:[PMCEA][SDP]T|(?:Pacific|Mountain|Central|Eastern|Atlantic) (?:Standard|Daylight|Prevailing) Time|(?:GMT|UTC)(?:[-+]\d{4})?)\b/g,
		timezoneClip = /[^-+\dA-Z]/g,
		pad = function (val, len) {
			val = String(val);
			len = len || 2;
			while (val.length < len) val = "0" + val;
			return val;
		};

	// Regexes and supporting functions are cached through closure
	return function (date, mask, utc) {
		var dF = dateFormat;

		// You can't provide utc if you skip other args (use the "UTC:" mask prefix)
		if (arguments.length == 1 && (typeof date == "string" || date instanceof String) && !/\d/.test(date)) {
			mask = date;
			date = undefined;
		}

		// Passing date through Date applies Date.parse, if necessary
		date = date ? new Date(date) : new Date();
		if (isNaN(date)) throw new SyntaxError("invalid date");

		mask = String(dF.masks[mask] || mask || dF.masks["default"]);

		// Allow setting the utc argument via the mask
		if (mask.slice(0, 4) == "UTC:") {
			mask = mask.slice(4);
			utc = true;
		}

		var	_ = utc ? "getUTC" : "get",
			d = date[_ + "Date"](),
			D = date[_ + "Day"](),
			m = date[_ + "Month"](),
			y = date[_ + "FullYear"](),
			H = date[_ + "Hours"](),
			M = date[_ + "Minutes"](),
			s = date[_ + "Seconds"](),
			L = date[_ + "Milliseconds"](),
			o = utc ? 0 : date.getTimezoneOffset(),
			flags = {
				d:    d,
				dd:   pad(d),
				ddd:  dF.i18n.dayNames[D],
				dddd: dF.i18n.dayNames[D + 7],
				m:    m + 1,
				mm:   pad(m + 1),
				mmm:  dF.i18n.monthNames[m],
				mmmm: dF.i18n.monthNames[m + 12],
				yy:   String(y).slice(2),
				yyyy: y,
				h:    H % 12 || 12,
				hh:   pad(H % 12 || 12),
				H:    H,
				HH:   pad(H),
				M:    M,
				MM:   pad(M),
				s:    s,
				ss:   pad(s),
				l:    pad(L, 3),
				L:    pad(L > 99 ? Math.round(L / 10) : L),
				t:    H < 12 ? "a"  : "p",
				tt:   H < 12 ? "am" : "pm",
				T:    H < 12 ? "A"  : "P",
				TT:   H < 12 ? "AM" : "PM",
				Z:    utc ? "UTC" : (String(date).match(timezone) || [""]).pop().replace(timezoneClip, ""),
				o:    (o > 0 ? "-" : "+") + pad(Math.floor(Math.abs(o) / 60) * 100 + Math.abs(o) % 60, 4),
				S:    ["th", "st", "nd", "rd"][d % 10 > 3 ? 0 : (d % 100 - d % 10 != 10) * d % 10]
			};

		return mask.replace(token, function ($0) {
			return $0 in flags ? flags[$0] : $0.slice(1, $0.length - 1);
		});
	};
}();

// Some common format strings
dateFormat.masks = {
	"default":      "ddd mmm dd yyyy HH:MM:ss",
	shortDate:      "m/d/yy",
	mediumDate:     "mmm d, yyyy",
	longDate:       "mmmm d, yyyy",
	fullDate:       "dddd, mmmm d, yyyy",
	shortTime:      "h:MM TT",
	mediumTime:     "h:MM:ss TT",
	longTime:       "h:MM:ss TT Z",
	isoDate:        "yyyy-mm-dd",
	isoTime:        "HH:MM:ss",
	isoDateTime:    "yyyy-mm-dd'T'HH:MM:ss",
	isoUtcDateTime: "UTC:yyyy-mm-dd'T'HH:MM:ss'Z'"
};

// Internationalization strings
dateFormat.i18n = {
	dayNames: [
		"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat",
		"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"
	],
	monthNames: [
		"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
		"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"
	]
};

// For convenience...
Date.prototype.format = function (mask, utc) {
	return dateFormat(this, mask, utc);
};

function setState (new_state)
{
	state = new_state;

	jsonURL = "/reports.json?count=20&state=" + state;
	
	getReports();
}

function setView (new_view)
{
	viewMode = new_view;
	offsetTop = 0;
	
	if (viewMode == "list")
		{
		$(".reportDisplayIcon:first").before("<div class=reportDisplayList></div>");
		}
		else if (viewMode == "grid")
		{
		$(".reportDisplayList:first").before("<div class=reportDisplayIcon></div>");
		
		}
	
	//getReports();
}

	boot(_widgetVersion);

