﻿// alternative resize callback
(function($,sr){
// debouncing function from John Hann
// http://unscriptable.com/index.php/2009/03/20/debouncing-javascript-methods/
var debounce = function (func, threshold, execAsap) {
var timeout;
return function debounced () {
var obj = this, args = arguments;
function delayed () {
if (!execAsap)
func.apply(obj, args);
timeout = null;
};
if (timeout)
clearTimeout(timeout);
else if (execAsap)
func.apply(obj, args);
timeout = setTimeout(delayed, threshold || 500);
};
}
// smartresize
jQuery.fn[sr] = function(fn){ return fn ? this.bind('resize', debounce(fn)) : this.trigger(sr); };
})(jQuery,'smartresize'); 

// indexOf for IE
if ($.browser.msie) {
if (!Array.prototype.indexOf) {
Array.prototype.indexOf = function (searchElement /*, fromIndex */ ) {
"use strict";
if (this === void 0 || this === null) {
throw new TypeError();
}
var t = Object(this);
var len = t.length >>> 0;
if (len === 0) {
return -1;
}
var n = 0;
if (arguments.length > 0) {
n = Number(arguments[1]);
if (n !== n) { // shortcut for verifying if it's NaN
n = 0;
} else if (n !== 0 && n !== (1 / 0) && n !== -(1 / 0)) {
n = (n > 0 || -1) * Math.floor(Math.abs(n));
}
}
if (n >= len) {
return -1;
}
var k = n >= 0 ? n : Math.max(len - Math.abs(n), 0);
for (; k < len; k++) {
if (k in t && t[k] === searchElement) {
return k;
}
}
return -1;
}
}
}

function preloader(doit, callback){
	
	// функция запускающая / останавливающая прелоадер
	
	switch (doit){
		case 'show':
			$('#preloader .progress').css({'left': ($(window).width()/2-115)+'px', 'top': $(window).height()/2-115+'px'});
			$('#preloader').addClass('active').removeClass('notactive');
			$('#preloader .bg').addClass('on');
			$('#preloader .progress').addClass('show');
			
			$('#preloader').data({'callback': callback, 'timestamp': new Date().getTime()});
			//spriteLogo();
			
			break;
		case 'hide':
			//$('#preloader').fadeOut('fast');
			if ( ( new Date().getTime()-1000 ) < $('#preloader').data('timestamp') ) {
				setTimeout(function(){
					preloader('hide');
				}, 100);
			} else {
				//spriteLogo('hide');
				$('#preloader .progress').addClass('hide');
				setTimeout(function(){
					$('#preloader .bg').removeClass('on');
					if (typeof($('#preloader').data('callback')) == 'function') {
						$('#preloader').data('callback')();
					}
				}, 400);
				setTimeout(function(){
					//$('#preloader').hide();
					$('#preloader').removeClass('active').addClass('notactive');
					$('#preloader .progress').removeClass("hide").removeClass("show");
				}, 1200);
				
			}
		break;
	}
	
}



var sInterval;
function spriteLogo(doit){
	
	// вспомогательная функция для прелоадера
	doit = doit || false;
	
	var $sLogo = $('.spriteLogo');
	
	if (!doit) {
		var bPosition = 0;
		sInterval = setInterval(function(){
			if (bPosition==-2700) { bPosition = 0; }
			$sLogo.css('background-position', bPosition+'px 0px');
			bPosition = bPosition - 90;
		}, 50);
	} else {
		
		clearInterval(sInterval)
		$sLogo.css('background-position', '-2700px 0px');
	}
	
}

;(function($){
	$.fn.ivideo = function(options) {  
		opt = $.extend({
			target: undefined,
			playlist: [],
			originalSize: [1900, 700],
			width: '100%',
			height: undefined,
			fixedcontent: false,
			scrollarea: $('#scrollarea'),
			eventsProxy: $('html'),
			preloader: null,
			swf: '/assets/flash/ivideo.swf'
		}, options);
		
		var html5 = !!document.createElement('video').canPlayType;

		//html5 = false;

		var ios = navigator.userAgent.toLowerCase().match(/(iphone|ipad)/);
		
		if (typeof(api) != 'object') {
			api = {};
		}

		
		//var html5 = true;
		api.scrollarea = opt.scrollarea;
		api.events = opt.eventsProxy;
		api.stopimg = opt.stopimg;
		api.utils = {};
		api.movehistory = [];
		api.movehistory.push(opt.startItem.startPos);
		var video = false;

		//var api = {};
		
		
		if (transitionEnd) {
			$(api.stopimg).live( transitionEnd.event, function( event ){
				//console.log('end transition', this);
				if ($(this).hasClass('fadeIn')) {
					//$(this).removeClass('fadeIn').removeClass('fadeOut');
					console.log('TRIGGER FADEIN');
					$(this).trigger('fadeIn');
				}
				if ($(this).hasClass('fadeOut')) {
					//$(this).css('opacity', '0').removeClass('fadeOut').removeClass('fadeIn');
					$(this).trigger('fadeOut');
					console.log('TRIGGER FADEOUT');
				}
			});
		}
		
		function stopimgFader(doit){

			if (!transitionEnd) {
				if (doit=='fadeOut') {
					$(api.stopimg).fadeOut(10, function(){
						$(api.stopimg).trigger('fadeOut');
					});
				} else {
					$(api.stopimg).fadeIn(10, function(){
						$(api.stopimg).trigger('fadeIn');
						$(api.stopimg).show();
					});
				}
			} else {
				if (doit=='fadeOut') {
					console.log('transitionEnd fadeOut');
					$(api.stopimg).removeClass('fadeIn').addClass('fadeOut');
				} else {
					console.log('transitionEnd fadeIn');
					$(api.stopimg).removeClass('fadeOut').addClass('fadeIn');
				}
			}
		}
		
		
		function canPlayType(){
			var supported = [];
			if (html5) {
				var v = document.createElement('video');
				if (v.canPlayType('video/webm') == 'probably' || v.canPlayType('video/webm') == 'maybe') {
					supported.push('video/webm');
				}
				if ((v.canPlayType('video/ogg') == 'probably' || v.canPlayType('video/ogg') == 'maybe') && !/chrome/.test(navigator.userAgent.toLowerCase())) {
					supported.push('video/ogg');
				}
				if ((v.canPlayType('video/mp4') == 'probably' || v.canPlayType('video/mp4') == 'maybe') && !/chrome/.test(navigator.userAgent.toLowerCase())) {
					supported.push('video/mp4');
				}
			} else {
				//alert('flash!');
				supported.push('video/mp4');
			}
			return supported;
				
		}
		
		function selectVideo(src){
			var supported = canPlayType();
			var selectedSource = false;
			for (var i=0; i<src.length; i++) {
				if (supported.indexOf(src[i][1]) != -1) {
					if (html5) {
						selectedSource = src[i][0];
					} else {
						selectedSource = src[i][0].split('.m4v')[0] + '_flash.m4v';
					}
					break;
				}
			}
			console.log('selectedSource', selectedSource);
			return selectedSource;
		}
		
		function cueItem(name, start, end, playlistName){
			
			this.name = name;
			this.start = start.time;
			this.end = end.time;
			this.startimg = start.img;
			this.endimg = end.img;
			this.startaction = start.action;
			this.stopaction = end.action;
			this.playlist = playlistName;
						
		}
		
		api.utils.cueItem = cueItem;
		
		function parsePlaylist() {
			console.log('opt.playlist', opt.playlist);
			api.utils.parsePlaylist(opt.playlist);
		}
		
		api.utils.parsePlaylist = function(playlist) {
			
			var inst = {};
			api.playlists = {};
			
			for (var i=0; i<playlist.length; i++) {
				playlist[i].src = selectVideo(playlist[i].video_src);
				api.playlists[playlist[i].name] = playlist[i];
				
				
				
				for (var j=0; j<playlist[i].cue.length; j++) {
					inst[playlist[i].cue[j].name] = {
						start       : playlist[i].cue[j].start,
						end         : playlist[i].cue[j].end,
						startimg    : playlist[i].cue[j].onstartimg,
						endimg      : playlist[i].cue[j].onendimg,
						name        : playlist[i].cue[j].name,
						stopaction  : playlist[i].cue[j].stopaction,
						startaction : playlist[i].cue[j].startaction,
						playlist    : playlist[i].name
						}
					
				}
			}
			
			api.inst = inst;
			
		}
		
		api.utils.addCue = function(cue) {
			
			api.playlists[cue.playlist].cue.push(cue);
			api.inst[cue.name] = cue;
			
		}
		
		
		function isInteger(value) {
			return /^[0-9]+$/.test(value);
		};
		
		// вычисляем video ratio
		function reduceRatio(numerator, denominator) {
			var gcd, temp, divisor;
			
			gcd = function (a, b) { 
				if (b === 0) return a;
				return gcd(b, a % b);
			}

			// take care of some simple cases
			if (!isInteger(numerator) || !isInteger(denominator)) return '? : ?';
			if (numerator === denominator) return '1 : 1';

			divisor = gcd(+numerator, +denominator);

			return +numerator > +denominator ? (numerator / divisor) + ' : ' + (denominator / divisor) : (denominator / divisor) + ' : ' + (numerator / divisor);
		}
		
		// отталкиваясь от video ratio, указывая нужную ширину (окно браузера), подсчитывает правильную высоту
		function solve(width, height, numerator, denominator) {
			var value;

			// solve for width
			if ('undefined' !== typeof width) {
				value =  width / (numerator / denominator); //:  Math.round(width / (numerator / denominator));
			}
			// solve for height
			else if ('undefined' !== typeof height) {
				value = height * (numerator / denominator); // : Math.round(height * (numerator / denominator));
			}

			return value;
		}
		
		function videoSizeFix() {
			var ww = $(window).width();
			var wh = $(window).height();
			
			// TODO! Добавить фуллскрин мод.
			
			if (opt.fixedcontent && !opt.height) { 
				if ($(opt.fixedcontent).length > 1) {
					var allheight = 0;
					for (var i=0; i<$(opt.fixedcontent).length; i++) {
						var _this = $(opt.fixedcontent)[i];
						allheight += $(_this).height();
					}
					wh = wh - allheight; 
				} else {
					wh = wh - $(opt.fixedcontent).height();
				}
				
				console.log('FIXEDCONTENT HEIGHT:', allheight);
				
			}
			
			if (opt.height) {
				wh = opt.height;
			}

			if (opt.width) {
				ww = opt.width;
			}
				
			var trueHeight = solve(ww, undefined, opt.originalSize[0], opt.originalSize[1]);
			console.log('1 trueHeight : ', trueHeight);
			if (trueHeight < wh) {
				console.log('if (trueHeight['+trueHeight+'] < wh['+wh+'])');
				while(trueHeight < wh) {
					console.log('while(trueHeight['+trueHeight+'] < wh['+wh+'])');
					trueHeight = solve(ww, undefined, opt.originalSize[0], opt.originalSize[1]);
					ww++;
				}
			}
			
			
			trueWidth = ww.toFixed(0);
			trueHeight = trueHeight.toFixed(0);
			
			//console.log('trueWidth ' + trueWidth + ' trueHeight ' + trueHeight);
			
			
			$('> video, > div', opt.target).height(trueHeight+'px');
			$('> video, > div', opt.target).width(ww+'px');
			//console.log('api.scrollarea', api.scrollarea);
			$(api.scrollarea).height(wh+'px');
			//$(api.scrollarea).width($(window).width()+'px');
			$(api.scrollarea).data({'width': ww, 'height': trueHeight});
			//$('#stopkeys').css({'width': ww+'px', 'height': trueHeight+'px'});
			
			var leftoffset = 0;
			if ($(window).width() < ww) {
				leftoffset = ($(window).width() - ww) / 2;
				leftoffset.toFixed(0);
			}
			
			var topoffset = 0;
			if (wh < trueHeight) {
				console.log('if (wh['+wh+'] < trueHeight['+trueHeight+'])');
				topoffset = (wh-trueHeight) / 2;
			}
			
			$(api.events).data({width: ww, height: trueHeight, left: leftoffset, top: topoffset})
			
			console.log('> div', $('#video_target > div'));
			$(opt.target).find('video, div').css({
				'width': ww,
				'height': trueHeight,
				//'left': leftoffset,
				'top': topoffset
			});
			$(api.stopimg).css({
				'width': ww,
				'height': wh,
				'overflow': 'hidden'
			});
			$(api.stopimg).find('div').css({
				'width': ww,
				'height': trueHeight,
				//'left': leftoffset,
				'top': topoffset,
				'position': 'absolute'
			});

			
			$(api.events).trigger('resized');
			// TODO! Добавить callback для момента изменения размера видео объекта
			opt.resize_callback(wh, false);
			
			$(opt.target).height(wh+'px');

			
		}
		
		function getNowPos(cueItem) {
			var nowPos = cueItem.name;
			$(api.events).trigger('changePos', nowPos);
			/*
			for (var i=0; i<api.nowplaylist.cue.length; i++) {
				if (api.nowplaylist.cue[i].name == cueItem.name && api.nowplaylist.cue.length-1 != i) {
					nowPos = api.nowplaylist.cue[i+1].name;
				}
				if (api.nowplaylist.cue[i].name == cueItem.name && api.nowplaylist.cue.length-1 == i) {
					nowPos = api.nowplaylist.cue[0].name;
				}
			}
			*/
			return nowPos;
		}
		
		api.setSrc = function(src) {
			//console.log('SETSRC.', src);
			if (!html5) {
				api.video.setSrc(src);
			} else {
				api.video.src = src;
			}
		}
		
		api.seek = function(time) {
			if (!html5) {
				api.video.seek(time);
			} else {
				api.video.currentTime = time;
			}
		}
		
		
		function chooseSizeImg(img_path) {
			// обработчик имен к стопимейджам. реагирует на ширину окна браузера.
			// переваривает любые пути, но в файле картинки не должно быть больше 1ой точки.
			
			var slashes = img_path.split('/');
			var filenameWithType = slashes[slashes.length-1];
			var filetype = filenameWithType.split('.')[1];
			var filename = filenameWithType.split('.')[0];
			
			var windowW = $(window).width();
			
			
			
		}
		
		function VideoFileLoader(){
			if (html5 && !ios) {
				// HTML5
				console.log('показываем прелоадер. запускаем видео');
				opt.preloader('show');
			
			  $(api.video).bind('play', function(){
				  console.log('начал воспроизводится');
				api.video.pause(); 
				$(api.video).unbind('play');
					// TODO!! Add callback after video inisialization
				
					function onCanPlay(){
						console.log('сработал ивент МОГУ воспроизводится');
						// hide preloader
						opt.preloader('hide');
						console.log('preloader hide onCanPlay');
					  api.video.removeEventListener('canplaythrough', onCanPlay, false);
					  api.video.removeEventListener('load', onCanPlay, false);
					  //api.video.removeEventListener('canplay', onCanPlay, false);
					  //video is ready
					  console.log('video is ready. nowplaylist = ', api.nowplaylist.ready);
					  api.nowplaylist.ready();
					  $(api.events).trigger('ready_callback');
					}
				
				  if(api.video.readyState !== 4){ //HAVE_ENOUGH_DATA
					api.video.addEventListener('canplaythrough', onCanPlay, false);
					//api.video.addEventListener('canplay', onCanPlay, false);
					api.video.addEventListener('load', onCanPlay, false); //add load event as well to avoid errors, sometimes 'canplaythrough' won't dispatch.
					setTimeout(function(){
					  api.video.pause(); //block play so it buffers before playing
					}, 1); //it needs to be after a delay otherwise it doesn't work properly.
				  }else{
					  // hide preloader
					  opt.preloader('hide');
					  console.log('preloader hide cideo_is_ready');
					  console.log('video is ready');
						api.nowplaylist.ready();
						$(api.events).trigger('ready_callback');
				  }
				
					$(api.events).trigger('init');
					console.log('video init done');
			  });
			  
			  api.video.load();
				api.video.play();
		  
			  $(this).trigger('self_click');
		  
		  } else if (!ios) {
			  console.log('показываем прелоадер. запускаем видео');
				opt.preloader('show');
				
				
				
				$(api.events).bind('loaded', function(){
				  //console.log('video is ready');
				  //console.log(_playlist);
					api.nowplaylist.ready();
					$(api.events).trigger('ready_callback');
					$(api.events).unbind('loaded');
					opt.preloader('hide');
			  });
			  $(this).trigger('self_click');
			  
		  }
		}
		
		function initNewPlaylist(playlist, startpos) {
			startpos = startpos || false;
			if (playlist == api.nowplaylist) {
				console.log('playlist.initDone playlist == api.nowplaylist');
				$(api.events).trigger('playlist.initDone');
				
				return playlist 
			} else {
				api.nowplaylist = playlist;
				if (startpos) {
					api.nowpos = startpos;
				} else {
					api.nowpos = playlist.startPos;
				}
				console.log("initNewPlaylist: api.nowpos: " +api.nowpos);
				changeStopImg(api.inst[api.nowpos].endimg);
				api.inst[api.nowpos].startaction();
				api.inst[api.nowpos].stopaction();
				$(api.events).trigger('changePos', api.nowpos);
				
				
				if (!ios) {
					if (api.video.currentSrc != playlist.src) { api.setSrc(playlist.src);} //console.log("CURRENT SRC = ", api.video.src, playlist.src) 
				
					// загружаем видео файл с нового плейлиста
					VideoFileLoader();
					$(api.events).bind('ready_callback', function(){
						console.log('playlist.initDone ready_callback');
						$(api.events).trigger('playlist.initDone');
						$(api.events).unbind('ready_callback');
					});
				} else {
					if (api.video.currentSrc != playlist.src) { api.setSrc(playlist.src);}
					$(api.events).trigger('playlist.initDone');
				}
			}
		}
		
		function changeStopImg(img) {
			setTimeout(function(){
				 if ($('img', api.stopimg).length) {
					 $('img', api.stopimg).attr('src', img);
				 } else {
					 $('div', api.stopimg).append('<img src="'+img+'" style="width: 100%; height: 100%;"/>');
				 }
			 }, 50);
		}
		
		api.utils.initNewPlaylist = initNewPlaylist;
		
		function loadClickEvents(){
			
			console.log('loadClickEvents');
						
			for (var i=0; i<opt.playlist.length; i++){
				$(opt.playlist[i].loadclick+':first').data({playlist: opt.playlist[i]});
				console.log($(''+opt.playlist[i].loadclick));
				$(''+opt.playlist[i].loadclick).live('click', function(){
					console.log('loadClickEvents. Click event handled on ', $(this), 'element');
					var selector = $(this).attr('class').split(' ');
					
					// ищем плейлист по loadclick селектору
					for (var e=0; e<selector.length; e++){
						for (var key in api.playlists) {
							console.log('пытаюсь найти плейлист по селектору: ', selector[e], '. сравниваю с key = ', key);
							if (selector[e] == key) {
								var playlist = api.playlists[key];
								break;
							}
						}
					}
					
					console.log(playlist);    
					
					// инициализируем новый плейлист
					if (!ios) {
						initNewPlaylist(playlist);
					} else {
						
						
					   $('#splashscreen').hide();
						
						
					}
					
					var startInstance = api.inst[playlist.startPos];
					
					if (startInstance.stopimg && startInstance.startimg) {
						if ($('img', api.stopimg).attr('src') != startInstance.startimg) { $('img', api.stopimg).attr('src') = startInstance.endimg; }
					}
				  
				});
			}
			
		}
		
		function buildFlash() {
			$.getScript('/assets/js/swfobject.js', function() {
				
				/// есть ли флеш. и если его нет, работать без видео подлетов.
				
				
				
				var flashvars = {
					autoResize: 0,
					updateInterval: 20,
					initCallback: 'initComplete',
					loadCallback: 'videoLoadComplete',
					stopCallback: 'videoStopped'
				};
				var params = {};
				params.wmode = 'opaque';
				params.allowscriptaccess = 'always';
				params.quality = 'high';
				params.scale = 'noscale';
				var attributes = {
					id: "ivideoflashplayer"
				};
				
				$(opt.target).append('<div style="position: absolute;top:0;left:0;"><div id="ivideotarget"/></div>');
				
				videoSizeFix();
				
				swfobject.embedSWF(opt.swf, 'ivideotarget', '100%', '100%', "10.0.0","expressInstall.swf", flashvars, params, attributes);
				
				
				
			});
			
			
			

			
			
			initComplete = function(){
				console.log("FLASH VIDEO PLAYER INIT");
				api.video_origin = document.ivideoflashplayer;
				$(api.video_origin).bind(function(){
					alert('!');
					return false;
				});
				$('object').css('visibility', 'hidden');
				api.video.currentSrc = '';
				api.video = {};
				console.log('opt.startItem.src '+opt.startItem.src);
				document.ivideoflashplayer.load('../../../../'+opt.startItem.src);
				
				
				videoStopped = function(time, cuename){
					
					$(api.events).trigger('pause_callback');
					var stopaction = $(api.events).data('stopaction');
					if (stopaction) {
						stopaction();
					}
					$('object').css('visibility', 'hidden');
					
					stopimgFader('fadeIn');
					
					//$(api.stopimg).removeClass('fadeOut').addClass('fadeIn');
				}
				videoLoadComplete = function(){
					console.log("FLASH VIDEO LOADED");
					$(api.events).trigger('loaded');
				}
				api.video.pause = function(){
					//console.log('flash pause');
				}
				api.video.play = function(from, to){
					from = from || false;
					to = to || false;
					//console.log('PLAY FLASH', from, to);
					if (!from && !to) {return false;}
					api.nowpos = getNowPos(from);
					$('object').css('visibility', 'visible');
					
					stopimgFader('fadeOut');
					
					
					$(api.scrollarea).bind('fadeOut', function(){
						//console.log('fadeOut trigger');
						if (to.endimg){
							$('img', api.stopimg).attr('src', to.endimg);
							var nowzindex = $(api.stopimg).css('z-index');
							$(api.stopimg).css({
								'z-index': '0'
							});
							setTimeout(function(){
								$(api.stopimg).css({
									'z-index': nowzindex
								});
							}, 200);
						}
						//console.log('FLASH PLAY', to.name);
						if (to.stopaction) {
							$(api.events).data({'stopaction': to.stopaction});
						} else {
							$(api.events).data({'stopaction': false});
						}
						//console.log('from'+from.start+' end: '+to.end);
						document.ivideoflashplayer._play(from.start, to.end);
						//api.video_origin._play(from.start, to.end);
						$(api.scrollarea).unbind('fadeOut');
						

					});
					
					if (to.startaction) {
						to.startaction();
					}

				}
				api.video.setSrc = function(src){
					console.log('api.video.setSrc');
					document.ivideoflashplayer.load('../../../../'+src);
					api.video.currentSrc = src;
				}
				api.video.seek = function(time){
					document.ivideoflashplayer.seek(time);
				}

				
				
			
			}
			
			
			return 'video'
		}
		
		function initBuild(){
			if (html5) {
				
				console.log('opt.startItem.src', opt.startItem.src, api.nowplaylist);
				
				video = document.createElement('video');
				video.controls = false;
				video.autoplay = false;
				video.autobuffer = true;
				video.preload = 'auto';
				video.src = opt.startItem.src;
				$(opt.target).append(video);
				$(video).css({
					'position': 'absolute',
					'top': 0,
					'left':0,
					'z-index': 11,
					'width': '100%',
					'height': '100%'
				});
			} else {
				video = buildFlash();
			}
			
			var startInst = api.inst[opt.startItem.startPos];
			api.stopimg = opt.stopimg;            
			$(api.stopimg).append('<div><img src="'+startInst.startimg+'" style="width: 100%; height: 100%;" alt=""/></div>');//.hide();
			
			
			
			
			
			

			
			api.video = video;
			//console.log(opt.startItem);
			api.nowplaylist = opt.startItem;
			VideoFileLoader();
			videoSizeFix();
			
		}
		
		//selectVideo();
		//canPlayType();
		
		parsePlaylist();
		loadClickEvents();
		initBuild();
		
		
		$(window).smartresize(function(){  
			console.log('smartresize');
			videoSizeFix();
		});
		
		
		if (html5) {
			api.move = function(from, to) {
				to = to || from;
				console.log('move func, to = ' + to.name);
			
				$(api.video).bind('seeked', function(){
					
					console.log('seeked');
					
					$(api.video).trigger('preplay');
				
					var timer;
					var addedtime = 0.0;
					if (to.endimg) { addedtime = 0 }
					timer = setInterval(function(){

						if (api.video.currentTime >= to.end-(0.04+addedtime)) {  /// && api.video.currentTime <= to.end+0.5
							//api.video.pause();
							//api.video.currentTime = to.end;
							if (to.endimg) {
								console.log('video stopped on '+api.video.currentTime+', to.end = '+to.end);
								api.video.pause();
								stopimgFader('fadeIn');
								//$(api.video).trigger('showstopimg');
							} else {
								api.video.pause();
							}
							
							
							
							if (to.stopaction) {
								to.stopaction();
							}
							$(api.video).trigger('pause_callback');
							api.nowpos = getNowPos(to);
							clearInterval(timer);
						}

					}, 5);
					$(api.video).unbind('seeked');
				});
			
				//api.video.pause();
			
				$(api.video).bind('preplay', function(){
					//console.log('video played');
					 //.css('display', 'none'); //fadeOut(400, function(){
					//$(api.stopimg).removeClass('fadeIn').addClass('fadeOut');
					
					
					
					
					
					if (to.endimg) {
						api.video.play();
						$(api.scrollarea).bind('fadeOut', function(){
							console.log("CURRENT TIME OF VIDEO::: "+api.video.currentTime+"; NEED TIME TO START:: "+to.start);
							
							setTimeout(function(){
								if ($('img', api.stopimg).length) {
									$('img', api.stopimg).attr('src', to.endimg);
								} else {
									$(api.stopimg).append('<img src="'+to.endimg+'" style="width: 100%; height: 100%;"/>');
								}
							}, 50);
							$(api.scrollarea).unbind('fadeOut');
						});
					} else {
						setTimeout(function(){ api.video.play(); }, 100);
					}
					if (to.startaction) {
						to.startaction();
					}
					
					stopimgFader('fadeOut');
					
					$(api.video).unbind('preplay');
					$(api.video).bind('showstopimg', function(){
						//$(api.stopimg).removeClass('fadeOut').addClass('fadeIn');  //.css('display', 'block');
						stopimgFader('fadeIn');                        
						
						/*
						$(api.scrollarea).bind('fadeIn', function(){ 
							$(api.scrollarea).unbind('fadeIn');
						});
						*/
						//$(api.stopimg).fadeIn(200, function(){
						//    api.video.pause();
						//});
						$(api.video).unbind('showstopimg');
					});
				});
				
				// проверка src видео - нужный ли видео файл сейчас подключен к плееру.
				/*
				console.log(to, to.playlist);
				var thisPlaylistSrc = selectVideo(api.playlists[to.playlist].video_src);
				if (api.video.currentSrc.split(location.host)[1] != thisPlaylistSrc) {
					api.video.src = thisPlaylistSrc;
				}
				*/
				
				
			
				//console.log('api.video.currentTime', api.video.currentTime, from.start);
				if (api.video.currentTime.toFixed(1) == from.start.toFixed(1)) {
					console.log('trigger seeked');
					$(api.video).trigger('seeked');
				} else {
					console.log('currentTime ' + api.video.currentTime + ' from.start ' + from.start);
					api.video.currentTime = from.start;
					
					//$(api.video).trigger('seeked');
					
				}
				
			

			
			}
		} else {
			// ПЕРЕОПРЕДЕЛЯЕМ API.MOVE
			api.move = function(from, to){
				//api.video.seek(from.start);
				to = to || from;
				api.video.play(from, to);
				console.log("FLASH MOVE TO ", from.start, to.end);
			}

		}
		
		api.movenow = function(to) {
			
			
			//console.log('MOVENOW', to);
			
			//$(api.stopimg).removeClass('fadeIn').addClass('fadeOut');
			
			
			//$(api.video).css('opacity', 0);
			
			if (to.startaction) {
				to.startaction();
			}
			
			// show preloader
			opt.preloader('show');
			
			function movenowfunc(){
				
				if (to.name == '1fly') {
					var newstop = to.startimg;
				} else {
					var newstop = to.endimg;
				}
				
				var newstopImg = new Image();
				newstopImg.src = newstop;
				newstopImg.style.width='100%';
				newstopImg.style.height='100%';
				api.nowpos = getNowPos(to);

				if ($('img', api.stopimg).length) {
					$('img', api.stopimg).after(newstopImg);
				} else {
					$(api.stopimg).append(newstopImg);
				}
				
				$(newstopImg).load(function(){
					if ($('img', api.stopimg).length > 1) { $('img:first', api.stopimg).remove(); }
					opt.preloader('hide');
				}).each(function(){
					// trigger events for images that have loaded,
					// other images will trigger the event once they load
					if ( this.complete && this.naturalWidth !== 0 ) {
						$( this ).trigger('load');
					}
				});
				


				
				
				if (to.stopaction) {
					to.stopaction();
				}


			}
			
			movenowfunc();
			
			
			
			
			
			
		}
		
		return api;  
	};
})(jQuery);


// alternative resize callback
(function($,sr){

  // debouncing function from John Hann
  // http://unscriptable.com/index.php/2009/03/20/debouncing-javascript-methods/
  var debounce = function (func, threshold, execAsap) {
	  var timeout;

	  return function debounced () {
		  var obj = this, args = arguments;
		  function delayed () {
			  if (!execAsap)
				  func.apply(obj, args);
			  timeout = null; 
		  };

		  if (timeout)
			  clearTimeout(timeout);
		  else if (execAsap)
			  func.apply(obj, args);

		  timeout = setTimeout(delayed, threshold || 500); 
	  };
  }
  // smartresize 
  jQuery.fn[sr] = function(fn){  return fn ? this.bind('resize', debounce(fn)) : this.trigger(sr); };

})(jQuery,'smartresize');


var transitionEnd = (function (WINDOW) { // Munge "window"

	var prefixes = [
		"",       // Firefox
		"webkit", // Webkit-based
		"o"       // Opera
	],
	i = -1,
	l = prefixes.length,
	ret = false,
	vendor;

	while ((i += 1) < l) {

		vendor = prefixes[i];

		if (("on" + vendor + "transitionend") in WINDOW) {

			ret = new WINDOW.Boolean(true);
			ret.event = ((vendor) ? vendor + "T" : "t") + "ransitionEnd";

			break;

		}

	}

	return ret;

}(this));
