/* 

Resizify_vimeo 0.2 FAUSTMOD
	
Copyright (c) 2010, Robb Irrgang <robb@cartelblanche.com>
All rights reserved.

Please don't take the code and run with it, a proper open sourcing is coming soon. 

*/

(function($) {
    $.fn.extend({
		resizify_vimeo: function(url, options) {
		var settings = $.extend({
			cache_folder: 'cache/resizify_',
			ratio: 16/9
		}, options);
				
		var movie_url		= url;
		var movie_ratio		= settings.ratio;
		var base_directory	= movie_url.substr(0, movie_url.lastIndexOf('/')+1);
		var base_file		= movie_url.substr(movie_url.lastIndexOf('/')+1);
		var base_extension	= base_file.substr(base_file.lastIndexOf('.'));
		var base_filename	= base_file.substr(0, base_file.length-base_extension.length);
		var ref				= this;
			
		var window_w;
		var window_h;
		var movie_w;
		var movie_h;
		var resize_timeout;

		$(ref).hide();
			
		$(this).addClass('backdrop');						
			function setDimensions() {
				window_w = $(window).width();
				window_h = $(window).height();		
				
				movie_w = window_w;
				movie_h = Math.round(movie_w/movie_ratio);

				if (movie_h < window_h) {
					movie_h = window_h;
					movie_w = Math.round(movie_h*movie_ratio);
				}
																
				if (settings.max_def && movie_h > settings.max_def) {
					movie_h = settings.max_def;
					movie_w = Math.round(movie_h*movie_ratio);
					$('#vimeo_backdrop').show();
				}

				$(ref).find('iframe').get(0).width = movie_w;
				$(ref).find('iframe').get(0).height = movie_h;
				
				$(ref)
					.css('width', movie_w+'px')
					.css('height', movie_h+'px')
					.css('margin-left', -Math.round(movie_w/2)+'px')
					.css('margin-top', -Math.round(movie_h/2)+'px');
			}
			
			function loadMovie(url, chainable) {
				$(ref).html('<iframe src="http://player.vimeo.com/video/'+url+'?title=0&amp;byline=0&amp;portrait=0&amp;color=F15A22&amp;autoplay=1&amp;loop=1" width="'+movie_w+'" height="'+movie_h+'" frameborder="0"></iframe>');	
				$(ref).show();	
				setDimensions();
			}
			
			$(window).unbind('resize');

			$(window).bind('resize', function() {
				setDimensions();
				
				if (resize_timeout) {
					clearTimeout(resize_timeout);
					resize_timeout = false;
				}

				resize_timeout = setTimeout(function() {  }, 1000);
			});

			return this.each(function() { //main
				loadMovie(movie_url);
			});
		}
	});
})($);

