/* teaser.js by Daniel Winterstein (c) Winterwell 2010
 */

/* You can edit these variables */

var SECONDS_BETWEEN_TWEETS = 2.5;
var SECONDS_TO_AUTOSTART = 8;
var AUTO_SELECT = "dream";

/* ------------------------------- */

// Hide header
$(function(){$('#header').hide();});

var FOOTER_SPACE = 160;

/**
 * Add in a crude console.log() if FireBug is not present 
 */
var console;
if (console==undefined || ! console) {
	console = new Object();
}
if ( ! console.log) {
	$(document).append("<div id='substitute-console' style='display:none;'></div>");
	console.log = function(obj) {
		var con = document.getElementById('substitute-console');
		if (con) con.innerHTML = con.innerHTML + "<p>"+obj+"</p>";
	};
}

// Make sure we have some content even if Twitter plays up
var tweets = {"dream": 
["Moooorning!! I never remember what I dream, if I dream something...", 
"Love u @engkong666 ^_^RT @worldlifequotes: You're still the one that I love, the only one I dream of & you're ... http://tmi.me/11sUX", 
'@3vanescia i dream the future so i am familiar with that "real" feeling since i stopped dating no more future to dream, just blank', 
"RT @kryswil I dream about you when I sleep... //I know u do.lol.jk.", 
"@eileenwoo yeah i dream of my beer everyday ..", 
"@simonpegg come on now I dream about zombies like 3 times a week......", "i dream of you , ILOVEYOU !", "I dream about you when I sleep...", "SATEEE..to watch you fade away, i dream of you tonight.. *efek laper*", "RT @worldlifequotes: You're still the one that I love, the only one I dream of & you're still the one I want for life #WLQ", "You see things; and you say, 'Why?' But I dream things that never were; and I say, 'Why not?' #MDH", "Every single dream I dream...♥", "lmfao just remebered my dream from last night. why do i dream these strange strange strange things :|", "I stay to watch you fade away, i dream of you tonight, tomorrow you'll be gone #np", "@PinkBety At all times girl, i dream of seeing you. Thats why i asked. Is it me or my eyes!", "I sit behind netbook, and I dream to communicate with people from different countries .... If anything, add me as a friend ...", "RT @worldlifequotes: You're still the one that I love, the only one I dream of & you're still the one I want for life #WLQ", "RT: worldlifequotes, Ur still the 1 that I love, the only 1 I dream of & you're still the 1 I want for life, guess the song @mattjholding!!", "Only as high as I reach can I grow, only as far as I seek can I go, only as deep as I look can I see, only as much as I dream can I be.", "I'm ms sabado gigante b/c I DREAM that Doug Heffernan was real and my friend!", 
'Some men see things as they are and say "why?", I dream things that never were and say "why not?"', 
"come to think my dream was like super what the fuck .I dream of.. something that is impossible and being cheated by friend?", "@BeautBieber i'm sure u do haha! I dream about the weirdest things like wtf lol <3", "RT @worldlifequotes: You're still the one that I love, the only one I dream of & you're still the one I want for life #WLQ", "RT @worldlifequotes: You're still the one that I love, the only one I dream of & you're still the one I want for life #WLQ", "even when i close my eyes, i dream about you all the time. cuz i just wanna have you right here by my side.", "RT @rachmaleiwa: RT @worldlifequotes: You're still the one that I love, the only one I dream of & you're still the one I want for life #WLQ", "RT @worldlifequotes: You're still the one that I love, the only one I dream of & you're still the one I want for life #WLQ", "RT @worldlifequotes: You're still the one that I love, the only one I dream of & you're still the one I want for life #WLQ", "You're still the one that I love, the only one I dream of & you're still the one I want for life #WLQ", "Wow. I dream of the silliest things. And they always feel so real! Last night, I dreamt that Bobby Valentino and I were skiing in France! :s", "I dream of cheese!!! xx http://twitpic.com/2l42cl", "Eh bang eja tau juga hohohoRT @gunawrez: All day i dream about se*RT @annisabijeeey Adidas", 
"RT @worldlifequotes: You're still the one that I love, the only one I dream of & you're still the one I want for life #WLQ", "RT @worldlifequotes: You're still the one that I love, the only one I dream of & you're still the one I want for life #WLQ", "Uh Uh, I dream bad stuff. goodmorning.", "Gombal haha RT @uwabaramuli: RT @worldlifequotes: You're still the one that I love, the only one I dream of & you're still the one I want...", "RT @worldlifequotes: You're still the one that I love, the only one I dream of & you're still the one I want for life #WLQ", "RT @worldlifequotes: You're still the one that I love, the only one I dream of & you're still the one I want for life #WLQ", "RT @worldlifequotes: You're still the one that I love, the only one I dream of & you're still the one I want for life #WLQ", "@vincilam cause i dream about them nearly every night. :D i just can't remember most of them but i know they're awesome. :D haha", "RT @worldlifequotes: You're still the one that I love, the only one I dream of & you're still the one I want for life #WLQ", "I dream of zombies...good schtuff.", "RT @mcfluurryy: RT @worldlifequotes: You're still the one that I love, the only one I dream of & you're still the one I want for life #WLQ", "Waa :(RT @worldlifequotes: You're still the one that I love, the only one I dream of & you're still the one I want for life #WLQ", "RT @worldlifequotes: You're still the one that I love, the only one I dream of & you're still the one I want for life #WLQ", "RT @worldlifequotes: You're still the one that I love, the only one I dream of & you're still the one I want for life #WLQ", "RT @worldlifequotes: You're still the one that I love, the only one I dream of & you're still the one I want for life #WLQ", "RT @worldlifequotes: You're still the one that I love, the only one I dream of & you're still the one I want for life #WLQ", "RT: @worldlifequotes: You're still the one that I love, the only one I dream of & you're still the one I want for life #WLQ", "RT worldlifequotes: You're still the one that I love, the only one I dream of & you're still the one I want for life #WLQ", "RT @worldlifequotes: You're still the one that I love, the only one I dream of & you're still the one I want for life #WLQ", "RT @worldlifequotes: You're still the one that I love, the only one I dream of & you're still the one I want for life #WLQ", "RT @worldlifequotes: You're still the one that I love, the only one I dream of & you're still the one I want for life #WLQ", "RT @lizazs RT @worldlifequotes: You're still the one that I love, the only one I dream of & you're still the one I want for life #WLQ", "RT @worldlifequotes: You're still the one that I love, the only one I dream of & you're still the one I want for life #WLQ", 
"RT @worldlifequotes: You're still the one that I love, the only one I dream of & you're still the one I want for life #WLQ", "RT @worldlifequotes: You're still the one that I love, the only one I dream of & you're still the one I want for life #WLQ", "You're still the one that I love, the only one I dream of & you're still the one I want for life #WLQ", "when i wake up in the morning i think of youwhen i dream at night i dream of you", "RT @ladygaga: Little monsters heart I keep, and as I lay me down to sleep, I dream of rainbow roads to love, for now New York city's my drug", "I dream of a better tomorrow where chickens can cross the road and not have there motives questioned.", "idk why but i dream of @LisaSurihani last night. we were playing kejar-kejar di tepi sawah. damn, i nvr seen sawah bfore!", "@AlexisLovesMe you dont mind if i dream about do you? lol", "I dream of that one dae, wen i reach a thousand tweetz, but im only at 200 this meanz im gonna tweet crap", "step up 3d Is awsm with mind bogling dance moves.:) i dream to Be a part of dance group like pirates.:)", "Do you ever dream an amazing pun then wake to find you can't remember it? (Yes, I dream about puns)", "Everytime ive fallen asleep, i dream its 9...and i have to say goodbye...and i wake myself up crying....", "Normally I talk in my sleep so people know what I dream about! if I did that with this one. Embaressing!", "And that thing i dream about is ...", "Yesterday night, i dream about something really super weird !", "I dream to gp to de pacific ocean", "I'm here without you baby But you're still on my lonely mind I think about you baby And I dream about you all the time @ddlovato", "RT @DavidRoads: You see things & you say, why? But I dream things that never were & I say, why not? -George Bernard Shaw", "Got me paranoid for real to go out. I dream crazy dreams, but one never as gruesome as this. (This dream took place in the 60'/70's era)", "Missing The Man I Love The 1 I Dream About All The Time,The 1 I Always Think About,And The One I Will B With 4 The Rest My Life....I Love U…", "@TerrenceJ106 how did you end up on 106 and park? i dream big", "RT @xTYSHON: RT @BytchThisWEST: It's hard to go ta sleep sometimes wit alot on yo mind thas prolly y I dream so much", "RT @BytchThisWEST: It's hard to go ta sleep sometimes wit alot on yo mind thas prolly y I dream so much", "OMG how can I dream one pussyole boy from brixton dat used to b in my class set me up..he got ppl to run up in my yard -___-", "It's hard to go ta sleep sometimes wit alot on yo mind thas prolly y I dream so much", "Love ya TTYL;) love you luvies I'll be up early!but goodnight and send me sweet dreams please:D but gn HOPE I DREAM ABOUT JUSTIN BIEBER!", "I just wake up from a nap. I have a nightmare (T_T), I dream about i was fighting with a lot of animals in the... http://plurk.com/p/7d0hdq", "i dream that i lost a lot of followers t.t im happy that its not real!", "@Cannelle38 I dream of sunshine and warm, it's so fall here.", "@_karmadorje I dream of it everyday, children around and puppies kitten everywhere :)", "@Eveweezy I recite lines from Dark Knight randomly lol and I dream of havin' Alonzo's '79 Monte Carlo one day. the more I know..(:", "How often do you visit your ship's interiorr / I dream of the day when you can make your own... http://j.mp/aJ7aed #cryptic_dstahl #sto", "I Hope When I Dream, I Dream of You, to Dream that Dream Would Be a Dream Come True", "Playing now♪ Dreams I Dream Of You:Creation", "Some men see things as they are and say, Why ? I dream of things that never were and say, Why not ?? - George Bernard", 
'"I dream of a better tomorrow, where chickens can cross the road & not be questioned about their motives."',
 "RT @thomaskish: Some men see things as they are and say, Why? I dream of things that never were and say, Why not? George Bernard Shaw", "RT @FvckForLove: I think about you, and I dream about you all the time #FFL", 
'I dream, therefore I exist". J. August. Strindberg. Buenos días!', 
"I think about you baby, and I dream about you all the time...", "She laughs at my dreams, but I dream about her laughter.The Click Five", 
'DREAM BIG!!! I dream girl beutiful... I say "wow, whether this real" haha lol. #dreaming'
],

"want":["People think i hate Vampire Sucks because i love twilight, dude because of that i want want to see it!",
"All i want want to do.. Is tell you i love you *shaking bumbum*",
"RT @Jerzakletsyo: i want want @stephenjerzak to go on silent library",
"RT @TeenDoesThat: I DON'T CARE IF IT'S A LONG STORY, I WANT WANT TO KNOW! #TeenDoesThat",
"RT @CiaraMinaj: If Ciara does perform at the VMA's, I want want her on the MAIN STAGE. No Pre-show shit...however, if that's all we can get...so be it"],

"wish":["I wish wish that I could just get away.", "What a beautiful morning. I wish wish I were jumping today.", "sometimes i wish wish i spoke every language in the world", "I wish wish I could meet myself. I think I'd be starstruck you know."]};


function fetchedWant(json) {
	fetched(json, "want");
}
function fetchedWish(json) {
	fetched(json, "wish");
}
function fetchedDream(json) {
	fetched(json, "dream");
}

function fetched(json, word) {
	console.log(json);
	var rs = json["results"];
	var texts = [];
	for(i=0; i<rs.length; i++) {
		texts.push(rs[i].text);		
	}
	console.log("Fetched "+texts.length+" for "+word);
	tweets[word] = texts;
}

var selected = false;
var slidUp = false;
function select(wordSpan) {		
	var w = $(wordSpan).text().toLowerCase();	
	select2(w);
}
function select2(w) {	
	selected = w;
	console.log("Selected "+selected+".");
	if (slidUp) {
		if ( ! msgOn) {msgOn=true; msg();}
		return;
	}
	slidUp = true;
	var h = $('#stream').height();	
	h = h + 90;
	$('#words').animate({"margin-top":"10", "font-size":"50px"}, "slow", "swing", select3);
}
function select3() {
	// in case animate fails
	$('#words').css("margin-top", "10px");
	$('#words').css("font-size", "50px");
	$('#words a').css("margin-left","20px");
	$('#words a').css("margin-right","20px");	
	fixSizes(); 
	msgOn=true; 
	msg();
}

var i=0;
var msgOn = true;

/** Convert urls into links */
function linkify(tweetHtml) {
	tweetHtml = tweetHtml.replace(/(http:\S+[^ \t\r\n\.,\)])/g, "<a href='$1' rel='nofollow' target='_blank'>$1</a>");
	return tweetHtml; 
}

function msg() {
	if ( ! msgOn) return;
	var tws = tweets[selected];
	if ( ! tws) {
		setTimeout("msg();", SECONDS_BETWEEN_TWEETS*1000);
		return;
	}
	if (i >= tws.length) i = 0;
	var tweet = tws[i];
	tweet = linkify(tweet);
	var tweetHtml = "<span class='pre'>"+tweet+"</span>";
	var rgx = new RegExp("I "+selected,"i");
	var m = rgx.exec(tweet);
	if (m) {
		var mi = tweet.indexOf(m);	
		var pre = tweet.substring(0,mi);
		var post = tweet.substring(mi + (""+m).length);
		console.log(m+" "+mi+" "+(""+m).length+": "+post);
		// Don't do a new line for empty, " or '
		if (pre.length > 1) pre = "<span class='pre'>"+pre+"</span><br>";
		else pre = "<span class='pre'>"+pre+"</span>";
		tweetHtml = pre+"<span class='search "+selected+"'>"+m+"</span> <span class='post'>"+post+"</span>";
	}
	$('#stream').prepend("<div class='tweet'>"+tweetHtml+"</div>");
	$('#stream > .tweet:first').slideDown();
	i++; 
	setTimeout("msg();", SECONDS_BETWEEN_TWEETS*1000);
}

function autoSelect() {
	console.log("Auto-Select");
	if (selected) return;
	select2(AUTO_SELECT);
}

/* nice idea but not cross browser compatible
function fetchAll() {
	$("#words > span").each(function(){
		var cb = $(this).text().toLowerCase();
		var q = $(this).attr("search");
		console.log(q);
		if ( ! q) return;
		eval("fetched"+cb+" = function fetched"+cb+"(json) {fetched(json, cb)};");
		document.write("<script type='text/javascript' src='http://search.twitter.com/search.json?q="+q+"&rpp=3&callback=fetched"+cb+"'></script>");
	});
}
*/

function mid() {
	var h = $(window).height() - FOOTER_SPACE - 70;
	var mt = (h - 80)/2;
	$('#words').css('margin-top', mt);
}

function fixSizes() {
	var h = $(window).height();
	var top = $('#stream').offset()["top"];
	h = h - top - FOOTER_SPACE;
	$('#stream').height(h);
	//console.log("stream height: "+h);
}

$(mid);
$(fixSizes);

function pause() {
	msgOn = ! msgOn;
	if (msgOn && selected) msg();
	if (msgOn) $('#paused').fadeOut();
	else $('#paused').fadeIn();
}
function maybePause(event) {
	console.log(event.keyCode); 
	if (event.keyCode==32 || event.keyCode==0) pause();
}
$(document).keypress(maybePause);

// is this a page refresh of a rolling stream?
var url = ""+window.location;
var hi = url.indexOf("#");
if (hi != -1 && hi < url.length-1) {	
	var word = url.substring(hi+1);
	AUTO_SELECT = word;
	$(autoSelect);
} else {
	// auto select dream after 10 seconds
	setTimeout("autoSelect();", SECONDS_TO_AUTOSTART*1000);
}

// reload after 5 minutes
setTimeout("window.location = ''+window.location;", 1000*5*60);

