/* DEFAULTS */
var hap_source_path='', hap_players = [], hap_mediaArr = [];
var isMobile = (/Android|webOS|iPhone|iPad|iPod|sony|BlackBerry/i.test(navigator.userAgent));
var isIOS=false, agent = navigator.userAgent;
var isAndroid = agent.indexOf("Android") > -1;
var isiPhoneIpod = agent.indexOf('iPhone') > -1 || agent.indexOf('iPod') > -1;
var isiPad = agent.indexOf('iPad') > -1;
if(agent.indexOf('iPhone') > -1 || agent.indexOf('iPod') > -1 || agent.indexOf('iPad') > -1) {
	 isIOS=true;
}
var mobile_type;
if (agent.indexOf('iPhone') > -1 || agent.indexOf('iPod') > -1 || agent.indexOf('iPad') > -1) {
	if(agent.indexOf('iPhone') > -1)mobile_type = 'iPhone';
	else if(agent.indexOf('iPod') > -1)mobile_type = 'iPod';
	else if(agent.indexOf('iPad') > -1)mobile_type = 'iPad';
}

//http://stackoverflow.com/questions/9847580/how-to-detect-safari-chrome-ie-firefox-and-opera-browser
var isSafari = Object.prototype.toString.call(window.HTMLElement).indexOf('Constructor') > 0;
var isChrome = !isSafari && testCSS('WebkitTransform');
if(isIOS && navigator.userAgent.match('CriOS'))isChrome = true;
var isOpera = !!(window.opera && window.opera.version);
function testCSS(prop) {
	return prop in document.documentElement.style;
}

var isIE = false, ieBelow9 = false, ieBelow8 = false;
var ie_check = getInternetExplorerVersion();
if (ie_check != -1){
	isIE = true;
	if(ie_check < 9)ieBelow9 = true;
	if(ie_check < 8)ieBelow8 = true;
} 

function getInternetExplorerVersion(){
  var rv = -1;
  if (navigator.appName == 'Microsoft Internet Explorer')
  {
	var ua = navigator.userAgent;
	var re  = new RegExp("MSIE ([0-9]{1,}[\.0-9]{0,})");
	if (re.exec(ua) != null)
	  rv = parseFloat( RegExp.$1 );
  }
  else if (navigator.appName == 'Netscape')
  {
	var ua = navigator.userAgent;
	var re  = new RegExp("Trident/.*rv:([0-9]{1,}[\.0-9]{0,})");
	if (re.exec(ua) != null)
	  rv = parseFloat( RegExp.$1 );
  }
  return rv;
}

var hasLocalStorage = supports_local_storage();
function supports_local_storage() {
  try {
	return 'localStorage' in window && window['localStorage'] !== null;
  } catch(e){
	return false;
  }
}

function inject_facebook_sdk(fs_app_id) {
	var fb_root, script, protocol = $.inArray(window.location.href.split(':')[0], ['http', 'https']) ? 'https://' : '//';
	//console.log(protocol);
	if (!window.FB && fs_app_id && !document.body.querySelector('#fb-root')) {
	  script = document.createElement("script");
	  script.text = "window.fbAsyncInit=function(){FB.init({appId:'" + fs_app_id + "',status:true,xfbml:true})};(function(e,t,n){var r,i=e.getElementsByTagName(t)[0];if(e.getElementById(n)){return}r=e.createElement(t);r.id=n;r.src='" + protocol + "connect.facebook.net/en_US/all.js';i.parentNode.insertBefore(r,i)})(document,'script','facebook-jssdk')";
	  fb_root = document.createElement("div");
	  fb_root.id = "fb-root";
	  document.body.appendChild(fb_root);
	  return document.body.appendChild(script);
	}
}
function createScript(url, callback){
	var script = document.createElement('script');
	if(callback){
		if(script.readyState)script.onreadystatechange = callback;
		else script.onload = callback;
	}
	script.type = "text/javascript";
	script.src = url;
	if(document.getElementsByTagName('script').length){
		var firstScriptTag = document.getElementsByTagName('script')[0];
		firstScriptTag.parentNode.insertBefore(script, firstScriptTag);
	}else{
		var head = document.head || document.getElementsByTagName('head')[0];
		head.appendChild(script);
	}
}
function createStyle(url){
	var script = document.createElement('link');
	script.type = "text/css";
	script.rel = "stylesheet";
	script.href = url;
	if(document.getElementsByTagName('link').length){
		var firstScriptTag = document.getElementsByTagName('link')[0];
		firstScriptTag.parentNode.insertBefore(script, firstScriptTag);
	}else{
		var head = document.head || document.getElementsByTagName('head')[0];
		head.appendChild(script);
	}
}
/* END DEFAULTS */


/*
 * Total Video Player v1.02
 * 
 */

(function($) {

	$.fn.videoGallery = function(settings, is_popup) {
	
	//*************** start vars
	var _componentInited=false, 
	_self = this, _body = $('body'), 
	_window = $(window), 
	_doc = $(document), 
	baseURL = window.location.href,
	_downEvent = "", 
	_moveEvent = "", 
	_upEvent = "", 
	hasTouch, 
	touchOn=true;
	if("ontouchstart" in window) {
		hasTouch = true;
		_downEvent = "touchstart.ap";
		_moveEvent = "touchmove.ap";
		_upEvent = "touchend.ap";
	}else{
		hasTouch = false;
		_downEvent = "mousedown.ap";
		_moveEvent = "mousemove.ap";
		_upEvent = "mouseup.ap";
	}
	var mp4Support = canPlayMP4(), 
	vorbisSupport = canPlayVorbis(), 
	webmSupport = canPlayWebM(), 
	html5Support=(!!document.createElement('video').canPlayType);
	if(!html5Support)mp4Support=true;
	//html5Support=false;
	
	//console.log("vorbisSupport = " + vorbisSupport, ", mp4Support = " + mp4Support, ", webmSupport = " + webmSupport);
	
	hap_mediaArr.push({player_id: _self, media_id: settings.media_id});
	
	var markup = 
		'<div class="componentWrapper">'+
		
             '<div class="playerHolder">'+
                 
                 '<div class="mediaHolder"></div>'+
                 
                 '<div class="mediaPreview"></div>'+
                 
                 '<div class="preloader"></div>'+
                 
             	 '<div class="big_play"><div class="big_play_bg"></div><i class="fa fa-play ap_bplay"></i></div>';
                 
                 if(settings.useControls) markup += '<div class="playerControls">'+
                	  '<div class="player_toggleControl"><i class="fa fa-play ap_play"></i></div>'+
                      
                      '<div class="player_mediaTime_current"><p>00:00</p></div> '+ 
                      
                      '<div class="player_seekbar">'+
                          '<div class="progress_bg">'+
                              '<div class="load_level"></div>'+
                              '<div class="progress_level"></div>'+
                          '</div>'+
                          '<div class="player_progress_tooltip aptooltip" data-aptitle=""></div>'+
                      '</div>'+
                      
                      '<div class="player_mediaTime_total"><p>00:00</p></div>'+
                      
                      '<div class="player_volume_wrapper">'+
                          '<div class="player_volume aptooltip" data-aptitle="'+settings.volumeTooltipText+'"><i class="fa fa-volume-up ap_vol"></i></div>'+
                         ' <div class="volume_seekbar">'+
                             '<div class="player_volume_tooltip aptooltip" data-aptitle="'+settings.volumeTooltipText+'"></div>'+
                             '<div class="volume_bg"></div>'+
                             '<div class="volume_level"></div>'+
                          '</div>'+
                      '</div>'+
                      
                      '<div class="player_fullscreen aptooltip" data-aptitle="'+settings.fullscreenTooltipText+'"><i class="fa fa-expand ap_fs_ent"></i></div>'+
                      
                      '<div class="player_ctrl_wrapper"> '+
                      	 ' <div class="player_ctrl"><i class="fa fa-caret-up ap_more"></i></div>'+
                          '<div class="player_ctrl_rest"> '+
                              '<div class="player_captions"> '+
                                  '<div class="caption_holder"></div>'+
                                  '<div class="caption_btn aptooltip" data-aptitle="'+settings.captionsTooltipText+'"><i class="fa fa-tag ap_cc"></i></div>'+
                              '</div> '+
                              '<div class="player_quality"> '+
                              	  '<div class="quality_holder"></div>'+
                                  '<div class="quality_btn aptooltip" data-aptitle="'+settings.qualityTooltipText+'"><i class="fa fa-gear ap_qual"></i></div>'+
                              '</div> '+
                              '<div class="player_download aptooltip" data-aptitle="'+settings.downloadTooltipText+'"><i class="fa fa-download ap_down"></i></div>'+
                              '<div class="player_info aptooltip" data-aptitle="'+settings.videoInfoTooltipText+'"><i class="fa fa-file-text-o ap_info"></i></div>'+
                              '<div class="player_share aptooltip" data-aptitle="'+settings.shareTooltipText+'"><i class="fa fa-share-square-o ap_shr"></i></div>'+
                      	  '</div> '+
                      '</div> '+
                 '</div>';
                 
    	 		 markup += '<div class="playerLogo aptooltip" data-aptitle="'+settings.logoTooltipText+'">';
				 
				 if(!isEmpty(settings.logoLink)){
					 markup+='<a href="'+settings.logoLink+'" target="'+settings.logoTarget+'"><img src="'+settings.logoPath+'" alt="logo" /></a></div>'; 
				 }else{
					 markup+='<img src="'+settings.logoPath+'" alt="logo" /></div>';  
				 }
                  
                 markup+='<div class="infoHolder">'+
                  	 '<div class="infoInner"></div>'+
					 '<div class="close_info aptooltip" data-aptitle="'+settings.closeTooltipText+'"><i class="fa fa-times ap_clinfo"></i></div>'+
                 '</div>'+
                 
                 '<div class="shareHolder">'+
                     '<div class="embedInner">'+
					 	 '<div class="embed_wrap">'+
							 '<div class="embed_title">Embed code:</div>'+
							 '<div class="embed_code_wrap">'+
								 '<div class="embed_code"></div>'+
							 '</div>'+
							 '<div class="embed_copy">COPY</div>'+
							 '<div style="clear: both;"></div>'+
						 '</div>'+
                     '</div>'+
					 '<div class="ap_share_holder">'+
						 '<div class="share_title">Share this:</div>'+
						 '<div class="ap_share_wrapper">'+
							'<ul>'+
							'</ul>'+
						 '</div>'+
				     '</div>'+
					 '<div class="close_share aptooltip" data-aptitle="'+settings.closeTooltipText+'"><i class="fa fa-times ap_clinfo"></i></div>'+
                 '</div>'+
                  
            	 '<div class="ap_adv_skip">'+
				     '<div class="ap_adv_msg"><p></p></div>'+
                     '<div class="ap_adv_img"></div>'+
                     '<div class="ap_adv_msg_end"><p>SKIP AD >></p></div>'+
                 '</div>'+
                 
             '</div>'+
        '</div>';
		
		$(markup).appendTo($(this));
	
	
	
	
	
	var aspectRatio=2,
	media_id = settings.media_id,
	autoPlay =settings.autoPlay,
	yt_autoPlay = settings.autoPlay,
	initialAutoplay= settings.autoPlay,
	autoHideControls=isMobile ? false : settings.autoHideControls,
	randomPlay=false,
	loopingOn=false,
	useWebmVideoFormat,
	layout100perc=settings.layout100perc,
	useYoutubeHighestQuality,
	useTooltips = isMobile ? false : settings.useTooltips,
	autoReuseMailForDownload = settings.autoReuseMailForDownload,
	endAction = settings.endAction,
	closeRemovesEvents = settings.closeRemovesEvents,
	useWebmVideoFormat = settings.useWebmVideoFormat,
	useYoutubeHighestQuality = settings.useYoutubeHighestQuality,
	useYoutubeApi = settings.useYoutubeApi,
	useContextMenu=isMobile ? false : settings.useContextMenu;
	
	if(isMobile){
		autoPlay =false;
		yt_autoPlay = false;
	}
	
	
	var sequence_counter=0, sequence_length,
	gapi_key='',ytApiVersion=2,
	activeItem, 
	_activeItemID, 
	_autoInitActiveItem=false,
	_currentInsert, 
	_activePlaylist, 
	_activePlaylistID, 
	lastPlaylist, 
	_playlistLength=0, 
	_playlistTransitionOn=false, 
	playlistDataArr = [], 
	processPlaylistLength,
	processPlaylistCounter, 
	playlistInited,  
	_playlistLoaded = false, 
	_videoProcessDataUrl=[], 
	_videoProcessCounter=0, 
	_videoProcessData=[],
	timedElements = [], eventsCreated, currVideoData, getEventsDone,
	captionArr = [], currCaptionArr = [], getCaptionsDone,
	videoDataInterval=100, videoDataIntervalID,
	
	youtubeTypeArr = ['youtube_playlist', 'youtube_user_favourites', 'youtube_user_uploads', 'youtube_video_query', 'youtube_related_video_query', 'youtube_playlist_query', 'youtube_user_playlists', 'youtube_channel_query', 'youtube_standard_feed'],
	_youtubePlayer,
	_youtubeInited=false,
	_youtubeChromeless=true, 
	youtubeEnlargeCounter=50, 
	youtubeCounter, 
	youtubeLimit,
	youtubeType,
	_ytArr=[],
	_youtubeStarted,//ios fix
	
	lastTime,
	captionsCreated, 
	curr_lang,
	off_lang = 'Off',
	active_caption_item, 
	captions_menu, 
	captionMenuSizeTaken,
	qualityExist=false, 
	active_quality_item, 
	quality_menu, 
	qualityMenuSizeTaken, 
	qualityDataArr=[], 
	qualityMenuArr=[], 
	curr_time, 
	curr_quality, 
	quality_change,
	
	flashMain,
	flashReadyInterval = 100, 
	flashReadyIntervalID, 
	controlsTimeout = settings.controlsTimeout, 
	controlsTimeoutID,
	dataInterval = 100, 
	dataIntervalID,
	
	prevX=0,
	mediaWidth, 
	mediaHeight, 
	mediaType, 
	mediaPath,
	componentSize = 'normal', 
	iosRealFs=false,
	previewOrigW, 
	previewOrigH, 
	previewPoster,
	video, 
	videoUp2Js, 
	html5video_inited=false, 
	videoInited=false, 
	mediaPlaying=false, 
	media_started = false,
	infoOpened=false, 
	shareOpened=false, 
	videoForcePause,
	_counter=-1;
	
	
	
	
	
	
	
	//*************** start elements
	var mainWrapper = $(this),
	componentWrapper = mainWrapper.find('.componentWrapper'),
	playerHolder=mainWrapper.find('.playerHolder'),
	player_mediaTime_current=mainWrapper.find('.player_mediaTime_current'),
	player_mediaTime_total=mainWrapper.find('.player_mediaTime_total'),
	playerControls=mainWrapper.find('.playerControls'),
	player_toggleControl = mainWrapper.find('.player_toggleControl'),
	player_seekbar = mainWrapper.find('.player_seekbar'),
	progress_bg = mainWrapper.find('.progress_bg'),
	load_level = mainWrapper.find('.load_level'),
	progress_level = mainWrapper.find('.progress_level');
	
	if(!settings.useLogo)mainWrapper.find('.playerLogo').remove();
	if(!settings.useSharing && !settings.useEmbedCode)mainWrapper.find('.player_share').remove();
	
	if(isiPhoneIpod){//we cant use elements above video
		mainWrapper.find('.playerControls').remove();
	}
	
	//advert skip
	var showControlsInVideo,
	disableSeekbarInVideo,
	showSkipButtonInVideo,
	skipEnableTime,
	skipTimeHappened,
	ap_adv_skip= mainWrapper.find('.ap_adv_skip').appendTo(playerHolder).css('cursor', 'pointer').bind('click', function(){
		if(!_componentInited || _playlistTransitionOn) return false;
		if(skipEnableTime && !skipTimeHappened)return false;
		if(!isMobile)setAutoplay(true);
		videoEndHandler();
		return false;
	}),
	ap_adv_img = mainWrapper.find('.ap_adv_img'),
	ap_adv_msg = mainWrapper.find('.ap_adv_msg'),
	ap_adv_msg_end = mainWrapper.find('.ap_adv_msg_end'),
	skipBtnText = 'You can skip video in';
	
	var infoHolder = mainWrapper.find('.infoHolder'), 
	infoInner = mainWrapper.find('.infoInner'),
	close_info = mainWrapper.find('.close_info').css('cursor','pointer').on('click', function(){
		if(!_componentInited) return false;
		closeInfo();
		return false;
	});
	
	var player_info = mainWrapper.find('.player_info').css('cursor','pointer').on('click', function(){
		if(!_componentInited || _playlistTransitionOn) return false;
		if(isMobile){
			caption_holder.css('display','none');
			quality_holder.css('display','none');
			resizeControls();
		}
		openInfo();
		return false;
	});
	if(!isMobile){
		player_info.bind('mouseenter', function(e){
			if(!_componentInited) return false;
			caption_holder.css('display','none');
			quality_holder.css('display','none');
			resizeControls();
			$(e.currentTarget).find('i').removeClass('ap_info').addClass('ap_info_on');
		}).bind('mouseleave', function(e){
			if(!_componentInited) return false;
			$(e.currentTarget).find('i').removeClass('ap_info_on').addClass('ap_info');
		});
	}
	
	if(settings.useSharing || settings.useEmbedCode){
		var shareHolder = mainWrapper.find('.shareHolder'), 
		embedInner = mainWrapper.find('.embedInner'),
		close_share = mainWrapper.find('.close_share').css('cursor','pointer').on('click', function(){
			if(!_componentInited) return false;
			closeShare();
			return false;
		});
		
		var player_share = mainWrapper.find('.player_share').css('cursor','pointer').on('click', function(){
			if(!_componentInited || _playlistTransitionOn) return false;
			if(isMobile){
				caption_holder.css('display','none');
				quality_holder.css('display','none');
				resizeControls();
			}
			openShare();
			return false;
		});
		if(!isMobile){
			player_share.bind('mouseenter', function(e){
				if(!_componentInited) return false;
				caption_holder.css('display','none');
				quality_holder.css('display','none');
				resizeControls();
				$(e.currentTarget).find('i').removeClass('ap_shr').addClass('ap_shr_on');
			}).bind('mouseleave', function(e){
				if(!_componentInited) return false;
				$(e.currentTarget).find('i').removeClass('ap_shr_on').addClass('ap_shr');
			});
		}
	}
	
	var youtubeIframeMain,
	playerHolder=mainWrapper.find('.playerHolder'),
	mediaHolder=mainWrapper.find('.mediaHolder').on('click', function(){
		if(!_componentInited || _playlistTransitionOn) return false;
		togglePlayBack();
		return false;
	}),
	mediaPreview=mainWrapper.find('.mediaPreview').on('click', function(){
		if(!_componentInited || _playlistTransitionOn) return false;
		togglePlayBack();
		return false;
	}),
	
	big_play =mainWrapper.find('.big_play').css('cursor', 'pointer').on('click', function(){
		if(!_componentInited || _playlistTransitionOn) return false;
		if(media_started){
			if(currVideoData.link != undefined){
				if(currVideoData.target != undefined && currVideoData.target == '_blank'){	
					window.open(currVideoData.link);
				}else{//parent
					window.location = currVideoData.link;
				}
			}
		}
		togglePlayBack();
		return false;
	}),
	big_play_bg = mainWrapper.find('.big_play_bg'),
	ap_bplay = mainWrapper.find('.ap_bplay'),
	preloader =mainWrapper.find('.preloader'),
	playlistControls =mainWrapper.find('.playlistControls'),
	
	toggleControl_width = mainWrapper.find('.player_toggleControl').outerWidth(true),
	current_time_width = mainWrapper.find('.player_mediaTime_current').outerWidth(true),
	total_time_width = mainWrapper.find('.player_mediaTime_total').outerWidth(true),
	volume_width = mainWrapper.find('.player_volume_wrapper').outerWidth(true),
	fullscreen_width = mainWrapper.find('.player_fullscreen').outerWidth(true),
	player_ctrl_wrapper_width = mainWrapper.find('.player_ctrl_wrapper').outerWidth(true);
	//*************** end elements
	
	
	//*************** start context menu
	if(useContextMenu){
		var contextMenu = 
			'<div class="ap-context-menu">' + 
				'<ul>' + 
					'<li class="ap-context-play"><span>Play</span></li>' + 
					'<li class="ap-context-mute"><span>Mute</span></li>' + 
					'<li class="ap-context-full"><span>Fullscreen</span></li>'; 
			
		if(!isEmpty(settings.contextMenuText)){
			contextMenu+='<li class="ap-context-copyright"><span>'+settings.contextMenuText+'</span></li>';
		}
		contextMenu+='</ul></div>';//close
		
		var contextMenu = $(contextMenu).appendTo(_body),
		contextTogglePlayback = $(".ap-context-play").css('cursor','pointer').on("click", togglePlayBack),
		contextToggleFs = $(".ap-context-full").css('cursor','pointer').on("click", toggleFullscreen),
		contextToggleVol = $(".ap-context-mute").css('cursor','pointer').on("click", function(){
			toggleVolume();
			setVolume();
		});
		if(!isEmpty(settings.contextMenuLink))$(".ap-context-copyright").css('cursor','pointer').on("click", copyrightClick);
		if(!autoPlay)contextTogglePlayback.find('span').html('Play');
		
		playerHolder.bind("contextmenu", showContextMenu);
		_body.on("mouseleave", hideContextMenu);
		_doc.bind("contextmenu", hideContextMenu).keyup(function(e){
		  if(e.keyCode == 27){ //esc
			  hideContextMenu();
		  }  
		});
	}
	function copyrightClick(){
		if(settings.contextMenuTarget == "_blank"){	
			if(mediaPlaying)togglePlayBack();
			window.open(settings.contextMenuLink);
		}else{//parent
			window.location = settings.contextMenuLink;
		}
	}
	function showContextMenu(e) {
		if($(e.target).hasClass('embed_code'))return true;
		e.preventDefault();
		e.stopPropagation();
		var x = e.pageX, y = e.pageY;
		contextMenu.css({left: x+'px', top: y+'px', display:'block'});
		_body.one("click.apvideo", hideContextMenu);
	}
	function hideContextMenu() {
		_body.unbind("click.apvideo", hideContextMenu);
		contextMenu.css('display','none');
	}
	//*************** end context menu
	
	
	
	//*************** start controls rest
	var player_ctrl_wrapper = mainWrapper.find('.player_ctrl_wrapper'),
	player_ctrl = mainWrapper.find('.player_ctrl').css('cursor','pointer'),
	player_ctrl_rest = mainWrapper.find('.player_ctrl_rest');
	if(player_ctrl_rest.children().size()==0){
		player_ctrl_wrapper.css('display','none');
	}else{
		var w = 0;
		player_ctrl_rest.children().each(function(){
			//console.log($(this).width())	
			w+=$(this).outerWidth(true);
		})
		player_ctrl_rest.width(w);
		if(!isMobile){
			player_ctrl.bind('mouseenter', function(e){
				if(!_componentInited || _playlistTransitionOn) return false;
				player_ctrl_rest.css('display','block');
				$(e.currentTarget).find('i').removeClass('ap_more').addClass('ap_more_on');
				player_ctrl_wrapper.unbind().bind('mouseleave', function(e){
					player_ctrl_rest.css('display','none');
					caption_holder.css('display', 'none');
					quality_holder.css('display', 'none');
					resizeControls();
				});
			}).bind('mouseleave', function(e){
				if(!_componentInited) return false;
				$(e.currentTarget).find('i').removeClass('ap_more_on').addClass('ap_more');
			});
		}else{
			player_ctrl.on('click', function(){
				if(!_componentInited) return false;
				caption_holder.css('display','none');
				quality_holder.css('display','none');
				volume_seekbar.hide();
				player_ctrl_rest.toggle();
				resizeControls();
				return false;
			});
		}
	}
	
	//*************** end controls rest
	

	
	//*************** start captions
	var player_captions= mainWrapper.find('.player_captions'),
	caption_holder= mainWrapper.find('.caption_holder'),
	caption_btn= mainWrapper.find('.caption_btn').css('cursor','pointer');
	if(!isMobile){
		caption_btn.bind('mouseenter', function(e){
			if(!_componentInited || _playlistTransitionOn) return false;
			quality_holder.css('display','none');
			if(!captionMenuSizeTaken)checkCaptionMenuSize();
			caption_holder.css('display','block');
			resizeControls();
			$(e.currentTarget).find('i').removeClass('ap_cc').addClass('ap_cc_on');
		}).bind('mouseleave', function(e){
			if(!_componentInited || _playlistTransitionOn) return false;
			$(e.currentTarget).find('i').removeClass('ap_cc_on').addClass('ap_cc');
		});
	}else{
		caption_btn.on('click', function(){
			if(!_componentInited || _playlistTransitionOn) return false;
			quality_holder.css('display','none');
			if(!captionMenuSizeTaken)checkCaptionMenuSize();
			caption_holder.toggle();
			resizeControls();
			return false;
		});
	}
	function checkCaptionMenuSize(){
		caption_holder.css({display: 'block'});
		var sum = 0;
		captions_menu.find('li').each(function() {
		   sum += $(this).outerHeight(true); 
		});
		//console.log('toggleCaptionMenu: ', sum)
		//console.log(playerHolder.offset(), caption_btn.offset(), caption_holder.height(), captions_menu.height());
		if(captions_menu.height() < caption_btn.offset().top){//fits above
			caption_holder.css({top: -sum-2+'px', display: 'none'});
		}else{
			caption_holder.css({top: caption_btn.height()+'px', display: 'none'});
		}
		captionMenuSizeTaken=true;
	}
	function createCaptions(){
		//console.log('createCaptions');
		var div = $('<div>'), li, a, default_caption;
	
		//create caption menu list
		captions_menu = $("<ul class='captions_menu'></ul>").appendTo(caption_holder);
		
		var i, len = captionArr.length, _item, title;
		for(i = 0;i<len;i++){
			_item = captionArr[i];
			title=_item.title;
			
			li = $('<li/>').appendTo(captions_menu);
			a = $('<a href="#"/>').text(title).addClass('captionOut').attr('data-srclang',title).on('click', captionToggle).appendTo(li);
			if(!isMobile)a.bind('mouseover', overCaption).bind('mouseout', outCaption);
			
			if (_item._default){
				default_caption=true;
				findDefaultCaptions(title);
				active_caption_item=a.removeClass('captionOut').addClass('captionOver').data('active', true).css('cursor', 'default');
			}
		}
		//off caption
		li = $('<li/>').appendTo(captions_menu);
		a = $('<a href="#"/>').text(off_lang).addClass('captionOut').attr('data-srclang',off_lang).on('click', captionToggle).appendTo(li);
		if(!default_caption)active_caption_item=a.removeClass('captionOut').addClass('captionOver').data('active', true).css('cursor', 'default');
		if(!isMobile)a.bind('mouseover', overCaption).bind('mouseout', outCaption);
		
	}
	function findDefaultCaptions(lang){
		//console.log('findDefaultCaptions');
		if(lang != off_lang){
			var j = 0, len = captionArr.length, captions;
			for(j;j<len;j++){
				if(lang == captionArr[j].title){
					captions = captionArr[j].items;
					break;	
				}
			}
			playerHolder.children("div[class='ap_sub']").remove();//remove subtitles
			currCaptionArr = $.extend(true, [], captions);//deep copy
			j = 0, len = currCaptionArr.length;
			for(j;j<len;j++){
				big_play.after($(currCaptionArr[j].item));
			}
			curr_lang= currCaptionArr;
		}else{
			playerHolder.children("div[class='ap_sub']").remove();//remove subtitles
			currCaptionArr = [];
		}
		if(videoInited){//trigger change
			lastTime=0;	
			trackVideoData();
		}
		//console.log(curr_lang);
		if(typeof tvpCaptionChange !== 'undefined')tvpCaptionChange(_self, media_id, lang);//callback
	}
	function captionToggle(){
		var _item = $(this);
		if(_item.data('active') == true)return false;//active item
		if(active_caption_item)active_caption_item.removeClass('captionOver').addClass('captionOut').data('active', false).css('cursor', 'pointer');
		active_caption_item = _item.removeClass('captionOut').addClass('captionOver').data('active', true).css('cursor', 'default');
		var lang = _item.attr('data-srclang');
		findDefaultCaptions(lang);
		return false;
	}
	function overCaption(){
		$(this).removeClass('captionOut').addClass('captionOver');
		return false;
	}
	function outCaption(){
		if($(this).data('active') != true)$(this).removeClass('captionOver').addClass('captionOut');
		return false;
	}
	//*************** end captions
	
	
	//*************** start quality
	var player_quality = componentWrapper.find('.player_quality'),
	quality_holder = componentWrapper.find('.quality_holder'),
	quality_btn = componentWrapper.find('.quality_btn').css('cursor','pointer');
	if(!isMobile){
		quality_btn.bind('mouseenter', function(e){
			if(!_componentInited || _playlistTransitionOn) return false;
			caption_holder.css('display','none');
			if(!qualityMenuSizeTaken)checkQualityMenuSize();
			quality_holder.css('display','block');
			resizeControls();
			$(e.currentTarget).find('i').removeClass('ap_qual').addClass('ap_qual_on');
		}).bind('mouseleave', function(e){
			if(!_componentInited || _playlistTransitionOn) return false;
			$(e.currentTarget).find('i').removeClass('ap_qual_on').addClass('ap_qual');
		});
	}else{
		quality_btn.on('click', function(){
			if(!_componentInited || _playlistTransitionOn) return false;
			caption_holder.css('display','none');
			if(!qualityMenuSizeTaken)checkQualityMenuSize();
			quality_holder.toggle();
			resizeControls();
			return false;
		});
	}
	function checkQualityMenuSize(){
		quality_holder.css({display: 'block'});
		var sum = 0;
		quality_menu.find('li').each(function() {
		   sum += $(this).outerHeight(true); 
		});
		//console.log('toggleQualityMenu: ', sum)
		if(quality_menu.height() < quality_btn.offset().top){//fits above
			quality_holder.css({top: -sum-2+'px', display: 'none'});
		}else{
			quality_holder.css({top: quality_btn.height()+'px', display: 'none'});
		}
		qualityMenuSizeTaken=true;
	}
	function checkQuality(type, cc){
		//console.log('checkQuality', type);
		if(type=='youtube'){
			var arr = _youtubePlayer.getQualityLevels();
			curr_quality = _youtubePlayer.getCurrQuality();
		}else{
			var arr = [], qualities = currVideoData.path;
			
			qualityDataArr=[];
			qualityMenuArr=[];
			$.each(qualities, function (i, e) { 
				//console.log('title='+ i + ', value=' +e);
				arr.push(i);
				if(i.match(/default/i))curr_quality = i;
				qualityDataArr.push({quality:i, mp4:e, ogv: e.replace(/mp4/,'ogv'), webm: e.replace(/mp4/,'webm')});
			});
			if(cc)curr_quality=cc;//create quality menu
			//console.log(qualityDataArr, curr_quality);
		}
		//console.log(qualityDataArr);
		
		if(arr.length==0)return;
		
		var i = 0, len = arr.length, _item, li, a;
		quality_menu = $("<ul class='quality_menu'></ul>").appendTo(quality_holder);
		
		for(i;i<len;i++){
			_item=arr[i];
			//console.log(_item);
			
			li = $('<li/>').appendTo(quality_menu);
			a = $('<a href="#"/>').text( _item).addClass('qualityOut').attr('data-quality',_item).on('click', qualityToggle).appendTo(li);
			if(!isMobile)a.bind('mouseover', overQuality).bind('mouseout', outQuality);
			qualityMenuArr.push({quality: _item, item: a});
			
			//console.log(curr_quality, _item);
			//disable current quality
			if (curr_quality == _item){
				default_exist=true;
				active_quality_item=a.removeClass('qualityOut').addClass('qualityOver').data('active', true).css('cursor', 'default');
			}
		}
		player_quality.css('display','block');
		//console.log(qualityMenuArr);
	}
	function setQualityMenuItem(_item){
		if(active_quality_item)active_quality_item.removeClass('qualityOver').addClass('qualityOut').data('active', false).css('cursor', 'pointer');
		if(_item)active_quality_item = _item.removeClass('qualityOut').addClass('qualityOver').data('active', true).css('cursor', 'default');
	}
	function qualityToggle(){
		var _item = $(this);
		if(_item.data('active') == true)return false;//active item
		setQualityMenuItem(_item);
		
		var quality = _item.attr('data-quality');
		if(mediaType == 'local'){
			var i = 0, len = qualityDataArr.length;
			for(i;i<len;i++){
				if(quality == qualityDataArr[i].quality){
					curr_quality = quality;
					break;
				}
			}
			curr_time=null;
			//save current time
			if(html5Support){
				if(videoUp2Js){
					try{
						curr_time = videoUp2Js.currentTime;
					}catch(er){}	
				}
			}else{
				if(flashMain && typeof getFlashMovie(flashMain) !== "undefined")curr_time = getFlashMovie(flashMain).pb_getTime(); 
			}
			_findMedia(true);
		}else{
			_youtubePlayer.setPlaybackQuality(quality);
		}
		return false;
	}
	function overQuality(){
		$(this).removeClass('qualityOut').addClass('qualityOver');
		return false;
	}
	function outQuality(){
		if($(this).data('active') != true)$(this).removeClass('qualityOver').addClass('qualityOut');
		return false;
	}
	//*************** end quality
	
	
	
	//*************** start download
	var _downloadOn,  mailSet, dl_mail,
	player_download = mainWrapper.find('.player_download').css('cursor','pointer').on('click', function(e){
		if(!_componentInited || _playlistTransitionOn) return false;
		caption_holder.css('display','none');
		quality_holder.css('display','none');
		resizeControls();
		globalDownload();
		return false;
	})
	if(!isMobile){
		player_download.bind('mouseenter', function(e){
			if(!_componentInited) return false;
			caption_holder.css('display','none');
			quality_holder.css('display','none');
			resizeControls();
			$(e.currentTarget).find('i').removeClass('ap_down').addClass('ap_down_on');
		}).bind('mouseleave', function(e){
			if(!_componentInited) return false;
			$(e.currentTarget).find('i').removeClass('ap_down_on').addClass('ap_down');
		});
	}
	if(componentWrapper.find("iframe[id='dl_iframe']").length==0){
		var dl_iframe = $('<iframe id="dl_iframe"/>').css({position:'absolute',left:-10000+'px',display:'none'}).appendTo(componentWrapper);
	}else{
		var dl_iframe = componentWrapper.find("iframe[id='dl_iframe']");
	}
	if(isMobile){//download confirmation
		var downConf_timeoutID, downConf_timeout=2000;
		if(playerHolder.find("div[id='download_confirm']").length==0){
			var download_confirm = $('<div id="download_confirm"><p>DOWNLOAD STARTING</p></DIV>').addClass('download_confirm').css({opacity:0, zIndex:1000}).appendTo(playerHolder);	
		}else{
			var download_confirm = playerHolder.find("div[id='download_confirm']");	
		}
	}
	function globalDownload(){
		if(_downloadOn)return false;
		var path = currVideoData.download, name = currVideoData.title,
		 dwn = getDownloadPath(mediaType, name, path);
		//console.log(dwn.name, dwn.path);
		//return;
		checkDownload(dwn.name, dwn.path);	
	}
	function getDownloadPath(type, name, path){
		if(path.indexOf('\\')){//replace backward slashes
			path = path.replace(/\\/g,"/");
		}
		//construct full download path 
		if(!path.match(/^http([s]?):\/\/.*/)){
			//console.log(window.location);
			var main_path = window.location.href;
			main_path = main_path.substr(0, main_path.lastIndexOf('/')+1);
			if((/^\.\.\//i).test(path)){//replace ../ for one level up since we have media files one level up from root
				path = path.substr(3);//remove ../
				if(main_path.charAt(main_path.length-1)=='/')main_path = main_path.substr(0,main_path.lastIndexOf('/'));//remove last slash
				main_path = main_path.substr(0,main_path.lastIndexOf('/')+1);//remove current directory
			}	
			path = main_path + path;
		}
		name = name.replace(/[^A-Z0-9\-\_\.]+/ig, "_");//remove spaces and spec chars
		if(path.lastIndexOf('.') > 0){
			var ext = path.substr(path.lastIndexOf('.'));
			//console.log(ext, new RegExp('/' + ext + '$/i'));
			if(!(new RegExp('/' + ext + '$/i')).test(name)){
				name+=ext;//append extension
			}
		}
		return {name:name, path:path};
	}
	function checkDownload(name, path){
		if(!isMobile){
			dl_iframe.attr('src',hap_source_path+"php/dl.php?path="+path+"&name="+name);
		}else{
			_downloadOn = true;
			if(autoReuseMailForDownload){
				if(!mailSet){
					dl_mail = getMail();
					if(dl_mail)mailSet = true;
				}
				if(dl_mail)sendMail(dl_mail, name, path);
				else _downloadOn = false;	
			}else{
				var email = getMail();
				if(email)sendMail(email, name, path);
				else _downloadOn = false;	
			}
		}
	}
	function sendMail(mail, name, path){
		//console.log('sendMail');
		var data = "mail=" + mail + "&name=" + name + "&path=" + path;
		//console.log(data);
		$.ajax({
			type: "POST",
			url: hap_source_path+"php/mail.php",
			data: data
		}).done(function(msg) {
			//console.log('Send mail success: ' + msg);
			_downloadOn = false;	
		}).fail(function(jqXHR, textStatus, errorThrown) {
			//console.log('Send email error: ' + jqXHR.responseText);
			alert('Send email error: ' + jqXHR.responseText);
			hideDownConf();
			_downloadOn = false;
		});	
		download_confirm.css({marginTop:-download_confirm.height()/2+'px',display:'block'}).stop().animate({'opacity': 1},{duration: 500});
		if(downConf_timeoutID) clearTimeout(downConf_timeoutID);
		downConf_timeoutID = setTimeout(hideDownConf, downConf_timeout);
	}
	function hideDownConf(){
		if(downConf_timeoutID) clearTimeout(downConf_timeoutID);
		download_confirm.stop().animate({'opacity': 0}, {duration: 500, complete: function(){
			download_confirm.css('display','none');	
		}});
	}
	function getMail(){
		var email = prompt("Please enter your email address where download link will be sent:");
		//validate email
		var emailReg = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/;
		while(!emailReg.test(email) || isEmpty(email)){
			if(email == null)break;
			email = prompt("Please enter a valid email address:");
		}
		return email;
	}
	//*************** end download


	
	//*************** start share
	if(settings.useEmbedCode){
		//console.log(baseURL);
		var embed_code = mainWrapper.find('.embed_code').attr('id',embed_code+parseInt(Math.random()*99999999)).on("click", function(){
			selectText($(this).attr('id'));
		}),
		embed_copy = mainWrapper.find('.embed_copy').css('cursor','pointer').on('click', function(e){
			window.prompt("Copy to clipboard: Ctrl+C", embed_code.html());
		});
		embed_code.html(baseURL+'#'+mainWrapper.attr('id'));
	}else{
		mainWrapper.find('.embedInner').remove();
	}
	if(settings.useSharing){
		var ap_share_holder = mainWrapper.find('.ap_share_holder'), shareArr = [], use_fs, ap_share_wrapper = mainWrapper.find('.ap_share_wrapper'), goshare = ap_share_wrapper.find('ul');

		if(settings.sharingSites.facebook)$('<li><a class="aptooltip" href="#" data-type="facebook" data-aptitle="'+settings.sharingSites.facebook.tooltipText+'"><img src="'+settings.sharingSites.facebook.iconUrl+'" alt="facebook"/></a></li>').appendTo(goshare);
		if(settings.sharingSites.twitter)$('<li><a class="aptooltip" href="#" data-type="twitter" data-aptitle="'+settings.sharingSites.twitter.tooltipText+'"><img src="'+settings.sharingSites.twitter.iconUrl+'" alt="twitter"/></a></li>').appendTo(goshare);
		if(settings.sharingSites.google)$('<li><a class="aptooltip" href="#" data-type="google" data-aptitle="'+settings.sharingSites.google.tooltipText+'"><img src="'+settings.sharingSites.google.iconUrl+'" alt="google"/></a></li>').appendTo(goshare);
		if(settings.sharingSites.pinterest)$('<li><a class="aptooltip" href="#" data-type="pinterest" data-aptitle="'+settings.sharingSites.pinterest.tooltipText+'"><img src="'+settings.sharingSites.pinterest.iconUrl+'" alt="pinterest"/></a></li>').appendTo(goshare);
		if(settings.sharingSites.linkedin)$('<li><a class="aptooltip" href="#" data-type="linkedin" data-aptitle="'+settings.sharingSites.linkedin.tooltipText+'"><img src="'+settings.sharingSites.linkedin.iconUrl+'" alt="linkedin"/></a></li>').appendTo(goshare);
		if(settings.sharingSites.digg)$('<li><a class="aptooltip" href="#" data-type="digg" data-aptitle="'+settings.sharingSites.digg.tooltipText+'"><img src="'+settings.sharingSites.digg.iconUrl+'" alt="digg"/></a></li>').appendTo(goshare);
		if(settings.sharingSites.reddit)$('<li><a class="aptooltip" href="#" data-type="reddit" data-aptitle="'+settings.sharingSites.reddit.tooltipText+'"><img src="'+settings.sharingSites.reddit.iconUrl+'" alt="reddit"/></a></li>').appendTo(goshare);
		if(settings.sharingSites.tumblr)$('<li><a class="aptooltip" href="#" data-type="tumblr" data-aptitle="'+settings.sharingSites.tumblr.tooltipText+'"><img src="'+settings.sharingSites.tumblr.iconUrl+'" alt="tumblr"/></a></li>').appendTo(goshare);
		if(settings.sharingSites.stumbleupon)$('<li><a class="aptooltip" href="#" data-type="stumbleupon" data-aptitle="'+settings.sharingSites.stumbleupon.tooltipText+'"><img src="'+settings.sharingSites.stumbleupon.iconUrl+'" alt="stumbleupon"/></a></li>').appendTo(goshare);
		if(settings.sharingSites.delicious)$('<li><a class="aptooltip" href="#" data-type="delicious" data-aptitle="'+settings.sharingSites.delicious.tooltipText+'"><img src="'+settings.sharingSites.delicious.iconUrl+'" alt="delicious"/></a></li>').appendTo(goshare);
		
		ap_share_wrapper.find('ul').children('li').each(function(){
			shareArr.push($(this).children('a[class*=aptooltip]'));
			if($(this).children('a[class*=aptooltip]').attr('data-type').toLowerCase() == 'facebook')use_fs=true;
			//console.log($(this).children('a[class*=aptooltip]').attr('data-type'));
		});
		if(use_fs)inject_facebook_sdk(settings.sharingSites.facebook.fs_app_id);
			
		$(shareArr).each(function(){
			$(this).on('click', function(e){
				
				if(currVideoData){
				
					var type = $(this).attr('data-type').toLowerCase(), 
					w = 600, h = 300, cw = (window.screen.width - w) / 2, ch = (window.screen.height - h) / 2,
					data = currVideoData, path,
					title = data.title,
					description = data.description,
					td = data.title+' \n'+data.description,
					thumb = data.thumb,
					url = data.deeplink;	
						
					if(type == "facebook"){	
						path = 'http://www.facebook.com/sharer/sharer.php?u='+encodeURIComponent(thumb);
						if(window.FB){
							getFbSdk(url, thumb, title, description);
							return false;	
						}
					}else if(type == "twitter"){	
						path = 'http://twitter.com/share?url='+encodeURIComponent(url)+'&text='+encodeURIComponent(td);
					}else if(type == "google"){	
						path = 'http://plus.google.com/share?url='+encodeURIComponent(thumb);
					}else if(type == "pinterest"){		
						path = 'https://www.pinterest.com/pin/create/button?url='+encodeURIComponent(thumb)+'&description='+encodeURIComponent(title)+'&media='+encodeURIComponent(thumb);
					}else if(type == "linkedin"){		
						path = 'http://www.linkedin.com/shareArticle?mini=true&url='+encodeURIComponent(thumb)+'&title='+encodeURIComponent(title)+'&summary='+encodeURIComponent(description);
					}else if(type == "digg"){	
						path = 'http://digg.com/submit?url='+encodeURIComponent(url);
					}else if(type == "reddit"){	
						path = 'http://reddit.com/submit?url='+encodeURIComponent(url)+'&title='+encodeURIComponent(td);
					}else if(type == "tumblr"){		
						path = 'http://www.tumblr.com/share/link?url='+encodeURIComponent(url)+'&name='+encodeURIComponent(title)+'&description='+encodeURIComponent(description);
					}else if(type == "stumbleupon"){	
						path = 'http://www.stumbleupon.com/submit?url='+encodeURIComponent(url)+'&title='+encodeURIComponent(title);
					}else if(type == "delicious"){	
						path = 'http://del.icio.us/post?url='+encodeURIComponent(url)+'&title='+encodeURIComponent(td);
					}
					if(path)window.open(path, '', 'menubar=no,toolbar=no,resizable=yes,scrollbars=yes,width='+w+',height='+h+',left='+cw+',top='+ch+'');
				}
				if(useTooltips)$(e.currentTarget).tooltipster('hide');
				return false;
			});		
		});
	}else{
		mainWrapper.find('.ap_share_holder').remove();
	}
	function getFbSdk(url, thumb, title, description){
		//console.log(window.FB);
		if(window.FB){
			 return FB.ui({
				method: 'feed',
				name: document.title,
				link: url,
				picture: thumb,
				caption: title,
				description: description
			 });
		}
	}	
	//*************** end share
	
	
	//********** start fullscreen
	var fullscreenCount=0, fullscreenPossible = false, fs_removed = false,
	player_fullscreen= mainWrapper.find('.player_fullscreen');
	if(checkFullScreenSupport()){
		fullscreenPossible = true;
	}else{
		//remove fs button in 100% layout becuase it doesnt do anything.
		if(layout100perc){
			fs_removed=true;
			mainWrapper.find('.player_fullscreen').remove();
		}	
	}
	function setFullscreenIcon(dir){
		if(dir=='on'){
			player_fullscreen.find('i').removeClass().addClass('fa fa-expand ap_fs_ent');
			if(useContextMenu)contextToggleFs.find('span').html('Fullscreen');
		}else{
			player_fullscreen.find('i').removeClass().addClass('fa fa-compress ap_fs_exit');
			if(useContextMenu)contextToggleFs.find('span').html('Exit Fullscreen');
		}
	}
	if(fullscreenPossible){
		_doc.on("fullscreenchange mozfullscreenchange MSFullscreenChange webkitfullscreenchange", function(e){
			if(componentSize== "fullscreen" && fullscreenCount>0){
				componentSize="normal";
				resizeComponent();	
				if(useContextMenu)hideContextMenu();
			}
			fullscreenCount=1;//fix for escape key
		});
	}
	
	function toggleFullscreen(btnInitiated){
		//console.log('toggleFullscreen', fullscreenPossible);
		fullscreenCount=0;
		
		if(componentSize== "normal")componentSize= "fullscreen";
		else componentSize="normal";
		//http://stackoverflow.com/questions/8427413/webkitrequestfullscreen-fails-when-passing-element-allow-keyboard-input-in-safar
					
		if(fullscreenPossible){
			var elem = document.documentElement;
			if (elem.requestFullscreen) {
				if (document.fullscreenElement || document.fullscreenElement) {
					document.exitFullscreen();
				} else {
					elem.requestFullscreen();
				}
			} else if (elem.webkitRequestFullScreen) {
				if (document.webkitIsFullScreen) {
					document.webkitCancelFullScreen();
				} else {
					elem.webkitRequestFullScreen();
				}
			} else if (elem.msRequestFullscreen) {
				if (document.msIsFullscreen || document.msFullscreenElement) {
					document.msExitFullscreen();
				} else {
					elem.msRequestFullscreen();
				}
			} else if (elem.mozRequestFullScreen) {
				if (document.fullscreenElement || document.mozFullScreenElement) {
					document.mozCancelFullScreen();
				} else {
					elem.mozRequestFullScreen();
				}
			}
			else if(isIOS){
				if(componentSize=="fullscreen"){
					try{
						if(videoUp2Js && videoUp2Js.webkitEnterFullScreen != undefined)videoUp2Js.webkitEnterFullScreen();
					}catch(error){}
				}
			}
		}
		if(!fullscreenPossible) {
			resizeComponent();	
		}else if(componentSize=="normal" && btnInitiated){
			resizeComponent();		
		}
	}
	function checkFullScreenSupport() {
		var support=false;
		if (document.fullscreenEnabled || document.webkitFullscreenEnabled || document.mozFullScreenEnabled || document.msFullscreenEnabled)support=true;
		else if (document.documentElement.requestFullscreen || document.documentElement.mozRequestFullScreen || document.documentElement.msRequestFullscreen || document.documentElement.oRequestFullscreen || document.documentElement.webkitRequestFullScreen) support=true;
		return support;
	}
	//********** end fullscreen
	

	
	//********** start progress seekbar
	var seekBarDown=false,seekBarElementsSize,playerControlsSize,seekBarSize, player_seekbar_offset=30;
	player_seekbar.css('cursor', 'pointer').bind(_downEvent,function(e){
		if(disableSeekbarInVideo)return false;
		_onDragStartSeek(e);
		return false;		
	}); 
	function _onDragStartSeek(e) {
		if(!_componentInited || _playlistTransitionOn) return false;
		if(volumebarDown) return false;
		if(!seekBarDown){					
			var point;
			if(hasTouch){
				var currTouches = e.originalEvent.touches;
				if(currTouches && currTouches.length > 0) {
					point = currTouches[0];
				}else{	
					return false;						
				}
			}else{
				point = e;								
				e.preventDefault();						
			}
			seekBarDown = true;
			_doc.bind(_moveEvent, function(e) { _onDragMoveSeek(e); });
			_doc.bind(_upEvent, function(e) { _onDragReleaseSeek(e); });		
		}
		return false;	
	}
	function _onDragMoveSeek(e) {	
		var point;
		if(hasTouch){
			var touches;
			if(e.originalEvent.touches && e.originalEvent.touches.length) {
				touches = e.originalEvent.touches;
			}else if(e.originalEvent.changedTouches && e.originalEvent.changedTouches.length) {
				touches = e.originalEvent.changedTouches;
			}else{
				return false;
			}
			// If touches more then one, so stop sliding and allow browser do default action
			if(touches.length > 1) {
				return false;
			}
			point = touches[0];	
			e.preventDefault();				
		} else {
			point = e;
			e.preventDefault();		
		}
		setProgress(point.pageX);
		
		return false;		
	}
	function _onDragReleaseSeek(e) {
		if(seekBarDown){	
			seekBarDown = false;			
			_doc.unbind(_moveEvent).unbind(_upEvent);	
			
			var point;
			if(hasTouch){
				var touches;
				if(e.originalEvent.touches && e.originalEvent.touches.length) {
					touches = e.originalEvent.touches;
				}else if(e.originalEvent.changedTouches && e.originalEvent.changedTouches.length) {
					touches = e.originalEvent.changedTouches;
				}else{
					return false;
				}
				// If touches more then one, so stop sliding and allow browser do default action
				if(touches.length > 1) {
					return false;
				}
				point = touches[0];	
				e.preventDefault();				
			} else {
				point = e;
				e.preventDefault();		
			}
			setProgress(point.pageX);
		}
		return false;
	}	
	function setProgress(x) {
		var newPercent,ct,ct2f, seekPercent;
		
		seekPercent = x - progress_bg.offset().left;
		if(seekPercent<0) seekPercent=0;
		else if(seekPercent>seekBarSize) seekPercent=seekBarSize;
		newPercent = Math.max(0, Math.min(1, seekPercent / seekBarSize));
		//console.log('newPercent = ', newPercent);
		
		if(mediaType == 'local'){
			progress_level.css('width', seekPercent+'px');
			if(html5Support){
				if(videoInited){
					ct = newPercent * videoUp2Js.duration;
					ct2f = ct.toFixed(1);
					//console.log(videoUp2Js.seekable, videoUp2Js.seekable.length)
					try{
						videoUp2Js.currentTime = ct2f;
					}catch(er){}
				}
			}else{
				if(flashMain && typeof getFlashMovie(flashMain) !== "undefined")getFlashMovie(flashMain).pb_seek(newPercent); 
			}
		}else if(mediaType == 'youtube'){
			if(html5Support){
				if(_youtubePlayer){
					ct = newPercent * _youtubePlayer.getDuration();
					ct2f = ct.toFixed(1);
					_youtubePlayer.seek(ct2f);
				}
			}else{
				if(flashMain && typeof getFlashMovie(flashMain) !== "undefined")getFlashMovie(flashMain).pb_seek(newPercent);
			}
		}
	}
	function setProgress2(val) {
		if(mediaType == 'local'){
			if(html5Support){
				if(videoInited){
					try{
						videoUp2Js.currentTime = val;
					}catch(er){}
				}
			}else{
				if(flashMain && typeof getFlashMovie(flashMain) !== "undefined")getFlashMovie(flashMain).pb_seek(val); 
			}
		}else if(mediaType == 'youtube'){
			if(html5Support){
				if(_youtubePlayer){
					_youtubePlayer.seek(val);
				}
			}else{
				if(flashMain && typeof getFlashMovie(flashMain) !== "undefined")getFlashMovie(flashMain).pb_seek(val);
			}
		}
	}
	if(!isMobile){
		var player_progress_tooltip = mainWrapper.find('.player_progress_tooltip').css({'left': parseInt(player_seekbar.css('left'), 10) + 'px'});
		player_seekbar.bind('mouseover', mouseOverHandlerSeek);
	}
	function mouseOverHandlerSeek() {
		if(!videoInited) return false;
		if(disableSeekbarInVideo)return false;
		if(useTooltips)player_progress_tooltip.css('display', 'block').tooltipster('show');
		player_seekbar.bind('mousemove', mouseMoveHandlerSeekTooltip).bind('mouseout', mouseOutHandlerSeek);
		_doc.bind('mouseout', mouseOutHandlerSeek);
	}
	function mouseOutHandlerSeek() {
		if(!videoInited) return false;
		if(useTooltips)player_progress_tooltip.css('display', 'none').tooltipster('hide');
		player_seekbar.unbind('mousemove', mouseMoveHandlerSeekTooltip).unbind('mouseout', mouseOutHandlerSeek);
		_doc.unbind('mouseout', mouseOutHandlerSeek);
	}
	function mouseMoveHandlerSeekTooltip(e){
		var s = e.pageX - progress_bg.offset().left;
		if(s<0) s=0;
		else if(s>seekBarSize) s=seekBarSize;
		
		var center = parseInt(e.pageX - player_seekbar.offset().left - player_progress_tooltip.width() / 2,10);
		player_progress_tooltip.css('left', center + 'px');
		
		var newPercent = Math.max(0, Math.min(1, s / seekBarSize)), value, dur;
		
		if(mediaType == 'local'){
			if(html5Support){
				value=newPercent * videoUp2Js.duration, dur = videoUp2Js.duration;
			}else{
				if(flashMain && typeof getFlashMovie(flashMain) !== "undefined"){
					dur = getFlashMovie(flashMain).pb_getFlashDuration();
					value=newPercent * dur;
				}else{
					return;	
				}
			}
		}else if(mediaType == 'youtube'){
			if(html5Support){
				value=newPercent *_youtubePlayer.getDuration();
				dur = _youtubePlayer.getDuration();
			}else{
				if(flashMain && typeof getFlashMovie(flashMain) !== "undefined"){
					dur = getFlashMovie(flashMain).pb_getFlashDuration();
					value=newPercent * dur;
				}else{
					return;	
				}
			}
		}
		if(useTooltips)player_progress_tooltip.tooltipster('content', formatCurrentTime(value)+' | '+formatDuration(dur));
	}
	//********** end progress seekbar
	
	
	
	//********** start volume
	if(isIOS)mainWrapper.find('.player_volume_wrapper').remove();
	var volume_seekbar_autoHide = true;
	var defaultVolume =settings.defaultVolume, _lastVolume, volumebarDown=false;
	if(defaultVolume<0) defaultVolume=0;
	else if(defaultVolume == 0) _lastVolume=0.5;//if we click unmute from mute on the beginning
	else if(defaultVolume>1)defaultVolume=1;
	if(defaultVolume!=0)_lastVolume = defaultVolume;
	
	var player_volume =mainWrapper.find('.player_volume').css('cursor','pointer'),
	player_volume_wrapper =mainWrapper.find('.player_volume_wrapper'),
	volume_seekbar = mainWrapper.find('.volume_seekbar'),
	volume_bg = mainWrapper.find('.volume_bg'),
	volume_level = mainWrapper.find('.volume_level').css('height', defaultVolume*volumeSize+'px'),
	volumeSize=volume_bg.height();
	setVolume();
	
	if(!isMobile){
		player_volume.bind('mouseenter', function(e){
			if(!_componentInited) return false;
			volume_seekbar.css('display','block');
			if(defaultVolume==0)$(e.currentTarget).find('i').removeClass('ap_mute').addClass('ap_mute_on');
			else $(e.currentTarget).find('i').removeClass('ap_vol').addClass('ap_vol_on');
			player_volume_wrapper.unbind().bind('mouseleave', function(){
				volume_seekbar.css('display','none');
			});
		}).bind('mouseleave', function(e){
			if(!_componentInited) return false;
			volume_seekbar.css('display','block');
			if(defaultVolume==0)$(e.currentTarget).find('i').removeClass('ap_mute_on').addClass('ap_mute');
			else $(e.currentTarget).find('i').removeClass('ap_vol_on').addClass('ap_vol');
			player_volume_wrapper.unbind().bind('mouseleave', function(){
				volume_seekbar.css('display','none');
			});
		}).on('click', function(){
			if(!_componentInited) return false;
			toggleVolume();
			setVolume();
			return false;
		});
	}else{
		player_volume.on('click', function(){
			if(!_componentInited) return false;
			player_ctrl_rest.hide();
			volume_seekbar.toggle();
			return false;
		});
	}
	volume_seekbar.css({'cursor': 'pointer'}).bind(_downEvent,function(e){
		_onDragStartVol(e);
		return false;		
	}); 
	function _onDragStartVol(e) {
		if(!_componentInited || _playlistTransitionOn) return false;
		if(seekBarDown) return false;
		if(!volumebarDown){					
			var point;
			if(hasTouch){
				var currTouches = e.originalEvent.touches;
				if(currTouches && currTouches.length > 0) {
					point = currTouches[0];
				}else{	
					return false;						
				}
			}else{
				point = e;								
				e.preventDefault();						
			}
			volumebarDown = true;
			_doc.bind(_moveEvent, function(e) { _onDragMoveVol(e); }).bind(_upEvent, function(e) { _onDragReleaseVol(e); });		
		}
		return false;	
	}
	function _onDragMoveVol(e) {	
		var point;
		if(hasTouch){
			var touches;
			if(e.originalEvent.touches && e.originalEvent.touches.length) {
				touches = e.originalEvent.touches;
			}else if(e.originalEvent.changedTouches && e.originalEvent.changedTouches.length) {
				touches = e.originalEvent.changedTouches;
			}else{
				return false;
			}
			// If touches more then one, so stop sliding and allow browser do default action
			if(touches.length > 1) {
				return false;
			}
			point = touches[0];	
			e.preventDefault();				
		} else {
			point = e;
			e.preventDefault();		
		}
		volumeTo(point.pageY);
		
		return false;		
	}
	function _onDragReleaseVol(e) {
		if(volumebarDown){	
			volumebarDown = false;			
			_doc.unbind(_moveEvent).unbind(_upEvent);	
			
			var point;
			if(hasTouch){
				var touches;
				if(e.originalEvent.touches && e.originalEvent.touches.length) {
					touches = e.originalEvent.touches;
				}else if(e.originalEvent.changedTouches && e.originalEvent.changedTouches.length) {
					touches = e.originalEvent.changedTouches;
				}else{
					return false;
				}
				// If touches more then one, so stop sliding and allow browser do default action
				if(touches.length > 1) {
					return false;
				}
				point = touches[0];	
				e.preventDefault();				
			} else {
				point = e;
				e.preventDefault();		
			}
			volumeTo(point.pageY);
		}
		return false;
	}	
	function volumeTo(y) {
		defaultVolume = Math.max(0, Math.min(1, (y - volume_bg.offset().top) / volumeSize));
		defaultVolume = 1 - defaultVolume;//reverse
		setVolume();
	}
	function toggleVolume(){
		if(!_componentInited || _playlistTransitionOn) return false;
		if(defaultVolume>0){
			_lastVolume = defaultVolume;//remember last volume
			defaultVolume = 0;//set mute on (volume to 0)
		}else{
			defaultVolume = _lastVolume;//restore last volume
		}
	}
	function setVolume(){
		//console.log('setVolume ', defaultVolume);
		volume_level.css('height', defaultVolume*volumeSize+'px');
		//if(!videoInited)return false;
		if(html5Support){
			if(mediaType == 'local'){
				if(videoUp2Js)videoUp2Js.volume = defaultVolume;
			}else{
				if(_youtubePlayer) _youtubePlayer.setVolume(defaultVolume);
			}
		}else{
			if(flashMain && typeof getFlashMovie(flashMain) !== "undefined")getFlashMovie(flashMain).pb_setVolume(defaultVolume); 
		}
		if(defaultVolume == 0){
			player_volume.find('i').removeClass('fa-volume-up ap_vol_on ap_vol').addClass('fa-volume-off ap_mute');
			if(useContextMenu)contextToggleVol.find('span').html('UnMute');
		}else if(defaultVolume > 0){
			player_volume.find('i').removeClass('fa-volume-off ap_mute_on ap_mute').addClass('fa-volume-up ap_vol');
			if(useContextMenu)contextToggleVol.find('span').html('Mute');
		}
	}
	if(!isMobile){
		volume_seekbar.bind('mouseover', mouseOverHandlerVolume);
		var player_volume_tooltip = componentWrapper.find('.player_volume_tooltip'), player_volume_tooltip_origT = parseInt(player_volume_tooltip.css('top'),10);
	}
	function mouseOverHandlerVolume() {
		if(useTooltips)player_volume_tooltip.css('display', 'block').tooltipster('show');
		volume_seekbar.bind('mousemove', mouseMoveHandlerVolumeTooltip).bind('mouseout', mouseOutHandlerVolume);
		_doc.bind('mouseout', mouseOutHandlerVolume);
	}
	function mouseOutHandlerVolume() {
		if(useTooltips)player_volume_tooltip.css('display', 'none').tooltipster('hide');
		volume_seekbar.unbind('mousemove', mouseMoveHandlerVolumeTooltip).unbind('mouseout', mouseOutHandlerVolume);
		_doc.unbind('mouseout', mouseOutHandlerVolume);
	}
	function mouseMoveHandlerVolumeTooltip(e){
		var s = e.pageY - volume_bg.offset().top;
		if(s<0) s=0;
		else if(s>volumeSize) s=volumeSize;
		
		var center = parseInt(s - player_volume_tooltip.height()/2+player_volume_tooltip_origT,10);
		player_volume_tooltip.css('top', center + 'px');
		
		var newPercent = Math.max(0, Math.min(1, s / volumeSize));
		newPercent = 1 - newPercent;//reverse
		var value=parseInt(newPercent * 100, 10);
		if(useTooltips)player_volume_tooltip.tooltipster('content', value+' %');
	}
	//********** end volume

	
	
	//********** start playlist process
	function _endLoad(){
		preloader.css('display','none');
		_playlistTransitionOn=false;		
	}
	function initTooltip(){
		//console.log('initTooltip');
		mainWrapper.find('.aptooltip').tooltipster({
			onlyOne:true,
			updateAnimation:false,
			offsetY:3,//rollover menu in ie<10 (same as below)
			speed:0//pointer events none?
		 });
	}
	function _endInit(){
		//console.log('endInit');
		
		//console.log(playlistDataArr);
		
		if(!_componentInited){
			_componentInited=true;
			_doneResizing();
			
			if(useTooltips)initTooltip();
			
			if(autoHideControls){
				playerHolder.bind('mouseenter', overComponent).bind('mouseleave', outComponent);
			}else{
				showControls();
			}
			if(typeof tvpSetupDone !== 'undefined'){
				setTimeout(function(){
					clearTimeout(this);
					tvpSetupDone(_self, media_id);
				},50);	
			}
		}
		
		if(playlistDataArr.length){
			if(typeof tvpVideoLoaded !== 'undefined')tvpVideoLoaded(_self, media_id);//callback
			_playlistLoaded= true;
			showControls2();
			_counter=0;
			getVideoData();
		}
		
	}
	function getPlaylistData(data){
		
		var type = data.type,
		title = data.title ? data.title : '',
		description = data.description ? data.description : '', 
		thumb='', download, captions, events, link, target, showControls = true, disableSeekbar = false, showSkipBtn = false, skipEnableTime = 0;
		
		if(typeof data.previewImage !== 'undefined' && !isEmpty(data.previewImage))thumb = qualifyURL(data.previewImage);
		if(typeof data.downloadPath !== 'undefined' && !isEmpty(data.downloadPath))download = data.downloadPath;
		if(typeof data.captions !== 'undefined' && !isEmpty(data.captions))captions = data.captions;
		if(typeof data.events !== 'undefined' && !isEmpty(data.events))events = data.events;
		if(typeof data.link !== 'undefined' && !isEmpty(data.link))link = data.link;
		if(typeof data.target !== 'undefined' && !isEmpty(data.target))target = data.target;
		if(typeof data.showControls !== 'undefined')showControls = data.showControls;
		if(typeof data.disableSeekbar !== 'undefined')disableSeekbar = data.disableSeekbar;
		if(typeof data.showSkipBtn !== 'undefined')showSkipBtn = data.showSkipBtn;
		skipBtnText = typeof data.skipBtnText !== 'undefined' && !isEmpty(data.skipBtnText) ? data.skipBtnText : '';
		if(typeof data.skipEnableTime !== 'undefined')skipEnableTime = Math.abs(parseInt(data.skipEnableTime,10));
		
		var sett={'id': 0, type: type, 'title': title, 'description': description, thumb: thumb, path: data.path, captions: captions, events: events, 'deeplink': baseURL, 'download': download, link:link, target:target, showControls: showControls, disableSeekbar: disableSeekbar, showSkipBtn: showSkipBtn, skipBtnText:skipBtnText, skipEnableTime: skipEnableTime}
		
		if(type == 'youtube' && useYoutubeApi){
			_ytArr.push({path:data.path, set:sett});
		}
		
		return sett;
	}
	function _setPlaylist(data){
		if(data.length==0){
			alert('No videos found!');
			return false;	
		}
		//console.log('_setPlaylist');
		_playlistTransitionOn=true;
		_playlistLoaded=false;
		preloader.css('display','block');
		
		playlistDataArr=[];
		_videoProcessData=[];
		_ytArr=[];
		playlistDataArr.push({sequence:[]});
		
		var i, len = data.length;
		for(i=0;i<len;i++) {
			playlistDataArr[0].sequence.push(getPlaylistData(data[i]));
		}
		
		sequence_counter = settings.sequence_counter ? settings.sequence_counter : 0;
		settings.sequence_counter=null;
		sequence_length = playlistDataArr[0].sequence.length;
		
		if(_ytArr.length){
			checkYoutube();
		}else{
			_endLoad();
			_endInit();
		}
	}
	function checkYoutube() {
		if(_ytArr.length){
			_processYoutubeSingle(_ytArr.shift());
		}else{
			_endLoad();
			_endInit();
		}
	}
	function _processYoutubeSingle (data) {
		if(ytApiVersion==2){
			var url = 'http://gdata.youtube.com/feeds/api/videos/'+data.path+'?v=2&format=5&alt=jsonc';
		}else{
			var url = 'https://www.googleapis.com/youtube/v3/videos?id='+data.path+'&key='+gapi_key+'&part=snippet,contentDetails,statistics,status';
		}
		$.ajax({
			url: url,
			dataType: "jsonp"
		}).done(function(response) {
			ytApiVersion == 2 ? processYtSuccessV2(response, data.set) : processYtSuccessV3(response, data.set);
		}).fail(function(jqXHR, textStatus, errorThrown) {
			alert('There was an error retrieveing youtube data: ' + jqXHR.responseText);
			checkYoutube();
		});	
	}
	function processYtSuccessV2(response, set) {
		 //console.log(response);
		 var _item = response.data;
		 if(_item && _item.accessControl){//skip deleted, private videos
			 //http://apiblog.youtube.com/2011/12/understanding-playback-restrictions.html
			 //https://developers.google.com/youtube/2.0/developers_guide_protocol_uploading_videos#Setting_Access_Controls
			 //console.log(_item.status.value);
			 var title=_item.title?_item.title:'',description=_item.description?_item.description:'',thumb='';
			 if(_item.thumbnail)thumb=_item.thumbnail.hqDefault ? _item.thumbnail.hqDefault : _item.thumbnail.sqDefault;
			 if(!isEmpty(thumb))thumb=qualifyURL(thumb);
			 set.title = title;
			 set.description = description;
			 set.thumb = thumb;
			 checkYoutube();
		 }else{
			 alert('Error retrieving Youtube single video!');
			 checkYoutube();
		 }
	}
	function processYtSuccessV3(response, set) {
		 //console.log(response);
	
		 var i = 0, len = response.items.length, obj;
		 for(i; i < len; i++){
			 _item = response.items[i];
			 if(_item){
				 if(type=='youtube_playlist' || type=='youtube_single'){
					 if(_item.status.privacyStatus != 'private'){
						 _videoProcessData.push(getYtItemData(_item, type));
					 }else{
						 //console.log(_item.status.privacyStatus);	 	 
					 }
				 }
				 else if(type=='youtube_video_query'){
					 _videoProcessData.push(getYtItemData(_item, type));
				 }else if(type=='user_channels' || type=='youtube_channel'){
					 ytChannelArr.push(_item.contentDetails.relatedPlaylists.uploads);//get playlist ids
				 }
			 }
		 }
		 
		 if(type=='youtube_single'){
			  //console.log(_videoProcessData.length, _videoProcessData); 
			  
			  var thumb =_videoProcessData[0].thumb;
			  if(!isEmpty(thumb))thumb=qualifyURL(thumb);
			  
			  set.title = _videoProcessData[0].title;
			  set.description = _videoProcessData[0].description;
			  set.thumb = thumb;
			  
			  checkYoutube();
			  
		 }else{
			  if(type!='user_channels' && type!='youtube_channel'){
				 youtubeCounter += youtubeEnlargeCounter;	
				// console.log(youtubeCounter, youtubeLimit);
				 if(youtubeCounter < youtubeLimit){
					  var totalResults = response.pageInfo.totalResults;
					  if(youtubeCounter <= totalResults && response.nextPageToken){
						  if(type=='youtube_playlist'){
							  var url = 'https://www.googleapis.com/youtube/v3/playlistItems?pageToken='+response.nextPageToken+'&part=snippet,status,contentDetails&maxResults=50&playlistId='+pl_id+'&key='+gapi_key+'';
						  }
						  else if(type=='youtube_video_query'){
							  var url = 'https://www.googleapis.com/youtube/v3/search?pageToken='+response.nextPageToken+'&part=id,snippet&maxResults='+youtubeEnlargeCounter+'&order='+yt_order+'&q='+query+'&key='+gapi_key+''; 
						  }
						  processYtData(url);
					  }else{
						  //console.log(_videoProcessData.length, _videoProcessData);  
					  }
				 }else{
					 if(user_channel_process){
						channel_counter++;
						if(channel_counter<ytChannelArr.length){
							youtubeCounter=0;//reset
							pl_id = ytChannelArr[channel_counter];
							var url = 'https://www.googleapis.com/youtube/v3/playlistItems?part=snippet,status,contentDetails&maxResults=50&playlistId='+pl_id+'&key='+gapi_key+'';
							processYtData(url);
						}else{
							user_channel_process = false;
							//console.log(_videoProcessData.length, _videoProcessData); 
						}
					 }
					 //console.log(_videoProcessData.length, _videoProcessData); 
				 }
			 }else{
				 if(ytChannelArr.length){
					 //console.log(ytChannelArr);
					 //for user_channels we need to get playlist ids for all channels, then process each playlist id! 
					 if(ytChannelArr.length>1)user_channel_process=true;
					 pl_id = ytChannelArr[channel_counter];
					 var url = 'https://www.googleapis.com/youtube/v3/playlistItems?part=snippet,status,contentDetails&maxResults=50&playlistId='+pl_id+'&key='+gapi_key+'';
					 type='youtube_playlist';//switch
					 processYtData(url);
				 }else{
					 //console.log(_videoProcessData.length, _videoProcessData); 
				 }
			 }
		 }
	 }
	function getYtItemData(_item, type) {
		 var obj = {};
		 obj.dataid = _videoProcessData.length;
		 obj.type = 'youtube';
		 //if(useDeeplink)obj.deeplink = currentProcessDeeplink;
		 if(type=='youtube_single'){
			obj.path = obj.id = _item.id;
		 }else if(type=='youtube_playlist'){
			obj.path = obj.id = _item.contentDetails.videoId;
		 }else if(type=='youtube_video_query'){
			obj.path = obj.id = _item.id.videoId; 
		 }
		 obj.title=_item.snippet.title?_item.snippet.title:'';
		 obj.description=_item.snippet.description?_item.snippet.description:'';
		 if(_item.snippet.thumbnails){
			 if(_item.snippet.thumbnails.medium)obj.thumb=_item.snippet.thumbnails.medium.url;
			 else if(_item.snippet.thumbnails.standard)obj.thumb=_item.snippet.thumbnails.standard.url;
		 	 /*
			 if(_item.snippet.thumbnails.default)obj.thumb=_item.snippet.thumbnails.default.url;//"default" - reserved keyword, fails in ie8!
			 else if(_item.snippet.thumbnails.medium)obj.thumb=_item.snippet.thumbnails.medium.url;
			 else if(_item.snippet.thumbnails.standard)obj.thumb=_item.snippet.thumbnails.standard.url;
			 */
		 }
		 //obj.item = _videoProcessDataUrl[_videoProcessCounter].item; 
		 return obj;
	}
	//********** end playlist process
	
	var buttonArr=[
		mainWrapper.find('.player_toggleControl'),
		mainWrapper.find('.player_fullscreen')
	];
	var btn,len = buttonArr.length,i=0;
	for(i;i<len;i++){
		btn = $(buttonArr[i]).css('cursor', 'pointer').on('click', clickControls);
		if(!isMobile)btn.bind('mouseenter', overControls).bind('mouseleave', outControls);
	}
	function clickControls(e){
		if(!_componentInited || _playlistTransitionOn) return false;
		if (!e) var e = window.event;
		if(e.cancelBubble) e.cancelBubble = true;
		else if (e.stopPropagation) e.stopPropagation();
		
		var currentTarget = $(e.currentTarget),c=currentTarget.attr('class'), m = c.split(' ');
		
		if($.inArray('player_toggleControl', m) != -1){	
			togglePlayBack();
		}else if($.inArray('player_fullscreen', m) != -1){	
			toggleFullscreen(true);
			if(useTooltips)$(e.currentTarget).tooltipster('hide');
		}
		return false;
	}
	function overControls(e){
		if(!_componentInited || _playlistTransitionOn) return false;
		if (!e) var e = window.event;
		if(e.cancelBubble) e.cancelBubble = true;
		else if (e.stopPropagation) e.stopPropagation();
		
		var currentTarget = $(e.currentTarget),c=currentTarget.attr('class'), m = c.split(' '), i=currentTarget.find('i');
		
		if($.inArray('player_toggleControl', m) != -1){	
			if(mediaPlaying){
				i.removeClass('ap_pause').addClass('ap_pause_on');
			}else{
				i.removeClass('ap_play').addClass('ap_play_on');
			}
		}else if($.inArray('player_fullscreen', m) != -1){	
			if(componentSize== "normal"){
				i.removeClass('ap_fs_ent').addClass('ap_fs_ent_on');
			}else{
				i.removeClass('ap_fs_exit').addClass('ap_fs_exit_on');
			}
		}
		return false;
	}
	function outControls(e){
		if(!_componentInited || _playlistTransitionOn) return false;
		if (!e) var e = window.event;
		if(e.cancelBubble) e.cancelBubble = true;
		else if (e.stopPropagation) e.stopPropagation();
		
		var currentTarget = $(e.currentTarget),c=currentTarget.attr('class'), m = c.split(' '), i=currentTarget.find('i');
		
		if($.inArray('player_toggleControl', m) != -1){	
			if(mediaPlaying){
				i.removeClass('ap_pause_on').addClass('ap_pause');
			}else{
				i.removeClass('ap_play_on').addClass('ap_play');
			}
		}else if($.inArray('player_fullscreen', m) != -1){	
			if(componentSize== "normal"){
				i.removeClass('ap_fs_ent_on').addClass('ap_fs_ent');
			}else{
				i.removeClass('ap_fs_exit_on').addClass('ap_fs_exit');
			}
		}
		return false;
	}
	function toggleBigPlay(dir) {
		//console.log('toggleBigPlay ', dir);
		big_play.css('left', 0+'px');
		big_play.css('display', 'block'); 	
		if(dir=='off'){
			big_play.css('opacity', 0); 
			if(isIE && ieBelow9){
				big_play_bg.css('display', 'none'); 	
				ap_bplay.css('display', 'none'); 	
			}
		}else{
			big_play.css('opacity', 1); 	
			if(isIE && ieBelow9){
				big_play_bg.css('display', 'block');
				ap_bplay.css('display', 'block');
			} 	
		}
	}
	
	//*******************
	
	function overComponent(e) {
		//console.log('overComponent ', _playlistTransitionOn);
		if(!_componentInited || _playlistTransitionOn) return false;
		//console.log('overComponent');
		if (!e) var e = window.event;
		if(e.cancelBubble) e.cancelBubble = true;
		else if (e.stopPropagation) e.stopPropagation();
		showControls();
		return false;
	}
	
	function outComponent(e) {
		if(!_componentInited || _playlistTransitionOn) return false;
		//console.log('outComponent');
		if (!e) var e = window.event;
		if(e.cancelBubble) e.cancelBubble = true;
		else if (e.stopPropagation) e.stopPropagation();
		if(autoHideControls && componentSize!= "fullscreen")hideControls();
		return false;
	}
	
	function showControls(){
		//console.log('showControls');
		if(!videoInited) return false;
		if(settings.useControls && showControlsInVideo)playerControls.css('display','block');
		if(showSkipButtonInVideo)ap_adv_skip.css('display','block');
	}
	function showControls2(){
		if(!settings.useControls)return;
		//console.log('showControls');
		if(!videoInited) return false;
		if(settings.useControls && showControlsInVideo)playerControls.css('display','block');
		if(showSkipButtonInVideo)ap_adv_skip.css('display','block');
	}
	function hideControls(){
		//console.log('hideControls');
		playerControls.css('display','none');
	}
	
	
	//*******************
	function cleanMedia(){
		//console.log('cleanMedia');
		if(videoDataIntervalID)clearInterval(videoDataIntervalID);
		if(dataIntervalID) clearInterval(dataIntervalID);
		
		captionMenuSizeTaken = qualityMenuSizeTaken = null;
		ap_adv_skip.hide();	
		ap_adv_msg_end.hide();	
		hideControls();
		infoHolder.css('display','none');
		infoOpened=false;
		if(settings.useSharing)shareHolder.css('display','none');
		player_download.css('display','none');
		
		if(mediaType && mediaType == 'local'){
			if(html5Support){
				if(videoUp2Js){
					//var memLeak = mediaHolder.html(); //http://stackoverflow.com/questions/5170398/ios-safari-memory-leak-when-loading-unloading-html5-video
					videoUp2Js.pause();
					try{
						videoUp2Js.currentTime = 0;
					}catch(er){}
					videoUp2Js.src = '';
					//mediaHolder.html("").html(memLeak);
				}
				if(video)video.unbind();
				
				mediaHolder.css('display', 'none');
				if(!isMobile & html5Support){
					mediaHolder.html('');
					html5video_inited=false;	
				}
			}else{
				if(typeof getFlashMovie(flashMain) !== "undefined")getFlashMovie(flashMain).pb_dispose();
			}
		}else if(mediaType && mediaType == 'youtube'){
			if(html5Support){
				if(_youtubePlayer) _youtubePlayer.stop();
				youtubeIframeMain.css('left', -10000+'px');
			}else{
				if(typeof getFlashMovie(flashMain) !== "undefined")getFlashMovie(flashMain).pb_dispose();
			}
		}	
		
		toggleBigPlay('off');
		if(previewPoster){
			previewPoster.remove();
			previewPoster=null;
		} 
		mediaPreview.css('display', 'none');
		
		if(quality_menu)quality_menu.remove();
		player_quality.css('display','none');
		quality_holder.css('display','none');
		
		videoForcePause=false;
		resetData();
		mediaPlaying=false;
		videoInited=false;//reset
		media_started = false;
		
		resizeControls();
		mediaWidth=mediaHeight=null;
		
		playerHolder.children("div[class='ap_sub']").remove();//remove subtitles
		if(captions_menu)captions_menu.remove();
		player_captions.css('display','none');
		caption_holder.css('display','none');
		currCaptionArr=[];
		captionsCreated=false;
		
		//we cannot have timed elements in new div (they have to float freely) because they might be interactive and we cant place new div over big_play (which toggles the video!), big_play has to be last interactive element before player controls (subs as well)
		playerHolder.children("div[class='ap_elem']").remove();//remove timed captions
		eventsCreated = false;
	}
	
	function cleanMediaQuality(){//quality change
		//console.log('cleanMediaQuality');
		if(videoDataIntervalID)clearInterval(videoDataIntervalID);
		if(dataIntervalID) clearInterval(dataIntervalID);
		
		if(mediaType && mediaType == 'local'){
			if(html5Support){
				if(videoUp2Js){
					//var memLeak = mediaHolder.html(); //http://stackoverflow.com/questions/5170398/ios-safari-memory-leak-when-loading-unloading-html5-video
					videoUp2Js.pause();
					try{
						videoUp2Js.currentTime = 0;
					}catch(er){}
					videoUp2Js.src = '';
					//mediaHolder.html("").html(memLeak);
				}
				if(video)video.off("ended", videoEndHandler).off("loadedmetadata", videoMetadata).off("waiting",waitingHandler).off("playing", playingHandler).off("play", playHandler).off("pause", pauseHandler);
				mediaHolder.css('display', 'none');
				if(!isMobile & html5Support){
					mediaHolder.html('');
					html5video_inited=false;	
				}
			}else{
				if(typeof getFlashMovie(flashMain) !== "undefined")getFlashMovie(flashMain).pb_dispose();
			}
		}else if(mediaType && mediaType == 'youtube'){
			if(html5Support){
				if(_youtubePlayer) _youtubePlayer.stop();
				youtubeIframeMain.css('left', -10000+'px');
			}else{
				if(typeof getFlashMovie(flashMain) !== "undefined")getFlashMovie(flashMain).pb_dispose();
			}
		}	
		
		resetData();
		mediaPlaying=false;
		videoInited=false;//reset
		media_started = false;
		
	}
	
	function getEvents(url){
		$.ajax({
			url: url,
			dataType: "html",
			cache: false
		}).done(function(result) {
			timedElements=[];
			$(result).find("div[class='ap_elem']").each(function(){
				var _item = $(this);
				timedElements.push({
					start:!isNaN(parseInt(_item.attr('data-show'),10)) ? parseInt(_item.attr('data-show'),10) : 0,
					end:!isNaN(parseInt(_item.attr('data-hide'),10)) ? parseInt(_item.attr('data-hide'),10) : 100000,
					item:_item
				});
			});
			getEventsDone=true;
			//console.log(timedElements,timedElements.length);
		}).fail(function(jqXHR, textStatus, errorThrown) {
			//alert('events load fail: ' + url);
			getEventsDone=true;
		});	
	}
	
	function getCaptions(url){
		$.ajax({
			url: url,
			dataType: "html",
			cache: false
		}).done(function(result) {
			//console.log(result);
			captionArr = [];
			$(result).find("div[class='sub_group']").each(function(){
				var _item = $(this), obj = {};
				obj.title = _item.attr('data-title');
				if(_item.attr('data-default') != undefined)obj._default=true;
				obj.items=[];
				captionArr.push(obj);
				_item.find("div[class='ap_sub']").each(function(){
					var c = $(this);
					obj.items.push({
						start:parseInt(c.attr('data-show'),10),
						end:parseInt(c.attr('data-hide'),10),
						item:c
					});
				});	
			});	
			//console.log(captionArr,captionArr.length);
			getCaptionsDone=true;
		}).fail(function(jqXHR, textStatus, errorThrown) {
			//alert('captions load fail: ' + url);
			getCaptionsDone=true;
		});	
	}
	function videoDataCheckEnd(){
		if(getEventsDone && getCaptionsDone){
			if(videoDataIntervalID)clearInterval(videoDataIntervalID);
			_findMedia();
		}
	}
	function getVideoData(){
		//console.log('getVideoData')
		currVideoData = playlistDataArr[_counter].sequence[sequence_counter];
		//console.log(currVideoData);
		
		var waitData;
		timedElements=[];
		if(currVideoData.events != undefined){
			waitData=true;
			getEventsDone=false;
			getEvents(currVideoData.events);
		}else{
			getEventsDone=true;	
		}
		captionArr = [];
		if(currVideoData.captions != undefined){
			waitData=true;	
			getCaptionsDone=false;
			getCaptions(currVideoData.captions);
		}else{
			getCaptionsDone=true;	
		}
		if(waitData){
			if(videoDataIntervalID)clearInterval(videoDataIntervalID);
			videoDataIntervalID = setInterval(videoDataCheckEnd, videoDataInterval);
		}else{
			_findMedia();
		}
	}
	function getQuality(){
		if(mediaType== 'local'){
			var i = 0, len = qualityDataArr.length, obj, path;
			for(i;i<len;i++){
				obj=qualityDataArr[i];
				if(curr_quality == obj.quality){
					if(mp4Support){
						path = obj.mp4;
					}else{
						if(!useWebmVideoFormat && vorbisSupport){
							path = obj.ogv;
						}else if(useWebmVideoFormat && webmSupport){
							path = obj.webm;
						}
					} 
					if(typeof tvpQualityChange !== 'undefined')tvpQualityChange(_self, media_id, curr_quality);//callback
					break;
				}
			}
		}else{
			path = currVideoData.path;
		}
		//console.log('getQuality: ', path,curr_quality);
		return path;
	}
	
	function _findMedia(qc){
		//console.log('_findMedia');
		
		quality_change = qc ? qc : null;//only on quality toggle btn
		quality_change ? cleanMediaQuality(): cleanMedia();
		
		if(!quality_change){
			mediaType = currVideoData.type;
			
			if(mediaType=='local')checkQuality('local');
		
			//captions
			if(captionArr.length && !captionsCreated){
				createCaptions();
				player_captions.css('display','block');
				captionsCreated=true;
			}

			showControlsInVideo = currVideoData.showControls;
			showSkipButtonInVideo = currVideoData.showSkipBtn;
			disableSeekbarInVideo = currVideoData.disableSeekbar;
			skipEnableTime = currVideoData.skipEnableTime;
			skipBtnText = currVideoData.skipBtnText;
			//console.log(skipBtnText);
			if(showSkipButtonInVideo){
				skipTimeHappened=false;
				if(skipEnableTime>0){
					ap_adv_msg.show().find('p').html(skipBtnText);
					//next video thumb
					if(sequence_counter+1<sequence_length && !isEmpty(playlistDataArr[_counter].sequence[sequence_counter+1].thumb)){
						ap_adv_img.empty().show().append($('<img class="adv_thumb" src="'+playlistDataArr[_counter].sequence[sequence_counter+1].thumb+'" alt=""/>'));
					}else{
						ap_adv_img.hide();
					}
				}else{
					skipEnableTime=null;
					ap_adv_img.hide();
					ap_adv_msg.hide();
					ap_adv_msg_end.show();
					disableSeekbarInVideo=false;
				}
			}
		}
	
		mediaPath = getQuality();
		//console.log(mediaType,mediaPath);
		
		if(mediaType == 'local'){
			if(autoPlay){
				if(html5Support){
					initVideo();
				}else{
					if(flashMain && typeof getFlashMovie(flashMain) !== "undefined"){
						getFlashMovie(flashMain).pb_play(mediaPath, aspectRatio, componentWrapper.width(), componentWrapper.height(), 'local', true, quality_change ? curr_time : null);
						videoInited=true;
					}
				}
			}else{
				loadPreview();
				showControls();
			}
		}else if(mediaType == 'youtube'){
			if(html5Support){
				_initYoutube();
			}else{
				if(flashMain && typeof getFlashMovie(flashMain) !== "undefined"){
					getFlashMovie(flashMain).pb_play(mediaPath, aspectRatio, componentWrapper.width(), componentWrapper.height(), 'youtube', yt_autoPlay, null);
					if(autoPlay)videoInited=true;
				}
			}
		}
		if(typeof videoPlayerItemTriggered !== 'undefined'){
			setTimeout(function(){videoPlayerItemTriggered(_self, media_id, _counter);},50);	
		}
	}
	
	
	//*************** start youtube
	function _initYoutube() {
		//console.log('_initYoutube ', _youtubeInited);
		
		if(!_youtubeStarted){//ios fix, we need to start yt playback by clicking on yt player first time!!
			mediaHolder.css('display','none');
			big_play.css('left', -10000+'px');
		}
		
		if(!_youtubeInited){
			youtubeIframeMain = $("<div class='youtubeIframeMain'/>").prependTo(playerHolder);
			var data={'autoPlay': yt_autoPlay, 'defaultVolume': defaultVolume, 
			'mediaPath': mediaPath, 'youtubeHolder': youtubeIframeMain, 'youtubeChromeless': _youtubeChromeless, 
			'isMobile': isMobile, 'initialAutoplay': initialAutoplay, 'quality':useYoutubeHighestQuality};
			//console.log(data);
			_youtubePlayer = $.youtubePlayer(data);
			$(_youtubePlayer).bind('ap_YoutubePlayer.YT_READY', function(){
				//console.log('ap_YoutubePlayer.YT_READY');
				resizeVideo();
			});
			$(_youtubePlayer).bind('ap_YoutubePlayer.START_PLAY', function(){
				//console.log('ap_YoutubePlayer.START_PLAY');
				_youtubeStarted=true;
				videoInited=true;
				if(!isMobile)setAutoplay(true);
				checkQuality('youtube');
				resizeVideo();
				if(!quality_change)checkInfo();
				showControls();
				if(dataIntervalID) clearInterval(dataIntervalID);
				dataIntervalID = setInterval(trackVideoData, dataInterval);	
				
				toggleBigPlay('on');
				
				if(isIE && ieBelow9){
					big_play.css('display', 'block');
				} 
			});
			$(_youtubePlayer).on('ap_YoutubePlayer.END_PLAY', function(){
				//console.log('ap_YoutubePlayer.END_PLAY');
				videoEndHandler();	
			});
			$(_youtubePlayer).on('ap_YoutubePlayer.STATE_PLAYING', function(){
				//console.log('ap_YoutubePlayer.STATE_PLAYING');
				playHandler();
			});
			$(_youtubePlayer).on('ap_YoutubePlayer.STATE_PAUSED', function(){
				//console.log('ap_YoutubePlayer.STATE_PAUSED');
				pauseHandler();
			});
			$(_youtubePlayer).on('ap_YoutubePlayer.STATE_CUED', function(){//cue doesnt fire always
				//console.log('ap_YoutubePlayer.STATE_CUED');
				preloader.css('display','none');
			});
			$(_youtubePlayer).on('ap_YoutubePlayer.QUALITY_CHANGE', function(e, quality){
				//qualityconsole.log('ap_YoutubePlayer.QUALITY_CHANGE', quality);
				if(useYoutubeHighestQuality && qualityMenuArr.length){
					setQualityMenuItem(qualityMenuArr[0].item);	
				}
				if(typeof tvpQualityChange !== 'undefined')tvpQualityChange(_self, media_id, quality);//callback
			});
			_youtubeInited=true;
		}else{
			resizeVideo();
			_youtubePlayer.initVideo(mediaPath);
		}
		setTimeout(function(){preloader.css('display','none')},1000);
		showControls();
	}
	//*************** end youtube
	
	
	//*************** start local video
	function loadPreview(){
		//console.log('loadPreview');
		
		mediaPreview.css('display', 'block');
	    preloader.css('display','block');

		var path = currVideoData.thumb, url = path+"?rand=" + (Math.random() * 99999999);
		//console.log(url);
		
		$(new Image()).css({
		   position: 'absolute',
		   display: 'block',
		   opacity: 0
		}).appendTo(mediaPreview)
		.load(function() {
			preloader.css('display','none');
			previewOrigW=this.width;
			previewOrigH=this.height;
			mediaWidth=this.width;
			mediaHeight=this.height;
			previewPoster = $(this);
			resizePreview(previewPoster);
			previewPoster.animate({'opacity': 1},  {duration: 500});
			toggleBigPlay('on');
		}).error(function(e) {
			//console.log("error " + e);
		}).attr('src', url);
	}
	function initVideo(){
		//console.log('initVideo');

		preloader.css('display','block');
		
		mediaPath+="?rand=" + (Math.random() * 99999999);//ios fix

		if(!html5video_inited){//we need one video source if we want to auto-advance on ios (with no click)
		
			var videoCode='';
			videoCode += '<video class="video_cont" width="'+mediaWidth+'" height="'+mediaHeight+'">';
			videoCode += '<source src="'+mediaPath+'" />';
			videoCode += '</video>';
			
			if(!isAndroid){//no type on android
				var append;
				if(mp4Support){
					append = 'type="video/mp4"';
				}else if(!useWebmVideoFormat && vorbisSupport){
					append = 'type="video/ogg"';
				}else if(useWebmVideoFormat && webmSupport){
					append = 'type="video/webm"';
				}
				
				var m = videoCode.match(/\/\>/);//closing source tag
				videoCode = videoCode.slice(0, m.index) + append + videoCode.slice(m.index);
			}
			//console.log(videoCode);
			
			mediaHolder.css({opacity:0, display:'block'}).html(videoCode);
			
			video = mediaHolder.find('.video_cont');//get player reference
			videoUp2Js = video[0];
			//console.log(video, videoUp2Js);
			
			if(isiPad){
				//webkitSupportsFullscreen (Note: The webkitSupportsFullscreen property is not valid until the movie metadata has loaded. You can detect when the metadata is loaded by installing an event listener for the loadedmetadata event.)
				video.on("webkitbeginfullscreen", function(e){
					componentSize="fullscreen";
					iosRealFs=true;
				}).on("webkitendfullscreen", function(e){
					componentSize="normal";
					iosRealFs=false;
				});
			}
			
		}else{
			
			mediaHolder.css({opacity:0, display:'block'});
			
			video = mediaHolder.find('.video_cont');//get player reference
			videoUp2Js = video[0];
			
			videoUp2Js.src = mediaPath;
			videoUp2Js.load();
			
		}

		videoUp2Js.volume = defaultVolume;
		video.css('position','absolute').on("ended", videoEndHandler).on("loadedmetadata", videoMetadata).on("waiting",waitingHandler).on("playing", playingHandler).on("play", playHandler).on("pause", pauseHandler);
			
		if(isIOS && !html5video_inited){
			videoUp2Js.src = mediaPath;
			videoUp2Js.load();
		}
		else if(isAndroid && !html5video_inited){
			videoUp2Js.play();
			
			toggleBigPlay('off');
			if(previewPoster){
				previewPoster.stop().animate({ 'opacity':0},  {duration: 500, complete:function(){
					previewPoster.remove();
					previewPoster=null;
				}});
			}
			videoInited=true;
			showControls();
		}
		
		html5video_inited=true;
		
	}
	function waitingHandler(e){//show preloader
		 //console.log('waitingHandler');
		 if(mediaPlaying) preloader.css('display','block');
	}
	function playingHandler(e){//hide preloader
		//console.log('playingHandler');
		 preloader.css('display','none');
	}
	function playHandler(e){
		//console.log('playHandler');
		player_toggleControl.find('i').removeClass('fa-play ap_play ap_play_on').addClass('fa-pause ap_pause');
		if(useContextMenu)contextTogglePlayback.find('span').html('Pause');
		toggleBigPlay('off');
		if(!media_started){//fires only first time media is played
			if(isiPhoneIpod){//we cant use elements above video
				mainWrapper.find('.big_play').remove();
			}
			if(typeof tvpVideoStart !== 'undefined')tvpVideoStart(_self, media_id, _counter);//callback
			if(isIE && ieBelow9){
				big_play.css('display', 'block');
			} 	
			media_started=true;	
		}
		if(typeof tvpVideoPlay !== 'undefined')tvpVideoPlay(_self, media_id, _counter);//callback 
		mediaPlaying=true;
	}
	function pauseHandler(e){
		//console.log('pauseHandler');
		player_toggleControl.find('i').removeClass('fa-pause ap_pause ap_pause_on').addClass('fa-play ap_play');
		if(useContextMenu)contextTogglePlayback.find('span').html('Play');
		toggleBigPlay('on');
		if(typeof tvpVideoPause !== 'undefined')tvpVideoPause(_self, media_id, _counter);//callback 
		mediaPlaying=false;
	}
	function videoMetadata(e){
		//console.log("videoMetadata: ", videoUp2Js.duration, videoUp2Js.videoWidth, videoUp2Js.videoHeight);
		if(videoUp2Js.videoWidth)mediaWidth=videoUp2Js.videoWidth;
		if(videoUp2Js.videoHeight)mediaHeight=videoUp2Js.videoHeight;
		resizeVideo();
		if(dataIntervalID) clearInterval(dataIntervalID);
		dataIntervalID = setInterval(trackVideoData, dataInterval);
		
		videoUp2Js.play();
		videoInited=true;
		
		mediaHolder.stop().animate({'opacity':1}, {duration: 300});
		
		if(quality_change){
			try{
				videoUp2Js.currentTime=curr_time-2;//-2 to buffer better
			}catch(er){}
		}
		
		//if(isiPad && videoUp2Js.webkitSupportsFullscreen)fullscreenPossible=true;//we loose elements above video in fs
		
		if(!quality_change)checkInfo();
		if(!isMobile)setAutoplay(true);
		else autoPlay=true;
		showControls();
		
	}
	function setAutoplay(val){
		autoPlay=yt_autoPlay=vim_autoPlay=initialAutoplay=val;
		if(_youtubePlayer)_youtubePlayer.setAutoPlay(val);
		//if(!html5Support)if(flashMain && typeof getFlashMovie(flashMain) !== "undefined")getFlashMovie(flashMain).pb_setAutoplay(val);
	}
	function togglePlayBack(){
		//console.log('togglePlayBack');
		if(_counter == -1) return false;
		if(mediaType == 'local'){
			 if(!videoInited && !autoPlay){
				preloader.css('display','block');	
				toggleBigPlay('off'); 
				if(previewPoster) {
					previewPoster.stop().animate({ 'opacity':0},  {duration: 500, complete:function(){
						previewPoster.remove();
						previewPoster=null;
					}});
				}
				if(html5Support){
					initVideo();
				}else{
					if(flashMain && typeof getFlashMovie(flashMain) !== "undefined")getFlashMovie(flashMain).pb_play(mediaPath, aspectRatio, componentWrapper.width(), componentWrapper.height(), 'local', true, quality_change ? curr_time : null);
				}
			 }else{
				if(html5Support){
				    if (videoUp2Js.paused) {
					    videoUp2Js.play();
				    } else {
					    videoUp2Js.pause();
				    }
				}else{
					if(flashMain && typeof getFlashMovie(flashMain) !== "undefined")getFlashMovie(flashMain).pb_togglePlayback();
				}
			 }
		 }else if(mediaType == 'youtube'){
			  if(html5Support){
				  if(_youtubePlayer)_youtubePlayer.togglePlayback();
			  }else{
				  if(flashMain && typeof getFlashMovie(flashMain) !== "undefined")getFlashMovie(flashMain).pb_togglePlayback();	
				  videoInited=true;
			  }
	   	 }
		 videoInited=true;
	}
	function trackVideoData(){
		var ct;
		if(mediaType == 'local'){
			if(html5Support){
				//console.log(videoUp2Js.currentTime);
				player_mediaTime_current.find('p').html(formatCurrentTime(videoUp2Js.currentTime));
				player_mediaTime_total.find('p').html(formatDuration(videoUp2Js.duration));
				if(!seekBarDown){
					progress_level.width((videoUp2Js.currentTime / videoUp2Js.duration) * seekBarSize);
					try{
						var buffered = Math.floor(videoUp2Js.buffered.end(0));
					}catch(error){}
					if(!isNaN(buffered)){
						var percent = buffered / Math.floor(videoUp2Js.duration);
						//console.log(percent, buffered);
						if(!isNaN(percent)){
							load_level.width(percent * seekBarSize);	
						}
					}
				}
				ct=parseInt(parseInt(videoUp2Js.currentTime),10);
			}
		}else if(mediaType == 'youtube'){
			if(html5Support){
				//console.log(_youtubePlayer.getCurrentTime());
				player_mediaTime_current.find('p').html(formatCurrentTime(_youtubePlayer.getCurrentTime()));
				player_mediaTime_total.find('p').html(formatDuration(_youtubePlayer.getDuration()));
				if(_youtubePlayer && !seekBarDown){
					progress_level.width((_youtubePlayer.getCurrentTime() / _youtubePlayer.getDuration()) * seekBarSize);
					percent = _youtubePlayer.getVideoBytesLoaded() / _youtubePlayer.getVideoBytesTotal();
					load_level.width(percent * seekBarSize);
					ct=parseInt(_youtubePlayer.getCurrentTime(),10);
				}
			}
		}	
		if(timedElements && timedElements.length || typeof curr_lang !== "undefined" && curr_lang.length){
			if(ct != lastTime)trackTimedElements(ct);
		}
		if(showSkipButtonInVideo && skipEnableTime != null && !skipTimeHappened){
			//console.log(ct, skipEnableTime);
			if(ct < skipEnableTime){
				ap_adv_msg.find('p').html(skipBtnText+' '+(skipEnableTime-ct).toString());	
			}else{
				skipTimeHappened = true;	
				ap_adv_img.hide();
				ap_adv_msg.hide();
				ap_adv_msg_end.show();
				disableSeekbarInVideo=false;
			}
		}
	};
	function trackTimedElements(ct){
		 //console.log(ct);
		 //timed elements
		 var i = 0, len = timedElements.length, elem, show_t, hide_t, item;
		 for(i; i < len; i++){
			 elem = timedElements[i], show_t = elem.start, hide_t = elem.end, item = elem.item;
			 //console.log(ct, elem, show_t, hide_t);
			 if(ct >= parseInt(show_t,10) && ct <= parseInt(hide_t-1,10)){
				 item.css('display','block');
			 }else{
				 item.css('display','none');
			 }	
		 }
		 //subs
		 if(typeof curr_lang !== "undefined" && curr_lang.length){
			 var j = 0, len2 = curr_lang.length, elem2, show_t2, hide_t2, item2;
			 for(j; j < len2; j++){
				 elem2 = curr_lang[j], show_t2 = elem2.start, hide_t2 = elem2.end, item2 = elem2.item;
				// console.log(ct, elem2, show_t2, hide_t2);
				 if(ct >= parseInt(show_t2,10) && ct <= parseInt(hide_t2-1,10)){
					 item2.css('display','block');
				 }else{
					 item2.css('display','none');
				 }
			 }
		 }
		 lastTime=ct;
	}
	function videoEndHandler(){
		//console.log('videoEndHandler');
		if(typeof tvpVideoFinish !== 'undefined')tvpVideoFinish(_self, media_id);//callback
		
		if(sequence_counter+1<sequence_length){
			sequence_counter++;
			getVideoData();
		}else{
			//console.log(endAction);
			if(endAction == 'stop'){
			}else if(endAction == 'loop'){
				if(html5Support){
					if(mediaType == 'local'){
						try{
							videoUp2Js.currentTime=0;
						}catch(er){}
						if(videoUp2Js.paused)videoUp2Js.play();
					}else if(mediaType == 'youtube'){
						_youtubePlayer.play();
						toggleBigPlay('off');
					}
				}
			}else if(endAction == 'link'){
				if(!isEmpty(settings.endLink)){	
					ap_adv_skip.hide();	//optional
					if(settings.endTarget == '_blank')window.open(settings.endLink);
					else window.location = settings.endLink;
				}
			} 
		}
	}
	
	
	
	
	
	//*************** start info
	function checkInfo(){
		//console.log('checkInfo');
		if(currVideoData.description && !isEmpty(currVideoData.description)){
			var infoData = currVideoData.description;
			//console.log(infoData);
			infoInner.html('<p>'+infoData+'</p>');
			player_info.css('display','block');
		}
		if(timedElements.length && !eventsCreated){//eventsCreated - dont reacreate on quality change 
			var i, len = timedElements.length, _item;
			for(i = 0;i<len;i++){
				_item = timedElements[i].item.css('display','none').bind('mouseenter', function(e){
					$(this).addClass('ap_elem_hover').find('.ap_el_close').show();
				}).bind('mouseleave', function(e){
					$(this).removeClass('ap_elem_hover').find('.ap_el_close').hide();
				});
				_item.find('.ap_el_close').on('click', function(){
					closeRemovesEvents ? $(this).parent().remove() : $(this).parent().hide();
					return false;
				});
				if(settings.useControls){
					playerControls.before(_item);
				}else{
					if(playerHolder.children("div[class='ap_sub']").length>0){
					   playerHolder.children("div[class='ap_sub']").last().after(_item);//above subs	
					}else{
						big_play.after(_item);
					}
				}
			}
			mainWrapper.find('.apctooltip').tooltipster({
				onlyOne:true,
				updateAnimation:false,
				offsetY:3,//rollover menu in ie<10 (same as below)
				speed:0//pointer events none?
			});
			eventsCreated=true;
		}
		if(currVideoData.download != undefined){
			player_download.css('display','block');
		}
		resizeControls();
	}
	function openInfo(){
		if(mediaPlaying){
			_self.pauseMedia();
			videoForcePause=true;
		}
		if(shareOpened){
			shareHolder.css('display','none');
			shareOpened=false;	
		}
		if(componentSize=='normal')var w = componentWrapper.width(), h = componentWrapper.height();
		else var w = playerHolder.width(), h = playerHolder.height();
		//console.log(w,h);
		infoHolder.css({width:w+'px', height:h+'px', left:0+'px', top:-h+'px', display:'block'});
		resizeInfo();
		infoHolder.stop().animate({'top':0+'px'}, {duration: 300});
		infoOpened=true;
	}
	function closeInfo(){
		if(componentSize=='normal')var h = componentWrapper.height();
		else var h = playerHolder.height();
		infoHolder.stop().animate({'top':-h+'px'}, {duration: 200, complete: function(){
			infoHolder.css('display','none');
		}});
		infoOpened=false;
		if(videoForcePause){
			videoForcePause=false;
			_self.playMedia();
		}
	}
	function resizeInfo(){
		if(componentSize=='normal')var w = componentWrapper.width(), h = componentWrapper.height();
		else var w = playerHolder.width(), h = playerHolder.height();
		//console.log(w,h, playerHolder.width(), playerHolder.height());
		infoHolder.css({width:w+'px', height:h+'px'});
		infoInner.css({left:parseInt((w/2-infoInner.outerWidth(true)/2),10)+'px', top:parseInt((h/2-infoInner.outerHeight(true)/2),10)+'px'});
	}
	//*************** end info
	
	
	//*************** start share
	function openShare(){
		if(mediaPlaying){
			_self.pauseMedia();
			videoForcePause=true;
		}
		if(infoOpened){
			infoHolder.css('display','none');
			infoOpened=false;
		}
		if(componentSize=='normal')var w = componentWrapper.width(), h = componentWrapper.height();
		else var w = playerHolder.width(), h = playerHolder.height();
		//console.log(w,h);
		shareHolder.css({width:w+'px', height:h+'px', left:0+'px', top:-h+'px', display:'block'});
		resizeShare();
		shareHolder.stop().animate({'top':0+'px'}, {duration: 300});
		shareOpened=true;
	}
	function closeShare(){
		if(componentSize=='normal')var h = componentWrapper.height();
		else var h = playerHolder.height();
		shareHolder.stop().animate({'top':-h+'px'}, {duration: 200, complete: function(){
			shareHolder.css('display','none');
		}});
		shareOpened=false;
		if(videoForcePause){
			videoForcePause=false;
			_self.playMedia();
		}
	}
	function resizeShare(){
		if(componentSize=='normal')var w = componentWrapper.width(), h = componentWrapper.height();
		else var w = playerHolder.width(), h = playerHolder.height();
		shareHolder.css({width:w+'px', height:h+'px'});
		//console.log(w,h,ap_share_holder.outerWidth(true),ap_share_wrapper.outerWidth(true));
		
		if(settings.useEmbedCode && settings.useSharing){
			var l = parseInt((w/2-embedInner.outerWidth(true)/2),10) > 0 ? parseInt((w/2-embedInner.outerWidth(true)/2),10) : 0,
			t = parseInt((h/2-embedInner.outerHeight(true)-5),10) > 0 ? parseInt((h/2-embedInner.outerHeight(true)-5),10) : 0;
			embedInner.css({left:l+'px', top:t+'px'});
			ap_share_holder.css({left:parseInt((w/2-ap_share_holder.outerWidth(true)/2),10)+'px', top:parseInt((h/2+5),10)+'px'});
			ap_share_holder.css({left:parseInt((w/2-ap_share_holder.outerWidth(true)/2),10)+'px', top:parseInt((h/2+5),10)+'px'});
		}
		else if(settings.useEmbedCode){
			var l = parseInt((w/2-embedInner.outerWidth(true)/2),10) > 0 ? parseInt((w/2-embedInner.outerWidth(true)/2),10) : 0,
			t = parseInt((h/2-embedInner.outerHeight(true)/2),10) > 0 ? parseInt((h/2-embedInner.outerHeight(true)/2),10) : 0;
			embedInner.css({left:l+'px', top:t+'px'});
		}
		else if(settings.useSharing){
			ap_share_holder.css({left:parseInt((w/2-ap_share_holder.outerWidth(true)/2),10)+'px', top:parseInt((h/2-ap_share_holder.outerHeight(true)/2),10)+'px'});
			ap_share_holder.css({left:parseInt((w/2-ap_share_holder.outerWidth(true)/2),10)+'px', top:parseInt((h/2-ap_share_holder.outerHeight(true)/2),10)+'px'});
		}
	}
	//*************** end share



	//*************** start resize
	_window.resize(function() {
		 if(!_componentInited || _playlistTransitionOn) return false;
		 _doneResizing();
	});
	if(isMobile){
		_window.doubletap(function() { 
			setTimeout(function(){
				clearTimeout($(this));
				_doneResizing();
			 },500);
		 });	
	}
	function _doneResizing(){
		//console.log('_doneResizing');
		if(componentSize== "fullscreen"){
			if(!iosRealFs)resizeComponent();	
		}else{
			if(mediaType == 'local'){
				if(!videoInited){
					if(previewPoster)resizePreview(previewPoster);
				}else{
					if(html5Support)resizeVideo();
				}
			}else if(mediaType == 'youtube'){
				resizeVideo();
			}
		}
		if(settings.useControls)resizeControls();
		if(infoOpened)resizeInfo();
		if(settings.useSharing || settings.useEmbedCode)resizeShare();
	}
	function resizeComponent(){
		//console.log('resizeComponent');
		if(controlsTimeoutID) clearTimeout(controlsTimeoutID);
		_doc.unbind('mousemove',trackFsMouse);
		if(componentSize== "fullscreen"){
			_body.addClass('fsOverflow');
			playerHolder.removeClass('playerHolder').addClass('playerHolder_fs');
			if(isMobile){
				controlsTimeoutID = setTimeout(function() {clearTimeout(controlsTimeoutID);checkActivity();},controlsTimeout);
			}else{
				_doc.unbind('mousemove', trackFsMouse).bind('mousemove',trackFsMouse);
				controlsTimeoutID = setTimeout(function() {clearTimeout(controlsTimeoutID);trackFsMouse();},controlsTimeout);
			}
			setFullscreenIcon('off');
			if(typeof tvpFsEnter !== 'undefined')tvpFsEnter(_self, media_id);//callback
		}else{
			_body.removeClass('fsOverflow');//restore original overflow
			playerHolder.removeClass('playerHolder_fs').addClass('playerHolder');
			setFullscreenIcon('on');
			if(typeof tvpFsExit !== 'undefined')tvpFsExit(_self, media_id);//callback
		}
		if(previewPoster)resizePreview(previewPoster);
		if(html5Support)resizeVideo();
		if(infoOpened)resizeInfo();
		if(settings.useSharing || settings.useEmbedCode)resizeShare();
		if(settings.useControls){
			resizeControls();
			showControls();
		}
	}
	//chrome fix, 
	//http://stackoverflow.com/questions/17818493/mousemove-event-repeating-every-second
	//http://stackoverflow.com/questions/4579071/jquery-mousemove-is-called-even-if-the-mouse-is-still
	function trackFsMouse(e){
		if(!videoInited) return false;
		//console.log('trackFsMouse');
		if(controlsTimeoutID)clearTimeout(controlsTimeoutID);
		if(e){
			if (prevX != e.clientX) {
				//show controls
				//console.log('mouse moved');
				showControls2();
			}
			prevX = e.clientX;
		}
		controlsTimeoutID = setTimeout(function(){
			//hide controls
			//console.log('mouse still');
			hideControls();
		},controlsTimeout);
	}
	if(isMobile){
		_doc.bind("touchend.ap2",function(e){
			if(componentSize== "fullscreen"){
				if(controlsTimeoutID) clearTimeout(controlsTimeoutID);
				showControls2();
				controlsTimeoutID = setTimeout(function() {clearTimeout(controlsTimeoutID);checkActivity();},controlsTimeout);
			}
		});
	}
	function checkActivity(){
		if(controlsTimeoutID) clearTimeout(controlsTimeoutID);
		hideControls();
		controlsTimeoutID = setTimeout(function() {clearTimeout(controlsTimeoutID);checkActivity();},controlsTimeout);
	}
	function checkActivity2(){
		if(controlsTimeoutID) clearTimeout(controlsTimeoutID);
		hideControls();
	}
	function resizeControls(){
		//console.log('resizeControls');
		seekBarElementsSize = getSeekBarElementsSize();
		playerControlsSize = playerControls.width();
		seekBarSize = playerControlsSize - seekBarElementsSize - player_seekbar_offset;
		//console.log(playerControlsSize, seekBarSize, seekBarElementsSize, player_seekbar_offset);
		player_seekbar.width(seekBarSize + player_seekbar_offset);
		progress_bg.width(seekBarSize);
	}
	function getSeekBarElementsSize(){
		var a = player_mediaTime_current.css('display') == 'block' ? current_time_width : 0;
			b = player_mediaTime_total.css('display') == 'block' ? total_time_width : 0; 
			c = player_volume.css('display') == 'block' ? volume_width : 0; 
			d = player_fullscreen.css('display') == 'block' ? fullscreen_width : 0;
			e = player_ctrl_wrapper.css('display') == 'block' ? player_ctrl_wrapper_width : 0;
			if(fs_removed)d=0;
			//console.log(player_toggleControl.outerWidth(true),a,b,c,d,e);
		return player_toggleControl.outerWidth(true) + a + b + c + d + e;
	}
	function resizePreview(img) {
		if(!img) return false;
		//console.log('resizePreview ');
		var o, x, y, w = getComponentSize('w') != 0 ? getComponentSize('w') : getDocumentWidth(), h = getComponentSize('h') != 0 ? getComponentSize('h') : getDocumentHeight();
		
		if(aspectRatio == 0) {//normal media dimensions
			o=getMediaSize();
		}else if(aspectRatio == 1) {//fitscreen
			o = retrieveObjectRatio(true, img,previewOrigW,previewOrigH);
		}else if(aspectRatio == 2) {//fullscreen
			o = retrieveObjectRatio(false, img,previewOrigW,previewOrigH);
		}
		//console.log(o);
		x = parseInt(((w - o.width) / 2),10);
		y = parseInt(((h - o.height) / 2),10);
		
		img.css({
			width: o.width+ 'px',
			height: o.height+ 'px',
			left:x+'px',
			top:y+'px'
		});
	}
	function resizeVideo() {
		if(_counter==-1) return false;
		//console.log('resizeVideo');
		var o, x, y, w = getComponentSize('w') != 0 ? getComponentSize('w') : getDocumentWidth(), h = getComponentSize('h') != 0 ? getComponentSize('h') : getDocumentHeight();
		
		if(aspectRatio == 0) {//normal media dimensions
			o=getMediaSize();
		}else if(aspectRatio == 1) {//fitscreen
			o = retrieveObjectRatio(true);
		}else if(aspectRatio == 2) {//fullscreen
			o = retrieveObjectRatio(false);
		}
		x = parseInt(((w - o.width) / 2),10);
		y = parseInt(((h - o.height) / 2),10);
		
		if(mediaType == 'local'){
			if(video){
				video.css({
					width: o.width+ 'px',
					height: o.height+ 'px',
					left:x+'px',
					top:y+'px'
				});
			}
		}else if(mediaType == 'youtube'){
			if(youtubeIframeMain){
				youtubeIframeMain.css({
					width: o.width+ 'px',
					height: o.height+ 'px',
					left:x+'px',
					top:y+'px'
				});
			}
		}
	}
	function retrieveObjectRatio( _fitScreen, obj, cw,ch) {
		//console.log('retrieveObjectRatio', _fitScreen, obj, cw,ch); 
		var _paddingX=0,_paddingY=0;
	 
		var w = getComponentSize('w') != 0 ? getComponentSize('w') : getDocumentWidth(), h = getComponentSize('h') != 0 ? getComponentSize('h') : getDocumentHeight(), targetWidth, targetHeight, val={};
		//console.log(w,h);
		
	 	if(!obj){
			var obj = getMediaSize();
			targetWidth = obj.width;
			targetHeight = obj.height;
		}else{
			if(typeof(cw) !== "undefined" && typeof(ch) !== "undefined"){
				targetWidth = cw;
				targetHeight = ch;
			}else{
				targetWidth = obj.width();
				targetHeight = obj.height();
			}
		}
		var destinationRatio = (w - _paddingX) / (h - _paddingY), targetRatio = targetWidth / targetHeight;
		//console.log(targetRatio, destinationRatio);
		//console.log(targetWidth,', ',targetHeight);

		if (targetRatio < destinationRatio) {
			if (!_fitScreen) {//fullscreen
				val.height = ((w - _paddingX) /targetWidth) * targetHeight;
				val.width = (w - _paddingX);
			} else {//fitscreen
				val.width = ((h - _paddingY) / targetHeight) *targetWidth;
				val.height = (h - _paddingY);
			}
		} else if (targetRatio > destinationRatio) {
			if (_fitScreen) {//fitscreen
				val.height = ((w - _paddingX) /targetWidth) * targetHeight;
				val.width = (w - _paddingX);
			} else {//fullscreen
				val.width = ((h - _paddingY) / targetHeight) *targetWidth;
				val.height = (h - _paddingY);
			}
		} else {//fitscreen & fullscreen
			val.width = (w - _paddingX);
			val.height = (h - _paddingY);
		}
		return val;
	}
	function getMediaSize() {
		//console.log('getMediaSize');
		var o={}, default_w=640, default_h=360;
		//console.log(videoUp2Js.videoWidth, mediaWidth, videoUp2Js.videoHeight, mediaHeight);
		if(mediaType=='local'){
			if(!mediaWidth || isNaN(mediaWidth) || !mediaHeight || isNaN(mediaHeight)){
				if(videoUp2Js){
					o.width = videoUp2Js.videoWidth;
					o.height = videoUp2Js.videoHeight;
				}else{
					o.width = default_w;//default values (16:9)
					o.height = default_h;
				}
			}else{
				o.width=mediaWidth;
				o.height=mediaHeight;	
			}
		}else if(mediaType == 'youtube'){
			if(!mediaWidth || isNaN(mediaWidth) || !mediaHeight || isNaN(mediaHeight)){
				o.width = default_w;//default youtube values (16:9)
				o.height = default_h;
			}else{
				o.width=mediaWidth;
				o.height=mediaHeight;	
			}
		}
		return o;
	}
	function getComponentSize(type) {
		if(type == "w"){//width
			return componentSize == "normal" ? componentWrapper.width() : getDocumentWidth();
		}else{//height
			return componentSize == "normal" ? componentWrapper.height() : getDocumentHeight();
		}
	}
	function getDocumentWidth(){
		return Math.max(
			_window.width(),
			/* For opera: */
			document.documentElement.clientWidth
		);
	};	
	function getDocumentHeight(){
		return Math.max(
			_window.height(),
			/* For opera: */
			document.documentElement.clientHeight
		);
	};
	//*************** end resize
	
	
	//*************** start flash
	this.flashVideoPause = function(){
		pauseHandler();
	}
	this.flashVideoResume = function(){
		playHandler();
	}
	this.flashVideoEnd = function(){
		videoEndHandler();	
	}
	this.flashVideoStart = function(){
		videoInited=true;
		playHandler();
		showControls();
		if(!quality_change)checkInfo();
	}
	this.dataUpdateFlash = function(bl,bt,t,d){
		load_level.width((bl/bt) * seekBarSize);	
		progress_level.width((t/d) * seekBarSize);
		player_mediaTime_current.html(formatCurrentTime(t));
		player_mediaTime_total.html(formatDuration(d));
		
		if(timedElements && timedElements.length || typeof curr_lang !== "undefined" && curr_lang.length){
			if(t != lastTime)trackTimedElements(parseInt(t,10));	
		}
		if(showSkipButtonInVideo && skipEnableTime != null && !skipTimeHappened){
			if(parseInt(t,10) < skipEnableTime){
				ap_adv_msg.find('p').html(skipBtnText+' '+(skipEnableTime-parseInt(t,10)).toString());	
			}else{
				skipTimeHappened = true;	
				ap_adv_img.hide();
				ap_adv_msg.hide();
				ap_adv_msg_end.show();
				disableSeekbarInVideo=false;
			}
		}
	}
	function checkFlashReady(){
		//console.log('checkFlashReady');
		if(getFlashMovie(flashMain).setData != undefined){
			if(flashReadyIntervalID) clearInterval(flashReadyIntervalID);
			getFlashMovie(flashMain).setData(settings);//pass data to flash
			if(settings.video && settings.video.length>0)_setPlaylist(settings.video);
			else _endInit();
		}
	}
	function getFlashMovie(name) {
		if(name.charAt(0)=='#')name = name.substr(1);//remove'#'
		if(isSafari)return window[name];
		else return (navigator.appName.indexOf("Microsoft") != -1) ? window[name] : document[name];
	}	
	function embedFlash(){
		
		mediaHolder.remove();
		
		hap_players.push(_self);
		var id = hap_players.length-1;
		
		var f_id = 'flashMain' + id;
		flashMain = '#'+f_id;
		settings.flash_id = id;
		
		var flash_path = 'fallback.swf', 
		flash = $('<object id="'+f_id+'" type="application/x-shockwave-flash" data="' + flash_path + '" width="100%" height="100%">' + 
					'<param name="movie" value="' + flash_path + '" />' + 
					'<param name="allowScriptAccess" value="always" />' + 
					'<param name="bgcolor" value="#000000" />' + 
					'<param name="allowfullscreen" value="true" />' +  
					'<param name="wmode" value="transparent" />' + 
					'<a href="http://get.adobe.com/flashplayer/" target="_blank"><img src="http://www.adobe.com/images/shared/download_buttons/get_flash_player.gif" /></a>' +
				'</object>');
		
		$('<div/>').addClass('flashMain').append(flash).prependTo(playerHolder);
		
		var interval = setInterval(function(){
			//console.log(typeof getFlashMovie(flashMain));
			if(flashMain && typeof getFlashMovie(flashMain) !== "undefined"){
				clearInterval(interval);
				flashReadyIntervalID = setInterval(checkFlashReady, flashReadyInterval);	
			}
		},50);
	}
	//*************** end flash
	
	
	
	//*************** start helper
	function checkKey() {
		this.value = this.value.replace(/[^0-9]/g, "");
	}
	function isNumber(n) {
	   return !isNaN(parseFloat(n)) && isFinite(n);
	}
	function isEmpty(str) {
	    return str.replace(/^\s+|\s+$/g, '').length == 0;
	}
	function resetData(){
	  player_mediaTime_current.find('p').html('00:00');
	  player_mediaTime_total.find('p').html('00:00');
	  progress_level.width(0);
	  load_level.width(0);
	}	
	function keysrt(arr, type, desc){
		if(type == 'path'){
			arr.sort(function(a, b) { 
				return a.path == b.path ? 0 : a.path < b.path ? -1 : 1 
			});	
		}
		if(desc)arr.reverse();
	}	
	function canPlayVorbis() {
		var v = document.createElement('video');
		return !!(v.canPlayType && v.canPlayType('video/ogg; codecs="theora, vorbis"').replace(/no/, ''));
	}
	function canPlayMP4() {
		var v = document.createElement('video');
		return !!(v.canPlayType && v.canPlayType('video/mp4; codecs="avc1.42E01E, mp4a.40.2"').replace(/no/, ''));
	}
	function canPlayWebM() {
		var v = document.createElement('video');
		return !!(v.canPlayType && v.canPlayType('video/webm; codecs="vp8, vorbis"').replace(/no/, ''));
	}
	function formatCurrentTime(seconds) {
		seconds = Math.round(seconds);
		minutes = Math.floor(seconds / 60);
		minutes = (minutes >= 10) ? minutes : "0" + minutes;
		seconds = Math.floor(seconds % 60);
		seconds = (seconds >= 10) ? seconds : "0" + seconds;
		return minutes + ":" + seconds;
	}
	function formatDuration(seconds) {
		seconds = Math.round(seconds);
		minutes = Math.floor(seconds / 60);
		minutes = (minutes >= 10) ? minutes : "0" + minutes;
		seconds = Math.floor(seconds % 60);
		seconds = (seconds >= 10) ? seconds : "0" + seconds;
		return minutes + ":" + seconds;
	}
	function qualifyURL(url) {
		var a = document.createElement('a');
		a.href = url;
		return a.href;
	}
	function selectText(element) {
		var doc = document, text = doc.getElementById(element), range, selection;    
		if (doc.body.createTextRange) { //ms
			range = doc.body.createTextRange();
			range.moveToElementText(text);
			range.select();
		} else if (window.getSelection) { //all others
			selection = window.getSelection();        
			range = doc.createRange();
			range.selectNodeContents(text);
			selection.removeAllRanges();
			selection.addRange(range);
		}
	}
	
	function getObjLen(obj){
		var len=0;
		$.each(obj, function(i, elem) {
			len++;
		});
		return len;	
	}
	//*************** end helper
	
	
	// ******************************** PUBLIC API **************** //
	/* play active media */
	this.playMedia = function() {
		if(!_componentInited || _playlistTransitionOn || !mediaType) return false;
		if(mediaPlaying) return false;
		if(mediaType == 'local'){
			togglePlayBack();
		}else if(mediaType == 'youtube'){
			if(_youtubePlayer) _youtubePlayer.play();
		}
		mediaPlaying=true;
	}
	/* pause active media */
	this.pauseMedia = function() {	
		if(!_componentInited || _playlistTransitionOn || !mediaType)  return false;
		if(!mediaPlaying) return false;
		if(mediaType == 'local'){
			togglePlayBack();
		}else if(mediaType == 'youtube'){
			if(_youtubePlayer) _youtubePlayer.pause();
		}
		mediaPlaying=false;
	}	
	/* used in multiple instances to toggle one instance if another has started */ 
	this.checkMedia = function(act) {	
		if(!_componentInited || _playlistTransitionOn || !mediaType) return false;
		var action = act.toLowerCase();
		if(mediaPlaying){
			if(action=='pause'){
				if(mediaType == 'local'){
					togglePlayBack();
				}else if(mediaType == 'youtube'){
					if(_youtubePlayer) _youtubePlayer.pause();
				}
				mediaPlaying=false;
			}
		}
	}
	this.nextMedia = function(){
		if(!_componentInited) return;
		if(!isMobile)setAutoplay(true);
		videoEndHandler();
	}
	this.previousMedia = function(){
		if(!_componentInited) return;
		if(sequence_counter>0){
			cleanMedia();
			sequence_counter--;
			getVideoData();
		}
	}	
	/* toggle active media playback */
	this.togglePlayBack = function(){
		if(!_componentInited || _playlistTransitionOn) return false;
		if(!mediaType) return false;
		togglePlayBack();
	}
	/* set autoplay */
	this.setAutoPlay = function(val){
		if(!_componentInited) return false;
		setAutoplay(val);
	}
	/* get autoplay */
	this.getAutoPlay = function(){
		if(!_componentInited) return false;
		return autoPlay;
	}
	/* get volume (0-1) */
	this.getVolume = function(){
		if(!_componentInited || _playlistTransitionOn) return false;
		return defaultVolume;	
	}
	/* set volume (0-1) */
	this.setVolume = function(val){
		if(!_componentInited || _playlistTransitionOn) return false;
		if(!videoInited) return false;
		if(val<0) val=0;
		else if(val>1) val=1;
		defaultVolume = val;
		setVolume();
	}
	/* seek media (in seconds) */
	this.seek = function(val){
		if(!_componentInited || _playlistTransitionOn) return false;
		setProgress2(val);	
	}
	/* get title for active media */
	this.getTitle = function(value) {	
		if(!_componentInited || _playlistTransitionOn) return false;
		if(!currVideoData) return false;
		return currVideoData.title;
	}
	/* get description for active media */
	this.getDescription = function(value) {	
		if(!_componentInited || _playlistTransitionOn) return false;
		if(!currVideoData) return false;
		return currVideoData.description;
	}
	/* toggle description */
	this.toggleDescription = function() {	
		if(!_componentInited || _playlistTransitionOn) return false;
		if(!currVideoData) return false;
		if(currVideoData.description && !isEmpty(currVideoData.description)){
			if(!infoOpened)openInfo();
			else closeInfo();	
		}
	}
	/* toggle share */
	this.toggleShare = function() {	
		if(!_componentInited || _playlistTransitionOn) return false;
		if(!settings.useSharing && !settings.useEmbedCode) return false;
		if(!shareOpened)openShare();
		else closeShare();	
	}
	this.getSequenceCounter = function(data) {	
		if(!_componentInited || _playlistTransitionOn) return false;
		return sequence_counter;
	}
	this.cleanMedia = function() {	
		cleanMedia();
	}
	/* add track */
	this.addTrack = function(data) {	
		if(!_componentInited || _playlistTransitionOn) return false;
		cleanMedia();
		_setPlaylist(data);
	}
	/* return media id (player instance reference) */
	this.getMediaId = function(){
		if(!_componentInited) return false;
		return media_id;
	}
	/* return media playing or paused */
	this.getMediaPlaying = function(){
		if(!_componentInited || _playlistTransitionOn) return false;
		return mediaPlaying;
	}
	/* return playlist loading (is playlist loading) */
	this.getPlaylistTransition = function(){
		return _playlistTransitionOn;
	}
	/* return playlist loaded (finished loading) */
	this.getPlaylistLoaded = function(){
		return _playlistLoaded;
	}
	/* return media initiated (active video ready) */
	this.getVideoInited = function(){
		if(!_componentInited || _playlistTransitionOn) return false;
		return videoInited;
	}
	/* return component setup is finished */
	this.getSetupDone = function(){
		return _componentInited;
	}
	/* return playlist data */
	this.getPlaylistData = function(){
		if(!_componentInited || _playlistTransitionOn) return false;
		if(!lastPlaylist) return false;
		return playlistDataArr;	
	}
	/* return player settings */
	this.getSettings = function(){
		if(!_componentInited || _playlistTransitionOn) return false;
		return settings ? settings : null;
	}
	/* clean youtube player, so we can reinit it again (neccesarry in some instances where player (sometimes) looses events (if component set to display none or similar) */
	this.cleanYt = function(){
		if(!_componentInited || _playlistTransitionOn) return false;
		if(_youtubePlayer){
			$(_youtubePlayer).unbind();
			_youtubePlayer.clean();
			_youtubePlayer = null;	
		}
		_youtubeInited = false;
	}
	/* skip intro */
	this.skipIntro = function(){
		if(!_componentInited || _playlistTransitionOn) return false;
		if(skipEnableTime && !skipTimeHappened)return false;
		if(!isMobile)setAutoplay(true);
		videoEndHandler();
		return false;
	}
		
	if(html5Support){
		if(settings.video && settings.video.length>0)_setPlaylist(settings.video);
		else _endInit();
	}else{
		embedFlash();
	}

	return this;

	}
	
})(jQuery);



/* double tap  */
(function(a){var d=/android|iphone|ipad/i.test(navigator.userAgent.toLowerCase())?"touchend":"click";a.fn.doubletap=function(e,b){b=null==b?300:b;this.bind(d,function(d){var f=(new Date).getTime(),c=a(this).data("lastTouch")||f+1,c=f-c;c<b&&0<c?(a(this).data("lastTouch",null),null!==e&&"function"===typeof e&&e(d)):a(this).data("lastTouch",f)})}})(jQuery);








	
(function($) {

	 $.youtubePlayer = function(data) {
		return new ap_YoutubePlayer(data);
	 };
	 
	 function ap_YoutubePlayer(data){
		
		 var _self = this;
		 if(typeof $.videoGallery !== "undefined"){
			 if(typeof $.videoGallery.getSingleVideo !== "undefined"){
				 if(typeof $.videoGallery.getLooping !== "undefined" && $.videoGallery.getLooping() && typeof $.videoGallery.getAutoplay !== "undefined" && $.videoGallery.getAutoplay()){
					 //only if autoplay and loop is on construct raw iframe for seamless single yt video loop
					 this.singleVideo=$.videoGallery.getSingleVideo();
				 }
			 }
		 }
		 //console.log(this.singleVideo);
		 
		 this.isIE = data.isIE ? data.isIE : false;
		 this.isMobile = data.isMobile;
		 this.initialAutoplay = data.initialAutoplay;
		 this._initialAutoplaySet=false;//must be set after first play, not just load
		 this._inited = false;
		 this._player;
		 this._autoPlay = data.autoPlay;
		 this._defaultVolume = data.defaultVolume;
		 this._youtubeHolder = data.youtubeHolder;
		 this._frameId='ytplayer'+Math.floor(Math.random()*0xFFFFFF);
		 if(data.quality) this.quality=data.quality;
		 if(data.small_embed) this.small_embed=data.small_embed;
		 //load/cue methods called before player ready
		 this.lastID;
		 this.playerReadyInterval=100;
		 this.playerReadyIntervalID;
		 this.playerReady=false;
		 
		 var _youtubeChromeless = data.youtubeChromeless;
		 var zindexfix='&amp;wmode=transparent';
		 var youtubeApi='&amp;enablejsapi=1';
		 var no_controls='?controls=0';
		 var no_info='&amp;showinfo=0';
		 var theme='&amp;theme=dark';
		 var no_relVid = '&amp;rel=0';
		 var autoplay_on='&amp;autoplay=1';
		 var loop_on = '&amp;loop=1';
		 var videoIFrameSrc;
		 this.forceMainStop = false;
		 this.forcePreviewStop = false;
		 this.yt_preview_inited;
		 
		 this.isFirefox = testCSS('MozBoxSizing'); 
		 function testCSS(prop) {
			return prop in document.documentElement.style;
		 }
		 //console.log(this.isFirefox);
		 
		 if(!_youtubeChromeless){
			 no_relVid = '?rel=0';
			 videoIFrameSrc = 'http://www.youtube.com/embed/' + data.mediaPath + no_relVid + youtubeApi + theme + zindexfix;
		 }else{
			 if(this.small_embed){
				 if(!data.isIE){
					videoIFrameSrc = 'http://www.youtube.com/embed/' + data.mediaPath + no_controls + no_info + youtubeApi + zindexfix;	
				 }else{
					//remove zindex fix for small preview because it was braking the player in ie9 below minimum youtube allowed size! 	
				 	videoIFrameSrc = 'http://www.youtube.com/embed/' + data.mediaPath + no_controls + no_info + youtubeApi + zindexfix;	
				 }
			 }else{
				videoIFrameSrc = 'http://www.youtube.com/embed/' + data.mediaPath + no_controls + no_info + no_relVid + youtubeApi + theme + zindexfix;	
				//make raw autoplay and loop in this case
				if(this.singleVideo && !this.isIE)videoIFrameSrc = 'http://www.youtube.com/embed/' + data.mediaPath + no_controls + no_info + autoplay_on + loop_on + no_relVid + youtubeApi + theme + zindexfix;	
			 }
		 }
		 //console.log(videoIFrameSrc);
		  
		 this.youtubeVideoIframe = $('<iframe />', {
				frameborder: 0,
				src: videoIFrameSrc,
				width: 100 + '%',
				height: 100 + '%',
				id: this._frameId,
				webkitAllowFullScreen: true,
				mozallowfullscreen: true,
				allowFullScreen: true
		 });
		 //console.log(youtubeVideoIframe);
			
		 this._youtubeHolder.css('display', 'block').append(this.youtubeVideoIframe); 
		 if(this.small_embed){
			if(!this.yt_preview_inited){
				this._youtubeHolder.css('left', -this._youtubeHolder.width()+5+'px');//safari fix!
				this.yt_preview_inited=true;
			}
		} 
		 
		var tag = document.createElement('script');
		tag.src = "http://www.youtube.com/iframe_api";
		var firstScriptTag = document.getElementsByTagName('script')[0];
		firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
	 
		var interval = setInterval(function(){
			 if(window.YT && window.YT.Player){
				 if(interval) clearInterval(interval);
				 //console.log(window.YT, window.YT.Player);
				 _self._player = new YT.Player(_self._frameId, {
					events: {
						  'onReady': onPlayerReady,
						  'onPlaybackQualityChange': onPlayerPlaybackQualityChange,
						  'onStateChange': onPlayerStateChange,
						  'onError': onPlayerError
					}
				 });
				 
			 }
		 }, 100);
		 
		 window.onYouTubeIframeAPIReady = function() {
			//console.log('onYouTubeIframeAPIReady');
		 }
		 
		 function onPlayerReady(event) {
			//console.log('onPlayerReady');
			//console.log(_self._player);
			_self.playerReady=true;
			$(_self).trigger('ap_YoutubePlayer.YT_READY');
			if(typeof _self._player.setVolume !== "undefined"){
				_self._player.setVolume(_self._defaultVolume * 100);//Sets the volume. Accepts an integer between 0 and 100.
			}
			if(_self._autoPlay){
				_self._player.playVideo();
			}
		 }
		
		 function onPlayerPlaybackQualityChange(event) {
			//console.log('onPlayerPlaybackQualityChange: ', event.data);
			$(_self).trigger('ap_YoutubePlayer.QUALITY_CHANGE', [event.data]);
		 }
		
		 function onPlayerStateChange(event) {
			//console.log('onPlayerStateChange ', event.data);

			if(_self.forceMainStop){
				//console.log('_self.forceMainStop = ', _self.forceMainStop);
				_self.forceMainStop=false;
				if(typeof _self._player.stopVideo !== "undefined"){
					_self._player.stopVideo();
					$(_self).trigger('ap_YoutubePlayer.FORCE_MAIN_STOP');
					return;
				}
			}
		
			if(event.data == -1){//unstarted
			/*	if(typeof $.videoGallery !== "undefined" && typeof $.videoGallery.getVolume !== "undefined" && _self.isFirefox && typeof _self._player.setVolume !== "undefined")_self._player.setVolume($.videoGallery.getVolume() * 100);//firefox fix!*/
			}
			else if(event.data == 0){//ended
				//console.log('yt ended');
				if(!_self.isIE){
					if(!_self.singleVideo)$(_self).trigger('ap_YoutubePlayer.END_PLAY');
				}else{
					$(_self).trigger('ap_YoutubePlayer.END_PLAY');
				}
			}
			else if(event.data == 1){//playing
			
				if(!_self._initialAutoplaySet){//after first play (may not be on the first video!)
					//console.log('setting initialAutoplay');
					//if(_self.isMobile && _self.initialAutoplay) 
					_self._autoPlay=true;//FORCE AUTOPLAY FROM SECOND VIDEO	
					_self._initialAutoplaySet=true;
				}
			
				if(_self.small_embed && typeof _self._player.setVolume !== "undefined")_self._player.setVolume(0);//firefox fix in small preview!

				if(_self.forcePreviewStop){
					if(typeof _self._player.stopVideo !== "undefined")_self._player.stopVideo();
				}
				
				if(!_self._inited){
					$(_self).trigger('ap_YoutubePlayer.START_PLAY');
					_self._inited=true;	
					if(!_self.small_embed && _self.quality && _self.quality == true && typeof _self._player.getAvailableQualityLevels !== "undefined"){
						//console.log(_self._player.getAvailableQualityLevels());
						//console.log(_self._player.getPlaybackQuality());
						if(_self._player.getAvailableQualityLevels()[0])_self._player.setPlaybackQuality(_self._player.getAvailableQualityLevels()[0]);//set highest available
					}
					if(_self.small_embed){
						//console.log(_self._player.getAvailableQualityLevels());
						_self._player.setPlaybackQuality(_self._player.getAvailableQualityLevels()[_self._player.getAvailableQualityLevels().length-1]);//set lowest available
					}
				}
				
				$(_self).trigger('ap_YoutubePlayer.STATE_PLAYING');
			}
			else if(event.data == 2){//paused
				$(_self).trigger('ap_YoutubePlayer.STATE_PAUSED');
			}
			else if(event.data == 5){//paused
				$(_self).trigger('ap_YoutubePlayer.STATE_CUED');
			}
			
			/*
			
			YT.PlayerState.ENDED 0
			YT.PlayerState.PLAYING 1
			YT.PlayerState.PAUSED 2
			YT.PlayerState.BUFFERING 3
			YT.PlayerState.CUED 5
			
			-1 (unstarted)
			0 (ended)
			1 (playing)
			2 (paused)
			3 (buffering)
			5 (video cued).
			*/
		 }
		
		 function onPlayerError(e) {
			//console.log(e);
			
			/*
			event.data
			 2 – The request contains an invalid parameter value. For example, this error occurs if you specify a video ID that does not have 11 characters, or if the video ID contains invalid characters, such as exclamation points or asterisks.
			 5 – The requested content cannot be played in an HTML5 player or another error related to the HTML5 player has occurred.
			100 – The video requested was not found. This error occurs when a video has been removed (for any reason) or has been marked as private.
			101 – The owner of the requested video does not allow it to be played in embedded players.
			150 – This error is the same as 101. It's just a 101 error in disguise!
			*/
			
			switch(e.data){
				case 2:
				//console.log("Error code = "+e.data+": The request contains an invalid parameter value. For example, this error occurs if you specify a video ID that does not have 11 characters, or if the video ID contains invalid characters, such as exclamation points or asterisks.")
				break;
				case 100:
				//console.log("Error code = "+e.data+": Video not found, removed, or marked as private")
				break;
				case 101:
				//console.log("Error code = "+e.data+": Embedding disabled for this video")
				break;
				case 150:
				//console.log("Error code = "+e.data+": Video not found, removed, or marked as private [same as error 100]")
				break;
			}
			
			$(_self).trigger('ap_YoutubePlayer.ERROR_HANDLER', [e.data]);
			
		 }
		 
	 };
	 ap_YoutubePlayer.prototype = {
		clean:function() {
			if(this._player){
				if(typeof this._player.stopVideo !== "undefined") this._player.stopVideo();
				this._player=null;
			}
			if(this.youtubeVideoIframe){
				this.youtubeVideoIframe.attr('src','');
				this.youtubeVideoIframe.remove();//SCRIPT5009: '__flash__removeCallback' is undefined 
				this.youtubeVideoIframe=null;
			}
		},
		stopPreview:function() {
			this.forcePreviewStop=true;
		},
		initVideo:function(id) {
			this.forceMainStop=false;//reset 
			if(this.playerReady){
				if(this._player){
					this.forcePreviewStop=false;//reset
					this._inited=false;
					//console.log(this._autoPlay);
					if(this._autoPlay){
						if(typeof this._player.loadVideoById !== "undefined")this._player.loadVideoById(id);
					}else{
						if(typeof this._player.cueVideoById !== "undefined")this._player.cueVideoById(id);
					}
				}
			}else{
				var _self=this;
				this.lastID = id;//remember last id
				if(this.playerReadyIntervalID)return;//if already started
				this.playerReadyIntervalID = setInterval(function(){
					if(_self.playerReady){
						if(_self.playerReadyIntervalID) clearInterval(_self.playerReadyIntervalID);
						if(!_self.forceMainStop)_self.initVideo(_self.lastID);
					}
				}, this.playerReadyInterval);
			}
		},
		stop:function() {
			this.forceMainStop=true;
			if(this._player && typeof this._player.stopVideo !== "undefined") this._player.stopVideo();
		},
		play:function() {
			if(this._player && typeof this._player.playVideo !== "undefined") this._player.playVideo();
		},
		pause:function() {
			if(this._player && typeof this._player.pauseVideo !== "undefined") this._player.pauseVideo();
		},
		togglePlayback:function(state) {
			if(this._player) {
				if(state == undefined){
					if(typeof this._player.getPlayerState === "undefined") return false;
					var player_state = this._player.getPlayerState();
					//console.log('player_state = ', player_state);
					if(player_state == 1){//playing
						if(typeof this._player.pauseVideo !== "undefined")this._player.pauseVideo();
					}else if(player_state == 2){//paused
						if(typeof this._player.playVideo !== "undefined")this._player.playVideo();
					}else if(player_state == -1 || player_state == 5 || player_state == 0){//unstarted, cued, ended
						if(typeof this._player.playVideo !== "undefined")this._player.playVideo();
					}
				}else{
					if(state){//start
						if(typeof this._player.playVideo !== "undefined")this._player.playVideo();
					}else{//stop
						if(typeof this._player.pauseVideo !== "undefined")this._player.pauseVideo();
					}
				}
			}
		},
		seek:function(val) {
			if(this._player && typeof this._player.seekTo !== "undefined") this._player.seekTo(val);
		},
		isMuted:function() {
			if(this._player && typeof this._player.isMuted !== "undefined") return this._player.isMuted();
		},
		getDuration:function() {
			if(this._player && typeof this._player.getDuration !== "undefined") return this._player.getDuration();
		},
		getCurrentTime:function() {
			if(this._player && typeof this._player.getCurrentTime !== "undefined") return this._player.getCurrentTime();
		},
		getVideoLoadedFraction:function() {
			if(this._player && typeof this._player.getVideoLoadedFraction !== "undefined") return this._player.getVideoLoadedFraction();
		},
		getVideoBytesLoaded:function() {
			if(this._player && typeof this._player.getVideoBytesLoaded !== "undefined") return this._player.getVideoBytesLoaded();
		},
		getVideoBytesTotal:function() {
			if(this._player && typeof this._player.getVideoBytesTotal !== "undefined") return this._player.getVideoBytesTotal();
		},
		setVolume:function(val) {
			//Sets the volume. Accepts an integer between 0 and 100.
			if(val<0) vol=0;
			else if(val > 1) val = 1;
			if(this._player && typeof this._player.setVolume !== "undefined") this._player.setVolume(val * 100);
		},
		getPlayerState:function() {
			if(this._player && typeof this._player.getPlayerState !== "undefined") return this._player.getPlayerState();
		},
		setAutoPlay:function(val) {
			this._autoPlay = val;
		},
		getQualityLevels:function() {
			return this._player.getAvailableQualityLevels();
		},
		getCurrQuality:function() {
			return this._player.getPlaybackQuality();
		},
		setPlaybackQuality:function(val) {
			//http://developers.google.com/youtube/js_api_reference#Playback_quality
			this._player.setPlaybackQuality(val);
		}
	}

})(jQuery);



	
	






//******** flash callabcks
function isReady() {return document.readyState === "complete"}
function flashVideoEnd(data){
	if(hap_players && hap_players[data.id])hap_players[data.id].flashVideoEnd();
}
function flashVideoStart(data){
	if(hap_players && hap_players[data.id])hap_players[data.id].flashVideoStart();
}
function flashVideoPause(data){
	if(hap_players && hap_players[data.id])hap_players[data.id].flashVideoPause();
}
function flashVideoResume(data){
	if(hap_players && hap_players[data.id])hap_players[data.id].flashVideoResume();
}
function dataUpdateFlash(data){
	if(hap_players && hap_players[data.id])hap_players[data.id].dataUpdateFlash(data.bl,data.bt,data.t,data.d);
}







/* TRACKS FOR API */
var tvp_tracks_list = [
	[{
		type:'local',
		path:{
			High: '../media/video/2/02.mp4', 
			Default: '../media/video/2/02.mp4', /* default required! */
			Low: '../media/video/2/02.mp4' 
		},
		previewImage:'../media/video/2/02.jpg',
		
		/* optional below */
		showControls:true,/* show controls while video plays */
		disableSeekbar:true,/* disable seekbar in controls */
		showSkipBtn:true,/* show skip button */
		skipBtnText:'You can skip to video in',/* skip button message. */
		skipEnableTime:5,/* time until skip button is enabled, in seconds */
		link:'http://codecanyon.net/user/Tean/portfolio',/* click on video url link. Leave empty for none. */
		target:'_blank',/* _blank/_parent (opens in new/same window)  */
		
		title:'Pre advert video title',
		description:'<span class="infoTitle">This is a pre advert video description</span><br>Duis egestas, quam faucibus interdum tincidunt, enim sem tincidunt tellus, sed condimentum tellus <a href="http://codecanyon.net/user/Tean" target="_blank">varius</a> ut mi.',
		downloadPath:'../media/video/2/01.mp4',
		captions:'data/captions/captions_adv.xml'/* subtitles */
		
	},
	{
		type:'youtube',
		path:'F08U2yCxbYg',
		
		/* optional below */
		showControls:true,/* show controls while video plays */
		disableSeekbar:false,/* disable seekbar in controls */
		showSkipBtn:false,/* show skip button */
		skipBtnText:'You can skip to video in',/* skip button message. */
		skipEnableTime:0,/* time until skip button is enabled, in seconds */
		link:'',/* click on video url link. Leave empty for none. */
		target:'_blank',/* _blank/_parent (opens in new/same window)  */
		
		title:'Custom youtube video title',
		description:'<span class="infoTitle">Nulla mauris justo</span><br/>Custom youtube video description, blandit ut, metus. Maecenas magna dui, laoreet ac, malesuada quis, blandit vitae, leo. Maecenas porttitor <a href="http://codecanyon.net/user/Tean" target="_blank">varius</a> odio. Nunc auctor gravida odio. Sed ac ante viverra dolor suscipit gravida.',
		previewImage:'../media/video/2/01.jpg',
		downloadPath:'../media/video/2/01.mp4',
		captions:'data/captions/captions.xml',/* subtitles */
		events: 'data/events/events.xml'/* timed events over video */
	},
	{
		type:'local',
		path:{
			Default: '../media/video/2/02.mp4' /* default required! */
		},
		previewImage:'../media/video/2/02.jpg',
		
		/* optional below */
		showControls:false,/* show controls while video plays */
		disableSeekbar:false,/* disable seekbar in controls */
		showSkipBtn:false,/* show skip button */
		skipBtnText:'You can skip advertisement in',/* skip button message. */
		skipEnableTime:10,/* time until skip button is enabled, in seconds */
		link:'http://www.google.com',/* click on video url link. Leave empty for none. */
		target:'_blank',/* _blank/_parent (opens in new/same window)  */
		
		title:'After advert video title',
		description:'<span class="infoTitle">This is a after advert video description</span><br>Duis egestas, quam faucibus interdum tincidunt, enim sem tincidunt tellus, sed condimentum tellus <a href="http://codecanyon.net/user/Tean" target="_blank">varius</a> ut mi.',
		downloadPath:'../media/video/2/02.mp4',
		captions:'data/captions/captions_adv.xml',/* subtitles */
		events: 'data/events/events_after.xml'/*timed events over video */
	}]
];













/* CALLBACKS */
function tvpSetupDone(instance, media_id){
	/* called when component is ready to use public API. Returns player instance, media_id. */
	//console.log('tvpSetupDone: ', media_id);
	
	if(media_id == 'popup2'){
		if (hasLocalStorage) {
			if(localStorage.getItem('tvp_single_track')){
				var track = JSON.parse(localStorage.getItem('tvp_single_track'));
				localStorage.removeItem('tvp_single_track');
				instance.addTrack(track);
			}
		}
	}else if(media_id == 'popup' || media_id == 'popup_single'){
		$('.popup_toggle').css('opacity',1);
	}
}
function tvpVideoLoaded(instance, media_id){
	/* called when video data is loaded. Returns player instance, media_id. */
	//console.log('tvpVideoLoaded: ', media_id);
}
function tvpVideoStart(instance, media_id){
	/* called when current playing video starts. Returns player instance, media_id. */
	//console.log('tvpVideoStart: ', counter);
}
function tvpVideoPlay(instance, media_id){
	/* called when media is played. Returns player instance, media_id. */
	//console.log('tvpVideoPlay: ', counter);
	
	if(typeof(hap_mediaArr) !== 'undefined' && hap_mediaArr.length){
		var i = 0, len = hap_mediaArr.length;
		for(i;i<len;i++){
			if(media_id != hap_mediaArr[i].media_id){
				//console.log('videoPlayerPlay: ', media_id, hap_mediaArr[i].media_id);
				hap_mediaArr[i].player_id.checkMedia('pause');
			}
		}
	}
}
function tvpVideoPause(instance, media_id){
	/* called when media is played. Returns player instance, media_id. */
	//console.log('tvpVideoPause: ', counter);
}
function tvpVideoFinish(instance, media_id){
	/* called on video finish. Returns player instance, media_id. */
	//console.log('tvpVideoFinish: ', media_id);
}
function tvpFsEnter(instance, media_id){
	/* called on fullscreen enter. Returns player instance, media_id. */
	//console.log('tvpFsEnter: ', media_id);
	$('.toggle_panel').hide();
	$('#api_panel').hide();
	$('.popup_toggle').hide();
}
function tvpFsExit(instance, media_id){
	/* called on fullscreen exit. Returns player instance, media_id. */
	//console.log('tvpFsExit: ', media_id);
	if(typeof api_panel_inited !== 'undefined' && api_panel_inited){
		$('#api_panel').show();
		$('.toggle_panel').show();
	}
	$('.popup_toggle').show();
}
function tvpCaptionChange(instance, media_id, lang){
	/* called on caption change. Returns player instance, media_id, caption language. */
	//console.log('tvpCaptionChange: ', media_id, lang);
}
function tvpQualityChange(instance, media_id, quality){
	/* called on quality change. Returns player instance, media_id, quality. */
	//console.log('tvpQualityChange: ', media_id, quality);
}




/* POPUP */
var hap_popup;
function notify_popup(type){//called from popup window when popup window has opened!
	//console.log('notify_popup');
	if(hap_popup && hap_popup.initPopup != undefined){//dont do anything if we are not going to be able to open popup!
		try {
			if(hap_popup.initPopup != undefined){
			
				var settings = hap_player.getSettings();
				settings.sequence_counter = hap_player.getSequenceCounter();//copy active item
				
				if(type == 'popup_single'){
					hap_popup.initPopup(settings);
				}
			}
		}catch(e){
			alert('parent notify_popup error: ' + e.message);
			return false;
		}
	}
}

function open_popup(settings, ai){
	//console.log('open_popup');
	
	var url = settings.popup_url, w = settings.popup_width, h = settings.popup_height, 
	cw = (window.screen.width - w) / 2, ch = (window.screen.height - h) / 2;//center popup in window
	
	//if popup window not already opened!
	if(!hap_popup || hap_popup.closed) {
		hap_popup=window.open(url,'hap_popup_window','menubar=no,toolbar=no,location=no,scrollbars=1,resizable,width='+w+',height='+h+',left='+cw+',top='+ch+'');

		if(!hap_popup) {
			alert("Player can not be opened in a popup window because your browser is blocking Pop-Ups. You need to allow Pop-Ups in browser for this site to use the Player.");
			return false;
		}
		if (window.focus) {hap_popup.focus();}
	}else{
		//console.log('popup already opened!');	
		//play video in popup
		if(hap_popup.loadMedia != undefined)hap_popup.loadMedia(ai);
	}
	
	if(isIOS && isChrome && hasLocalStorage){//http://stackoverflow.com/questions/14637937/window-opener-not-set-in-ios-chrome
		if(interval)clearInterval(interval); 
		var interval = setInterval(function() {   
			if(hap_popup.closed) {  
				clearInterval(interval);  
				if(localStorage.getItem('tvp_popup_video')){
					var ap = JSON.parse(localStorage.getItem('tvp_popup_video'));
					if(hap_player && localStorage.getItem('tvp_popup_sc'))hap_player.getSettings().sequence_counter = JSON.parse(localStorage.getItem('tvp_popup_sc'));
					open_player(ap);
				}
			}  
		}, 2000);  
	}
	
	return false;
}

//called from popup window when popup is closed
function open_player(ap){
	$('#mainWrapper').css('display', 'block');
	$('.popup_toggle').show();
	if(hap_player)hap_player.addTrack(ap);
}
