/**
  * accordion
  */
	
function accordionInit(id) {
	//simultaneous showing and hiding
	  jQuery('div.'+id+':eq(0) > ul').hide(); 
	  jQuery('div.'+id+':eq(0) > div').click(function() {
	    	jQuery(this).next('ul').slideToggle('fast').siblings('ul:visible').slideUp('fast');
			jQuery('div.'+id+':eq(0) > div').removeClass('open');
	    	jQuery(this).addClass('open');
	  });
}	
	
 
 
/* **************************************************************** */ 

 	var Param={};
//	Обработка загрузки контента
 	function pageload(_url) {
//  		if(_url){jQuery("#spiner").show();}
		
		var rand=parseInt(Math.random()*9999999);
		var u =  _url.split("&")[0];
		var p =  _url.replace(u,'');
		if(p){Param.variable="?"+p+"&r="+rand}else{Param.variable="?r="+rand}
		if(u) {
  			jQuery("#pagecontent").fadeOut(300, function () {
// 				jQuery("#pagecontent").load(u+Param.variable,function(){ scroll(0,0); });
  				jQuery("#pagecontent").load(u+Param.variable,function(){jQuery("#pagecontent").fadeIn(100,function(){ scroll(0,0); })  });
 			});
		} else {
//			 jQuery("#pagecontent").empty();
			 jQuery("#pagecontent").load("/content/publisher/index.shtml",function(){jQuery("#pagecontent").fadeIn(); });
		}
			// Индикатор обращеий через аякс и вывод контента
//    			 jQuery("#spiner").ajaxStop(function() { jQuery(this).hide(); });
 		}
//	Инициализация ссылок
 	function initLinks(a){
	 		 jQuery("a[@rel="+a+"]").click(function(){
				var  hash = this.href;
				var q =(hash);
				q = q.split("/")[2];
				q ="http://"+q;
	 			hash = hash.replace(q, '');
				hash = hash.replace(/^.*#/, '');
				hash = hash.replace("?", '&');
				jQuery.historyLoad(hash);
				return false;
		});
	 } ;		
	 		 
	 
//	Обработка параметров
	function getQueryVariable(variable) {
		var query =  Param.variable;  
		 query = query.split("?")[1];
		if(query){
			var vars = query.split("&");
			for (var i=0;i<vars.length;i++) {
				var pair = vars[i].split("=");
			    if (pair[0] == variable) {
			      return pair[1];
			    }
		  } 
		}
	}
//	Стартовая инициализация программ	
	jQuery(document).ready(function(){
		jQuery.historyInit(pageload);
		initLinks('ajax');


		var so = new SWFObject("/images/themes/slideshow/slideshow.swf", "headerban", "490", "197", "6", "#FF6600");
		so.addVariable("flashVarText", "Главный баннер"); 
		so.addParam("wmode", "transparent");
		so.addParam("menu", "false");
 		so.write("flashcontent");		


 		accordionInit('accordMenu');
 		jQuery("#T_documents").treeview({ animated: "fast", collapsed: true, unique: true });
		jQuery("#T_gallery").treeview({ animated: "fast", collapsed: true, unique: true });
		jQuery("#T_catalogue").treeview({ animated: "fast", collapsed: true, unique: true });
		jQuery("#T_links").treeview({ animated: "fast", collapsed: true, unique: true });

//		getcounter(); 	
	});	

 
/* **************************************************************** */ 

/**
  * Проверка уникального числа
  */

getUniqueValue = function(r) {
	  var check =jQuery('#unique').attr("value") ;
	 if (  check !== undefined && check.length == 4 ){
			jQuery.ajax({
			  type: "POST",
			  url: "/cgi-bin/output/check.app",
			  data: '&rc='+r+'&in='+ jQuery('#unique').attr("value"),
			  success: function(result){
			   if(result == 1) {jQuery('#unique').removeClass("no").addClass("ok")}
			   else{jQuery('#unique').removeClass("ok").addClass("no")}
			  }
			});	 	 
		}	 
	}

 
/*
	К сожалению, стандартное поведение функции escape() при работе с русскими буквами не 
	соответствует тому, что обычно требуется для веб-приложений. Вызов escape('тест') 
	вместо %F2%E5%F1%F2 (закодированные символы в кодировке windows-1251) возвращает 
	бесполезную строку %u0442%u0435%u0441%u0442. Это можно поправить, если перед вызовом 
	escape() перевести нужные символы из Unicode в windows-1251. Следующий код заменяет 
	стандартную функцию и переводит буквы русского алфавита из Unicode в windows-1251 
	(таблицу перевода можно менять, как угодно):
*/
// Инициализируем таблицу перевода
	var trans = [];
	for (var i = 0x410; i <= 0x44F; i++)
		trans[i] = i - 0x350; // А-Яа-я
		trans[0x401] = 0xA8;    // Ё
 		trans[0x451] = 0xB8;    // ё
		trans[0x457] = 0xBF;    // ї
 		trans[0x407] = 0xAF;    // Ї
 		trans[0x456] = 0xB3;    // і
 		trans[0x406] = 0xB2;    // І
 		trans[0x454] = 0xBA;    // є
 		trans[0x404] = 0xAA;    // Є
		trans[0x218] = 0x27;    // `
		trans[0x219] = 0x27;    // ’
		trans[0x060] = 0x27;    // '
	
	// Сохраняем стандартную функцию escape()
	var escapeOrig = window.escape;
	
	// Переопределяем функцию escape()
	window.escape = function(str)
	{
	  var ret = [];
	  // Составляем массив кодов символов, попутно переводим кириллицу
	  for (var i = 0; i < str.length; i++)
	  {
	    var n = str.charCodeAt(i);
	    if (typeof trans[n] != 'undefined')
	      n = trans[n];
	    if (n <= 0xFF)
	      ret.push(n);
	  }
	  return escapeOrig(String.fromCharCode.apply(null, ret));
	}
	
/* **************************************************************** */ 

/**
  * Функция чтения значения cookie.
  */
 
function getCookie(name) {
  var prefix = name + "=";
  var cookieStartIndex = document.cookie.indexOf(prefix);
  if(cookieStartIndex == -1) return null;
  var cookieEndIndex = document.cookie.indexOf(";", cookieStartIndex + prefix.length);
  if(cookieEndIndex == -1) cookieEndIndex = document.cookie.length;
  return unescape(document.cookie.substring(cookieStartIndex + prefix.length, cookieEndIndex));
}

/* **************************************************************** */ 


/**
  * Функции чтения комментариев.
  */
	function commentload(i) {
		jQuery('#comment_'+i).slideToggle('fast',function(){ jQuery("#comment_"+i).load("/cgi-bin/output/comments/comments.app?id="+i);  });
	}
	function formload(i) { 
		jQuery('#linkloadform').slideUp('fast', function(){   jQuery('#commentform_'+i).slideDown('fast',function(){ jQuery("#commentform_"+i).load("/cgi-bin/output/comments/form.app?id="+i);  });   }); 
		
	}
	
	function formloadquote(i,n) {
		jQuery('#linkloadform').slideUp('fast', function(){ jQuery('#commentform_'+i).slideDown('fast',function(){ jQuery("#commentform_"+i).load("/cgi-bin/output/comments/form.app?id="+i , function(){jQuery("#comment").html('[ '+n+' ] : ') }   );   }); });
	}
	

/**
  * Функция счетчика
  */
//		function getcounter(){var myRandom=Math.random();var url='/cgi-bin/output/counter/counter.app?t='+myRandom;jQuery.getJSON(url,function(json){jQuery("#overall").html(data.overall);jQuery("#online").html(data.online);jQuery("#daily").html(data.daily);jQuery("#weekly").html(data.weekly);showcounter();});};function showcounter(){var to;try{clearTimeout(to);}catch(e){}to=setTimeout("getcounter()",parseInt(750000));};
 


	