var sThumbs = new Array();
var aUserInfo = new Array();
aUserInfo.session_id = '';
aUserInfo.breakview = 0;
aUserInfo.logged = 0;

aPayTubeConfig = new Array();
aPayTubeConfig.cookie_domain = '';
aPayTubeConfig.cookie_session_name = 'tubesession';
aPayTubeConfig.ajax_url = '/index.php';
aPayTubeConfig.ajax_image = '/images/loading.gif';

var iInterval = 30;

var iNoResume = 0;
var aCuepoints = new Array();
aCuepoints[0] = iInterval * 1000;

function StartThumbChange(sId, iThumbsCount, sPath)
{	
	sThumbs[sId] = true;
	
	ChangeThumb(sId, 3, iThumbsCount, sPath);
}

function EndThumbChange(sId, sPath)
{
	sThumbs[sId] = false;
//	$('#'+sId).attr('src', sPath + '.003.jpg');
}

function ChangeThumb(sId, i, iThumbsCount, sPath)
{
	if (sThumbs[sId])
	{
		if (i < 10)
		{
			sI = '00'+i;
		}
		else if (i < 100)
		{
			sI = '0'+i;
		}
		else
		{
			sI = i;
		}
		sVal = sPath + '.' + sI + '.jpg';
		$('#'+sId).attr('src', sVal);
		i = i % iThumbsCount;
		i++;

		setTimeout("ChangeThumb('" + sId + "'," + i + ", " + iThumbsCount + ", '" + sPath + "')", 1100);
	}
}	

// ------------------- Player -------------------
function ShowPlayerForPayTube(sPlayerId, sUrl, sImage, iWidth, iHeight, sPlayerPath, iAutoPlay, iDuration, sMainAdsStyles)
{
	sSessinId = Get_Cookie(aPayTubeConfig.cookie_session_name);
	if ( (sSessinId != '') && (sSessinId != null) )
	{
		sAdsMainId = 'ads_player_main';
		sAdsBottomId = 'ads_player_bottom';
		iStartPosition = 0;
	}
	else
	{
		sAdsMainId = 'ads_player_main_notlogged';
		sAdsBottomId = 'ads_player_bottom_notlogged';
		// расставим точки останова
		iStartPosition = Math.floor(iDuration / 2);
		iDuration = iDuration*1000;
		j = 1;
		for (i=iInterval*1000*2; i<=iDuration; i+=iInterval*1000)
		{
			aCuepoints[j] = i;
			j++;
		}
	}

	var iScrubber = 1;
	var sSessinId = Get_Cookie(aPayTubeConfig.cookie_session_name);
	if ( (sSessinId == '') || sSessinId == null)
	{
		iScrubber = 0;
	}

	ShowPlayer(sPlayerId, sUrl, sImage, iWidth, iHeight, sAdsMainId, sAdsBottomId, sPlayerPath, iAutoPlay, sMainAdsStyles, iScrubber, iStartPosition);
}

function ShowPlayer(sPlayerId, sUrl, sImage, iWidth, iHeight, sAdsMainId, sAdsBottomId, sPlayerPath, iAutoPlay, sMainAdsStyles, iShowScrubber, iStartPosition)
{
	var sAdsBottom = $('#'+sAdsBottomId).html();
	var sAdsMain = $('#'+sAdsMainId).html();
	var iScrubber;

	if (sAdsBottom == null) sAdsBottom = '';
	if (sAdsMain == null) sAdsMain = '';

	if (sPlayerPath == null) sPlayerPath = '/player/';

	if (iAutoPlay == null) iAutoPlay = false;

	if (sMainAdsStyles == null) sMainAdsStyles = sPlayerPath + 'content-plugin.css';

	if (iShowScrubber == null || iShowScrubber != 0)
	{
		iScrubber = 1;
	}
	else
	{
		iScrubber = 0;
	}

	if (iStartPosition == null || iStartPosition == '')
	{
		iStartPosition = 0;
	}

	$f(sPlayerId, sPlayerPath+"flowplayer.swf", { 

		canvas: { 
	    	backgroundColor: '#000000',
			backgroundGradient: [0, 0, 0],
			border: '2px solid #000000'
		},

		play: {
//			label: 'Play movie'
		},

		playlist: [
	        { 
    	        url: sImage,
	            scaling: 'fit' 
	        }, 

	    	{ 
	        	url: escape(sUrl),
		        provider: 'lighttpd',
		        autoPlay: iAutoPlay,
				start: iStartPosition,
//				autoBuffering: true,
				scaling: 'fit'
		    }
		],

		plugins: { 

		    lighttpd: {
	    	    url: sPlayerPath+'flowplayer.pseudostreaming.swf'
		    },

	    	controls: { 
	        	url: sPlayerPath+'flowplayer.controls.swf',
				fullscreen: iScrubber,
				scrubber: iScrubber,
				backgroundColor: '#333333'
		    },

			adsBottom: {
				url: sPlayerPath+'flowplayer.content.swf',
				html: sAdsBottom,
				style: {
					p: {fontSize:21, color:'#FFFFFF', fontFamily:'Verdana', fontWeight:'bold', textAlign: 'center'},
					a: {color:'#fcff00'}
				},
				borderRadius: 0,
				bottom: 30,
				height: 40,
				opacity: 0.98,
				display: 'none',
				backgroundColor: '#333333',
				border: '1px solid #777777',
				backgroundGradient: [0, 0, 0]
			},

			adsMain: {
				url: sPlayerPath+'flowplayer.content.swf',
				html: sAdsMain,
				borderRadius: 0,
				stylesheet: sMainAdsStyles,
				top: 12,
				height: (iHeight - 90),
				bottom: 85,
				opacity: 0.98,
				display: 'none',
				backgroundColor: '#333333',
				border: '1px solid #777777',
				backgroundGradient: [0, 0, 0]
			}
		}
	});

	function ShowAds(sId)
	{
		var plugin = $f(sPlayerId).getPlugin(sId); 
		plugin.show();
	}
	function HideAds(sId)
	{
		var plugin = $f(sPlayerId).getPlugin(sId); 
		plugin.hide();
	}

	$f(sPlayerId).onLoad(function() {
		if (sAdsBottom != '') ShowAds('adsBottom');
	});

	$f(sPlayerId).onPause(function() {
		if (sAdsMain != '') ShowAds('adsMain');
		if (sAdsBottom != '') ShowAds('adsBottom');
	});

	$f(sPlayerId).onBeforeBegin(function() {
		if($f(sPlayerId).getClip().index > 0)
		{
			if ( (aUserInfo.session_id != '') && (aUserInfo.session_id != null) )
			{
				$f(sPlayerId).getClip().update({url:sUrl+aUserInfo.session_id});
			}
		}
	});

	$f(sPlayerId).onFinish(function() {
		$f(sPlayerId).stop();
		if ( (sAdsMain != '') && ($f(sPlayerId).getClip().index > 0))	ShowAds('adsMain');
		if (sAdsBottom != '') ShowAds('adsBottom');
	});

	$f(sPlayerId).onCuepoint(aCuepoints, function() {
		if (aUserInfo.breakview == 1)
		{
			if (sAdsMain != '') ShowAds('adsMain');
			if (sAdsBottom != '') ShowAds('adsBottom');
			$f(sPlayerId).pause();
			iNoResume = 1;
		}
	});

	$f(sPlayerId).onResume(function() {
		if ( (sAdsMain != '') && (iNoResume != 1) )
		{
			HideAds('adsMain');
		}
	});

} // function ShowPlayer()
// ------------------- Player -------------------

function GetUserInfo()
{
	var sSessinId = Get_Cookie(aPayTubeConfig.cookie_session_name);

	ShowProcessMessage('user_info_loading', 'Loading user information...')

	$.get(aPayTubeConfig.ajax_url, {m:'getuserinfojson', session_id:sSessinId, nocache:1, noinfo:1}, function(aData) {
		if (aData.logged != 1)
		{
			aUserInfo.breakview = 1;
			$('#user_login_form').show();
			$('#user_info').hide();
			Delete_Cookie(aPayTubeConfig.cookie_session_name, '/', aPayTubeConfig.cookie_domain);
		}
		else
		{
			aUserInfo.session_id = '|'+sSessinId;
			aUserInfo.breakview = 0;
			$('#user_login_form').hide();
			$('#user_info_login').html(aData.login);
			$('#user_info_date_expare').html(aData.date_expare);
			$('#user_info').show();
		}

		$('#user_info_loading').hide();

	}, 'json');
}

function UserLogin(sLoginMessade)
{
	$('#user_login_form_fail').hide();
	ShowProcessMessage('user_login_form_result', sLoginMessade)

	$.get(aPayTubeConfig.ajax_url, {m:'loginjson', login:$('#user_login_form_login').val(), password:$('#user_login_form_password').val(), nocache:1, noinfo:1}, function(aData) 
	{
		if (aData.logged == 1)
		{
			$('#user_login_form_result').hide();
			$('#user_login_form_fail').hide();
			Delete_Cookie(aPayTubeConfig.cookie_session_name, '/', aPayTubeConfig.cookie_domain);
			Set_Cookie(aPayTubeConfig.cookie_session_name, aData.session_id, 365, '/', aPayTubeConfig.cookie_domain);
			GetUserInfo();
		}
		else
		{
			$('#user_login_form_result').hide();
			$('#user_login_form_fail').show();
			$('#user_login_form_fail_message').html(aData.message);
		}
	}, 'json');
}

function UserLogout(sLogoutMessade)
{
	var sSessinId = Get_Cookie(aPayTubeConfig.cookie_session_name);

	ShowProcessMessage('user_logout_result', sLogoutMessade);

	$.get(aPayTubeConfig.ajax_url, {m:'logoutjson', session_id:sSessinId, nocache:1, noinfo:1}, function(aData) {
		Delete_Cookie(aPayTubeConfig.cookie_session_name, '/', aPayTubeConfig.cookie_domain);
		$('#user_logout_result').hide();
		GetUserInfo();
	}, 'json');
}

function ShowLoginForm(sId)
{
	if (aUserInfo.logged != 1)
	{
		$('#'+sId).show();
	}
}

function ShowProcessMessage(sId, sMessage)
{
	if (sMessage == null) sMessage = 'Processing...';

	$('#'+sId).show();
	$('#'+sId).html('<IMG src="'+aPayTubeConfig.ajax_image+'" align="absmiddle" />&nbsp;'+sMessage+'...');
}

/*
	From http://www.mach5.com/support/analyzer/manual/html/General/CookiesJavaScript.htm
*/
function Get_Cookie(name) {
   var start = document.cookie.indexOf(name+"=");
   var len = start+name.length+1;
   if ((!start) && (name != document.cookie.substring(0,name.length))) return null;
   if (start == -1) return null;
   var end = document.cookie.indexOf(";",len);
   if (end == -1) end = document.cookie.length;
   return unescape(document.cookie.substring(len,end));
}
// This function has been slightly modified
function Set_Cookie(name,value,expires,path,domain,secure) {
	expires = expires * 60*60*24*1000;
	var today = new Date();
	var expires_date = new Date( today.getTime() + (expires) );
	var cookieString = name + "=" +escape(value) +
	( (expires) ? ";expires=" + expires_date.toGMTString() : "") +
	( (path) ? ";path=" + path : "") +
	( (domain) ? ";domain=" + domain : "") +
	( (secure) ? ";secure" : "");
	document.cookie = cookieString;
}
function Delete_Cookie(name,path,domain) {
   if (Get_Cookie(name)) document.cookie = name + "=" +
      ( (path) ? ";path=" + path : "") +
      ( (domain) ? ";domain=" + domain : "") +
      ";expires=Thu, 01-Jan-70 00:00:01 GMT";
}

// idea by stup
thumbStartIndex = 3;
thumbIndex = 3;
thumbdefURL = ""
thumbId = "";
thumbStamp = "";
thumbRotation = false;
function doThumbsStart(id, iThumbsCount, stamp) {
	if (thumbRotation && thumbStamp == stamp) {
		thumbIndex = thumbIndex % iThumbsCount;
		thumbIndex++;
		var img = document.getElementById(thumbId);
		var sThumbIndex = getRealIndex(thumbIndex);
		img.src = thumbdefURL.replace(/.cache.[0-9][0-9][0-9].jpg/, ".cache."+sThumbIndex+".jpg");
		setTimeout("doThumbsStart('"+id+"', "+iThumbsCount+", '"+stamp+"')", 600);
	}
}
function offThumbsRoll(id) {
	var img = document.getElementById(id);
	var thumbURL = img.src;
//	img.src = thumbURL.replace(/.cache.[0-9][0-9][0-9].jpg/, ".cache.00"+thumbStartIndex+".jpg");
	thumbRotation = false;
	thumbStamp = false;
}
function doThumbsRoll(id, iThumbsCount) {
	var d = new Date();
	thumbStamp = id + d.getTime();
	thumbRotation = true;
	var img = document.getElementById(id);
	thumbdefURL = img.src;
	thumbId = id;
	thumbIndex = thumbStartIndex + 1;
	var sThumbIndex = getRealIndex(thumbIndex);
	img.src = thumbdefURL.replace(/.cache.[0-9][0-9][0-9].jpg/, ".cache."+sThumbIndex+".jpg");
	setTimeout("doThumbsStart('"+id+"', "+iThumbsCount+", '"+thumbStamp+"')", 600);
}
function doPreloadThumbs(id, iThumbsCount) {
	thumbdefURL = document.getElementById(id).src;
	var num = thumbIndex;
	iThumbsCount = iThumbsCount - thumbIndex;
	while(num < iThumbsCount) {
		var preloadThumb = new Image();
		sNum = getRealIndex(num);
		preloadThumb.src = thumbdefURL.replace(/.cache.[0-9][0-9][0-9].jpg/, ".cache."+sNum+".jpg");
		num++;
	}
}
function getRealIndex(i)
{
	if (i < 10)
	{
		return '00'+i;
	}
	else if (i < 100)
	{
		return '0'+i;
	}
	else
	{
		return i;
	}
}

function ShowPlayerNew(sPlayerId, sUrl, sAdsDiv, sPlayerPath, iAutoPlay, iShowScrubber, iStartPosition)
{
	var iScrubber;

	if (sPlayerPath == null) sPlayerPath = '/player/';
	if (iAutoPlay == null) iAutoPlay = true;
	if (iShowScrubber == null || iShowScrubber != 0)
	{
		iScrubber = 1;
	}
	else
	{
		iScrubber = 0;
	}
	if (iStartPosition == null || iStartPosition == '')
	{
		iStartPosition = 0;
	}

	$f(sPlayerId, {src: sPlayerPath+"new/flowplayer.swf", wmode:"opaque"}, { 

		clip: { 
			url: escape(sUrl),
			provider: 'lighttpd',
			autoPlay: iAutoPlay,
			start: iStartPosition,
			scaling: 'fit',
			onBegin: function() {
				$('#'+sAdsDiv).hide();
			},
			onStart: function() {
				$('#'+sAdsDiv).hide();
			},
			onResume: function() {
				if (iNoResume != 1)
				{
					$('#'+sAdsDiv).hide();
				}
			},
			onFinish: function() {
				$f(sPlayerId).stop();
				$('#'+sAdsDiv).show();
			},
			onStop: function() {
				$('#'+sAdsDiv).show();
			},
			onPause: function() {
				$('#'+sAdsDiv).show();
			}
		},

		canvas: { 
			backgroundColor: '#000000',
			backgroundGradient: [0, 0, 0],
			border: '2px solid #000000'
		},

		play: {
//			label: 'Play movie'
		},

		plugins: { 

			lighttpd: {
				url: sPlayerPath+'new/flowplayer.pseudostreaming.swf'
			},

			controls: { 
				url: sPlayerPath+'new/flowplayer.controls.swf',
				fullscreen: iScrubber,
				scrubber: iScrubber,
				backgroundColor: '#333333'
			},
		}
	});

	$f(sPlayerId).onBeforeBegin(function() {
		if($f(sPlayerId).getClip().index > 0)
		{
			if ( (aUserInfo.session_id != '') && (aUserInfo.session_id != null) )
			{
				$f(sPlayerId).getClip().update({url:sUrl+aUserInfo.session_id});
			}
		}
	});

	$f(sPlayerId).onCuepoint(aCuepoints, function() {
		if (aUserInfo.breakview == 1)
		{
			$('#'+sAdsDiv).show();
			$f(sPlayerId).pause();
			iNoResume = 1;
		}
	});

} // function ShowPlayerNew()

