/**
 * dblg
 * Copyright (c) 2009 Grant Guthrie
 */
google.load("feeds","1",{"nocss":true});
google.load("jquery","1.3.2");
google.load("swfobject", "2.1");

var oTs,oPs,oVs;

var MOBILE_RSS='http://photocast.me.com/gfguthrie/100081/rss';
var VIDEO_RSS='http://vimeo.com/gfguthrie/videos/rss';

function replaceHtml(el,html){
	var oldEl=typeof el==="string"?$(el).get(0):el;
	/*@cc_on // Pure innerHTML is slightly faster in IE
		oldEl.innerHTML=html;
		return oldEl;
	@*/
	var newEl=oldEl.cloneNode(false);
	newEl.innerHTML=html;
	oldEl.parentNode.replaceChild(newEl,oldEl);
	/* Since we just removed the old element from the DOM, return a reference
	to the new element, which can be used to restore variable references. */
	return newEl;
}

function populateMainlineGrid(VideoResult){
    var aPosts=[];
    var oT,tl,pl,vl;

	if(!VideoResult.error){
		oVs=VideoResult;
	}

    function processTweet(TweetText){
		return TweetText.replace(/((https?|s?ftp|ssh)\:\/\/[^"\s<\>]*[^.,;'">\:\s<\>\)\]\!])/g,function(s1){return s1.link(s1);}).replace(/\B@([_a-z0-9]+)/ig,function(s2){return s2.link('http://twitter.com/'+s2.substring(1));}).replace(/\B#([_a-z0-9]+)/ig,function(s3){return s3.link('http://search.twitter.com/search?q=%23'+s3.substring(1));}).replace(/&/g,'&amp;');
    }

	// standard twitter relative time function
	function relative_time(C){var B=C.split(' ');C=B[1]+' '+B[2]+', '+B[5]+' '+B[3];var A=Date.parse(C);var D=(arguments.length>1)?arguments[1]:new Date();var E=parseInt((D.getTime()-A)/1000,10);E=E+(D.getTimezoneOffset()*60);if(E<60){return 'less than a minute ago';}else{if(E<120){return 'about a minute ago';}else{if(E<(60*60)){return (parseInt(E/60,10)).toString()+' minutes ago';}else{if(E<(120*60)){return 'about an hour ago';}else{if(E<(24*60*60)){return 'about '+(parseInt(E/3600,10)).toString()+' hours ago';}else{if(E<(48*60*60)){return '1 day ago';}else{return (parseInt(E/86400,10)).toString()+' days ago';}}}}}}}

	aPosts.push($('#static1').outer());
	aPosts.push($('#static2').outer());

    for(var i=0,tl=oTs.length;i<tl;i++){
    	oT=oTs[i];

		var sTweetText=oT.text;
		var sProcessedTweetText=processTweet(sTweetText);

		var sReplyToText='';
		var sExtraClass='';

		if(oT.in_reply_to_status_id){
			sReplyToText=' <a href="http://twitter.com/'+oT.in_reply_to_screen_name+'/status/'+oT.in_reply_to_status_id+'">in reply to '+oT.in_reply_to_screen_name+'</a>';
		}

		if(sTweetText.indexOf('#photo')===0){
			if(oPs){
				for(var j=0,pl=oPs.feed.entries.length;j<pl;j++){
					var oP=oPs.feed.entries[j];
					var sTitle=oP.title.replace(/&/g,'&amp;');
					if(sTweetText.indexOf(sTitle)===7){
						sProcessedTweetText='<img src="'+google.feeds.getElementsByTagNameNS(oP.xmlNode,'','enclosure')[0].getAttribute('url')+'" alt="" /><br /><br />'+sTitle;

						sExtraClass=' twocols';
					}
				}
			}
		}

		if(sTweetText.indexOf('#video')===0){
			if(oVs){
				for(var k=0,vl=oVs.feed.entries.length;k<vl;k++){
					var oV=oVs.feed.entries[k];
					var sVTitle=oV.title.replace(/&/g,'&amp;');
					if(sTweetText.indexOf(sVTitle)===7){
						sProcessedTweetText='<object width="430" height="247"><param name="wmode" value="transparent" /><param name="allowfullscreen" value="true" /><param name="allowscriptaccess" value="always" /><param name="movie" value="'+google.feeds.getElementsByTagNameNS(oV.xmlNode,'','enclosure')[0].getAttribute('url')+'&amp;server=vimeo.com&amp;show_title=0&amp;show_byline=0&amp;show_portrait=0&amp;color=537A94&amp;fullscreen=1" /><embed src="'+google.feeds.getElementsByTagNameNS(oV.xmlNode,'','enclosure')[0].getAttribute('url')+'&amp;server=vimeo.com&amp;show_title=0&amp;show_byline=0&amp;show_portrait=0&amp;color=537A94&amp;fullscreen=1" type="application/x-shockwave-flash" wmode="transparent" allowfullscreen="true" allowscriptaccess="always" width="430" height="247"></embed></object><br /><br />'+sVTitle;

						sExtraClass=' twocols';
					}
				}
			}
		}

		if(sTweetText.length>137){
			sExtraClass=' twocols';
		}

		aPosts.push('<div class="eachpost'+sExtraClass+'"><div><div class="content"><p>'+sProcessedTweetText+'</p></div><div class="info"><a href="http://twitter.com/'+oT.user.screen_name+'/statuses/'+oT.id+'">'+relative_time(oT.created_at)+'</a>'+sReplyToText+'</div></div></div>');
    }

	aPosts.push($('#static3').outer());
	aPosts.push($('#static4').outer());

    replaceHtml($('#grid').get(0),aPosts.join(''));

	// when images load, call again
    $('img').bind('load readystatechange',function(e){
        if(this.complete||(this.readyState==='complete'&&e.type==='readystatechange')){
			arrange();
    	}
	});

    arrange();
    
    window.scrollTo(0,1);
}

function getMainlineVideos(PhotoResult){
	if(!PhotoResult.error){
		oPs=PhotoResult;
	}

	var feed=new google.feeds.Feed(VIDEO_RSS);

	feed.setResultFormat(google.feeds.Feed.MIXED_FORMAT);
	feed.load(populateMainlineGrid);
}

function getFeed(Rss,CallbackFn){
	var feed=new google.feeds.Feed(Rss);

	feed.setResultFormat(google.feeds.Feed.MIXED_FORMAT);
	feed.load(CallbackFn);
}

function main(){
	getFeed(MOBILE_RSS,getMainlineVideos);
}

function apiLoaded(){
	jQuery.fn.outer=function(){
		return $('<div>').append(this.eq(0).clone()).html();
	};

	main();
}

function twttrCallback(Ts){
	oTs=Ts;
	google.setOnLoadCallback(apiLoaded);
}
