var ytplayer;



Effect.DocumentScroll = Class.create();
Object.extend(Object.extend(Effect.DocumentScroll.prototype, Effect.Base.prototype), {
  initialize: function(element) {
		this.element = element;
		
    var options = Object.extend({
      x:    0,
      y:    Position.cumulativeOffset($(element))[1],
			yOffset:0,
      mode: 'absolute'
    } , arguments[1] || {}  );
    this.start(options);
  },
  setup: function() {
    if (this.options.continuous && !this.element._ext ) {
      this.element.cleanWhitespace();
      this.element._ext=true;
      this.element.appendChild(this.element.firstChild);
    }
		
    this.originalLeft = document.body.scrollLeft;
    this.originalTop = document.body.scrollTop;
		
		//alert(window.pageYOffset)
		
    if(this.options.mode == 'absolute') {
      this.options.x -= this.originalLeft;
      this.options.y -= this.originalTop;
    } else {
			
    }
  },
  update: function(position) {   

    var y  = this.options.y * position + this.originalTop; //- this.options.yOffset;
		window.scrollTo(0,y);

  }
});

var currentlyPlaying = -1;
var currentlyPlayingId;

var urls = [];

var fTweets = [];

function previousVideo() {
	if(currentlyPlaying > 0)
		loadNewVideo(currentlyPlaying-1);	
}
function nextVideo() {
	loadNewVideo(currentlyPlaying+1);
}

function togglePlay() {
	if(fState == 1) {
		ytplayer.pauseVideo();
	} else {
		ytplayer.playVideo();
	}
}





function showLoader() {
	$('loader').show();
}
function hideLoader() {
	$('loader').hide();	
}




function getVideo(pIdx) {
	return urls[pIdx];
}


function loadPlayerFirstTime(pId) {
	var dims = {};
	dims.w = '100%';
	dims.h='100%';
	var params = { allowScriptAccess: "always", bgcolor: "#cccccc", allowfullscreen: "true", wmode:'transparent' };
	var atts = { id: "mtplayer" };
	swfobject.embedSWF("http://www.youtube.com/v/"+pId+"?border=0&amp;showsearch=0&amp;showinfo=0&amp;hd=1&amp;enablejsapi=1&amp;playerapiid=ytplayer&fs=1&amp;rel=0", "mtplayer", dims.w, dims.h, "8", null, null, params, atts);		
}

function onYouTubePlayerReady(playerId) {
	
  ytplayer = document.getElementById("mtplayer");
  ytplayer.addEventListener("onStateChange", "onytplayerStateChange");
  ytplayer.addEventListener("onError", "onPlayerError");
}

var fState;

function onytplayerStateChange(newState) {
	fState = newState;
	
	if(fState == 1) {
		$('playpause').src = '/images/pause.png';
	} else if(fState == 5 || fState == 2) {
		$('playpause').src = '/images/play.png';
	}
	
	if(newState == 0) 
		loadNextVideo();
}

function onPlayerError(errorCode) {
 	//loadNewVideo(currentlyPlaying);
}

function loadNextVideo() {
	loadVideo(fTweets[currentlyPlaying + 1].vid);
}



function loadVideo(id) {
	if(!ytplayer) {
		loadPlayerFirstTime(id);
		getTweetHolder(id).addClassName('playing');
	}
	
	loadVideoInfo(id);
	
	
	if (ytplayer) {
		if(getTweetHolder(currentlyPlayingId))
			getTweetHolder(currentlyPlayingId).removeClassName('playing');
			
		ytplayer.loadVideoById(id, parseInt(0));
		getTweetHolder(id).addClassName('playing');
	}
	
	
	var i = 0;
	for(var k = 0; k < fTweets.length; k++) {
		var lTweet = fTweets[k];	
		if(id == lTweet.vid) {
			currentlyPlaying = i;
			break;
		}
		i++;
	}
	currentlyPlayingId = id;
}

function loadVideoInfo(pId) {
	var lUrl = '/videos/' + pId + '/info';
	new Ajax.Request(lUrl, {asynchronous:true, evalScripts:true, onComplete:function(request){}, parameters:'authenticity_token=' + encodeURIComponent('fsy5YMv2XoXHKvMhhsPxCfWSQdzS+oSK6syICKH1ER4=')});

}

function getTweetHolder(id) {
	return $('tweet-' + id);
}

function showRetweetForm(pTweetId, pText) {
	
	//pTweet = pTweet.video_tweet;
	$('retweet-id').value = pTweetId; // pTweet.twitter_id;
	$('retweet-text').value = pText;
	limitText($("retweet-text"), $("retweet-count"), 140);
	$('retweet-div').show();
	$('retweet-loading').hide();
	
	
	$('retweet-form').oldtext.value = pTweet.text;
	$('retweet-form').thumbnail.value = pTweet.thumbnail;
	$('retweet-form').screen_name.value = pTweet.screen_name;
	$('retweet-form').twitter_created_at.value = pTweet.twitter_created_at;
	

	$('retweet-form').show();
	
}

function setFormLoader(pForm, pLoader) {
	
	pForm.hide();
	pLoader.show();

}



function showLoader() {
	$('loader').show();
}


function hideLoader() {
	$('loader').hide();
}



function setTweets(pTweets) {
	fTweets = pTweets;
}


function getIndex(pTweet) {
	for(var i = 0; i < fTweets.length; i++) {
		if(fTweets[i].twitter_id == pTweet.twitter_id) return i;
	}
	return -1;
}


function addTweetAtIndex(pObj, pIndex) {
	
	for(var i = fTweets.length; i >= pIndex; i--) {
		fTweets[i] = fTweets[i-1];
	}
	
	fTweets[pIndex] = pObj;
}

function getTweetIndex(pTweet) {
	var i = 0;
	for(i = 0; i < fTweets.length; i++) {
		if(pTweet.twitter_id >= fTweets[i].twitter_id) return i;
	}
	return i;
}

function addTweet(pTweet, pHtml) {
	pTweet = pTweet.video_tweet;
	var lAllready = getIndex(pTweet);
	if( lAllready != -1)
		return;
	
	


	var lIndex = getTweetIndex(pTweet);
	addTweetAtIndex(pTweet, lIndex);

	
	lIndex = getTweetIndex(pTweet) ;

	
	
	

	if(lIndex == 0) {
		$('tweets').insert({top: pHtml});
	} else if(lIndex + 1 == fTweets.length) {
		$('tweets').insert({bottom: pHtml});
	} else {
		var lElement = getTweetHolder(fTweets[lIndex-1].vid);
		lElement.insert({after:pHtml});
	}
	
	getTweetHolder(pTweet.vid).appear();

}



function getMaxTwitterId() {
	var lMaxId = -1;
	
	for(var i = 0; i < fTweets.length; i++) {
		var lTweet = fTweets[i];
		lMaxId = lMaxId == -1 || lMaxId < lTweet.twitter_id ? lTweet.twitter_id : lMaxId;
	}
	return lMaxId;
}

function getMinTwitterId() {
	var lMinId = -1;

	for(var i = 0; i < fTweets.length; i++) {
		var lTweet = fTweets[i];
		lMinId = lMinId == -1 || lMinId > lTweet.twitter_id ? lTweet.twitter_id : lMinId;
	}
	return lMinId;
}

function pollForTweets() {
	var lUrl = '/videos/my';
	var lVars = {}
	var lMinId = getMinTwitterId();
	var lMaxId = getMaxTwitterId();
	
	
	
	if(lMinId != -1)
		lVars["min_id"] = lMinId;
	
	if(lMaxId != -1)
		lVars["max_id"] = lMaxId;

	var lFirst = true;
	for(var lK in lVars) {
		if(lFirst) {
			lUrl += "?";
			lFirst = false;
		} else {
			lUrl += "&";
		}
		lUrl += lK + "=" + lVars[lK]
	}
	
	new Ajax.Request(lUrl, {asynchronous:true, evalScripts:true, onComplete:function(request){setPollTimeout();}, parameters:'authenticity_token=' + encodeURIComponent('fsy5YMv2XoXHKvMhhsPxCfWSQdzS+oSK6syICKH1ER4=')});

}

function pollForPublicTweets() {
	showLoader();
	new Ajax.Request('/videos/public?q=' + fSearchTerm, {asynchronous:true, evalScripts:true, onComplete:function(request){hideLoader();}, parameters:'authenticity_token=' + encodeURIComponent('fsy5YMv2XoXHKvMhhsPxCfWSQdzS+oSK6syICKH1ER4=')});
}


function searchTrends(pTrend) {
	clearList();
	fSearchTerm = pTrend;
	pollForPublicTweets();
}



// can be 1 or 2, 1 if it's doing a job, 2 if it's not
var POLLING = 1;
var NOT_POLLING = 2;
var fPollMode = 2;

function setPollMode(pPollMode) {
	if(pPollMode == NOT_POLLING) {
		hideLoader();
	} else {
		showLoader();
	}
	fPollMode = pPollMode;
}

function setPollTimeout() {
	var	lPollTimeout = fPollMode == POLLING ? 4000 : 30000;
	setTimeout("pollForTweets()", lPollTimeout);
}

function clearList() {
	$('tweets').update('');
	fTweets = [];
}


function loadFirst() {
	if(fTweets[0] != undefined && currentlyPlaying == -1)
	 loadVideo(fTweets[0].vid);
}

function limitText(limitField, limitCount, limitNum) {
	if (limitField.value.length > limitNum) {
		limitField.value = limitField.value.substring(0, limitNum);
	} else {
		limitCount.value = limitNum - limitField.value.length;
	}
}

var fPage = 1;
function loadMore() {
	var lUrl = '/videos/public.js?more=1';
	lUrl += "&page=" + fPage;
	lUrl += "&q=" + fSearchTerm;
	showLoader();
	new Ajax.Request(lUrl, {asynchronous:true, evalScripts:true, parameters:'authenticity_token=' + encodeURIComponent('Bjnt1/ZOcH14bq9KcYkn7UIaN/UbNv4/4dOEnFKFaxM='), onComplete:function() {fPage++}}); return false;
}



function showTellFriends() {
		$('tellfriends-div').show();
}

function followOnTwitter() {
		if(confirm("By clicking OK you follow @ape55 on Twitter, the makers of Tweetz.tv.")) {
			new Ajax.Request('/followus', {asynchronous:true, evalScripts:true, parameters:'authenticity_token=' + encodeURIComponent('Bjnt1/ZOcH14bq9KcYkn7UIaN/UbNv4/4dOEnFKFaxM='), onComplete:function() {alert("Thanks!")}}); return false;
		} else {
			
		}
}


function showLink(pLink) {
	$('showlink-div').show();
	$('link').value = pLink;
	$('link').focus();
	$('link').select();
}

function helpWithEnquete(pResult) {
	if(!pResult) {
		new Ajax.Request('/dashboard/close_enquete', {asynchronous:true, evalScripts:true, parameters:'authenticity_token=' + encodeURIComponent('Bjnt1/ZOcH14bq9KcYkn7UIaN/UbNv4/4dOEnFKFaxM='), onComplete:function() {$('enquete').fade();}}); return false;
		
	} else {
		
		new Ajax.Request('/dashboard/taking_enquete', {asynchronous:true, evalScripts:true, parameters:'authenticity_token=' + encodeURIComponent('Bjnt1/ZOcH14bq9KcYkn7UIaN/UbNv4/4dOEnFKFaxM='), onComplete:function() {$('enquete').fade();}}); 

		mypopup();
		
	}
	
}


function mypopup()
 {
   mywindow = window.open ('http://spreadsheets.google.com/viewform?formkey=dGIwaEV5ZWhvQ0RXZEFsdDVPelcwOVE6MA',"mywindow","location=0,status=0,scrollbars=0, width=700,height=400");
  mywindow.moveTo(0,0);
 }


function firstLogin() {
	$('firstlogin-div').appear();
}

