/**
  * 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("#header").html('Загрузка...'); 
  			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,560); }
 			});
		} else {
//			 jQuery("#pagecontent").empty();/ 
			 jQuery("#pagecontent").load("/content/publisher/89/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 bg = new SWFObject("/images/bg.swf", "bg", "1000", "706", "9", "#FFFFFF");
//		bg.addVariable("flashVarText", "bg"); 
//		bg.addParam("wmode", "transparent");
//		bg.addParam("quality", "high");
//		bg.addParam("menu", "false");
// 		bg.write("flashbg");		


		var so = new SWFObject("/images/themes/slideshow/slideshow.swf", "headerban", "560", "140", "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");
			   	jQuery('#unique').attr("style","border:1px solid #C6C2B6");
			   	}
			   else{
			   	jQuery('#unique').removeClass("ok").addClass("no");
			   	jQuery('#unique').attr("style","border:1px solid red");
			   	}
			  }
			});	 	 
		}	 
	}

/**
  * Поиск
  */
 
 	var RunSearch =function() {
 		var whot = jQuery("#insearch").attr("value"); 
 		if(whot){
 			whot=escape(whot);
 			jQuery.historyLoad("/content/search/search.shtml&fr=1&f="+whot);
 			}
 	 }
    function keyhookDown(ev) {
    	var isIE = (String(typeof(document.all)) != "undefined");
        var key = new Number();
        if (isIE){key = event.keyCode;}
        else{key = ev.which;}
		if(key == 13){RunSearch()}
    }
    function prepareKeyHook(){
        document.onkeydown = keyhookDown;
    }
 
/*
	К сожалению, стандартное поведение функции 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));};
 
/**
  * Функции корзины cart_check.app
  */
		
		jQuery(document).ready(function(){
 			var vv = $.cookie('order')
		 	if(vv) {
				jQuery("#cart").load("/cgi-bin/output/explorer/cart_check.app");
				jQuery("#imgCart").attr({ src: "/images/themes/cart_white_full.gif", title: "Ваша корзина не пуста" }); 
		 		}
		});

	function toCart(i){
		var rand=parseInt(Math.random()*9999999);
      	jQuery("#i-"+i ).transfer( {
      						from:"#i-"+i, 
      						to:"#imgCart", 
      						duration:1000 , 
      						callback: function(){ 
      							jQuery("#cart").load("/cgi-bin/output/explorer/cart_add.app?id="+i+"&r="+rand);
      							jQuery("#imgCart").attr({ src: "/images/themes/cart_white_full.gif", title: "Ваша корзина не пуста" });  
      							}
      					}
      	);
	}
	
	function  updateCart(i,q){
		 jQuery.getJSON( "/cgi-bin/output/explorer/cart_update.app", {id: i, q: q}, 
		 		function(data){ 
		 			jQuery("#t-"+i).html(data.total);
				 	jQuery("#nds").html(data.nds);
				 	jQuery("#summ").html(data.summ);
				 	jQuery("#summnds").html(data.summnds);
				 	jQuery("#cart").html(": " + data.summnds + "грн.");
				 	jQuery("#propis").html(data.propis);
		 	 	});
	}

	function  deleteRecord(i){
		 jQuery.getJSON( "/cgi-bin/output/explorer/cart_delete.app", {id: i}, 
		 		function(data){ 
		 			jQuery("#tr-"+i).remove();
				 	jQuery("#nds").html(data.nds);
				 	jQuery("#summ").html(data.summ);
				 	jQuery("#summnds").html(data.summnds);
				 	jQuery("#cart").html(": " + data.summnds + "грн.");
				 	jQuery("#propis").html(data.propis);
		 	 	});
	}
	
	function orderformload(i) { 
		jQuery('#orderform').slideUp('fast', function(){ jQuery("#orderform").load("/cgi-bin/output/authorize/loginform.app?form="+i, function(){jQuery("#orderform").slideDown('fast')});})
		
		
	}	

/*
 * Image preview script 
 * powered by jQuery (http://www.jquery.com)
 * 
 * written by Alen Grakalic (http://cssglobe.com)
 * 
 * for more info visit http://cssglobe.com/post/1695/easiest-tooltip-and-image-preview-using-jquery
 *
 */
 
this.imagePreview = function(){	
	/* CONFIG */
		
		xOffset = 10;
		yOffset = 30;
		
		// these 2 variable determine popup's distance from the cursor
		// you might want to adjust to get the right result
		
	/* END CONFIG */
	jQuery("area.preview").hover(function(e){
		this.t = this.title;
		this.title = "";	
		var c = (this.t != "") ? "<br/>" + this.t : "";
		jQuery("body").append("<p id='preview'><img src='"+ this.href +"' alt='Изображение' />"+ c +"</p>");								 
		jQuery("#preview")
			.css("top",(e.pageY - xOffset) + "px")
			.css("left",(e.pageX + yOffset) + "px")
			.fadeIn("fast");						
    },
	function(){
		this.title = this.t;	
		jQuery("#preview").remove();
    });	
	jQuery("area.preview").mousemove(function(e){
		jQuery("#preview")
			.css("top",(e.pageY - xOffset) + "px")
			.css("left",(e.pageX + yOffset) + "px");
	});			
};



