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

$(document).ready(function() {
	initChat();
	addPlaceHolders();
	checkIE6();
});

/* Initializes Twitter Chat Functionality */

function initChat() {
	
	/* Custom scrollbars
	$('#chat-messages ul').jScrollPane();
	$('.jScrollPaneContainer').hover(function() {
		$('.jScrollPaneTrack',this).fadeIn('normal');
	});
	$('.jScrollPaneContainer').mouseleave(function() {
		$('.jScrollPaneTrack',this).fadeOut('normal');
	});*/
	$('#form-chat-login-submit').click(function(){
		$('#form-chat-login').hide();
		$('#chat-follow').fadeIn('slow');
	});
	
	$('#chat-follow-start_chatting').click(function(){
		$('#chat-follow').hide();
		$('#chat-update').fadeIn('slow');
	});
	
	$('#chat-update-logout').click(function(){
		$('#chat-update').hide();
		$('#form-chat-login').fadeIn('slow');
	});
}

/* 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 checkIE6() {
	jQuery.each(jQuery.browser, function(i) {
	if($.browser.msie && parseInt(jQuery.browser.version.substr(0)) <= "6"){
	  	$('#ie6').slideDown("slow");
	  }
	});
}


/* -------------------------------------------------------
 * 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;
}

function checkUserLogin(hash) {
	$('#header-top').load('/sessions/checkuserlogin?t=' + (new Date()).getTime() + (DO("broadcast-disabled-status").value == "1" ? "&disabled=1" : "&disabled=0") + "&channel=" + hash,
		{evalScripts: true,
                onComplete:function(req) {
                        if ($("#user-login-submit").size() == 0 && $("#chat-follow").css("display") == "block") {
                                showTweetLogin(hash);
                        }
                }}
	);
}

function showTweetLogin(hash) {
	$('#tweetUpdates').load('/sessions/showTweetLogin?channel=' + hash + '&t=' + (new Date()).getTime(),
		{evalScripts: true}
	);
}

/* -------------------------------------------------------
 * 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 newEntry = false;

function initializeChat() {
	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 broadcastID = DO('broadcastID').value
        if(broadcastID == null || broadcastID == "")
               return;
	encodedQuery = "twitcam.com%3f" + broadcastID

	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);
	//$('#chat-messages ul').jScrollPane();
}

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

	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, 20, 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));
			}
			
		}
	}
}

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=\"/user/" + user + "\" title=\"Go to\" + user + \"'s account\" class=\"thumbnail\" target=\"_blank\">" +
                "<span class=\"mask\"></span><img src=\"" + url + "\" /></a>" +
                "<p><a href=\"/user/" + user + "\" title=\"Go to\" + user + \"'s account\" target=\"_blank\">" + user + "</a>: " + replaceBroadcaster(text) + "</p>" +
                "<span class=\"date\" id=\"formattedDate\">" + formatDate(datePublished) + "</span><span id=\"publishDate\" style=\"display:none\">" + datePublished + "</span>";
	return li;
}

function replaceBroadcaster(mainString)
{
   replaceThis = "(@" + DO('broadcasterName').value + " live on http://twitcam.com/" + DO('broadcastID').value + ")";
   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');
			$('#login-error div.error').fadeIn('slow');
			setTimeout("$('#login-error div.error').fadeOut('slow');",7000);
			checkUserLogin();
			DO('broadcastID').value = broadcastID;
                }
        });
        return false;
}

function twitLogout(broadcastID) {
	$.ajax({
	  url: '/sessions/twitLogout?channel=' + broadcastID,
	  success: function(data) {
	    if(DO('chat-follow') != null)
		DO('broadcastID').value = broadcastID;
	   checkUserLogin(broadcastID);   
	    
	  }
	});
        return false;
}

function chatLogin(broadcastID) {
        if(DO('chat-follow') != null) DO('chat-follow').style.display='none';
	$('#tweetUpdates').load('/sessions/twitLogout',
		{evalScripts: true}, 
		function(){
			DO('broadcastID').value = broadcastID;
		        if(DO('chat-follow') != null) DO('chat-follow').style.display='none';
			showTweetLogin(broadcastID);
			checkUserLogin(broadcastID);
	});
	return false;
}

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

function startCountTimer() {
	timerCount++;
	var timeLeft = 30 - 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;
		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 deleteClip(hash) {
	$.get('/broadcast/deleteClip?hash=' + hash,
		function(response) {
			if(response.substring(0,1) == "1") {
				window.location.href = "/user/" + response.substring(1);
				return false;
			}
			if(response == "0") {
				return false;
			}
	});
	return false;
}

function followTwitCam_newWindow() {
        $('#chat-follow').fadeOut('fast');
        DO('chat-follow').style.display='none';
        DO('chat-update').style.display='block';
        DO('form_chat_message').focus();
	window.open("http://twitter.com/twitcam",'new_window','height=900,width=1000');
        return false;
}


function followTwitCam() {
        $('#chat-follow').load('/startnewbroadcast/followTwitCam',
                {evalScripts: true},
                function(){
                        //setTimeout("$('#chat-follow').fadeOut('slow');",3000);
			DO('chat-follow').style.display='none';
        		DO('chat-update').style.display='block';
		        //setTimeout("DO('chat-update').style.display='block'",4000);
		        DO('form_chat_message').focus();
        });
        return false;
}

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;
}

function disableBroadcast(source) {
	if(source.disabled == true) return;
	source.className = "disabled";
	window.location.href ="/startnewbroadcast";
	source.disabled = true;
	source.href = "#";
	return false;
}/*Function for popup*/
function popup(mylink, windowname)
{
if (!window.focus)return true;
var href;
if (typeof(mylink) === 'string')
   href=mylink;
window.open(href, windowname, 'width=800,height=400');
return false;
}
