/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * 
 * js.js - main Javascript template to drive flash player  *
 *         and asyncronous functionality; Currently not    *
 *         compatible with any release version of IE       *
 *                                                         *
 *  This file is a part of the djidio package              *
 *                                                         *
 *   Copyright (c) 2008 Samuel Sutch, SamuraiFilms.org     *
 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */


var Player = new (function() {
	this.playlist = [];
	this.current_item = null;
	this.current_item_info = null;
	this.last_requested_name = null;
	this.first_play = true;
	this.playing = false;
	this.player_object = null;
	
	var THIS = this;
	
	var embed_and_play = function(elem) { 
		return $(elem).flashembed({
				src: "http://media.beta.samuraifilms.org//flash/FlowPlayerLight.swf",
				width: 710,
				height: 400
			}, {
				config: {
					autoPlay: true,
					videoFile: THIS.current_item_info['flv_url'],
					initialScale: 'fit',
					controlsOverVideo: 'ease',
					showPlayListButtons: false,
					controlBarBackgroundColor: -1,
					timeDisplayFontColor: 255,
					progressBarColor1: 1,
					progressBarColor2: 1,
					progressBarBorderColor1: 0,
					progressBarBorderColor2: 0,
					controlsAreaBorderColor: 0
				}
			}
		);
	};
	
	this.set_player_object = function(obj) { THIS.player_object = obj; };
	
	this.play_video = function() {
		var play = function() { return embed_and_play('#player-area'); };
		if (START_PLAYING) window.location.hash = escape(THIS.current_item_info['title']);
		if (THIS.first_play === true) {
			THIS.first_play = false;
			THIS.show_playing_in(play);
		} else {
			THIS.update_information();
			return play();
		}
	};
	
	this.update_playlist = function(episode_name) {
		THIS.last_requested_name = episode_name;
		$.ajax({
			url: "/playlist/" + episode_name,
			processData: true,
			dataType: 'json',
			success: THIS.on_playlist_fetch_update
		});
	};
	
	this.pause = function() {
		if (THIS.player_object)
			THIS.player_object.Pause();
	};
	
	this.update_information = function() {
		$.ajax({
			dataType: 'html',
			processData: true,
			url: '/player/'+escape(THIS.current_item_info['title']),
			success: function(res) {
				var _html = $(res);
				$("#player .title-area").replaceWith(_html.filter("div.title-area"));
				THIS.add_back_button();
				$("#player #episodeinformation").replaceWith(_html.filter("div#episodeinformation"));
				truncate_longshit();
			}
		});
	};
	
	this.add_back_button = function() {
		if (ADD_BACKTO_BUTTON) {
			$("#player .title-area h3").prepend('<a title="Go back to page" id="backtobutton" href="#">&laquo;&nbsp;</a> ')
			$("#backtobutton").click(function() { location.reload(true); });
		}
	};
	
	this.play_item = function(item) {
		$("#playlist-area ul li[item="+THIS.current_item+"]").removeClass('playing');
		$("#playlist-area ul li[item="+item+"]").addClass('playing');
		THIS.current_item = item;
		THIS.current_item_info = THIS.playlist[item];
		THIS.play_video();
	};
	
	this.get_next_item = function() {
		if (typeof(THIS.playlist[THIS.current_item + 1]) == 'undefined')
			return 0;
		else
			return THIS.current_item + 1;
	};
	
	this.show_loading = function(el) {
		el.html('<p class="showloading clear">Loading...<br /><img src="http://media.beta.samuraifilms.org/images/loader.gif" /></p>');
	};
	
	this.on_playlist_fetch_update = function(json) {
		THIS.playlist = json;
		var _playlist = $("#playlist-area");
		THIS.show_loading(_playlist);
		
		var _html = ['<div class="box2 clear"><h3>Playlist</h3>', '<ul>'];
		var classes;
		var to_play = false;
		
		for (var i in json) {
			classes = [];
			if (json[i]['title'] == THIS.last_requested_name) {
				THIS.current_item = Number(i);
				THIS.current_item_info = json[i];
				classes.push('playing');
				to_play = true;
			}
			_html.push('<li item="'+i+'" class="playlistitem ' + classes.join(' ') + '">' +
				THIS.playlist[i]['title'] + '</li>');
		}
		_html.push('</ul></div>');
		_playlist.html(_html.join("\n"));
		$("#playlist-area ul li").click(THIS.on_playlist_item_click);
		if (to_play === true)
			THIS.play_video();
		else {
			THIS.current_item = 0;
			THIS.current_item_info = json[0]['fields'];
			THIS.play_video()
		}
	};
	
	this.on_playlist_item_click = function() {
		var item = Number($(this).attr('item'));
		THIS.play_item(item);
	};
	
	this.show_playing_in = function(cb) {
		$("#player-area").html('<div id="playingin">Video Will Begin Playing in <span></span> Click Here to Stop</div>');
		var stop = false;
		$("#playingin").click(function() {
			$("#player-area").html('<div id="playingin">Choose a Video</div>');
			stop = true;
		});
		$("#playingin span").countdown({
			until: (function(){var i=new Date();i.setSeconds((new Date).getSeconds() + 7.5);return i;})(),
			format: 'S',
			description: '',
			onExpiry: function() { if (!stop) cb(); }
		})
	};
})();


/// FLOWPLAYER SWF CALLBACKS
function onPlay(clip) {
	setTimeout("Player.playing=true", 100);
}

function onPause(clip) {
	setTimeout("Player.playing=false", 100);
}

function onStop(clip) {
	setTimeout("Player.playing=false", 100);
}

function onClipDone(clip) {
	setTimeout("Player.play_item(Player.get_next_item())", 100);
}

//var _onFlowPlayerReady = function() {
//	player = $("#player-area > :first")[0];
//	Player.player_object = player;
//};

function onFlowPlayerReady() {
	setTimeout('Player.set_player_object($("#player-area > :first")[0])', 100);
}


///
/// VIDEO FINDER, MISC FUNCTIONS
///

var show_series = function(author_name) {
	// load series list
	var _series = $("#series");
	_series.load("/series/"+escape(author_name), null, function(res, sta, req) {
		alternate_background($("#series li"));
	
		// set it up to look at individual episodes
		var __series = $("#series ul li");
		__series.each(function(el) {
			var individual_series = $(__series[el]);
			individual_series.click(function() {
				show_episodes($(this).children(":first-child").text());
			});
		});
	
		$(".series-hover").hoverIntent({
			over: function(ev) { $(this).children(".loadme").slideDown('normal'); },
			out: function(ev) { $(this).children(".loadme").slideUp('normal'); },
			sensitivity: 25
		});
	});
	// loader
	_series.children('p').replaceWith('<p><img src="http://media.beta.samuraifilms.org/images/loader.gif" /></p>');
};

var show_episodes = function(series_name) {
	var _episodes = ($("#episode"));
	_episodes.load("/episodes/"+escape(series_name), null, function(res, sta, req) {
		alternate_background($("#episode li"));
	
		var __episodes = $("#episode ul li");
		__episodes.each(function(el) {
			var individual_episode = $(__episodes[el]);
			individual_episode.click(function() {
				present_video($(this).children('.episode-name').text());
			});
		});
	});
	// loader
	_episodes.children('p').replaceWith('<p><img src="http://media.beta.samuraifilms.org/images/loader.gif" /></p>');
};

var present_video = function(video_name) {
	var _player = $('<div id="player"> </div>');
	_player.load("/player/"+escape(video_name), function(res, sta, req) {
		if (expanded)
			toggle_video_finder();
		Player.update_playlist(video_name);
		// manipulate /player HTML
		Player.add_back_button();
		truncate_longshit();
	});
	$("#thecontent").html(_player);
};

var alternate_background = function(list_of_lis) {
	var counter = 0;
	$(list_of_lis).each(function(el) {
		counter += 1;
		var li = $(list_of_lis[el]);
		if (counter % 2 == 0)
			li.addClass('alt1');
		else
			li.addClass('alt2');
	});
};

var truncate_longshit = function() {
	$("#toolongdesc").truncate(150, {
		chars: /\s/,
		leave: false,
		trail: [true, '&nbsp; <a href="" title="Click to show more...">(more...)</a>',
					  '&nbsp; <a href="" title="Click to show less...">(less...)</a>']
	});
	$("#toolongcred").truncate(85, {
		chars: /\s/,
		leave: false,
		trail: [true, '&nbsp; <a href="" title="Click to show more...">(more...)</a>',
					  '&nbsp; <a href="" title="Click to show less...">(less...)</a>']
	});
};

var expanded = false;

var toggle_video_finder = function() {
	if (expanded == true) {
		$("#video-finder").hide('slow');
		expanded = false;
		$("#show-videos").css('background-image', 'url(http://media.beta.samuraifilms.org/images/choose-video-unselected.png)');
	} else {
		$("#video-finder").show('slow');
		expanded = true;
		$("#show-videos").css('background-image', 'url(http://media.beta.samuraifilms.org/images/choose-video-selected.png)');
	}
};

/// ONLOAD
$(document).ready(function() {
	/// image preload
	$.each([
		"http://media.beta.samuraifilms.org/images/choose-video-selected.png",
		"http://media.beta.samuraifilms.org/images/subscribe-hover.png"
	], function (index, item) {
		$("<img />").attr("src", item);
	});
	
	/// subscribe click
	$("#subscribe-podcast").click(function() {
		Player.pause();
	});
	
	/// authors list
	var _authors = $('#author ul li');
	_authors.each(function(el) {
		var _author = $(_authors[el]);
		_author.click(function() {
			show_series($(this).children(':first-child').text());
		});
	});
	alternate_background($("#author li"));
	$(".author-hover").hoverIntent({
		over: function(ev) { $(this).children(".loadme").slideDown('normal'); },
		out: function(ev) { $(this).children(".loadme").slideUp('normal'); },
		sensitivity: 25
	});
	
	/// show video link
	$("#show-videos").click(function() {
		toggle_video_finder();
	});
	

	/// archive months
	$(".archive_month").click(function() {
		$(this).children(".loadme").slideDown('normal');
	});

	/// archive links
	$(".archive_link").click(function() {
		present_video($(this).text());
	});
	
	if (START_PLAYING) {
		var _linked_to = unescape(window.location.hash.slice(1));
		if (!_linked_to.length)
			present_video(DEFAULT_PAGE);
		else
			present_video(_linked_to);
	}
});
