// JavaScript Document        
	var blackbg = false;
	var splash = true;
	var cur_cat=-1;
	var cur_page=-1;
	var stp_cat;
	var file_loaded = false;
	var cats_loaded = false;
	var file_count = new Array();
	var article_list = new Array();
	var filetable = '<table id="filestable" width="100%" border="0" cellpadding="0" cellspacing="0" style="display:none"><tbody id="filetable"><tr valign="top"><td></td><td class="ctd"></td><td></td></tr><tr valign="top"><td></td><td class="ctd"></td><td></td></tr><tr valign="top"><td></td><td class="ctd"></td><td></td></tr></tbody></table>';
	$(document).ready(function () {
		$('.latestnewsblock').ellipsis();
		$('#header').corner('10px');
		$('#mainnews, #fileslist, .latestnewsblock, #filescategory, #statstable, #files_prew>div, #files_next>div').corner('5px');
		$('img').corner('3px');
		$('#nginelogo').bind('mouseenter mouseleave', function () { $(this).children().fadeToggle();});
		/*$('#nginelogo').bind('click', 
			function () { $('body').animate({backgroundPosition: '0 -1600'}, 
				function(){
					if(blackbg){
						blackbg = false;
						document.cookie = 'bg_color=white';
						$('#copyrighttext, #copyrighttext>a').animate({color: '#000'});
						$('body')
							.css({'backgroundImage':'url(/templates/n-gine-dds/img/background.jpg)', 'background-repeat':'repeat-x'})
							.animate({backgroundColor: '#CDCDCD'},500,function(){
								$('body').animate({backgroundPosition: '0 0'},500);
						});
					}
					else{
						blackbg = true;
						document.cookie = 'bg_color=black';
						$('#copyrighttext, #copyrighttext>a').animate({color: '#FFF'});
						$('body')
							.css({'backgroundImage':'url(/templates/n-gine-dds/img/carbon.png)', 'background-repeat':'repeat'})
							.animate({backgroundColor: '#1C1C1C'},500, function(){
								$('body').animate({backgroundPosition: '0 0'},500);		
						});
					}
				});
			});
			*/
		$('#menuitems li')
			.bind('mouseenter', function () {
				$(this).stop().animate({ backgroundPosition: '0 0' },250);
			});
		$('#menuitems li').bind('mouseleave', function () {
			$(this).stop().animate({ backgroundPosition: '0 -76' },250);
			});
		$('#comments-form').css('display', 'none');
		$('#comments-footer').remove();
		$('#jc>h4')
			.bind('click', function () { $('#comments-form').slideToggle(); })
			.css('cursor','pointer');
		loadcontent();
		$(window).bind('hashchange', function() {
			loadcontent();
		});
		/*
		$.piroBox_ext({
			piro_speed :700,
			bg_alpha : 0.5,
			piro_scroll : true,
			piro_drag :false,
			piro_nav_pos: 'bottom'
		});
		*/
	});
//JavaScript Functions
	
//Load Files Page
	function loadfiles(x,y){
		if(!x) x=0;
		if(!y) y=0;
		$('#filescategory, #fileslist, #files_next, #files_prew').slideDown();
		$('#mainnews, #latestnewslist').slideUp();
		if(!cats_loaded)
			append_cats(x);
		if(file_loaded)
			$('#curfile').fadeOut(function(){$('#fileslistdiv').fadeIn();});
		if(window["files_"+x+'_'+y] == undefined)
			ajaxCall('ajax/getfiles.php?cat='+x+'&page='+y+'&limit=9',loadcontent);	
		else
		{
			if(cur_cat!=x&&cur_cat>=0)
			{
				if ($('#files_list_id_'+x).length > 0)
				{
					$('.catmainlink>.catdiv>img').css('display','none');
					$('#files_list_id_'+x+'>img').fadeIn(250);	
					if(x==0)
						$('.catmainlink>.catdiv').animate({opacity:1});
					else
					{
						$('.catmainlink>.catdiv:not(#files_list_id_'+x+')').animate({opacity:0.6});
						$('#files_list_id_'+x).animate({opacity:1}).parent().siblings().fadeIn().delay(2000).fadeOut();
					}
				}
			}
			if(cur_page!=y||cur_cat!=x||file_loaded)
			{
				if(cur_page<y)
					d=1;
				else
					d=0;
				load_files(x, y, d);
			}
			file_loaded=false;
			cur_page=y;
			cur_cat=x;
		}
	}
//Load File Page
	function loadfile(x){
		if(!x) return;
		if($('#fileslist').css('display')=='none')
		{
			$('#fileslistdiv, #files_next, #files_prew').hide();
			$('#curfile').show();
		}
		else
			$('#fileslistdiv, #files_next, #files_prew').fadeOut(function(){$('#curfile').fadeIn();});
		$('#filescategory, #fileslist').slideDown();
		$('#mainnews, #latestnewslist').slideUp();
		if(!cats_loaded)
			append_cats();
		if(window["file_id_"+x] == undefined)
			ajaxCall('ajax/getfile.php?id='+x,loadcontent);
		else
		{
			p_file=window["file_id_"+x];
			$('#curfile').empty().append('<table width="85%" style="margin:auto;"><tr><td colspan="2" class="file_page_title">' + p_file[1] + '<span style="font-size:16px;"> v' + p_file[6] + '</span></td></tr><tr><td style="width:420px"><a onclick="return hs.expand(this, {captionId: \'caption1\'})" href="images/' + (p_file[5]=='' ? 'filecats/NoImage.png' : 'jdownloads/screenshots/' + p_file[5]) + '"><img width="400px" style="border:solid 1px #000;" src="images/' + (p_file[5]=='' ? 'filecats/NoImage.png' : 'jdownloads/screenshots/' + p_file[5]) + '" alt="" style="border:none;" /></a></td><td class="file_page_desc">' + (p_file[11]=='' ? '' : 'Автор: ' + p_file[11] + '<br/><br/>') + (p_file[12]=='' ? '' : 'Мейл: ' + p_file[12] + '<br/><br/>') + (p_file[10]=='' ? '' : 'Сайт: ' + p_file[10] + '<br/><br/>') + (p_file[7]=='' ? '' : 'Размер: ' + p_file[7] + '<br/><br/>') + (p_file[13]=='' ? '' : 'Скачали: ' + p_file[13] + '<br/><br/>') + (p_file[3]==''?'':'<img class="exclusiveimg" src="images/filecats/' + p_file[3] + '.png" alt="" />') + '<br/><br/><a href="ajax/downloadfile.php?id=' + p_file[0] + '" class="downloadBtn"><img src="images/filecats/download_push.png" alt="Download" /></a></td></tr><tr><td colspan="2">' + p_file[4] + '</td></tr><tr><td><div class="socialShare"><a href="https://twitter.com/share" class="twitter-share-button" data-text="N-Gine.com / ' + p_file[1] + '" data-url="http://n-gine.com/#!/file/' + p_file[0] + '" data-count="horizontal" data-lang="ru">Tweet</a><script type="text/javascript" src="//platform.twitter.com/widgets.js"></script><fb:like href="http://n-gine.com/#!/file/' + p_file[0] + '" send="false" layout="button_count" width="50" show_faces="false"></fb:like>'+VK.Share.button('http://n-gine.com/#!/file/' + p_file[0], {type: "round", text: "Сохранить"})+'</div><div class="fb-comments" data-href="n-gine.com/#!/file/' + p_file[0] + '" data-num-posts="3" data-width="500"></div></td></tr></table>');
			$('#files_next, #files_prew').slideUp();
			/*$.piroBox_ext({
				piro_speed :700,
				bg_alpha : 0.5,
				piro_scroll : true,
				piro_drag :false,
				piro_nav_pos: 'bottom'
			});*/
			FB.XFBML.parse();
			file_loaded = true;
		}
	}
//Load Main Page
	function loadmain(){
		$('#filescategory, #fileslist').slideUp();
		$('#mainnews, #latestnewslist').slideDown();
	}
	function append_cats(x){
		if(x) stp_cat=x;
		if(cats_loaded){
			$('#filescategory').append(generate_cats(0));
			$('.catmainlink>div').each(function(index, element) {
                    $(this).delay(100*index).fadeIn(700);});
			$('.catmainlink>div').bind('mouseenter mouseleave', function () { 
				if($(this).attr('id')!='files_list_id_'+cur_cat) 
					$(this).children(':first-child').fadeToggle(250);
			});
		}
		else{
			cats_loaded =  true;
			ajaxCall('ajax/getcats.php',append_cats);
		}
			
	}
	function generate_cats(x){
		if(window["cats_"+x] != undefined)
		{
			var p_cats=window["cats_"+x];
			var data='';
			if(x==0)
				for(var i=0; i< p_cats.length; i++)
				{
					data += '<div class="catdiv"><a class="catmainlink" href="#!/files/' + p_cats[i][0] + '" title="' + p_cats[i][3] + '"><div id="files_list_id_'+p_cats[i][0]+'" class="catdiv" style="background-image:url(/images/filecats/' + p_cats[i][1] + '); display:none; ' + (p_cats[i][0]!=stp_cat&&stp_cat?'opacity:0.6;':'') + '"><img src="/images/filecats/Files_Glow.png" alt="" style="' + (p_cats[i][0]==stp_cat?'':'display:none;') + '" /></div></a>'+generate_cats(p_cats[i][0])+'</div>';
				}
			else
				for(var i=0; i< p_cats.length; i++)
				{
					data += '<a class="catsubdiv" href="#!/files/' + p_cats[i][0] + '" title="' + p_cats[i][3] + '" style="display:none;"><img src="/images/filecats/' + p_cats[i][1] + '" alt=""/></a>' + generate_cats(p_cats[i][0]);
				}
			return data;
		}
		else
			return '';
	}
	
	//Ajax call to url, Attach response as Script/Array
	function ajaxCall(url,callback){
		$.ajax({
			url: url,
			success: function(data) {
				if(data!='')
				{
					var script = document.createElement( 'script' );
					script.type = 'text/javascript';
					script.text = data;
					$('head').append( script );
					if(callback)
						callback();	
					return true;
				}
				else
					return false;
				}
			});
	}
	
	function load_files(x,y,d){
		$('#curfile').fadeOut(function(){
		$('#fileslistdiv').fadeIn();});
		 p_files=window["files_"+x+'_'+y];
		 if(d)
	 	$('#fileslistdiv')
		.children(':first-child')
		 	.animate({ marginTop:-465},function(){$(this).remove()})
			.after(filetable)
			.next().show()
			.find('td')
				.each(function(i, element) {
                        $(this).append(i<p_files.length?'<table class="single-file-table"><tr><td class="filelisttitle" colspan="2"><a href="#!/file/' + p_files[i][0] + '" title="' + p_files[i][1] + '">' + p_files[i][1] + '</a></td></tr><tr valign="top"><td class="filelistimg"><img src="images/' + (p_files[i][2]=='' ? 'filecats/NoImage.png' : 'jdownloads/screenshots/thumbnails/' + p_files[i][2]) + '" alt=""/></td><td class="filelisttext"><div style="height:60px; overflow:hidden;">Автор: ' + p_files[i][5] + '</div><div style="height:25px; overflow:hidden;">Размер: ' + p_files[i][4] + '</div>' + (p_files[i][3]==''?'':'<img class="exclusiveimg" src="images/filecats/' + p_files[i][3] + '.png" alt="" />') + '</td></tr></table>':'');
                   })	
		else
		$('#fileslistdiv')
		.prepend(filetable).children(':first-child').css({marginTop:-465}).show().animate({ marginTop:0},function(){$(this).next().remove()})
			.find('td')
				.each(function(i, element) {
                        $(this).append(i<p_files.length?'<table class="single-file-table"><tr><td class="filelisttitle" colspan="2"><a href="#!/file/' + p_files[i][0] + '" title="' + p_files[i][1] + '">' + p_files[i][1] + '</a></td></tr><tr valign="top"><td class="filelistimg"><img src="images/' + (p_files[i][2]=='' ? 'filecats/NoImage.png' : 'jdownloads/screenshots/thumbnails/' + p_files[i][2]) + '" alt=""/></td><td class="filelisttext"><div style="height:60px; overflow:hidden;">Автор: ' + p_files[i][5] + '</div><div style="height:25px; overflow:hidden;">Размер: ' + p_files[i][4] + '</div>' + (p_files[i][3]==''?'':'<img class="exclusiveimg" src="images/filecats/' + p_files[i][3] + '.png" alt="" />') + '</td></tr></table>':'');
                   })	
		if(y>0)
			$('#files_prew').attr('href','#!/files/' + x + '/' + y ).find('img').slideDown();
		else
			$('#files_prew').find('img').slideUp();
		if(file_count[x]>(y+1)*9)
			$('#files_next').attr('href','#!/files/' + x + '/' + (y+2) ).find('img').slideDown();
		else
			$('#files_next').find('img').slideUp();
	 }
		
		function load_article(a){
			if(window["article_id_"+a] != undefined)
			{
				var p_art=window["article_id_"+a];
				$('#mainnews')
					.append(p_art!=404?'<div id="article_' + a + '" style="display:none;"><div class="article_author">Автор: ' + p_art[5] + '<br/>Добавлен: ' + p_art[4] + '</div><div class="article_title">' + p_art[1] + '</div><div class="article_content">' + p_art[2] + '</div>' + (p_art[3]?'<a href="#" onclick="$(this).slideUp(function(){$(this).remove()}).next().slideDown();return false;">Подробнее...</a><div class="article_more">' + p_art[3] + '</div>':'') + '</div>':'<div class="article_title">Oops! 404 :D</div>');
				if(splash)
				{
					$('#splash')
						.delay(1500).slideUp(500,function(){$(this).remove()})
						.next()
						.delay(1500).slideDown(500);
					splash=false;
				}
				else
					$('#mainnews')
						.children(':first-child').slideUp(function(){$(this).remove()})
						.next().slideDown();
			}
			else
				ajaxCall('ajax/getarticle.php'+(a?'?id='+a:''),loadcontent);
		}
		
		function load_preview(){
			a=3;
			if(article_list[a] != undefined)
			{
				$('#latestnewslist')
					.append('<li class="latestnewsblock"><table><tr><td valign="top"><img src="http://www.n-gine.com/ajax/displaythumb.php?img=/' + article_list[a][4] + '&mw=100&mh=120" alt="" /></td><td><div class="newsblockhead"><a href="#!/home/' + article_list[a][0] + '">' + article_list[a][1] + '</a></div>' + article_list[a][2] + '</td></table></li>')
			}
			else
				ajaxCall('ajax/getarticles.php'+(a?'?id='+a:''),load_preview);
		}
		
		function getHashParams() {
			var hashParams = {};
			var e,
				a = /\+/g,  // Regex for replacing addition symbol with a space
				r = /([^&;=]+)=?([^&;]*)/g,
				d = function (s) { return decodeURIComponent(s.replace(a, " ")); },
				q = window.location.hash.substring(1);
		
			while (e = r.exec(q))
			   hashParams[d(e[1])] = d(e[2]);
		
			return hashParams;
		}
		
		function parseNewURL() {
			hash = new Array();
			hashParams = new Array();
			hashParams = window.location.hash.substring(3).toLowerCase().split('/');
			hash['page']=hashParams[0];
			if(hashParams[0]=='home' && hashParams[1])
					hash['article']=hashParams[1];
			if(hashParams[0]=='file' && hashParams[1])
					hash['file']=hashParams[1];
			if(hashParams[0]=='files' && hashParams[1])
					hash['cat']=hashParams[1];
			if(hashParams[0]=='files' && hashParams[2])
					hash['p']=hashParams[2];
			return hash;
		}
	 	function loadcontent(){
			if(window.location.hash.indexOf('!') == 1)
				hash = parseNewURL();
			else
				hash = getHashParams();
			if(hash['page']=='home'||!hash['page']){
				loadmain();
				if(hash['article'])
					load_article(parseInt(hash['article']));
				else
					load_article(latestarticle);
			}
			else if(hash['page']=='files'&&!hash['file'])
					loadfiles(hash['cat']?parseInt(hash['cat']):0,hash['p']?(parseInt(hash['p'])-1):0);
			else if(hash['page']=='file'||hash['file'])
					loadfile(parseInt(hash['file']));
		}
	
		function scrolltop(x){
			if(!x) x=0
			$('html, body').animate({ scrollTop: x });
		}
		
		(function(d){
  var js, id = 'facebook-jssdk'; if (d.getElementById(id)) {return;}
  js = d.createElement('script'); js.id = id; js.async = true;
  js.src = "//connect.facebook.net/en_US/all.js#xfbml=1";
  d.getElementsByTagName('head')[0].appendChild(js);
}(document));
