var comUpdInt = 0, uPII = 0, uPIS = 0, crPI = 0, giShowInt, giHideInt, ErrMsg = null, ErrIcon = null, SesErr = false, GlobalMsg = false, loaded = false, History = null;

function goSearch()
{
	var Regular =/^\s*/;
	
	TextBox = document.getElementById('querystring');
	
	Query = TextBox.value;
	Query = Query.replace(Regular, "");
	
	if(Query != "")
		document.location.href='/search/' + Query +'/';
}

$(document).ready(function()
{
	$('a').mouseup(function() {this.blur();});
	
	PrepareInputs();
	
	$('a.gInfo').mouseenter(function(e)
	{
		window.clearTimeout(giShowInt);
		giShowInt = window.setTimeout(function() { insertGameInfo(e.target, $(e.target).attr('rel'), e.pageX, e.pageY); }, 800);
	} );
	
	$('a.gInfo').mouseleave(function(e)
	{
		window.clearTimeout(giShowInt);
	} );
	
	if($('#commentform').length && !gotIsPS3)
	{
	  	$('#WindowTitle').append('<a href="#add_new" id="addcomlink" onclick="InsertEditor(\'/editor/user.js\'); return false;" style="float: right; margin-right: 8px">Расширенный режим</a>');	
		$('#commentform').submit(function(e) { e.preventDefault(); AddComment(); });
		$('#comment').keyup(function(e) { if(e.keyCode == 13 && e.ctrlKey == true) AddComment(); } );
	}
/*	
	History = window.History;
   
    if ( !History.enabled ) {
        return false;
    }
*/
/*    window.onpopstate = function()
	{
        var State = History.getState();
        History.log(State.data, State.title, State.url);
    };
	*/
	
	gotBoxLinks('gotboxlink');
	gotBoxGallery('thickbox,.gotboximg');
	
	dynComLinksInit();
	
	if(SesErr)
		gotBoxMessage(ErrMsg, {icon: ErrIcon});
	else if(GlobalMsg)
		gotBox(GlobalMsgURL, GlobalMsgTitle, true);
}
);

function dynComLinksInit()
{
	if($('#commentform').length)
	{
		$('a.compg').click(function()
		{
			$('.smload').css('visibility', 'visible');
			
			var plink = $(this).attr('href');
			var pgNum = parseInt($(this).attr('rel')) + 1;

			window.clearTimeout(comUpdInt);

			$.post('/comments/', {params: $('#comlinkdata').val(), comm_page: $(this).attr('rel')}, function(data)
			{
				$('#comblock').replaceWith(data);
				
				if(!$.browser.msie)
				{
					window.history.pushState({state: 1, type: 'coms', pagenum: (pgNum - 1)}, "pg" + pgNum, plink);
				}
				
				var title = document.title;
				
				if(title.indexOf('страница') != -1)
					document.title = title.replace(/страница [0-9]+/i, 'страница ' + pgNum);
				else
					document.title = title + ', страница ' + pgNum;
				
				dynComLinksInit();
			}
			);
			document.location.href = "#comments";

			return false;
		}
		);
		
		$('img.Avatar').mouseenter(function(e)
		{
			window.clearTimeout(uPII);
			uPII = window.setTimeout(function(){ insertUserInfo(e.target, $(e.target).attr('alt'), e.pageX, e.pageY); }, 400);
		} );
		
		$('img.Avatar').mouseleave(function() { window.clearTimeout(uPII); });
	}
		
	  $('a.copylink').each(function() {
	  $(this).zclip({path:'/images/flash/ZeroClipboard.swf', copy: window.location.protocol + '//' + window.location.hostname + window.location.pathname + $(this).attr('href')});
  });
  
	$('h5').not('.dont').each(function()
	{
		if($(this).attr('title') == null)
			$(this).attr('title', 'СПОЙЛЕР');
			
		$(this).replaceWith('<div class="spoiler"><a class="spoilerLink">[' +  $(this).attr('title') + ']</a><h5 class="dont" title="' + $(this).attr('title') + '">' + $(this).html() + '</h5></div>');
	}
	);
							
	$('a.spoilerLink').not('.dont').click(function()
	{
		$(this).parent().children('h5').slideToggle(300);
		$(this).addClass('dont');
	}
	);
	
	comUpdInt = window.setTimeout(UpdateComments, 20000);
}

function UpdateComments()
{
	var params = $('#comlinkdata').val();
	
	window.clearTimeout(comUpdInt);
	
	$.post('/comments/', {params: params, update: 'true', onpage: $('.CommentWindow').length}, function(data)
	{
		Response = data.split("{--$--}");
		
		switch(Response[0])
		{
			case '1':
				$('.Pagination').replaceWith(Response[1]);
				$('#cldform').replaceWith(Response[2]);
				dynComLinksInit();
			break;
			
			case '2':
				$('.Pagination').replaceWith(Response[1]);
				$('#cldform').remove();
				$('.CommentWindow').addClass('nob');
				$('.Pagination').last().before(Response[2]);
				$('.CommentWindow').not('.nob').addClass('HLBox');
				window.setTimeout(function() { $('.CommentWindow').not('.nob').removeClass('HLBox'); }, 20000);
				dynComLinksInit();
			break;
		}
		
		comUpdInt = window.setTimeout(UpdateComments, 20000);
	}
	);
}

function PrepareInputs()
{
	if(gotIsPS3)
		return; 
		
	var hlInputs = $('input:text,input:password,input:button,input:submit,select,textarea,button').not('.gotprepared') ;
	
	hlInputs.addClass('gotprepared');
	hlInputs.focus(function(){ $(this).addClass('hovered');	});
	hlInputs.blur(function(){ $(this).removeClass('hovered'); });
								
	$('input:button,input:submit,button').on('mousedown', function() { $(this).addClass('pressed'); $(this).removeClass('hovered'); });
	$('input:button,input:submit,button').on('mouseenter', function(){ $(this).addClass('hovered');	});
	$('input:button,input:submit,button').on('mouseleave', function(){ $(this).removeClass('hovered'); });
	$('input:button,input:submit,button').on('mouseup', function() { $(this).removeClass('pressed'); $(this).addClass('hovered'); });
	$('body').mouseup(function() { $('input.button,button').removeClass('pressed'); });	
}

function insertPopInfo(obj, id, mark)
{
	var pos = $(obj).offset();
	var x, y;
	
	$('#popInfo').remove();
	$("body").append('<div id="popInfo" style="top: ' + (pos.top - 90) + 'px; left:' + (pos.left - 70) + 'px"><h3>Загрузка...</h3><img src="/images/loading.gif" alt="Загрузка" /></div>');
	
	window.clearTimeout(crPI);
	crPI = window.setTimeout(function() {$('#popInfo').fadeOut(600); }, 2000);
	
	$('#popInfo').fadeIn('fast');
	
	$('#popInfo').mouseenter(function()
	{
		window.clearTimeout(crPI);
	});
		
	$('#popInfo').mouseleave(function()
	{
		crPI = window.setTimeout(function() {$('#popInfo').fadeOut(600); }, 700);
	});
	
	$.get('/likes/', {id: id, mark: mark}, function(data)
	{ 
		$('#popInfo').html(data);
		
		x = pos.left - ($('#popInfo').width())/2;
		y = pos.top - ($('#popInfo').height() + 20);
		$('#popInfo').css('top', y  + 'px');
		$('#popInfo').css('left', x + 'px');
	});
}

function insertUserInfo(obj, id, x, y)
{
	if(!$('#userInfo[class="uiw_' + id + '"]').length)
	{
		$('#userInfo').remove();
		$("body").append('<div id="userInfo" class="uiw_' + id + '" style="top: ' + (y - 20) + 'px; left:' + (x + 20) + 'px;"><h3>Загрузка...</h3><img src="/images/loading.gif" alt="Загрузка" /></div>');
				
		$('#userInfo').fadeIn(400);
		
		$('#userInfo').mouseenter(function() { window.clearTimeout(uPIS);});
		$('#userInfo').mouseleave(function() {$('#userInfo').delay(500).fadeOut(800);});
		
		$.post('/profile/', {id: id}, function(data)
		{ 
			$('#userInfo').html(data);
			uPIS = window.setTimeout(function() { $('#userInfo').fadeOut(800); }, 3000);
		});
	}
	else
	{
		$('#userInfo').css('top', (y - 20)  + 'px');
		$('#userInfo').css('left', (x + 20) + 'px');
		$('#userInfo').show();
	}
}

function insertGameInfo(obj, id, x, y)
{
	window.clearTimeout(giShowInt);
	
	if(!$('#gameInfo[class="giw_' + id + '"]').length)
	{
		$('#gameInfo').remove();
		$("body").append('<div id="gameInfo" class="giw_' + id + '" style="top: ' + (y - 90) + 'px; left:' + (x - 70) + 'px;"><h3>Загрузка...</h3><img src="/images/loading.gif" alt="Загрузка" /></div>');
		
//		$('embed').attr('wmode', 'opaque');
		
		$('#gameInfo').fadeIn(400);

		$('#gameInfo').mouseenter(function()
		{
			window.clearTimeout(giHideInt);
		});
		
		$('#gameInfo').mouseleave(function()
		{
			giHideInt = window.setTimeout(function() { $('#gameInfo').fadeOut(600); }, 700);
		});
		
		$.post('/gameinfo/', {id: id}, function(data)
		{ 
			$('#gameInfo').html(data);
			x = x - ($('#gameInfo').width()/2) + 20;
			y = y - ($('#gameInfo').height() + 20);
			$('#gameInfo').css('top', y  + 'px');
			$('#gameInfo').css('left', x + 'px');
			
			giHideInt = window.setTimeout(function() { $('#gameInfo').fadeOut(600); }, 1500);
		});
	}
	else
	{
		x = x - ($('#gameInfo').width()/2) + 20;
		y = y - ($('#gameInfo').height() + 20);
		$('#gameInfo').css('top', y  + 'px');
		$('#gameInfo').css('left', x + 'px');
		$('#gameInfo').show();
	}
}

var PollID = 0;

function PollVote(PollId, AnswNumber)
{	
	PollID = PollId;
	
	$.post('/vote/', {poll: PollId, answer: AnswNumber}, function(data) { VoteEnd(data);});
}

function VoteEnd(result)
{
	Result = result.split('{--$--}');

 //	setTimeout(function(){if(Result[0].length()) gotBoxMessage(Result[0], {icon: '/images/icon_info.jpg'});}, 300);

	if(Result[1])
		$('#Poll_' + PollID).html(Result[1]);
}

function ComRate(id, mark)
{
	$.get('/comrate/', {comment: id, mark: mark}, function(data)
	{
		Result = data.split('{--$--}');
		
		if(Result[0])
		{
			$('#crp_' + id).text(Result[1]);
			$('#crn_' + id).text(Result[2]);
		}
		
		insertPopInfo($('#imcr' + mark + id), id, mark);
	}
	);
}

function DeleteRequest(What, id)
{
	$('#el_' + id).block();
	$.get('/delete/' + What + '/' + id + '/', function(result)
	{
			Response = result.split("{--$--}");

	if(Response[0] > 0)
	{
		if(Response.length > 2)
			$('#el_' + Response[0]).before(Response[2]);
		
		$('#el_' + Response[0]).effect('explode', {}, 1000);
		//gotBoxMessage(Response[1], {icon: '/images/icon_bin.jpg'});
	}
	else
	{
	 	gotBoxMessage(Response[1], {icon: '/images/icon_error.jpg'});
		$('#el_' + id).unblock();
	}
	});
}

function FCKeditor_OnComplete(instance)
{
	if(instance.Name == 'comment')
	{
		EditorLoaded = true;
										
		$("#addcomlink").remove();
		
		if($('#ve').val() == -1)
		{
			gotBoxMessage('Всегда использовать расширенный режим редактирования?', {icon: '/images/icon_qst.jpg', buttons: {'Да' : 2, 'Нет': 0,  'Нет и отстаньте' : 1}, callback: function(r)
				{
					if(r)
					{
						$.post('/dyn-useve/', {dec: r}, function(){});
					}
				}
			});
		}

		gotBoxLoadingRemove();
		
		var edAr = $('iframe#comment___Frame').contents().find('td#xEditingArea').contents().contents();
		
		edAr.keyup(function(e) {
			if(e.keyCode == 13 && e.ctrlKey == true) AddComment();
			});
		
		instance.EditingArea.MakeEditable();
		instance.ResetIsDirty();
	}
	else if(instance.Name == 'message')
	{
		  try
		  {
			  if($('#pmbuf').length)
			  {
			  	$('#pmbuf').children('blockquote').remove();
			  	instance.SetHTML('<blockquote>' + $('#pmbuf').html() + '</blockquote><p>&nbsp;</p>');
			  }
		  }
		  catch(e)
		  {
		  }
	}
}
