/* -------------------------------------------------------
 * Initialization Functions
 * ------------------------------------------------------- */

$(document).ready(function() {        
	setChatHeight();
	addPlaceHolders();
});

$(window).resize(function() {
        setChatHeight();
});

/* -------------------------------------------------------
 * General Functions
 * ------------------------------------------------------- */

function DO(domId) {
	return window.document.getElementById(domId);
}

function ES(tag, containtId) {
	//This needs to be replaced with the corresponding jquery method
	if(containtId == null || containtId == ""){
		return $(tag);
	}else{
		return $(containtId+" "+tag);
	}
}

function loginUser() {
	$('#form-user-login button').addClass('loading');
	$('#form-user-login').ajaxSubmit({
		type: 'post',
		target : '#header-top',
		evalScripts: true,
		success: function() {
			$('#form-user-login button').removeClass('loading');
			$('#user_nav div.error').fadeIn('slow');
			setTimeout("$('#user_nav div.error').fadeOut('slow');",7000);
			if(DO('actionName').value !="broadcast" && DO('user-login-status').value !="0") {
				window.location.href = DO("userThumbnail").href;
				return false;
			}
		}
	});
	return false;
}

function twitLogin() {
	$('#form-login button').addClass('loading');
	$('#form-login').ajaxSubmit({
		type: 'post',
		evalScripts: true,
		success: function(response) {
			$('#form-login button').removeClass('loading');
			if(response.substring(0,1) =="1"){
				if(DO('redirect_to').value == null || DO('redirect_to').value =="") {
					window.location.href = "/user/" + response.substring(1) ;
					return false;
				} else {
					window.location.href = "/" + DO('redirect_to').value;
					return false;
				}

			} else {
				$('#left p.error').fadeIn('slow');
				setTimeout("$('#left p.error').fadeOut('slow');",7000);
				return false;
			}

		}
	});
	return false;
}


/* -------------------------------------------------------
 * Chat Helper Functions
 * ------------------------------------------------------- */

/* Update character limit badge in chat message */

function limitChars(textid, limit, infodiv,submit) {
	var text = $(textid).val();
	var textlength = text.length;
	if(textlength > limit)
	{
		$(infodiv).html((limit - textlength));
		$(infodiv).addClass('negative');
		$(submit).addClass('disabled');
		$(submit).attr("disabled", true);
		//$(textid).val(text.substr(0,limit));
		return false;
	}
	else
	{
		if($(infodiv).hasClass('negative')) {
			$(infodiv).removeClass('negative');
			$(submit).removeClass('disabled');
			$(submit).attr("disabled", false);
		}
		$(infodiv).html((limit - textlength));
		return true;
	}
}

var lastTweetID = null;
var script = null;
var rpp = 10;
var tweetIntervalID = -1;
var refreshInterval = 10;
var delayInterval = 30;
var newEntry = false;

function initializeChat(count, updateFreq, refreshFreq) {
	if(count != null && count > 10) rpp = count;
	updateFreq < 10 ? delayInterval = 10 : delayInterval = updateFreq;
	if(refreshFreq != null && refreshFreq > 10) refreshInterval = refreshFreq;
	refreshChat();
	var broadcasterName = DO('broadcasterName').value
	tweetIntervalID = window.setInterval(refreshChat, refreshInterval * 1000);
}


function clearTweetTimer()
{
	if(tweetIntervalID != -1) {
		window.clearInterval(tweetIntervalID);
		tweetIntervalID = -1;
	}
}

function refreshChat() {
	var url = DO('url').value
	if(url == null || url == "")
		return;
	var searchparam = DO('searchparam').value
	if(searchparam == null || searchparam == "")
		return;
	encodedQuery = escape(searchparam);

	if(script != null) {
		document.body.removeChild(script);
	}
	var url = 'http://search.twitter.com/search.json?random=' + Math.random() +
	'&callback=tweetCallback&q=' + encodedQuery +
	'&rpp=' + rpp + (lastTweetID == null ? "" : ('&since_id=' + lastTweetID));
	var script_tag = "<script type='text/javascript' src="+url+"'></script>";
	$('body').append(script_tag);
}

function tweetCallback(data) {
	if (lastTweetID === null || data.max_id_str > lastTweetID) {
		lastTweetID = data.max_id_str;
	}

	var tweets = data.results;
	if(tweets == undefined)
		return;
	var ul = document.getElementById("chatMessages");
	if(newEntry && tweets.length > 0) {
		newEntry = false;
		var lis = ul.getElementsByTagName("li");
		if(lis.length > 0) ul.removeChild(lis[0]);
	}

	removeSpillOverItems(ul, rpp, tweets.length);
	refreshTime(ul);
	var lis = ul.getElementsByTagName("li");
	var firstChild = lis != null && lis.length > 0 ? lis[0] : null;

	for (var i = tweets.length - 1; i >=0; i--) {
		var tweet = tweets[i];
		firstChild = createChatItem(ul, firstChild, tweet.from_user, tweet.profile_image_url, tweet.text, tweet.created_at);
	}
}

function removeSpillOverItems(ul, limit, newItems) {
	var lis = ul.getElementsByTagName("li");
	if(lis != null && lis.length >= limit) {
		for(var i = 0; i < lis.length + newItems - limit; i++) {
			ul.removeChild(lis[lis.length - i - 1]);
		}
	}
}

function refreshTime(ul) {
	/*var lis = ul.getElementsByTagName("li");
	if(lis != null) {
		for(var i = 0; i < lis.length; i++) {
			var publishDate = getChildNode(lis[i], "publishDate");
			var formattedDate = getChildNode(lis[i], "formattedDate");
			if(publishDate != null &&  formattedDate != null) {
				formattedDate.innerHTML = formatDate(new Date(publishDate.innerHTML));
			}

		}
	}*/

	$('#chat-messages ul li').each(function(){
		if($('.publishDate',this) != null &&  $('.formattedDate',this) != null) {
			$('.formattedDate',this).html(formatDate(new Date($('.publishDate',this).html())));
		}
	});
}

function getChildNode(parentNode, childId) {
	if(parentNode == null) {
		return null;
	}

	for(var i = 0; i < parentNode.childNodes.length; i++) {
		if(parentNode.childNodes[i].id == childId) return parentNode.childNodes[i];
	}
	return null;
}

function createChatItem(ul, sibling, user, url, text, publishedDate)  {
	datePublished = new Date(publishedDate);
	var li = document.createElement("li");
	li.className = "message";
	var txt = document.createTextNode("Check");
	li.appendChild(txt);
	if(sibling != null) {
		ul.insertBefore(li, sibling);
	} else {
		ul.appendChild(li);
	}

/*
	li.innerHTML =
	"<a href=\"http://twitter.com/" + user + "\" title=\"Go to\" + user + \"'s account\" class=\"thumbnail\" target=\"_blank\">" +
	"<span class=\"mask\"></span><img src=\"" + url + "\" /></a>" +
	"<p><a href=\"http://twitter.com/" + user + "\" title=\"Go to\" + user + \"'s account\" target=\"_blank\">" + user + "</a>: " + replaceSrcURL(text) + "</p>" +
	"<span class=\"date\" id=\"formattedDate\">" + formatDate(datePublished) + "</span><span id=\"publishDate\" style=\"display:none\">" + datePublished + "</span>";
*/

	li.innerHTML =
	'<a href="http://twitter.com/' + user + '" title="View ' + user + '\'s twitter profile" class="thumbnail" target="_blank">' +
	'<span class="mask"></span><img width="48px" height="48px" src="' + url + '" title="' + user + '\'s twitter avatar" alt="' + user + '\'s twitter avatar" /></a>' +
	'<p><a href="http://twitter.com/' + user + '" title="View ' + user + '\'s twitter profile" target="_blank">' + user + '</a>: ' + replaceSrcURL(text) + '</p>' +
	'<span class="date formattedDate">' + formatDate(datePublished) + '</span><span class="publishDate" style="display:none">' + datePublished + '</span>';

	return li;
}

function replaceSrcURL(mainString)
{
        url = DO('url').value;
        index = url.indexOf("http://");
        if(index == -1)
                replaceThis = " - " + DO('searchparam').value + " live on http://" + url;
        else
                replaceThis = " - " + DO('searchparam').value + " live on " + url;
        result = mainString.replace(replaceThis,"");
        return result;
}

function formatDate(datePublished) {
	var now = new Date();
	var secs = (now - datePublished) / 1000;
	if (secs < 5) {
		return 'less than 5 seconds ago';
	} else if (secs < 10) {
		return 'less than 10 seconds ago';
	} else if (secs < 20) {
		return 'less than 20 seconds ago';
	} else if (secs < 60) {
		return 'half a minute ago';
	} else if (secs < 120) {
		return '1 minute ago';
	} else if (secs < 60*60) {
		var minutes = Math.floor(secs / 60);
		return minutes + ' minutes ago';
	} else if (secs < 24*60*60) {
		var hours = Math.floor(secs / (60*60));
		if (hours == 1) {
			return 'about 1 hour ago';
		} else {
			return 'about ' + hours + ' hours ago';
		}
	} else {
		return datePublished.toDateString();
	}
}

function tweet(broadcastID) {
	$('#form-chat-login button').addClass('loading');
	$('#form-chat-login').ajaxSubmit({
		type: 'post',
		target : '#tweetUpdates',
		evalScripts: true,
		success: function() {
			$('#form-chat-login button').removeClass('loading');
			$('#form_chat_message').val('');
			$('#login-error div.error').fadeIn('slow');
			setTimeout("$('#login-error div.error').fadeOut('slow');",7000);
		}
	});
	return false;
}

function chatLogin() {
	if(DO('chat-follow') != null) DO('chat-follow').style.display='none';
	$('#tweetUpdates').load('/sessions/twitLogout?account=' + DO('account').value
		+ '&url=' + DO('url').value + '&searchparam=' + DO('searchparam').value  + '&results=' + DO('results').value
		+ '&refresh=' + DO('refresh').value + '&delay=' + DO('delay').value
		,
		{
			evalScripts: true
		},
		function(){
		});
	return false;
}

function widgetLoginBox() {
	if(DO('chat-follow') != null) DO('chat-follow').style.display='none';
	$('#tweetUpdates').load('/sessions/twitterWidgetLogout?account=' + DO('account').value
		+ '&url=' + DO('url').value + '&searchparam=' + escape(DO('searchparam').value)  + '&results=' + DO('results').value
		+ '&refresh=' + DO('refresh').value + '&delay=' + DO('delay').value + '&mode=' + DO('mode').value + '&showchat=' + DO('showchat').value + '&title=' + escape(DO('title').value) + '&channel=' + escape(DO('channel').value) + '&ls_twitter_chat=true'
		,
		{
			evalScripts: true
		},
		function(){
		});
	return false;
}


var timerCount = 0;
var targetBroadcastId = 0;
function tweetMessage(broadcastID) {
	var tweet = DO('form_chat_message').value;
	if(tweet == null || tweet == "" || jQuery.trim(tweet).length <= 0)
	{
		return false;
	}
	targetBroadcastID = broadcastID;
	clearTweetTimer();
	delayInterval = DO('delayInterval').value;
	startCountTimer();
	$("#tweetTimeContainer").fadeIn('fast');
	$("#form-chat-submit").attr("disabled", "disabled");
	$('#form-chat-submit').toggleClass('loading');
	submitTweet(broadcastID);
	targetBroadcastId = broadcastID;
	if(DO('showchat') != null && DO('showchat').value != "false")
	{
		var ul = document.getElementById("chatMessages");
		removeSpillOverItems(ul, rpp, 1);
		var lis = ul.getElementsByTagName("li");
		createChatItem(ul, (lis != null && lis.length > 0 ? lis[0] : null), DO("currentUserName").value, DO("profileImage").value, tweet, new Date().toString());
	}
	return false;
}

function startCountTimer() {
	timerCount++;
	var timeLeft = delayInterval - timerCount;
	if(timeLeft <= 0) {
		timerCount = 0;
		$("#tweetTimeContainer").fadeOut('fast');
		DO('form_chat_message').value = "";
		DO('broadcastID').value = targetBroadcastId;
		DO('form-chat-char_limit').innerHTML = DO('textLimit').value;
		$('#form-chat-submit').removeClass('loading');
		$("#form-chat-submit").removeAttr("disabled");
		newEntry = true;
		if(DO('showchat') != null && DO('showchat').value != "false")
		{
			initializeChat();
		}
	}else {
		if(DO("tweetTimeCounter") != null) {
			DO("tweetTimeCounter").innerHTML = timeLeft.toString();
			setTimeout(startCountTimer, 1000);
		}
	}
}

function submitTweet(broadcastID) {
	$('#form-chat').ajaxSubmit({
		type: 'post',
		evalScripts: true,
		success: function() {
		}
	});
	return false;
}

function followTwitter() {
	var accountToFollow = DO('account').value;
	$('#chat-follow').load('/twitterwidget/followTwitter?accountToFollow=' + accountToFollow,
	{
		evalScripts: true
	},
	function(){
		DO('chat-follow').style.display='none';
		DO('chat-update').style.display='block';
		DO('form_chat_message').focus();
	});
	return false;
}


// JSONP for checking is user is following twitcam
function checkIfFollowing(twitterUser,accountToFollow) {
        var baseurl = "http://twitter.com/friendships/exists.json?";
        var surl = baseurl + "user_a="+escape(twitterUser)+"&user_b="+accountToFollow+"&callback=?";
        $.getJSON(surl, function(data) {
                 if (data == true) {
                         $("#chat-follow").remove();
                 }
                 else {
                        $("#chat-update").hide();
                        $("#chat-follow").show();
                 }
              })
}
function continueChat()
{
	DO('chat-follow').style.display='none';
	DO('chat-update').style.display='block';
	DO('form_chat_message').focus();
	return false;
}


/* Outdated */

function checkChatBoxTextLimit(){
	var contain = DO('form_chat_message');
	var maxLength = contain.getAttribute? parseInt(contain.getAttribute("maxlength")) : ""
	var textLeft = maxLength - contain.value.length;
	if(textLeft < 0) textLeft = 0;
	DO('form-chat-char_limit').innerHTML = textLeft;
}

/* Add form field place holder functionality */
function addPlaceHolders() {
	$("input:text,input:password").not('#video-share-embed,#video-share-link').focus(function(){
		if($(this).val() == $(this).get(0).defaultValue) $(this).val("");
		if($('p.error').is(':hidden'))$('p.error').fadeOut("fast");
	});
	$("input:text,input:password").not('#video-share-embed,#video-share-link').blur(function(){
		if($(this).val() == "") $(this).val($(this).get(0).defaultValue);
	});

	$('#video-share-embed,#video-share-link').click(function(){
		$(this).select();
	});
}

function setChatHeight() {
        // adjust chat widget height and width
        var twitterIframeHeight = $('#chatWidgetHeight').val();                
        if(twitterIframeHeight != null && twitterIframeHeight != 0){                
                if(DO('chat-messages') != null)
                {
        		document.getElementById('chat-messages').style.height = twitterIframeHeight + "px";
        		document.getElementById('chatMessages').style.height = twitterIframeHeight + "px";
        	}
        }else{                
                autoHeight();
        }
}

function autoHeight()
{
        var showBar = true;
	var bar = DO("powered_by_livestream");
	if(bar == null) {
		showBar = false;
	}
	var myWidth = 0, myHeight = 0,tmpHeight=0,topHeight = 111;
	var bottomHeight = showBar? 27 : 0;
	var offsetHeight = $('#offsetHeight').val();

	if( typeof( window.innerWidth ) == 'number' ) {
	  //Non-IE
	  myWidth = window.innerWidth;
	  myHeight = window.innerHeight;
	} else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
	  //IE 6+ in 'standards compliant mode'
	  myWidth = document.documentElement.clientWidth;
	  myHeight = document.documentElement.clientHeight;          
	} else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
	  //IE 4 compatible
	  myWidth = document.body.clientWidth;
	  myHeight = document.body.clientHeight;          
	}

	if(DO('chat-messages') != null)
	{
                tmpHeight=myHeight - topHeight - bottomHeight -offsetHeight;
                (tmpHeight > 0 ? tmpHeight:tmpHeight=topHeight);
                   document.getElementById('chat-messages').style.height =tmpHeight + "px";
                   document.getElementById('chatMessages').style.height =tmpHeight + "px";
	}
}
function popup(mylink, windowname)
{
    var account= DO('account').value === null ? "" : DO('account').value;
    var url=DO('url').value === null ? "" : DO('url').value;
    var searchparam=escape(DO('searchparam').value) === null ? "" : escape(DO('searchparam').value);
    var results= DO('results').value === null ? "" :DO('results').value;
    var refresh=DO('refresh').value === null ? "" :DO('refresh').value;
    var delay=DO('delay').value === null ? "" :DO('delay').value;
    var mode=DO('mode').value === null ? "" :DO('mode').value;
    var showchat=DO('showchat').value === null ? "" :DO('showchat').value;
    var title=escape(DO('title').value) === null ? "" :escape(DO('title').value);
    var channel=escape(DO('channel').value) === null ? "" :escape(DO('channel').value);
    var ls_twitter_chat=true;
    var href;
    if (!window.focus){
        return true;
        }
    if (typeof(mylink) == 'string'){
       href=mylink+'?account='+account+'&url='+url+'&searchparam='+searchparam+'&=results='+results+'&refresh='+refresh+'&delay='+delay+'&mode='+mode+'&showcat='+showchat+'&title='+title+'&channel='+channel+'&ls_twitter_chat='+ls_twitter_chat;
    }
    else {
       href=mylink.href+'?account='+account+'&url='+url+'&searchparam='+searchparam+'&=results='+results+'&refresh='+refresh+'&delay='+delay+'&mode='+mode+'&showcat='+showchat+'&title='+title+'&channel='+channel+'&ls_twitter_chat='+ls_twitter_chat;
    }
       window.open(href, windowname, 'width=800,height=400');
       return false;
}

