// AJAX
function showAjaxDivLoggedIn(divName, url) {
		getUrlXMLResponse(url, showAjaxDivResponseLater(divName));
}

// Calls optional callback if the ajax call succeeds
function showAjaxPostDivLoggedIn(divName, url, data, callback) {
		postUrlXMLResponse(url, data, showAjaxDivResponseLater(divName, callback));
}

function showAjaxDiv(divName, url) {
	if(isLoggedIn) {
		showAjaxDivLoggedIn(divName,url)
	} else {
		alert(MSG_Login);
	}
}

function showAjaxPostDiv(divName, url, data) {
	if(isLoggedIn) {
		showAjaxPostDivLoggedIn(divName, url, data)
	} else {
		alert(MSG_Login);
	}
}

function showAjaxDivResponseLater(divName, callback) {
	return function(req) {
		_gel(divName).innerHTML =getNodeValue(req.responseXML, "html_content");
		if (callback) {
			callback();
		}
	};
}

function showAjaxDivResponse(req, divName) {
	_gel(divName).innerHTML =getNodeValue(req.responseXML, "html_content");
	openDiv(divName);
}

function postAjaxForm(divName, formName, successCallback) {
	postFormXMLResponse(formName, closeAjaxDivLater(divName, successCallback));
}

function closeAjaxDivLater(divName, successCallback) {
	return function (req) {
		closeDiv(divName);
		if (successCallback) {
			successCallback();
		}
	}
}


// Ad Rotation
var first_time = 1;
function changeBanner(img_url, ref_url, is_flash){
	var e = _gel("gad_leaderboardAd");

	if (first_time)
	{
		e.style.height = "90px";
		first_time = 0;
	}

	var url = "";
	if (is_flash == "true")
	{
		url += "<object width='728' height='90'>";
		url += "<" + "param value='clickTAG=" + encodeURIComponent(ref_url) + "' /" + ">";
		url += "<" + "embed src='" + img_url + "'";
		url += " type='application/x-shockwave-flash' wmode='transparent'";
		url += " flashvars='clickTAG=" + encodeURIComponent(ref_url) + "'";
		url += " width='728' height='90' /" + ">";
		url += "</object>";
	}
	else
	{
		url = "<" + "a href='" + ref_url + "' target='_blank'>";
		url += "<img src='" + img_url + "'>";
		url += "</a>";
	}

	e.innerHTML = url;
}



// Hover css
function actionOver(div) {
	div.className='actionOver';
}
function actionOut(div) {
	div.className='actionRow';
}
function actionClick(div) {
	div.className='actionClicked';
}
function actionOverBottom(div) {
	div.className='actionOverBottom';
}
function actionOutBottom(div) {
	div.className='actionRowBottom';
}
function actionClickBottom(div) {
	div.className='actionClickedBottom';
}

function closeDisplay(div) {
	if (_gel(div)) {
		_gel(div).style.display = "none";
	}
}

function closeAll(except) {
	var divs = ['addToFavesDiv', 'addToPlaylistDiv', 'shareVideoDiv', 'inappropriateVidDiv', 'customizeEmbedDiv', 'shareVideoEmailDiv'];
	for (var i = 0; i < divs.length; i++) {
		if ((divs[i] != except) && (_gel(divs[i]))){
			var theDiv = _gel(divs[i]);
			if (theDiv) {
				theDiv.style.display = "none";
			}
		}
	}
}

function postResponse() {
	if (isLoggedIn){
		closeAll('postResponseDiv');
		toggleDisplay('postResponseDiv');
	}
	else
	{
		alert(MSG_LoginPostResponse);
	}
}
function closeAfter(divName, delay) {
	setTimeout(function(){
			closeDisplay(divName)
		}, delay);
}


function postResponseClose() {
	toggleDisplay('postResponseDiv');
	toggleDisplay('postResponseResult');
	closeAfter('postResponseResult', 3000);
}

function customizeEmbed() {
	closeAll('customizeEmbedDiv');
	toggleDisplay('customizeEmbedDiv');
}

function addToFaves(formName) {
	if (isLoggedIn) {
		closeAll('addToFavesResult');
		toggleDisplay('addToFavesResult');
		postAjaxForm('addToFavesDiv', formName);
		_hbLink('Save+To+Favorites','Watch3');
		setTimeout("closeDisplay('addToFavesResult')",3000);
	}
	else {
		alert(MSG_LoginFavorites);
	}
}

function addToPlaylist(videoId) {
	if (isLoggedIn) {
		closeAll('addToPlaylistDiv');
		if (toggleDisplay('addToPlaylistDiv')) {
			showAjaxDivLoggedIn('addToPlaylistDiv', '/watch_ajax?video_id=' + videoId + '&action_get_new_playlists_component=1', true);
			_hbLink('Add+To+Playlists','Watch3');
		}
	}
	else {
		alert(MSG_LoginAddPlaylist);
	}
}

function addToPlaylistClose() {
	toggleDisplay('addToPlaylistDiv');
	toggleDisplay('addToPlaylistResult');
	closeAfter('addToPlaylistResult', 3000);
}

function reportConcern(videoId) {
	if (isLoggedIn) {
		closeAll('inappropriateVidDiv');
		if (toggleDisplay('inappropriateVidDiv')) {
			showAjaxDivLoggedIn('inappropriateVidDiv', '/watch_ajax?video_id=' + videoId + '&action_get_flag_video_component=1', true);
			_hbLink('Flag+Inappropriate','Watch3');
		}
	}
	else {
		alert(MSG_LoginReportConcern);
	}
}

function reportConcernClose() {
	toggleDisplay('inappropriateVidDiv');
	toggleDisplay('reportConcernResult');
	closeAfter('reportConcernResult', 3000);
}

function shareVideo(videoId) {
	closeAll('shareVideoDiv');
	toggleDisplay('shareVideoDiv');
	
	if (_gel('shareVideoDiv').style.display != "none") {
		if (this.loaded === undefined) {
			showAjaxDivLoggedIn('shareVideoDiv', '/watch_ajax?video_id=' + videoId + '&action_get_share_video_component=1', true);
			this.loaded = true;
		}
		_hbLink('Share+Video','Watch3');
	}
}

function shareVideoEmail(videoId) {
	toggleDisplay('shareVideoEmailDiv');
}

function shareVideoClose() {
	toggleDisplay('shareVideoDiv');
	toggleDisplay('shareVideoResult');
	closeAfter('shareVideoResult', 3000);
}

function shareWorld() {
	closeAll('shareWorldDiv');
	toggleDisplay('shareVideoDiv');
	toggleDisplay('shareWorldDiv');
}

function shareWorldClose() {
	toggleDisplay('shareWorldDiv');
	toggleDisplay('shareWorldResult');
	setTimeout("closeDisplay('shareWorldResult')",3000);
}

function embedIt() {
	closeAll('embedItDiv');
	toggleDisplay('embedItDiv');
}


function showHonorsContent() {
	getAndShowNavContent('honors', honorsLink);
}

function writeMoviePlayer(player_div, force) {
	var v = "7";
	if (force)
		v = "0";

	var fo = new SWFObject(swfUrl, "movie_player", "480", "395", v, "#FFFFFF");
	fo.addParam("allowFullscreen", "true");
	for (var x in swfArgs) {
		fo.addVariable(x, swfArgs[x]);
	}
	if (watchSourceId) {
		fo.addVariable("sourceid", watchSourceId);
	}
	if (watchSourceDetail) {
		fo.addVariable("sdetail", watchSourceDetail);
	}
	if (watchQuery) {
		fo.addVariable("q", watchQuery);
	}
	if (watchPlayerTrackingId) {
		fo.addVariable("plid", watchPlayerTrackingId);
	}
	if (watchGamUrl != null) {
		fo.addVariable("gam", watchGamUrl);
	}
	if (watchDCUrl != null) {
		fo.addVariable("ad_tag", watchDCUrl);
	}
	if (!watchIsPlayingAll) {
		fo.addVariable("playnext", 0);
	}

	player_written = fo.write(player_div);
}
function setSWFVersion(version_from_swf)
{
	if (watchTrackWithHitbox) {
		_hbPageView("WatchSWFTracker/" + player_written, "FlashTracker3");
	}
	if (!player_written)
		writeMoviePlayer("playerDiv", true);	
}

function closeFullStats() {
	toggleDisplay('fullStats');
	if (_gel('showhide')) {
		_gel('showhide').innerHTML = 'Show';
	}
}

function toggleFullStats(statsContent) {
	if (statsContent === undefined) {
		statsContent = 'honors';
		ajaxUrl = additionalStatsHonorsUrl;
		_gel('referDiv').style.display = 'block';
	}
	else if (statsContent == 'audio') {
		ajaxUrl = additionalStatsAudioUrl;
		_gel('referDiv').style.display = 'none';
	}

	var fsd = _gel('fullStats').style.display;

	if (fsd == 'none' || fsd == '') {
		showAjaxDivLoggedIn('additionalStatsDiv', ajaxUrl, false);
		if (statsContent == 'audio') {
			_gel('showhide').innerHTML = MSG_Hide;
		}
		toggleDisplay('fullStats');
	}
	else
	{
		if (((statsContent == 'honors' && _gel('audioStatHead')) || (statsContent == 'audio' && _gel('honorStatHead'))))
		{
			showAjaxDivLoggedIn('additionalStatsDiv', ajaxUrl, false);
			if (statsContent == 'honors') {
				_gel('showhide').innerHTML = MSG_Show;
			}
			else if (statsContent == 'audio') {
				_gel('showhide').innerHTML = MSG_Hide;
			}
		}
		else
		{
			toggleDisplay('fullStats');
			if (statsContent == 'audio') {
				_gel('showhide').innerHTML = MSG_Show;
			}
		}
	}
}

function showAllQueuedVideos() {
	setInnerHTML('show_all_queued_videos_div', MSG_Loading);
	getAndShowNavContent('watchlist_container', watchlistContainerUrl, postShowAllQueuedVideos);
}
function postShowAllQueuedVideos() {
	setInnerHTML('show_all_queued_videos_div', MSG_ShowingAll);
	jumpToNowPlaying();
}

// Player stuff

function openFull() {
	var fs = window.open( fullscreenUrl,
		"FullScreenVideo", "toolbar=no,width=" + screen.availWidth  + ",height=" + screen.availHeight
		+ ",status=no,resizable=yes,fullscreen=yes,scrollbars=no");
	fs.focus();
}

function gotoNext() {
	if (autoNextUrl) {
		window.location = autoNextUrl;
	}
}

function autoNext() {
	var p = _gel("movie_player");
	if(p.GetVariable("movie.is_playing") == "false" && p.GetVariable("movie.restart") == "true") {
		gotoNext();
	}
	else {
		p.SetVariable("playnext", "1");
	}

	hideDiv("playall");
	showDiv("playingall");
	return false;
}

function autoNextOff() {
	_gel("movie_player").SetVariable("playnext", "0");
	hideDiv("playingall");
	showDiv("playall");

	return false;
}

function CheckLogin() {
	return isLoggedIn;
}


function onQuickAddClick(img, eid, title, imgUrl, username, duration, scroll) {
	var before = getDivHeight(_gel('playlistDiv'));

	clickedQuickAdd(img, eid, imgUrl, title, username, duration);
	_hbLink('QuickList+AddTo','Watch3');

	var after = getDivHeight(_gel('playlistDiv'));
	if (before < after && scroll) {
		window.scrollBy(0, after - before);
	}

	img.blur();

	return false;
}

var delayLoadRegistry = [];
var delayLoadCompleted = [];
function delayLoad(id, img, src) {
	delayLoadRegistry[delayLoadRegistry.length] = [id, img, src];
	delayLoadCompleted[id] = false;
}


function performDelayLoad(id) {
	if (!delayLoadCompleted[id]) {
		delayLoadCompleted[id] = true;
		for (var i=0; i < delayLoadRegistry.length; i++) {
			if (delayLoadRegistry[i][0] == id) {
				delayLoadRegistry[i][1].onload = "";
				delayLoadRegistry[i][1].src = delayLoadRegistry[i][2];
			}
		}
	}
}

var showAjaxDivNotLoggedIn = showAjaxDivLoggedIn;

// Referrers show/hide
function hideLinkingSitesCallback() {
	hideDiv('referersList');
	hideInline('hideLinkingSites');
	showInline('showLinkingSites');
	showInline('linkingSitesDisabled');
}

function hideLinkingSites() {
	postUrlXMLResponse('/watch_ajax', 'action_hide_linking_sites=1&video_id='+ pageVideoId +'&' + axc, hideLinkingSitesCallback);
	return false;
}

function showLinkingSites() {
	hideInline('linkingSitesDisabled');
	showInline('hideLinkingSites');
	hideInline('showLinkingSites');
	showAjaxPostDivLoggedIn('referersList', '/watch_ajax', 'action_show_linking_sites=1&video_id='+ pageVideoId +'&' + axc);
	return false;
}

// Channel videos
function showMoreChannelVideos(username) {
	hideDiv('channel_videos_more');
	showDiv('channel_videos_full');
	showDiv('channelVidsLess');
	if (!_gel('more_channel_videos'))
		showAjaxDivLoggedIn('channel_videos_full', '/watch_ajax?user='+username + '&action_channel_videos');
	return false;
}

function showLessChannelVideos() {
	hideDiv('channelVidsLess');
	hideDiv('channelVidsPartnerHeading');
	showDiv('channel_videos_more');
	hideDiv('channel_videos_full');
	return false;
}

// Related
function showRelatedAsList() {
	setInnerHTML('relatedVidsBody', MSG_Loading);
	showAjaxDivLoggedIn('relatedVidsBody', relatedVideoListUrl);
	showInline("relatedList");
	hideInline("relatedNotList");
	showInline("relatedNotGrid");
	hideInline("relatedGrid");
	return false;
}

function showRelatedAsGrid() {
	setInnerHTML('relatedVidsBody', MSG_Loading);
	showAjaxDivLoggedIn('relatedVidsBody', relatedVideoGridUrl);
	hideInline("relatedList");
	showInline("relatedNotList");
	hideInline("relatedNotGrid");
	showInline("relatedGrid");
	return false;
}

var defaultRecipientFieldCount = 2;
var recipientFieldNamePrefix = "recipient";
var recipientFieldCount = defaultRecipientFieldCount;
var lastRecipientFieldId = recipientFieldNamePrefix + recipientFieldCount;
var maxRecipients = 10;
function addRecipientFieldIfNeeded(field) {
	if (field.id == lastRecipientFieldId && recipientFieldCount < maxRecipients) {
		newField = field.cloneNode(true);
		recipientFieldCount++;
		lastRecipientFieldId = recipientFieldNamePrefix + recipientFieldCount;
		newField.id = lastRecipientFieldId;
		newField.name = lastRecipientFieldId;
		_gel('recipients').appendChild(newField);
	}
}

function resetRecipients() {
	recipientFieldCount = defaultRecipientFieldCount;
	lastRecipientFieldId = recipientFieldNamePrefix + recipientFieldCount;
}

function consolidateRecipients() {
	hiddenRecipientsField = _gel('recipients');

	for (var i = 1; i <= recipientFieldCount; i++) {
		hiddenRecipientsField.value += (_gel(recipientFieldNamePrefix + "" + i).value + ",");
	}
}

// cookie utils
function readCookie(name, fallback) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}

	if (fallback) {
		return fallback;
	} else {
		return null;
	}
}

function readIntCookie(name) {
	val = readCookie(name);
	if (val) {
		return parseInt(val);
	} else {
		return 0;
	}
}

function createCookie(name,value,days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}

function eraseCookie(name) {
	createCookie(name,"",-1);
}

SHARED_RATINGS_INVITE_SHOW_MAX = 5
SHARED_RATINGS_INVITE_REJECT_MAX = 2
function displayRecentRatingsInvite() {
	if (!readCookie("stop_shared_ratings_invite")) {
		showDiv("recentRatingsInvite");
		var timesShown = parseInt(readCookie("shared_ratings_invite_shown", "0"));
		timesShown = timesShown + 1;
		createCookie("shared_ratings_invite_shown", timesShown);
		if (timesShown>=SHARED_RATINGS_INVITE_SHOW_MAX) {
			createCookie("stop_shared_ratings_invite", "1");
		}
	}
}

SHARED_RATINGS_INVITE_SHOW_MAX = 5
function rejectRecentRatings() {
	var timesRejected = parseInt(readCookie("shared_ratings_invite_rejected", "0"));
	timesRejected = timesRejected + 1;
	createCookie("shared_ratings_invite_rejected", timesRejected);
	if (timesRejected>=SHARED_RATINGS_INVITE_REJECT_MAX) {
		createCookie("stop_shared_ratings_invite", "1");
	}
}

function subscribe(username, token) {
	postUrlXMLResponse('/ajax_subscriptions', 'subscribe_to_user=' + username + '&session_token=' + token, function(result) { removeClass(_gel('unsubscribeDiv'), 'hid'); addClass(_gel('subscribeDiv'), 'hid'); });
}
function unsubscribe(username, token) {
	postUrlXMLResponse('/ajax_subscriptions', 'unsubscribe_from_user=' + username + '&session_token=' + token, function() { removeClass(_gel('subscribeDiv'), 'hid'); addClass(_gel('unsubscribeDiv'), 'hid'); });
}

