/* Written by August Li 27 Dec 2008 */

var rssCount = 30;
var isList = false;

var cookie = $.cookie('www.augustli.com');
if (cookie == "list") {
	isList = true;
}

//check for vertical parameter
var param = location.search;
param = param.substr(1);
if (param) {
	var params = param.split("&");
	for(var i=0; i<params.length;i++) {
		var n = params[i].split("=");
		if (n[0] == "view") {
			isList = (n[1] == "list");
		} else if (n[0] == "count") {
			rssCount = n[1];
			if (rssCount > 100) { //max limit
				rssCount = 100;
			}
		}
	}
}

if (isList) {	
	$("div.rss").css("top", "100px").css("left", "370px").css("width", "500px").css("height", "100%").css("display", "block");
	$("div.rss_list").css("top", "120px").css("left", "370px").css("width", "600px").css("height", (rssCount*20)+"px");
	$("div.images").css("top", "470px").css("left", "130px").css("width", "350px").css("height", "250px").css("display", "block");
	$("div.flickr_copyright").css("top", "700px").css("left", "45px").css("width", "350px").css("height", "15px").css("display", "block");	
	$("#view_timeline").wrap("<a class='tooltip' title='View as horizontal timeline' href='index.html?view=time'></a>");
	$.cookie('www.augustli.com', 'list');
} else {
	$("div.rss").css("top", "100px").css("left", "370px").css("width", "500px").css("height", "100%").css("display", "block");
	$("div.flickr_copyright").css("top", "72px").css("left", "740px").css("width", "100%").css("height", "20px").css("display", "block");
	$("div.rss_timeline").css("top", "120px").css("left", "370px").css("width", "100%").css("height", "100%");
	$("div.images").css("top", "20px").css("left", "740px").css("width", "100%").css("height", "60px").css("display", "block");		
	$("#portal").css("overflow", "hidden");
	$("#view_list").wrap("<a class='tooltip' title='View as vertical list' href='index.html?view=list'></a>");
	$.cookie('www.augustli.com', null);
}

function changeSuffix(text, suffix) {
	return text.substring(0, text.length-suffix.length) + suffix;
}

function pad(text, ch, places) {
	while(text.length < places) {
		text = ch + text;
	}
	return text;
}

/* Tooltip code based on code written by Alen Grakalic (http://cssglobe.com), modified for my website */

this.tooltip = function(){
	var xOffset = 10;
	var yOffset = 20;
	$(".tooltip").hover(function(e){
		this.t = this.title;
		this.title = "";
		$("body").append("<p id='tooltip'>"+ this.t +"</p>");
		$("#tooltip")
			.css("top",(e.pageY - xOffset) + "px")
			.css("left",(e.pageX + yOffset) + "px")
			.fadeIn("fast");
    },
	function(){
		this.title = this.t;
		$("#tooltip").remove();
    });
	$(".tooltip").mousemove(function(e){
		$("#tooltip")
			.css("top",(e.pageY - xOffset) + "px")
			.css("left",(e.pageX + yOffset) + "px");
	});
};

this.imagePreview = function(){
	var xOffset = (isList) ? 170 : 20; //for list, image is at bottom
  var yOffset = 30;
	$("a.flickr").hover(function(e){
		this.t = this.title;
		this.title = "";
		var c = (this.t != "") ? "<br/>" + this.t : "";
		$("body").append("<p id='flickr' ><img src='"+ this.rel +"' alt='Preview' />"+ c +"</p>");
		$("#flickr")
		  .css("position", "absolute")
			.css("top",(e.pageY - xOffset) + "px")
			.css("left",(e.pageX + yOffset) + "px")
			.fadeIn("fast");
    },
	function(){
		this.title = this.t;
		$("#flickr").remove();
    });
	$("a.flickr").mousemove(function(e){
		$("#flickr")
		  .css("position", "absolute")
			.css("top",(e.pageY - xOffset) + "px")
			.css("left",(e.pageX + yOffset) + "px");
	});
};

this.rssTooltip = function(){
	var xOffset = 10;
	var yOffset = 20;
	$("a.rss").hover(function(e){
		this.t = this.title;
		this.title = "";
		$("body").append("<p id='rssTooltip'>"+ $("#"+this.rel).text() +"</p>");
		$("#rssTooltip")
			.css("top",(e.pageY - xOffset) + "px")
			.css("left",(e.pageX + yOffset) + "px")
			.fadeIn("fast");
    },
	function(){
		this.title = this.t;
		$("#rssTooltip").remove();
    });
	$("a.rss").mousemove(function(e){
		$("#rssTooltip")
			.css("top",(e.pageY - xOffset) + "px")
			.css("left",(e.pageX + yOffset) + "px");
	});
};

//rss
$.getJSON("http://pipes.yahoo.com/pipes/pipe.run?_id=tKdujB7T3RGgUlr41L3fcQ&_render=json&count="+rssCount+"&_callback=?", function(data){
	var monthNames = [ "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" ];
	var lastItem = data.count - 1;
  var row = 0;
  var maxWidth = 300;
  var topMargin = 50;
  var horizontalSpacing = 20;
  var verticalSpacing = 40;
 	var firstYear = 0; 
 	var firstMonth = 0;  
 	var firstDay = 0;
  var loc = new Array();
  var lastMonth = 0;
  var lastYear = 0;
  $.each(data.value.items, function(i,item){
	  var d = item["y:published"];
	  var day = (d) ? monthNames[d.month-1]+" "+pad(d.day,"0",2) : "";
	  var c = item.title.substring(0, item.title.indexOf(":")).toLowerCase();
	  var icon = "<img border=0 width=15 height=15 src='images/"+c+".png' />";
	  var title = item.title.substring(c.length + 1);
	  if (c != "plurk") { //plurk will not have tooltip since it is same as title
	  	c = "rss";
	  }
    var re = /<img(\s+)(.+?)>/ig; //remove images
	  var desc = item.description.replace(re, " ");
	  if (isList) {
	  	var list_item_text = "<span class='rss_item'><a class='"+c+"' rel='rss"+i+"' href='"+item.link+"'>"+icon+" "+day+title+"</a><span id='rss"+i+"' class='rss_desc'>"+desc+"</span></span>";
	  	$(list_item_text).appendTo('#rss_list');
		} else {				
			if (firstYear == 0) {
				firstYear = d.year;
				firstMonth = d.month;
				firstDay = d.day;
			}
 	  	//draw lines
			if  ((lastMonth > 0 && lastMonth != d.month) || (i == lastItem)) {		
				var x = ((((firstYear-lastYear)*12) + (firstMonth-lastMonth+1)) * horizontalSpacing*31) - ((31-firstDay) * horizontalSpacing) ;
				$("<img style='position : absolute; width: 1px; height: 100%; top: 0px; left : "+x+"px;' src='images/graydot.gif' />").appendTo('#rss_timeline');	
				$("<span style='color: gray; position : absolute; width: 50px; height: 20px; top: 0px; left : "+(x-50)+"px;' src='images/graydot.gif' >"+monthNames[lastMonth-1]+" "+lastYear+"</span>").appendTo('#rss_timeline');
			}
			//draw items
  	  var left = ((((firstYear-d.year)*12) + (firstMonth-d.month)) * horizontalSpacing*31) + ((31 - d.day) * horizontalSpacing) - ((31-firstDay) * horizontalSpacing);
  	  row = loc.length;
  	  if (loc.length > 0) {
  	  	for(var j=0; j<loc.length; j++){
  	  		if (left - loc[j] > 20) {
  	  			row = j;
  	  			break;
  	  		}
  	  	}  	  	
  		} 
  	  var top = topMargin + (row * verticalSpacing);   
			var timeline_item_text = "<a class='"+c+"' rel='rss"+i+"' style='vertical-align:middle; position : absolute; width: "+maxWidth+"px; height: 20px; top: "+top+"px; left : "+left+"px;' href='"+item.link+"'>"+icon+" "+day+" "+title+"</a><span id='rss"+i+"' class='rss_desc'>"+desc+"</span>";
			$(timeline_item_text).appendTo('#rss_timeline');			
			loc[row] = left + (title.length * 5) + 80; //approx width, need to update if font is changed
			lastMonth = d.month;
			lastYear = d.year;
		}
	 	
  });
  rssTooltip();
  $("#rss_loading").css("display", "none");  
  $("#rss_title").html("What August posted recently:");
  if (isList) {
  	$("#rss_list").css("display", "block");  	
  } else {
  	$("#rss_timeline").css("display", "block");
	}
});

//flickr
$.getJSON("http://api.flickr.com/services/feeds/photos_public.gne?id=7526736@N06&lang=en-us&format=json&jsoncallback=?", function(data){
	if (isList) {
		var numPerRow = 4;		
		var row = 0;		
		$.each(data.items, function(i,item){
			if (i < (numPerRow*numPerRow)) {
				var top = ((row % numPerRow) * 55);
				var left = ((i % numPerRow) * 55);
				if (( (i+1) % numPerRow) == 0) {
					row++;
				}
				$("<a class='flickr' id='img"+i+"' title='"+item.title+"' rel='"+changeSuffix(item.media.m,"_m.jpg")+"' href='" + item.link + "'><img border=0 width=50 height=50 src='"+changeSuffix(item.media.m,"_s.jpg")+"'/></a>" ).appendTo("#images");
				$("#img"+i).css("top", top + "px").css("left",left + "px").css("position","absolute").fadeIn();
			}
		});		
	} else {
		$.each(data.items, function(i,item){
				var top = 0;
				var left = (i * 60);
				$("<a class='flickr' id='img"+i+"' title='"+item.title+"' rel='"+changeSuffix(item.media.m,"_m.jpg")+"' href='" + item.link + "'><img border=0 width=50 height=50 src='"+changeSuffix(item.media.m,"_s.jpg")+"'/></a>" ).appendTo("#images");
				$("#img"+i).css("top", top + "px").css("left",left + "px").css("position","absolute").fadeIn();							
		});
	}
	imagePreview();
	$("#flickr_loading").css("display", "none");	
});

// starting the script on page load
$(document).ready(function(){
	//setup tooltip for menu
	tooltip();
	//setup email link
	$('#email_me').each(function(){
			var e = "me/augustli.com".replace('/','@');
			this.href = 'mailto:' + e;
		});
		
	//setup mouse for scrolling
	$("#portal").mousedown(function (event) {
    // attach 3 pieces of data to the #timeline element
    $(this)
      .data('down', true) // a flag indicating the mouse is down
      .data('x', event.clientX) // the current mouse down X coord
      .data('scrollLeft', this.scrollLeft) // the current scroll position
      .data('y', event.clientY) // the current mouse down Y coord
      .data('scrollTop', this.scrollTop);        
    // return false to avoid selecting text and dragging links within the scroll window
    return false;
  }).mouseup(function (event) {
    // on mouse up, cancel the 'down' flag
    $(this).data('down', false);
  }).mousemove(function (event) {
    // if the mouse is down - start the drag effect
    if ($(this).data('down') == true) {
      // this.scrollLeft is the scrollbar caused by the overflowing content
      // the new position is: original scroll position + original mouse down X - new X
      // I'd like to see if anyone can give an example of how to speed up the scroll.
      this.scrollLeft = $(this).data('scrollLeft') + $(this).data('x') - event.clientX;
      this.scrollTop = $(this).data('scrollTop') + $(this).data('y') - event.clientY;      
    }
  }).css({
    //'overflow' : 'hidden', // change to hidden for JS users
    'cursor' : '-moz-grab' // add the grab cursor
  }).mousewheel(function (event, delta) {
    // now attaching the mouse wheel plugin and scroll by the 'delta' which is the
    // movement of the wheel - so we multiple by an arbitrary number.
    this.scrollLeft -= (delta * 30);
  });
		
});

// finally, we want to handle the mouse going out of the browser window and
// it not triggering the mouse up event (because the mouse is still down)
// but it messes up the tracking of the mouse down
$(window).mouseout(function (event) {
  if ($("#portal").data('down')) {
    try {
      // *try* to get the element the mouse left the window by and if
      // we really did leave the window, then cancel the down flag
      if (event.originalTarget.nodeName == 'BODY' || event.originalTarget.nodeName == 'HTML') {
        $("#portal").data('down', false);        
      }                
    } catch (e) {}
  }
});
