function showPolicy(){
	var winwidth, winheight, picWidth, picHeight;
	picWidth = 700;
	picHeight = 550;
	winwidth = (screen.availWidth - picWidth) / 2;
	winheight = (screen.availHeight - picHeight) / 2;
	statusPage = window.open("/user/termsOfUse.php", "termsOfUse", "height="+picHeight+",width="+picWidth+",left="+winwidth+",top="+winheight+",scrollbars=yes,resizable=yes")
	statusPage.focus()
}

function showCats(){
	document.getElementById('catsContainer').style.display = '';
	document.getElementById('tagsContainer').style.display = 'none';
	document.getElementById('tagsCatsSwitch').innerHTML = '<a href="#" onclick="showTags(); return false;">Тэги</a> | Категории';
	var expdate = new Date();
	expdate.setTime(expdate.getTime()+(12*30*24*60*60*1000)); // ~1 year
	setCookie("catsTags", "cats", expdate, "/");
}

function showTags(){
	document.getElementById('catsContainer').style.display = 'none';
	document.getElementById('tagsContainer').style.display = '';
	document.getElementById('tagsCatsSwitch').innerHTML = 'Тэги | <a href="#" onclick="showCats(); return false;">Категории</a>';
	var expdate = new Date();
	expdate.setTime(expdate.getTime()+(12*30*24*60*60*1000)); // ~1 year
	setCookie("catsTags", "tags", expdate, "/");
}

function loadMidContent( key ){
	var expdate = new Date();
	expdate.setTime(expdate.getTime()+(12*30*24*60*60*1000)); // ~1 year
	setCookie("midContent", key, expdate, "/");
	$('#midContent').html('<img src="/lib/images/progressCircle.gif" width=16 height=16 border=0>');
	$('#midContent').load('/ajax/content.php');
	$('#midTabs a div.tab').removeClass('selected');
	$('#midTabs a div.tab'+key).addClass('selected');
}

function showRating( n ){
	for( i = 0; i < 5; i++ ){
		var img = document.getElementById('ratingImage'+i);
		if( i >= n )
			img.src = '/img/grayStar.gif';
		else
			img.src = '/img/redStar.gif';
	}
}

var ratingTimer;

function hoverRating( n ){
	clearTimeout( ratingTimer );
	showRating( n );
}

function outRating(){
	ratingTimer = setTimeout( 'restoreRating()', 300 );
}

function restoreRating(){
	showRating( document.getElementById('ratingValue').innerHTML );
}

function voteVideo( videoId, rating, button, voteKey ){
	$(button).css("position", "relative");
	$(button).animate(
		{top: (-5*rating)+"px"},
		200,
		"swing",
		function(){
			$(button).animate(
				{top: "0px"},
				200,
				"swing",
				function(){}
			);
		}
	);
	$.ajax({
		url: '/ajax/voteVideo.php?VideoID='+videoId+'&Rating='+rating+'&Key='+voteKey,
		dataType: 'json',
		success: function(data){
			if(data.Error == ""){
				$('#voteCount').html(data.VoteCount);
				$('#voteScore').html(data.TotalVote);
			}
			else
				alert(data.Error);
		}
	});
}

function voteContestVideo( videoId, rating, contestId, voteKey ){
	$.ajax({
		url: '/ajax/voteContestVideo.php?VideoID='+videoId+'&Rating='+rating+'&Key='+voteKey+'&ContestID='+contestId,
		dataType: 'json',
		success: function(data){
			if(data.Error == ""){
				document.getElementById('ratingValue').innerHTML = rating;
				document.getElementById('ratingVoteCount').innerHTML = data.VoteCountText;
				restoreRating();
			}
			else
				alert(data.Error);
		}
	});
}

function ajaxError( error ){
	alert('Error ' + error.status + ' -- ' + error.statusText);
}

var activeImage;
var thumbTimer;
var stopRotateTimer;

function thumbOver(image){
	clearTimeout( thumbTimer );
	activeImage = image;
	showPlaylistButton();
	clearTimeout( stopRotateTimer );
	rotateThumb();
}

function rotateThumb(){
	if( !activeImage || !document.getElementById('thumbPreloader') )
		return false;
	var activeThumb = activeImage.getAttribute("activeThumb");
	var thumbCount = activeImage.getAttribute("thumbCount");
	var nextThumb = activeThumb;
	nextThumb++;
	if( nextThumb >= thumbCount )
		nextThumb = 0;
	var host;
	if( location.hostname.toLowerCase().indexOf('www.') == 0 )
		host = location.hostname.substr(4);
	else
		host = location.hostname;
	var nextSrc = 'http://img.'+ host + activeImage.src.substr( host.length + 11, 24 ) + "thumb"+nextThumb+".jpg";
	activeImage.setAttribute("nextThumb", nextThumb);
	document.getElementById('thumbPreloader').src = nextSrc;
}

function thumbOut(){
	stopRotateTimer = setTimeout('stopRotating()', 200 );
}

function stopRotating(){
	activeImage = null;
	clearTimeout( thumbTimer );
	hidePlaylistButton();
}

function thumbPreloaded(){
	if( activeImage ){
		activeImage.src = document.getElementById('thumbPreloader').src;
		activeImage.setAttribute("activeThumb", activeImage.getAttribute("nextThumb"));
		thumbTimer = setTimeout('rotateThumb()', 300 );
	}
}

function overAddButton( button ){
	clearTimeout( stopRotateTimer );
	button.src = '/img/plusRed.gif';
}

function outAddButton( button ){
	button.src = '/img/plus.gif';
	stopRotateTimer = setTimeout('stopRotating()', 200 );
}

function showPlaylistButton(){
	var button = document.getElementById('addButton');
	if(button){
		var offset = $(activeImage).offset();
		button.style.left = offset.left + 5 + 'px';
		button.style.top = offset.top + 5 + 'px';
		button.style.visibility = 'visible';
	}
}

function hidePlaylistButton(){
	var button = document.getElementById('addButton');
	button.style.visibility = 'hidden';
}

function addToPlaylist(){
	if(!authorize())
		return false;
	var videoId = activeImage.getAttribute('VideoID');
	new Ajax.Request('/ajax/addToPlaylist.php?VideoID='+videoId, {
	  onSuccess: playlistSuccess,
	  onFailure: ajaxError
	});
}

function playlistSuccess( transport ){
	var response = transport.responseText.evalJSON();
	document.getElementById('playlist').innerHTML = response.playlistText;
}

function deletePlaylist( videoId ){
	new Ajax.Request('/ajax/deleteFromPlaylist.php?VideoID='+videoId, {
	  onSuccess: playlistSuccess,
	  onFailure: ajaxError
	});
}

function clearPlaylist(){
	new Ajax.Request('/ajax/clearPlaylist.php', {
	  onSuccess: playlistSuccess,
	  onFailure: ajaxError
	});
}

function authorize(){
	if( authorized )
		return true;
	alert('Для использования этой функции вы должны зарегистрироваться');
	document.location.href = '/security/login.php';
	return false;
}

function sendComment(){
	document.getElementById('sendCommentButton').disabled = true;
	var nick = "";
	var captcha = "";
	if( !authorized ){
		nick = trim( $('#commentNick').attr('value') );
		if( nick == '' ){
			$('#commentNick').focus();
			alert('Заполните имя');
			return false;
		}
		if( document.getElementById('commentCaptcha') ){
			captcha = trim( $('#commentCaptcha').attr('value') );
			if( captcha == '' ){
				$('#commentCaptcha').focus();
				alert('Введите Число на картинке');
				return false;
			}
		}
	}
	var text = trim( $('#commentText').attr('value') );
	if( text == '' ){
		$('#commentText').focus();
		alert('Заполните комментарий');
		return false;
	}
	if( !moderator && (text.length > 3000) ){
		$('#commentText').focus();
		alert('Комментарий не более 3000 символов');
		return false;
	}
	$.ajax({
		url: '/ajax/addComment.php?Nick='+encodeURIComponent( nick )
		+'&Captcha='+encodeURIComponent( captcha )
		+'&VideoID='+encodeURIComponent( document.getElementById('videoId').value ),
		success: function(response){
			document.getElementById('sendCommentButton').disabled = false;
			if( response.error == '' ){
				document.getElementById('comments').innerHTML = response.commentsText;
				document.getElementById('commentText').value = '';
				document.getElementById('commentCountTab').innerHTML = 'Комментарии ('+response.commentCount+')';
				showTab('comment', 'List');
				document.location.href = '#commentsEnd';
			}
			else
				alert( response.error );
		},
		type: 'POST',
		data: 'Text='+encodeURIComponent( text ),
		dataType: 'json'
	});
}

function deleteComment( commentId ){
	if( !window.confirm('Удалить комментарий?') )
		return false;
	$.ajax({
		url: '/ajax/deleteComment.php?ID='+encodeURIComponent( commentId ),
		dataType: 'json',
		success: function(response){
			if( response.error == '' ){
				document.getElementById('comments').innerHTML = response.commentsText;
				document.getElementById('commentCountTab').innerHTML = 'Комментарии ('+response.commentCount+')';
				showTab('comment', 'List');
			}
			else
				alert( response.error );
		}
	});
}


function setBitRate( bitRate ){
	// rewrite player
	s = playerFlashVars;
	var re = /file=[^&]+&/igm;
	var videoName;
	if( bitRate == 0 )
		videoName = "video";
	else
		videoName = "video_"+bitRate;
	s = s.replace( re, "file=" + document.getElementById('BasePath').value + "/"+videoName+"."+document.getElementById('BaseExt').value+"&" );
	document.getElementById('bitRateLink'+activeBitRate).className = '';
	document.getElementById('bitRateLink'+bitRate).className = 'selected';
	var re = /vn_profile_id=[^&]+&vn_category_id=[^&]+&/igm
	s = s.replace(re, "");
	activeBitRate = bitRate;
        //s1 = new SWFObject("http://lovi.tv/flash/advPlayer.swf","ply","100%","100%","9","#FFFFFF");
        //s1.addParam("allowfullscreen","true");
        //s1.addParam("allowscriptaccess","always");
        //s1.addParam("wmode","opaque");
        s1.addParam("flashvars",s);
	s1.write("player");
	$.ajax({url:'/video/setBandWidth.php?BW='+bitRate});
        $(document).ready(function() {
                startPlay();
        });
}

function writeDocument(s){
	document.write(s);
}

function showPlayer(s){
	document.getElementById("player").innerHTML = s;
}

function showTab(prefix, tab){
	$('#'+prefix+'Tabs div.tab').removeClass("selected");
	$('#'+prefix+'Tabs div.tab'+tab).addClass("selected");
	$('#'+prefix+'TabsContent div.tab').css("display", "none");
	$('.lwCol').css("width", $('#'+prefix+'TabsContent').width()+"px");
	$('#'+prefix+'TabsContent div.tab'+tab).css("display", "");
}

function updateSizes(){
	return;
	var availWidth = $('#main').width();
	if($('.leftWideCol').length > 0){
		var left = Math.round(availWidth * 38/100);
		if(left < 400)
			left = 400;
		var right = availWidth - left - 10;
		var split = availWidth - left - right;
		$('.leftWideCol').css("width", left+'px');
		$('.rightWideCol').css("width", right+'px');
		$('.splitCol').css("width", split+'px');
	}
}

function searchClick(){
	var input = document.getElementById('searchText');
	if((input.value == '') || (input.value == 'Найти видео')){
		alert('Введите текст для поиска');
		return false;
	}
	document.getElementById('searchForm').submit();
}

function showAllCats(link){
	link.style.display = 'none';
	$('#catsHolder').animate({
		height: $('#cats').height() + 30 + "px"
	}, 1000);
}

var setBitrateCall = 0;

function setBitrateLink(bitrate){
	// ignore first call from player, afer loading
	setBitrateCall++;
	if(setBitrateCall == 1)
		return;
	// actual code
	// invert value, because we've got value before click
	if(bitrate == 0)
		bitrate = 512;
	else
		bitrate = 0;
	$.ajax({url:'/video/setBandWidth.php?BW='+bitrate});
	setTimeout('resizePlayerColumn('+bitrate+')', 100);
}

function resizePlayerColumn(bitrate){
	var playerCol = document.getElementById('playerCol');
	var rightCol = document.getElementById('rightCol');
	if(playerCol){
		if(bitrate == 0){
			// HQ
			if(playerCol.className == 'leftWideCol'){
				// make column wide
				playerCol.className = 'hqWideCol';
				if(rightCol)
					rightCol.className = 'hqNarrowCol';
			}
		}
		else{
			// small
			if(playerCol.className == 'hqWideCol'){
				// make column narrow
				playerCol.className = 'leftWideCol';
				if(rightCol)
					rightCol.className = 'rightWideCol';
			}
		}
	}
	setTimeout('updatePlayerSize()', 100);
}

function updatePlayerSize(){
	$('#player').css("height", Math.round($('#subPlayer').width()*playerHeight/playerWidth)+'px');
}
