var the_timeout = null;
var the_timeout2 = null;
var SubMenuID = '';
var SubMenuIDDisplay = '';
var BBBWindowID = '';

FleshOnLoad=false;
getMovieSel=false;
NavigatorName = navigator.appName;

function SowObject(IdObject)
{ 
	if ((the_timeout != null)&&(SubMenuID != IdObject)) {document.getElementById(SubMenuID).style.visibility='hidden';}
	clearTimeout(the_timeout);
	SubMenuID = IdObject;
    the_timeout = setTimeout("document.getElementById(" + IdObject + ").style.visibility='visible';",10);
}

function HideObject(IdObject)
{
    clearTimeout(the_timeout);
    the_timeout = setTimeout("document.getElementById(" + IdObject + ").style.visibility='hidden';",350);
}

function InlineObject(IdObject)
{
	if ((the_timeout2 != null)&&(SubMenuIDDisplay != IdObject)) {document.all.SubMenuIDDisplay.style.display='none';}
	clearTimeout(the_timeout2);
	SubMenuIDDisplay = IdObject;
    the_timeout2 = setTimeout("document.all." + IdObject + ".style.display='inline';",10);
}

function BlockObject(IdObject)
{
	if ((the_timeout2 != null)&&(SubMenuIDDisplay != IdObject)) {document.all.SubMenuIDDisplay.style.display='none';}
	clearTimeout(the_timeout2);
	SubMenuIDDisplay = IdObject;
    the_timeout2 = setTimeout("document.all." + IdObject + ".style.display='block';",10);
}
function noneObject(IdObject)
{
    clearTimeout(the_timeout2);
    the_timeout2 = setTimeout("document.all." + IdObject + ".style.display='none';",350);
}

function BBBShowWindow (IdObject)
{
    if (BBBWindowID != '') {document.all[BBBWindowID].style.display='none';}
	BBBWindowID = IdObject;
	if (navigator.appName!='Microsoft Internet Explorer') {document.all[IdObject].style.display='table';} else {document.all[IdObject].style.display='inline';}
	document.all['BBBbg'].style.display='inline';
}

function BBBClozeWindow ()
{
    document.all[BBBWindowID].style.display='none';
	document.all['BBBbg'].style.display='none';
}
	
function PopUpPos(IdObject, position)
{
    InlineObject(IdObject);
	if (window.event.clientX < (document.body.clientWidth-250))
	{
        document.all['PopUpLeft'].style.display='none';
		document.all['PopUpRight'].style.display='inline';
		document.all[IdObject].style.left = parseInt(window.event.clientX-20);
		document.all[IdObject].style.top = parseInt(window.event.clientY);
    }
	else
	{
		document.all['PopUpRight'].style.display='none';
		document.all['PopUpLeft'].style.display='inline';
		document.all[IdObject].style.left = parseInt(window.event.clientX-document.all[IdObject].width+30);
		document.all[IdObject].style.top = parseInt(window.event.clientY);
    }
	//document.all[PopUpHelpAutorName].writeln(position);
}
function checkEnter(e){ //e is event object passed from function invocation
var characterCode //literal character code will be stored in this variable

if(e && e.which){ //if which property of event object is supported (NN4)
e = e
characterCode = e.which //character code is contained in NN4's which property
}
else{
e = event
characterCode = e.keyCode //character code is contained in IE's keyCode property
}

if(characterCode == 13){ //if generated character code is equal to ascii 13 (if enter key)
//alert('enter');
return false
}
else{
return true
}

}
function checkEnterBasket (e,id){
    if(!checkEnter(e)){
        //alert('enter2');
        umiBasket.getInstance().updateCount(id,document.getElementById(id+'input').value);
        //document.getElementById(id+'span').innerHTML=document.getElementById(id+'input').value+' шт.';
    }
}
// Gallery scripts start
var 
	MoviNameT='pageflip_bbb';
	nameT='';	//variable for link file list
	the_timeout3 = null;

//dlja function pokaza okon (kak flash tak i raznih soobsheni) ja dobavil function prjatanija skrollbara okna i pokazivanija skrolbara diva
function HideDivBG()
	{
	document.all[BBBWindowID].style.visibility='hidden';
	if (NavigatorName!='Opera') {document.all[BBBWindowID].style.display='none';}
	
	document.all['BBBbg'].style.display='none';
	if (NavigatorName=='Netscape'){FleshOnLoad=false;} //kogda mozila dlja object s flash delaet displey none a posle block ili inline to on ee nachinaet avtomatom prokruchivat zanovo
	//if (navigator.appName=='Microsoft Internet Explorer') {document.body.style.overflow='auto';}
	if (navigator.userAgent.toLowerCase().indexOf('chrome')>-1) document.body.scrollTop = document.body.scrollTop+1;
		document.body.style.overflow='auto';
	}

function ShowGallery(objWin){
	/*if (navigator.appName=='Microsoft Internet Explorer') {document.body.style.overflow='hidden';}*/
	BBBWindowID=objWin.id;
	document.all['BBBbg'].style.display='block';
	/*if (NavigatorName!='Microsoft Internet Explorer')
		{objWin.style.display='table';}
			else
		{objWin.style.display='block';}*/
	objWin.style.display='block';
	clearTimeout(the_timeout3);
	//the_timeout3 = setTimeout(objWin.id+".style.visibility='visible';",5);
	objWin.style.visibility='visible';
	//if (objWin.getElementsByTagName('input')[0]) objWin.getElementsByTagName('input')[0].focus();
	document.body.style.overflow='hidden';
	}

function FlipOnLoad() {FleshOnLoad=true;} //kogda flash nachal podgrugatsa, useru ona ob etom soobshaet
	
function getMovie(MoviName) {
    	var M$ =  navigator.appName.indexOf("Microsoft")!=-1;
    	return (M$ ? window : document)[MoviName];
	}
	
function LoadVarInFlash() {
	
	if (FleshOnLoad==false)
		{clearTimeout(the_timeout2);
		the_timeout2 = setTimeout("LoadVarInFlash();",100);
		}
		else
		{
	movie = getMovie(MoviNameT);
	movie.SetVariable("_root.NameOfGallery", nameT);}
}
	
function SetFlashVariable(objWin,name) {
	ShowGallery(objWin);
	nameT=name;
	LoadVarInFlash();
}

//Konec scriptov dlja gallerei

//Nachalo scripta podskazok

window.onload=function(){
		findAutotPopUp ('AutorsRightBlock');
		MakeOnFocus ();
		};

function findAutotPopUp (ConteinerName){	
	var imgs,i;
		// poluchaem array of spans v object 
		//imgs=document.getElementsByTagName('img');
	
	if (document.getElementById(ConteinerName))
		{
	
 		imgs=document.getElementById(ConteinerName).getElementsByTagName('span');
		//vsem spanam naznachaem sobitie onOver i onOut (eti sobitija pokazivajut ili prjachut pervi div v spane)
 		for(i=0;i<imgs.length;i++)
 			{
		   imgs[i].onmouseover = function(){getBounds(this.getElementsByTagName('div')[0]);};
		   //imgs[i].getElementsByTagName('div')[0].onmouseover=function(){getBounds(this);};
		   
		  imgs[i].onmouseout = function(){HideBounds(this.getElementsByTagName('div')[0]);};
		   //imgs[i].onmouseout=function(){roll(this);};
		 }
		 }
	}
//prjachem element
function HideBounds(element)
	{element.style.display='none';
	document.getElementById("ArrowPopUp").style.display='none';
	}
//poluchaem koordinati elementa
function PositionBounds (element)
	{
  var left = element.offsetLeft;
  var top = element.offsetTop;
  
  for (var parent = element.offsetParent; parent; parent = parent.offsetParent)
  {
    left += parent.offsetLeft - parent.scrollLeft;
    top += parent.offsetTop - parent.scrollTop;
  }
  return {left: left, top: top, width: element.offsetWidth, height: element.offsetHeight};
  }

//pokazivaem element i pozicioniruem ego. Takge pozicioniruem strelku i naznachaem ei razmer ravhi shirine div
function getBounds(element)
{	
	element.style.display='block';
	ArrowT = document.getElementById("ArrowPopUp");
	
	var TPosBound = PositionBounds(element.parentNode);

	element.style.marginLeft = -(element.offsetWidth-TPosBound.width/4*3);
	element.style.marginTop = parseInt(TPosBound.height)-5;
	
	ArrowT.style.display='block';
	
	ArrowT.onmouseout = function(){HideBounds(element);};
	ArrowT.onmouseover = function(){getBounds(element);};
	
	ArrowT.style.width = element.offsetWidth;
	ArrowT.style.top=PositionBounds(element).top - ArrowT.offsetHeight + document.body.scrollTop;
	
	/*esli ukazani borderi, a u odnogo stoit none to IE i Hrome neschitajut ego, a Fox i Opera 
	vseravno schitajut pri poluchenii shirini object poetomu ja smotrju esli ne IE i esli ne Hrome 
	(navigator.userAgent.toLowerCase().indexOf('chrome')<0) to dobavljaju odin px*/
	if (NavigatorName!='Microsoft Internet Explorer')
		{ArrowT.style.top=parseInt(ArrowT.style.top)+1;}
	if (navigator.userAgent.toLowerCase().indexOf('chrome')>-1){ArrowT.style.top=parseInt(ArrowT.style.top)-1;}
	
	ArrowT.style.left=PositionBounds (element).left+document.body.scrollLeft;

/*tm=TPosBound.left+element.offsetWidth+TPosBound.width/3;
bm=document.body.clientWidth+document.body.scrollLeft;

if (bm<tm)
	{
	element.style.marginLeft = -(element.offsetWidth-TPosBound.width/3*4);
	element.style.marginTop = parseInt(TPosBound.height);
	}
	else
	{
	element.style.marginLeft = -TPosBound.width/3;
	element.style.marginTop = parseInt(TPosBound.height);
	}*/
}
	
//Konec script of help

//start of input action

var InputFocus = function(){
		t=this;
			if (!t.ChengeForm) {
			//if ($(this).hasClass('inputNone')==false) this.value = '';
		   	//this.style.color= '#222222';
			//this.style.fontStyle='normal';
			$(this).addClass('Act');
			}
			if ($(this).hasClass('inputNone')==false) $(this).attr({style: 'border: 1px solid #b70900'});
			if (this.nodeName=='INPUT') {this.select();} //esli pole input to videljaem ves text
		};
var InputBlur = function(){
			if (!this.ChengeForm) {
			//this.value = this.getAttribute('TValue');//esli v pole do etogo bilo nekoe znachenie to v sluchae esli pole neizmeneno ili pustoe to znachenie vozvrashaetsa
		   	/*this.style.color= '#adadad';
			this.style.fontStyle='italic';*/
			if (this.nodeName=='INPUT') $(this).removeClass('Act');
			}
			$(this).removeAttr("style");
			//this.style.border='1px solid #4c4c4c';
		};
var InputChenge = function(){
			if (this.value == '')
			{this.ChengeForm=false;}
			else
			{this.ChengeForm=true;
			if (this.nodeName=='INPUT') $(this).removeAttr("style");
			//this.style.border='1px solid #4c4c4c';
			}
		};
		
var ItnutNumber = function(){
	e=event;
	var e = ( e.keyCode || e.charCode );
	return /[\d]/.test(String.fromCharCode(e));};
	
var ItnutLat = function(){
	e=event;
	//var reg_exp = /^[a-z][\w\.]*@[\w\.]+\.[a-z]{2,4}/i;
	// esli v konstrukcii /[\ ]/ napisat 'w' to eto proverka na lat bukvi esli 'd' to na cifry
	var e = ( e.keyCode || e.charCode );
    //var result = false
	//proverjaem simvoli dlja e-mail    
	return /[\w\@\.\-]/.test(String.fromCharCode(e));
	
	//alert(test(String.fromCharCode(e)));
    //if(/[\w]/.test(String.fromCharCode(e))){result = true;}
    //return result;
	};


function MakeOnFocus (name){
	imgs=document.getElementsByTagName('input');
 		for(i=0;i<imgs.length;i++)
 			{
		   if (imgs[i].type=='text' || imgs[i].type=='password')
		   {	
		   		imgs[i].setAttribute('ChengeForm', false);
				imgs[i].setAttribute('TValue', imgs[i].value);
				SetFormAttribute (imgs[i]);
				if (imgs[i].id=="Number") imgs[i].onkeypress = ItnutNumber;
				if (imgs[i].id=="LatSybm") imgs[i].onkeypress = ItnutLat;
		   }
		 }
		
	imgs=document.getElementsByTagName('textarea');
 		for(i=0;i<imgs.length;i++)
 			{
		   		imgs[i].setAttribute('ChengeForm', false);
				imgs[i].setAttribute('TValue', imgs[i].value);
				SetFormAttribute(imgs[i]);
		 }
	}		
	
function SetFormAttribute (name){
	name.onmouseup = InputFocus;			
	name.onblur = InputBlur;
	name.onkeyup = InputChenge;
	}
	
/*function ChengeTypeP (name)
	{tElem = document.getElementsByName(name)[0];
	if (tElem.type=='text')
		{	tVal = this.value;
			tElem.setAttribute('type', 'password');
			this.value = tVal;}
		else
		{tVal = this.value;
		tElem.setAttribute('type', 'text');
		this.value = tVal;}
	}*/
	
//end of input action


// begin of hideShow obj
function hideShowID(element)
	{ element = document.getElementById(element);
	if( element.style.display == 'block' ){
            element.style.display = 'none';
        }else{
            element.style.display = 'block';
			element.getElementsByTagName('input')[0].focus();
        }
		return false;
	}

function hideShowSpan( name ){
	tElem = name.parentNode.getElementsByTagName('span')[1];
	tElemDots = name.parentNode.getElementsByTagName('span')[0];
	if ( tElem.style.display == 'inline' ){
			name.className = 'ListPlus2';
            tElem.style.display = 'none';
			tElemDots.style.display = 'inline';}
		else
			{
			name.className = 'ListMinus2';
            tElem.style.display = 'inline';
			tElemDots.style.display = 'none';
        }
		return false;
	}
// className
/*	eta funkcija pozvoljaet vvodit toka cifry
	
	inputName.onKeyPress = function(e){
    var result = false
    if(/[\d]/.test(String.fromCharCode(e.charCode ? e.charCode : e.keyCode))){result = true}
    return result;
}*/
// end of  of hideShow obj

//begin of TableSort
/*
* jQuery TinySort 1.0.2
* Copyright (c) 2008 Ron Valstar
* Dual licensed under the MIT and GPL licenses:
*   http://www.opensource.org/licenses/mit-license.php
*   http://www.gnu.org/licenses/gpl.html
*/
(function(B){B.tinysort={id:"TinySort",version:"1.0.2",defaults:{order:"asc",attr:"",place:"start",returns:false}};B.fn.extend({tinysort:function(H,I){if(H&&typeof (H)!="string"){I=H;H=null}var E=B.extend({},B.tinysort.defaults,I);var O={};this.each(function(S){var U=(!H||H=="")?B(this):B(this).find(H);var T=E.order=="rand"?""+Math.random():(E.attr==""?U.text():U.attr(E.attr));var R=B(this).parent();if(!O[R]){O[R]={s:[],n:[]}}if(U.length>0){O[R].s.push({s:T,e:B(this),n:S})}else{O[R].n.push({e:B(this),n:S})}});for(var G in O){var D=O[G];D.s.sort(function J(T,S){var R=T.s.toLowerCase?T.s.toLowerCase():T.s;var U=S.s.toLowerCase?S.s.toLowerCase():S.s;if(C(T.s)&&C(S.s)){R=parseFloat(T.s);U=parseFloat(S.s)}return(E.order=="asc"?1:-1)*(R<U?-1:(R>U?1:0))})}var L=[];for(var G in O){var D=O[G];var M=[];var F=B(this).length;switch(E.place){case"first":B.each(D.s,function(R,S){F=Math.min(F,S.n)});break;case"org":B.each(D.s,function(R,S){M.push(S.n)});break;case"end":F=D.n.length;break;default:F=0}var P=[0,0];for(var K=0;K<B(this).length;K++){var N=K>=F&&K<F+D.s.length;if(A(M,K)){N=true}var Q=(N?D.s:D.n)[P[N?0:1]].e;Q.parent().append(Q);if(N||!E.returns){L.push(Q.get(0))}P[N?0:1]++}}return this.setArray(L)}});function C(D){return/^[\+-]?\d*\.?\d*$/.exec(D)}function A(E,F){var D=false;B.each(E,function(H,G){if(!D){D=G==F}});return D}B.fn.TinySort=B.fn.Tinysort=B.fn.tsort=B.fn.tinysort})(jQuery);
//end of table sort

//begin of selectors
$(document).ready(function(){

	var TempPosBook = FirstPosBook = $(".BBBLeftBlock a.book");

	$("#book-header span").hover(function(){$(this).stop().find('ul').show();},function(){$(this).find('ul').hide();});
			
		$("#book-header span ul a").click(function() {
			var TcurentMen=$(this).parent().parent().find('b:first');
			$(TcurentMen).replaceWith($(TcurentMen).text());
			$(this).parent().parent().parent().find('b:first').html($(this).text());
			$(this).wrapInner("<b></b>");
			
			if ($(this).parent().parent().parent().attr('id') == "BookFilter") {
				switch ($(this).text()) {
					case "гуру": $("#BookSortCont a.book").hide().filter(":has(.Guru)").show();break;
					case "готовящиеся к печати": $("#BookSortCont a.book").hide().filter(":has(.Next)").show();break;
					case "новые": $("#BookSortCont a.book").hide().filter(":has(.New)").show();break;
					case "все": $("#BookSortCont a.book").hide().filter(".book").show();break;
					default: $("#BookSortCont a.book").hide().filter("." + $(this).text().toLowerCase()).show();break;
					}
				}
			
			if ($(this).parent().parent().parent().attr('id') == "BookSorter") {
				TcurentMen = $(this).parent().parent().parent();
				
				switch ($(this).text()) {
					case "дате издания": BBBSortFunct(0, "h2",TcurentMen,true);break;
					//case "дате издания": BBBSortFunct(0, FirstPosBook,TcurentMen);break;
					case "автору": BBBSortFunct(1, "h3",TcurentMen);break;
					case "названию": BBBSortFunct(2, "h2",TcurentMen);break;
					}
				}
			return false;
		});//click
		
		$("#send-email").click(function() {
            var complete = true;
            $("input[id^='email_']").each(function() {
                if(!$(this).val() || ($(this).attr('id')=='email_from' && $(this).val() == "Введите ваш E-mail")) {
                    complete = false;
                    $(this).parents("tr:first").children("th").css("color","#B70900");
                }
                else {
                    $(this).parents("tr:first").children("th").css("color","#000");
                }
                    
            });
            if(!complete) {
                $("#send_mail_error").show().html("<p style='color: #B70900;'>Все поля обязательны для заполнения</p>");
            }
            else {
                $("#send_mail_error").hide();
                var response =  $.ajax({
                        type: "POST",
                        url: "/webforms/post",
                        data: "email_to="+$('#email_to').val()+
                                "&data[fname]="+$("#email_from_name").val()+
                                "&data[email_from]="+$("#email_from").val()+
                                "&data[subject]="+$("#email_subject").val()+
                                "&message="+$("#email_message").val()+
                                "&email_captcha="+$("#email_captcha").val(),
                        async: false,
                        complete: function(){
                            //alert( "Data Saved: ");
                            $("#BBBbg").css("z-index",'200');
                            $("#ajaxImg").hide();   					
                        },
                        error: function(){
                            $("#changePassErr").show().html('Ошибка получения данных, свяжитесь с администрацией сайта.');
                        }
                }).responseText;
                //alert(response);
                var m = $(response).text();

                /*var re = /[OE][KR]R?O?R?/gm;
                var m = re.exec(response);*/
                if (m == null) {
                    $("#info_window_textcell").text("Ошибка отправки сообщения #1 ");
                } else {
                    if (m == "OK") {
                        $("#info_window_textcell").text("Ваше сообщение успешно отправлено. ");
                    }
                    else {
                        $("#info_window_textcell").text("Ошибка отправки сообщения #2");
                    }
                }
                HideDivBG();
                ShowGallery(BBBInfo);
            }
		});
});

var	aAsc=["desc"];
	tts	=false;
function BBBSortFunct(ts,t,tc,ta)
	{	//aAsc[ts] = aAsc=="asc"?"desc":"asc";
		if(tts!=ts)aAsc=["desc"];
		tts=ts;
		if ((aAsc[ts] == "asc"))
			{$(tc).find('b:first').removeClass().addClass("FilterTitleLinkMinD");
			aAsc[ts] = "desc";}
			else
			{$(tc).find('b:first').removeClass().addClass("FilterTitleLinkMinU");
			aAsc[ts] = "asc";}
		
	if (!ta) $(FirstPosBook).tsort(t,{order:aAsc[ts]}); else $(FirstPosBook).tsort(t,{attr:"class", order:aAsc[ts]});}	

//end of selectors


function checkRegisterForm(form,pass1,pass2,elemError,elemEmail,elemLogin,elemMindedId) {
	if(pass1 != pass2) {
		$(elemError).show().html("Введёные пароли не совпадают!");		
		return false;
	}
	else {
		if(pass1.length < 3) {
			$(elemError).show().html("Слишком короткий пароль. Пароль должен состоять не менее, чем из 3х символов.");
			return false;			
		}
		if( ! $("#"+elemMindedId+":checked").length) {
			$(elemError).show().html("Регистрация не может быть продолжена без получения Вашего согласия на обработку Ваших персональных данных в соответствие с п.1 статьи 6 Федерального Закона №152-ФЗ 'О персональных данных'.");
			return false;
		}
		$(elemEmail).val($(elemLogin).val());
		saveFormData(form);
		return true;
	}	
}