// ==========================================================
// Put functions for playerFrame here
// ==========================================================

var player = null;
var playerCurrentPosition = null;

var playerAudioBuffer = 3;
var playerVideoBuffer = 3;

var ajaxNetworkUpdateTimer = null;
var ajaxChatInitialised = false;

// Used for 'back' buttons in the right-content forms
var defaultRightContent = null;

var lastPosition = null;



// DO NOT ADD TO THIS FUNCTION,
// use playerFrameOnLoad to add functionality!
jQuery(document).ready(function() {
	playerFrameOnLoad(true);
});


/**
 * Main function executed when playerFrame is loaded
 * and also when network content is updated through ajax
 * @param {} initFlashPlayer
 */
function playerFrameOnLoad(initFlashPlayer){

	// Embed the right kind of player
	if (initFlashPlayer) {
		if (playerMediaType == 'Video') {
			embedVideoPlayer();
		} else {
			embedAudioPlayer();
		}
	}

	// Move flash player to the left when chat is enabled to make
	// room for the 'chat available' icon
	if (typeof(ajaxChatEnabled) != 'undefined' && ajaxChatEnabled == true) {
		jQuery('#player-container').addClass('chat-enabled');
	}

	// Read what is initially visible in right content panel
	// 'tag-form', 'comment-form', 'comment-list', 'player-container', etc.
	if (playerMediaType == 'Video') {
		// 'player-container' is a special case here.
		// It needs to be outside the #maximise-content for playback
		// to continue when minimise/maximise button is clicked
		defaultRightContent = 'player-container';
	} else {
		// Otherwise select whatever does not have a hidden class
		jQuery("#maximise-content .right-content .rc-container").children().each(function(i){
			if (jQuery(this).hasClass('hidden') == false) defaultRightContent = this.id;
		});
	}
	switchRightContentTo(defaultRightContent);

	// 'Flag this comment' tooltips
	initFlagTooltips()

	// Set timer to reload next broadcast on Networks
	if (typeof(ajaxNetworkUpdateTimeout) == 'undefined' || ajaxNetworkUpdateTimeout == null) {
		ajaxNetworkUpdateTimer = setTimeout("ajaxNetworkUpdate();", (30 * 1000));
	}
	else {
		ajaxNetworkUpdateTimer = setTimeout("ajaxNetworkUpdate();", (ajaxNetworkUpdateTimeout * 1000));
	}

	// Restore the 'Maximise' state from cookie
	// Video player always starts maximised
	if ( jQuery.cookie('playerFrameState') == "maximise" ||
		 (playerMediaType == 'Video' && jQuery('#no-access').length == 0)
		) {
		playerFrameMaximise();
	}

	// Reload the playlist if in playlist mode
	if (typeof(playlistMode) != 'undefined' && playlistMode == true) {
		if (typeof(mainFrame.playlistAjaxAction) != 'undefined') {
			var url = mainFrame.jQuery('#playlist-form').attr('action');
			mainFrame.playlistAjaxAction(url);
		}
	}

	// Redirect to registration page
	if (jQuery('#no-access').length > 0) {
		mainFrame.location.href = baseHref + 'register?show_content=1';
	}


	// ################################   EVENT HANDLERS    ###################################

	// Add Comment Button Click

	jQuery("#add-comment A, #add-comment-tabbutton A").click(function(){
		switchRightContentTo('comment-form');
	});


	// Ajax forms: Add Comment form, Add Tag form, Flag form

	jQuery("#submit-form-comment, #submit-form-tag, #submit-form-flag").click(function(e){
		e.preventDefault();
		$form = jQuery(this).parents('form');
		$loader = $form.find('.ajax-loader-small');
		$message = $form.find('.form-message');

		$message.empty();
		$loader.css('display','block');

		jQuery.post($form.attr('action'), $form.serialize(), function(response){
			$loader.css('display','none');

			$message.removeClass('ok');
			$message.removeClass('error');
			$message.addClass(response.status);
			$message.html(response.message);

			if (response.status == 'ok') {
				$form.find('textarea').val('');
			}
		}, 'json');

	});


	// Tag list more link click

	jQuery(".tag-list .tag-teaser .more-link").click(function(){
		var content;
		var parentEl = jQuery(this).parent();
		for (var i =0; i < 10; i++){
			parentEl = parentEl.parent();
			content = parentEl;
			if (jQuery(content).hasClass("tag-content")) break;
		}
		jQuery(content).find(".tag-teaser").css("display","none");
		jQuery(content).find(".tag-body").slideDown("slow");
		return false;
	});


	// Tag list more link click

	jQuery(".tag-list .tag-body .more-link").click(function(){
		var content;
		var parentEl = jQuery(this).parent();
		for (var i =0; i < 10; i++){
			parentEl = parentEl.parent();
			content = parentEl;
			if (jQuery(content).hasClass("tag-content")) break;
		}

		jQuery(content).find(".tag-body").slideUp("slow",function(){
			jQuery(content).find(".tag-teaser").css("display","block");
		});
		return false;
	});


	// Top Bar Tag Button Click

	jQuery('#button-tag, #add-tag-tabbutton A').click(function(e){
		e.preventDefault();
		playerFrameMaximise();
		//player.sendEvent("PLAY", "false");
		switchRightContentTo('tag-form');
		jQuery("#timestamp").val(getPlayerPlaytime( jQuery("#curr-player-play-pos").val() ));
	});


	// Top Bar Maximise/Minimise Button Click

	jQuery('#button-player, #button-chat-enabled').click(function(e){
		e.preventDefault();
		switchRightContentBack();

		if (jQuery('#player').attr("class") == "minimise") {
			playerFrameMaximise();
			ajaxNetworkUpdate();
		} else {
			playerFrameMinimise();
		}
	});

} // end of playerFrameOnLoad()


function runMarquee(){
	// basic version is: jQuery('div.demo marquee').marquee() - but we're doing some sexy extras
	jQuery('marquee').marquee('pointer').mouseover(function () {
		jQuery(this).trigger('stop');
	}).mouseout(function () {
		jQuery(this).trigger('start');
	}).mousemove(function (event) {
		if (jQuery(this).data('drag') == true) {
			this.scrollLeft = jQuery(this).data('scrollX') + (jQuery(this).data('x') - event.clientX);
		}
	}).mousedown(function (event) {
		jQuery(this).data('drag', true).data('x', event.clientX).data('scrollX', this.scrollLeft);
	}).mouseup(function () {
		jQuery(this).data('drag', false);
	});
}


/**
 * Player On Ready
 */
function playerReady(obj) {
	player = document.getElementById(obj['id']);
	playerCurrentPosition = 0;
	jQuery("#curr-player-play-pos").val("0");
	player.addModelListener("time","playerPosUpdate");
};


/**
 * Updates current playing time
 */
function playerPosUpdate(obj){
	//if (obj['position']) {
		playerCurrentPosition = obj["position"];
	//}
	//else {
		//playerCurrentPosition = programmeLength;
	//}
	jQuery("#curr-player-play-pos").val(playerCurrentPosition);

	// Playlist - jump to next item
	if (playlistMode !== undefined && playlistMode == true) {
		if ((obj['duration'] > 0 && playerCurrentPosition >= (obj['duration'] - 0.1)) || (lastPosition > 0 && playerCurrentPosition == 0)) {
//			log('jumping to next item');
			if (playlistNextURL !== undefined && playlistNextURL != false) {
				window.location.href = playlistNextURL;
			}
		}
	}
	lastPosition = playerCurrentPosition;
}


/**
 * Send Event to player
 */
function sendEvent(typ,prm) {
	player.sendEvent(typ,prm);
};


/**
 * Load and start playing a file
 */
function playFile(filename) {
	player.sendEvent('STOP');
	player.sendEvent('LOAD', filename);
	player.sendEvent('PLAY');
}


function embedAudioPlayer() {
	// Choose the right skin and dimensions for Programme or Network player
	var skinFile = (window.location.href.match(/loadNetwork/)) ? 'local/media/wrn_stream.swf' : 'local/media/wrn.swf';
	var width = '380';//(window.location.href.match(/loadNetwork/)) ? '68' : '380';
	var height = '31';

	embedPlayer("player-container",playerMediaServer,playerMediaFile,playerAudioBuffer,skinFile,width,height);
	jQuery("#player-container").removeClass("video-player");
	jQuery("#player-container").addClass("audio-player");
}


function embedVideoPlayer() {
	var skinFile = 'local/media/wrn.swf';
	var width = '465';
	var height = '310';

	embedPlayer("player-container",playerMediaServer,playerMediaFile,playerVideoBuffer,skinFile,width,height);
	jQuery("#player-container").removeClass("audio-player");
	jQuery("#player-container").addClass("video-player");
}


/**
 * Embed Player in container
 */
function embedPlayer(containerId,streamer,file,bufferlength,skin,width,height) {
	var s1 = new SWFObject("local/media/player.swf","playerID",width,height,"9","#e8e8e8");
	var autostart = window.location.href.match(/autostart/) ? "true" : "false";
	var flashvars = "type=rtmp&skin="+skin+ "&autostart="+autostart+"&bufferlength="+bufferlength+"&streamer="+streamer+"&file="+file;
	// Security Token
	if (typeof(playerSecurityToken) != 'undefined' && playerSecurityToken.length > 0) {
		flashvars += "&token=" + playerSecurityToken;
	}
//	log(flashvars);
	s1.addParam("flashvars", flashvars);
	s1.addParam("allowfullscreen","true");
	s1.addParam("allownetworking","all");
	s1.addParam("allowscriptaccess","always");
	s1.addParam("wmode","opaque");
	s1.addVariable("usefullscreen","false");
	s1.addVariable("overstretch","false");
	s1.addVariable("displayheight","9999");
	if (jQuery("#"+containerId).length > 0) s1.write(containerId);
}


/**
 * Get Player Current Play Time. return "min:sec"
 * Used in 'add tag' html form
 */
function getPlayerPlaytime(playerCurrPos){

	var plytime = playerCurrPos/60;
	plytime += '';
	plytime = plytime.split(".")
	var plymin = plytime[0];
	var plysec = playerCurrPos-(parseInt(plymin)*60);
	plysec += '';
	plysec = plysec.split(".");
	plysec = plysec[0];
	if (plysec.length < 2) plysec = "0"+plysec;

	return plymin+":"+plysec;
}


function playerFrameMaximise() {
	jQuery("#button-player").attr("class","up");
	if (window.location.href.match(/loadNetwork/) && (typeof(ajaxChatEnabled) == 'undefined' || ajaxChatEnabled == false)) {
		jQuery(frameset).attr("rows","128px, *");
	} else {
		jQuery(frameset).attr("rows","343px, *");
	}
	jQuery('#player').attr("class","maximise");
	jQuery("#maximise-content").css("display","block");
	initTabs(); // Inits tabs only once
	initChat(); // Inits ajax chat only once
	if (playerMediaType == 'Video') jQuery('#no-access').addClass('video');
	jQuery.cookie('playerFrameState', 'maximise', { path: cookieBaseURL});
}


function playerFrameMinimise() {
	jQuery("#button-player").attr("class","down");
	jQuery(frameset).attr("rows","33px, *");
	jQuery('#player').attr("class","minimise");
	jQuery("#maximise-content").css("display","none");
	if (playerMediaType == 'Video') jQuery('#no-access').removeClass('video');
	jQuery.cookie('playerFrameState', 'minimise', { path: cookieBaseURL});
}


/**
 * Refresh the playerFrame with the content for the programme specified
 * @param {} id
 * @param {} format ( e.g. 'MP4_32')
 * @param {} saveFormat bool
 * @param {} playlist bool (whether it's a playlist item or not)
 */
function loadProgramme(id, format, saveFormat, playlist) {
	var url = playerControllerURL + 'loadProgramme/' + id;
	url += '/' + format;
	url += '/' + (saveFormat ? '1' : '0');
	url += '/autostart';
	if (typeof(playlist) != 'undefined' && playlist == true) url += '/playlist';
	playerFrame.location.href = url;
}


/**
 * Refresh the playerFrame with the content for the network specified
 * @param {} id
 * @param {} format (e.g. 'MP4_32')
 * @param {} saveFormat bool
 */
function loadNetwork(id, format, saveFormat) {
	var url = playerControllerURL + 'loadNetwork/' + id;
	url += '/' + format;
	url += '/' + (saveFormat ? '1' : '0');
	url += '/autostart';
	playerFrame.location.href = url;
}


// FIXME: this doesn't work in IE
function initFlagTooltips() {
	// On hover, show Flag bubble
	jQuery(".flag").unbind('hover').hover(
      function () {
      	var pos = jQuery(this).offset();
        jQuery(".flag-popup").css("display","block");
        jQuery(".flag-popup").css("left",pos.left-120);
        jQuery(".flag-popup").css("top",pos.top-30);
      },
      function () {
        jQuery(".flag-popup").css("display","none");
      }
    );

    // On click, show Flag Form
    jQuery(".flag a").unbind('click').click(function(e){
    	e.preventDefault();
    	var params = jQuery(this).attr('rel').split('-');
    	jQuery('#flag-form').find('input[name=Entity]').val(params[0]);
    	jQuery('#flag-form').find('input[name=ID]').val(params[1]);
    	switchRightContentTo('flag-form');
    	jQuery(".flag-popup").css("display","none");
    });
}


/**
 * Inits tabs if necessary
 */
function initTabs() {
	if ( jQuery(".tab-container").length != 0 )	{
		jQuery(".tab-container").each(function(i) {
			if (typeof(this.tabsApplied) == 'undefined') {
				jQuery(this).tabs();
				// Show and hide Add tag/Add comment buttons
				jQuery(this).find('.tabs li a').each(function(i){
					jQuery(this).click(function(e){
						jQuery("#add-tag-tabbutton, #add-comment-tabbutton").addClass('hidden');
						if (this.rel != "") {
							jQuery('#'+this.rel).removeClass('hidden');
						}
					})
					//console.log();
				});
				this.tabsApplied = true;
			}
		});
	}
}


/**
 * Inits ajax chat if necessary
 */
function initChat() {
	// Live Ajax Chat
	if ((jQuery('#chat').length > 0) && (ajaxChatInitialised == false)){
		jQuery('#chat').ajaxChat({
					messagesScroller: '#chat .comment-list',
					updateInterval: 6000, // in miliseconds
					updateCallback: initFlagTooltips
		});
		ajaxChatInitialised = true;
	}
}


/**
 * Reveals the given div ID in the right content panel
 * E.g. 'tag-form', 'comment-form', 'comment-list', 'player-container', etc.
 */
function switchRightContentTo(id) {
	jQuery(".right-content .rc-container").children().addClass('hidden').css('display','none');
	jQuery(".video-player").addClass('hidden');
	$panel = jQuery('#'+id);
	$panel.find('.form-message').empty();
	$panel.removeClass('hidden').css('display','block');
	if (id == 'flag-form') jQuery('.player-top').addClass('force-white-bg'); // css hack for Flag form on Networks
}


function switchRightContentBack() {
	switchRightContentTo(defaultRightContent);
	jQuery('.player-top').removeClass('force-white-bg'); // css hack for Flag form on Networks
}


/**
 * Reloads next broadcast on Networks through ajax
 */
function ajaxNetworkUpdate() {
	jQuery.post(ajaxNetworkUpdateUrl, {}, function(response,status){
		if (status == 'success') {
			jQuery('.ajax-network-update').html(response);
			ajaxChatInitialised = false;
			playerFrameOnLoad(false);
		}
		else {
			ajaxNetworkUpdate();
		}
	}, 'html');
}