
jQuery.fn.player = function () {

	var o		= this,
		wrapper	= $('#wrapper'),
		title	= $(this).find('#title'),
		media	= $(this).find('#media'),
		author	= $(this).find('#author');

	var playerHeight, playerWidth;

	var c = config;

	var l = jQuery.fn.player.language;

	function repos(){

		var w, h;

		var area = {'width' : $(window).width(), 'height' : $(window).height()};

		var margin = {top: 0, left: 0};

		if ( area.width >= playerWidth && area.height >= playerHeight ) {
			w = playerWidth;
			h = playerHeight;

			margin.top	= (area.height-h) / 2;
			margin.left = (area.width-w)  / 2;
			
		} else {

			if ( (playerHeight * area.width / playerWidth) > area.height ) {
				h = area.height;
				w = area.height * playerWidth / playerHeight;

			} else {
				w = area.width;
				h = area.width * playerHeight / playerWidth;
			}
		}

		if ( w < 500 ) w = 500;
		if ( h < 350 ) h = 350;

		margin.left = (area.width-w) / 2;
		margin.top	= (area.height-h) / 2;

		if ( margin.top < 0 )  margin.top = 0;
		if ( margin.left < 0 ) margin.left = 0;

		wrapper.css({'width' : w, 'height' : h, 'margin-left' : margin.left, 'margin-top' : margin.top});

		fs.video.resizeProgressBar();
	}

	return this.each(function(){

		document.title = c.title;

		var titleBox = $('<div>', { 'text' : c.title }),
			hint;

		/* titleBox */

		hint = new Array();

		if (c.author.name)	hint.push(c.author.name);
		if (c.duration)		hint.push(c.duration);

		titleBox.append( $('<span>', {
			'class' : 'hint',
			'text' : ' (' + hint.join(', ') + ')'
		}) )

		title.html(titleBox);

		$(function(){

			playerWidth  = parseInt(wrapper.outerWidth(), 10)  + parseInt(c.width, 10);
			playerHeight = parseInt(wrapper.outerHeight(), 10) + parseInt(c.height, 10);

			var m = config.duration.split(':');

			if (m.length == 2)	var duration = (  60*parseInt(m[0], 10) +    parseInt(m[1], 10));
			if (m.length == 3)	var duration = (3600*parseInt(m[0], 10) + 60*parseInt(m[1], 10) + parseInt(m[2], 10));

			var index = config.index;
			// index
			if (config.author.photo) $(this).find('#author').append($('<img>', {'src' : config.author.photo}));

			fs.index.init( 'index', index, duration );

			var args = {
				'duration'	: duration,
				'poster'	: config.poster,
				'src'		: config.src,
				'index'		: index
			};
			
			if ( config.storyboard ) args.storyboard = config.storyboard;

			// video
			fs.video.init( 'player', {}, args );

			var tmr;

			repos();

			$(window).bind('resize orientationchange', function(){
				clearTimeout(tmr);
				tmr = setTimeout(function(){
					repos();
				}, 500);
			});
		});

	});

};

