
/* Slider
 *  (c) 2010 Andrey Nebogin anebogin@gmail.com
 *
 *  jQuery is used.
 *  Description: fade in-out the gallery
*/

function FadeInOut( el, opts )
{
	var self = this;
	
	var el = $(el);
	var container = null;
	
	var timer = null;
	var animationRun = false;
	
	var VERSION = "1.0.0";
	
	this.options = {
		path: '/js/fadeinout/', // path where slider is
		get_items_ajax_url: null, // url to get slides data, AJAX method is used
		
		slide_duration: 400,
		slide_easing: 'swing',
		slide_id_prefix: 'slider_player', // prefix of the id of the slide player ( flv, mov or stream )
		
		onClick: null,
		onLoadedFirst: null,
		onPlay: null,
		afterPlay: null,
		onMetaData: null,
		
		autoPlay: true,
		autoPlayInterval: 2000,
		
		showIdx: 0
	};
	
	this.isLoadedFirst = false; //flag shows if the first slide was loaded
	this.isLoadedAll = false; //flag shows if the all slides were loaded
	this.slidesData = null; // copy of the slides data which received using get_items_ajax_url
	this.slides = []; // created divs and addition data
	this.currentIdx = 0;
	
	this.getEl = function()
	{
		return( el );
	};
	
	var loadedFirst = function( func )
	{
		var thisTimer;
		thisTimer = setInterval( function()
		{
			if( self.isLoadedFirst == true )
			{
				clearInterval( thisTimer );
				func();
			}
		}, 20);
	};
	
	this.loadedFirst = function( func )
	{
		loadedFirst( func );
		return self;
	};
	
	var loadedAll = function( func )
	{
		var thisTimer;
		thisTimer = setInterval( function()
		{
			var loaded = true;
			for( var i=0; i<self.slides.length; i++ )
			{
				if( !self.slides[i].loaded )
				{
					loaded = false;
					break;
				}
			}
			if( loaded )
			{
				self.isLoadedAll == true;
				clearInterval( thisTimer );
				func();
			}
		}, 20);
	};
	
	this.loadedAll = function( func )
	{
		loadedAll( func );
		return self;
	};
	
	var getSizeCss = function( value )
	{
		var retval = value;
		
		var exp1 = /^.+px\s*$/i;
		var exp2 = /^.+%\s*$/i;
		if( exp1.test(value) ) retval = value;
		else if( exp2.test(value) ) retval = value;
		else retval = parseInt(value) +'px';
		
		return( value );
	};
	
	var createSlides = function( data )
	{
		self.slidesData = data.slides;
		
		container = $('<div></div>').css({
			'position': 'absolute',
			'z-index': 10,
			'width': getSizeCss(data.width),
			'height': getSizeCss(data.height)
		});
		el.append( container );
		
		for( var i=0; i<data.slides.length; i++ )
		{
			
			if( typeof(data.slides[i]) == 'object' )
			{
				var opts = {
					"width": data.width,
					"height": data.height,
					"data_path": data.data_path
				};
				createSlide( container, data.slides[i], i, opts );
			}
		}
	};
	
	var getExt = function( filename )
	{
		return filename.split('.').pop();
	};
	
	/*
		slide:
			id - ID of the slide
			small - small version of the original image
			original - original image or vide file
			url - stream video
	*/
	var createSlide = function( element, slide, idx, opts )
	{
		if( typeof(slide) == 'object' )
		{
			var id = slide.id;
			
			//var w = el.width();
			//var h = el.height();
			var w = '100%';
			var h = '100%';
			var div = $('<div></div>').css({
				'position': 'absolute',
				'display': 'none',
				'left': '0px',
				'top': '0px',
				'width': w,
				'height': h
			});
			
			element.append( div );
			
			var loader = null;
			if( idx == 0 )
			{
				loader = $("<div><img src='"+ self.options.path +"loader.png' border='0'/></div>").css({
					"position": "absolute",
					"z-index": 100,
					"width": '118px',
					"height": '90px',
					"background": 'transparent url('+ self.options.path +'loader.gif) no-repeat 50% 100%',
					"top": (div.height()/2 - 45) +"px",
					"left": (div.width()/2 - 59) +"px"
				});
				el.append( loader );
			}
			
			var filename  = null;
			var ext = null;
			var streamUrl = slide.url;
			filename = opts.data_path + slide.original;
			ext = getExt( slide.original ).toLowerCase();

			self.slides.push( {
				'id': id,
				'idx': idx,
				'ext': ext,
				'loaded': false,
				'div': div
			} );

			poster = '';
			if (slide.cover) {
				poster = opts.data_path + slide.cover;
			}

			if (ext == "flv" || ext == "flvold" || ext == "mov" || streamUrl != '') {
				var w = '100%';
				var h = '100%';
				
				var player = $('<div class="solik_video_back" id="' + self.options.slide_id_prefix + id + '"></div>').css({
					"width": w,
					"height": h,
					"position": "absolute",
					"z-index": 10
				});
				if( loader ) loader.remove();
				div.append( player );
				if( idx == 0 ) self.isLoadedFirst = true;
				self.slides[idx].loaded = true;

				player.css('background-image', 'url("' + poster + '")')
			        .css({
				        "filter": "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + poster + "', sizingMethod='scale')",
				        "-ms-filter": "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + poster + "', sizingMethod='scale')"
			        });

				var origWidth = 1920;
				var origHeight = 1300;
				var origVideoHeight = 610;
				var origVideoWidth = 1094;
				// calculate factor
				var aspectRatio = origWidth / origHeight; 
				var scaleFactorW = div.width() / origWidth;
				var scaleFactorH = div.height() / origHeight;
				var scaleFactor;
				if ((div.width() / div.height()) < aspectRatio) {
					scaleFactor = scaleFactorH;
				} else {
					scaleFactor = scaleFactorW;
				}
				// XXX: debug
				if (window.console) console.log('scaleFactorW',scaleFactorW);
				if (window.console) console.log('scaleFactorH',scaleFactorH);
				if (window.console) console.log('scaleFactor',scaleFactor);

				w = parseInt(Math.ceil(origVideoWidth * scaleFactor), 10);
				h = parseInt(Math.ceil(origVideoHeight * scaleFactor), 10);

//				player.html( '<video class="solik_mejs" poster="' + poster + '" width="' + w + '" height="' + h + '" src="' + ((streamUrl != '') ? decodeURIComponent(streamUrl) : filename) +'"></video>' );
				player.html( '<div class="solik_mejs_container"><video width="' + w + '" height="' + h + '" class="solik_mejs" src="' + ((streamUrl != '') ? decodeURIComponent(streamUrl) : filename) +'"></video></div>' );
				$('div.solik_mejs_container', player).css({
					'position': 'absolute',
					'top': '50%',
					'left': '50%',
					'margin-left': (parseInt(Math.ceil(-w / 2), 10)) + 'px',
					'margin-top': (parseInt(Math.ceil(-h / 2), 10) - parseInt(Math.floor(85 * scaleFactor), 10)) + 'px',
					'width': w + 'px',
					'height': h + 'px'
				});
				$('video', player).mediaelementplayer({
					"loop": false,
					"enableAutosize": true,
					"defaultVideoWidth": w + 'px',
					"defaultVideoHeight": h + 'px',
					"features": ['playpause','progress','fullscreen']
				});

			}
			else
			{
				//var w = el.width();
				//var h = el.height();
				var w = '100%';
				var h = 'auto';
				
				var img = $('<img class="image_to_fit" id="' + self.options.slide_id_prefix + id + '" src="' + filename + '" border="0" />').css({
					"position": "absolute",
					"width": w,
					"height": h,
					"z-index": 10
				}).load(function(){
					if( loader ) loader.remove();
					div.append( img );
					if( idx == 0 ) self.isLoadedFirst = true;
					self.slides[idx].loaded = true;
				});
			}
		}
	};
	
	var supportHTML5Video = function()
	{
		return( !!document.createElement('video').canPlayType );
	};
	
	var show = function( idx )
	{
		if( self.slides.length > 0 )
		{
			self.currentIdx = idx;
			var s = self.slides[idx].div;
			animationRun = true;
			s.fadeIn( function() { animationRun = false; } );
			if( $.browser.msie ) s.children('img').first().fadeIn();
			if( self.options.onLoadedFirst != null )
			{
				self.options.onLoadedFirst( self, self.slidesData[self.options.showIdx] );
			}
		}
	};
	
	this.prev = function()
	{
		if( !animationRun && self.slides.length > 1 && self.currentIdx-1 >= 0 )
		{
			var prevIdx = self.currentIdx;
			self.currentIdx --;
			//if( self.currentIdx < 0 ) self.currentIdx = self.slides.length - 1;
		
			play( self.currentIdx, prevIdx, -1 );
		}
	};
	
	this.next = function()
	{
		if( !animationRun && self.slides.length > 1 && self.currentIdx+1 < self.slides.length )
		{
			var prevIdx = self.currentIdx;
			self.currentIdx ++;
			//if( self.currentIdx >= self.slides.length ) self.currentIdx = 0;
		
			play( self.currentIdx, prevIdx, 1 );
		}
	};
	
	this.play = function( idx )
	{
		if( !animationRun )
		{
			var prevIdx = self.currentIdx;
			self.currentIdx = idx;
			if( self.currentIdx >= self.slides.length ) self.currentIdx = 0;
			
			if( idx != prevIdx ) play( self.currentIdx, prevIdx, 1 );
		}
	};
	
	/* direction = 1 -next, -1 -prev */
	var play = function( idx, prevIdx, direction )
	{
		if( !animationRun )
		{
			if( self.slides[prevIdx].ext == 'flv' || self.slides[prevIdx].ext == 'url' )
			{
				$f(self.options.slide_id_prefix+self.slides[prevIdx].id).stop();
			}
			
			clearTimeout( timer );
			
			animationRun = true;
			
			self.slides[prevIdx].div.fadeOut( function() {
				var etot_slide = self.slides[idx].div;
				/**
				 * trigger window resize in the correct place with visible containers
				 * @author Solik 
				 */
				if (etot_slide.is(':hidden')) {
					etot_slide.css({'display': 'block', 'opacity': 0});
					$(window).resize();
					etot_slide.css({'display': 'none', 'opacity': 1});
				}
				etot_slide.fadeIn( function() {
					if( self.options.afterPlay != null ) self.options.afterPlay( self, self.slidesData[idx] );
					animationRun = false;
				});
			});
			if( $.browser.msie ) self.slides[prevIdx].div.children('img').first().fadeOut( function() {
				self.slides[idx].div.children('img').first().fadeIn();
			});
			if( self.options.onPlay != null ) self.options.onPlay( self, self.slidesData[idx] );
			
			if( self.options.autoPlay )
			{
				var duration = self.options.autoPlayInterval;
				
				timer = setTimeout( function() {
					self.next();
				}, duration );
			}
		}
	};

	var initialize = function( opts )
	{
		if( typeof(opts) != "undefined" )
		{
			for(var key in opts) self.options[key] = opts[key];
		}
		
		if( self.options.get_items_ajax_url )
		{
			$.ajax(
			{
				type: 'POST',
				dataType: "json",
				url: self.options.get_items_ajax_url,
				data: null,
				success: function( data )
				{
					createSlides( data );
					
					loadedFirst( function() {
						self.slides[self.options.showIdx].div.css({
							'left': '0px'
						});
						if( self.options.onLoadedFirst != null )
						{
							self.options.onLoadedFirst( self, self.slidesData[self.options.showIdx] );
						}
						show( self.options.showIdx );
						if( self.options.autoPlay )
						{
							var duration = self.options.autoPlayInterval;
							
							timer = setTimeout( function() {
								self.next();
							}, duration );
						}
					} );
				},
				error: function( XMLHttpRequest, textStatus, errorThrown ) { alert('error get data: '+textStatus ); try {} catch (e) {} }
			});
		}
	};
	
	initialize( opts );
};

