/*!
 * jQuery Pinchevideo
 * Copyright (c) 2009 Pablo Ziliani, Kultroom
 * Version: 2.00 (02-NOV-2009)
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
 * Requires: jQuery > v1.2.6, Flowplayer > v3.1
 */
;(function($) {

$.fn.pinchevideo = function(settings) {
	var config = {
		videos: 'a[href*=".flv"]',
		player: '<a class="video" style="background-image:${ thumbnail }"><img src="${ play_image }" /> ${ title }</a>',
		play_image: '/images/play.png',
		fp_url: '/js/flowplayer/flowplayer-3.1.5.swf',
		fp_config: {
			clip: {
				autoBuffering: true
			},
			playlist:[],
			plugins: {
				controls: {
					playlist: true
				}
			}
		},
		activeClass: 'active'
	};

	if (settings) $.extend(config, settings);

	return this.each(function() {
		var $widget = $(this),
			$videos = $widget.find(config.videos),
			fp_config = $.extend({}, config.fp_config),
			starting_clip_index = 0,
			starting_clip;

		$videos.each(function(index){
			var clip, img,
				href = this.href,
				url = href.split('#')[0],
				thumb = href.match(/thumb=([^&]+)/),
				$li = $(this).click(function(){
						$(this).data('player').play(index);
						return false;
					}).parent();

			if (thumb) {
				img = new Image();
				img.src = thumb[1]; // preload
				thumb = 'url('+img.src+')';
			} else thumb = 'none';

			fp_config.playlist.push({
				url: url,
				thumbnail: thumb,
				play_image: config.play_image,
				title: $(this).text(),
				onBegin: (function(clip){
					$li.addClass(config.activeClass)
					.siblings().removeClass(config.activeClass);
				})
			});
			if ($li.is('.' + config.activeClass))
				starting_clip_index = index;
		});
		starting_clip = fp_config.playlist[starting_clip_index];
		$videos.data('player',
			$(config.player
				.replace(/\$\{\s*([^}]+?)\s*\}/g, function(tag, name){
					return starting_clip[name]||'';
				})
			)
			.prependTo(this)
			.click(function(){$f(this).play(starting_clip_index)})
			.flowplayer(config.fp_url, fp_config)
			.flowplayer(0)
		);
	});

};

})(jQuery);