var placeholders_supported = ('placeholder' in document.createElement('input'));

function SMSStickerClose() {
  try {document.body.removeChild(__el('error_overlay'))} catch (err){}
	try {
  __el('master_page_div').removeChild(__el('sms_sticker'));
	} catch (err){}
}

function OpenPassToggle(prefix) {
	var passopen=document.getElementById('show_pass'+prefix).checked;
	var opwf=document.getElementById('open_pwd'+prefix);
	var cpwf=document.getElementById('pwd'+prefix);

	if(passopen) {
		opwf.value=cpwf.value;
	} else {
		cpwf.value=opwf.value;
	}

	cpwf.style.display=passopen?'none':'inline';
	opwf.style.display=passopen?'inline':'none';
}

Function.prototype.bind = function(object) {
    var method = this
    return function() {
        return method.apply(object, arguments)
    }
}

function getCSSRule(ruleName) {
  ruleName=ruleName.toLowerCase();
  if (document.styleSheets) {
    for (var i=0; i<document.styleSheets.length; i++) {
      var styleSheet=document.styleSheets[i];
      var ii=0;
      var cssRule=false;
      do {
        if (styleSheet.cssRules) {
          cssRule = styleSheet.cssRules[ii];
        } else if (styleSheet.rules) {
          cssRule = styleSheet.rules[ii];
        }
        if (cssRule && cssRule.selectorText)  {
          if (cssRule.selectorText.toLowerCase()==ruleName) {
            return cssRule;
          }
        }
        ii++;
      } while (cssRule)
    }
  }
  return false;
}

function cloneCSSRule(selector,doc){
	if (!doc) doc = document;
	var sheet = doc.styleSheets[0];
	var cr = getCSSRule(selector);
	if (sheet && cr && cr.style){
		if (sheet.insertRule) {        // Firefox, Google Chrome, Safari, Opera
			if (cr.cssText) sheet.insertRule(cr.cssText, 0);
		} else {
			for (var r in cr.style){
				if (r == 'cssText') continue;
				if (cr.style[r] != '') {
					var rr = r.replace(/[A-Z]/g,function(s){return '-'+s.toLowerCase()});
					if (sheet.addRule) {        //Internet Explorer
						var rs = cr.style[r];
						if (/(error_sticker|error_overlay)$/.test(selector)){
							if (rr == 'position') rs = 'absolute';
							if (rr == 'top') rs = 'expression(ignoreMe = document.documentElement.scrollTop + "px")';
						}
						sheet.addRule (selector, rr+':'+rs, 0);
					}
				}
			}
		}
	}
}

function ClosePopOffersForm() {
	SMSStickerClose();
	var curr_date = new Date();
	GUJ.PutRequest({
		url: '/pages/ajax_epmty/',
		params: { action:'set_subscr_reminder', utc_offset_min: -curr_date.getTimezoneOffset(), rand:Math.random() }
	});
	return false;
}


var CustomAlertBox = function() {
  this.visible=false;
  this.msgs=new Array();
  this.tmp_eval=Array();

  this.errorSticker=document.createElement('div');
  this.errorSticker.className="error_sticker";
  this.errorSticker.innerHTML='<div class="err_title">Сообщение</div>';

  this.errorStickerText=document.createElement('p');
  this.errorStickerText.className="err_text";
  this.errorSticker.appendChild(this.errorStickerText);

  this.errorStickerButtons = Array();

	for(var i=0;i<3;i++) {
    this.errorStickerButtons[i]=document.createElement('input');
    this.errorStickerButtons[i].type='button';
    this.errorStickerButtons[i].className='coolbutn';
	}

  this.errorStickerButtons[0].value='OK';
  this.errorStickerButtons[0].style.width='70px';
  this.errorStickerButtons[0].onclick=this.evalclose.bind(this);

  this.errorStickerButtons[1].value='';
  this.errorStickerButtons[1].style.marginLeft='10px';
  this.errorStickerButtons[1].style.display='none';
  this.errorStickerButtons[1].onclick=this.evalclose2.bind(this);

  this.errorStickerButtons[2].value='Отмена';
  this.errorStickerButtons[2].style.width='70px';
  this.errorStickerButtons[2].style.marginLeft='10px';
  this.errorStickerButtons[2].onclick=this.close.bind(this);

  this.errorSticker.appendChild(this.errorStickerButtons[0]);
  this.errorSticker.appendChild(this.errorStickerButtons[1]);
  this.errorSticker.appendChild(this.errorStickerButtons[2]);

  this.errorOverlay=document.createElement('div');
  this.errorOverlay.className="error_overlay";
}

CustomAlertBox.prototype.close = function () {
	var doc = top.document || document;
  doc.body.removeChild(this.errorSticker);
  doc.body.removeChild(this.errorOverlay);
  this.visible=false;
  this.errorStickerButtons[1].style.display='none';
  if(this.msgs.length>0) { this.show(); }
}

CustomAlertBox.prototype.evalclose = function () {
  if(typeof(this.tmp_eval[0]) != 'undefined') this.tmp_eval[0]();
  this.close();
}

CustomAlertBox.prototype.evalclose2 = function () {
  if(typeof(this.tmp_eval[1]) != 'undefined') this.tmp_eval[1]();
  this.close();
}


var AddStylesToTop = [
		'.coolbutn',
		'input.coolbutn',
		'.error_overlay',
		'.error_sticker',
		'.err_text',
		'.err_title',
		'.error_sticker .err_text',
		'.error_sticker .coolbutn'
];

CustomAlertBox.prototype.show = function () {
  var str=this.msgs.shift();
	var doc = top.document || document;
  this.visible=true;
  if(str.constructor.toString().indexOf("Array") == -1) {
    this.errorStickerButtons[2].style.display='none';
    this.tmp_eval[0]=undefined;
  } else {
    this.errorStickerButtons[2].style.display='inline';
    this.tmp_eval[0]=str[1];
    if(typeof(str[2])!='undefined') {
      this.tmp_eval[1]=str[2];
    }
    str=str[0];
  }

  this.errorStickerText.innerHTML=str;
	if (doc !== document && !doc.cssAdded){
		for (var i=0; i<AddStylesToTop.length; i++){
			cloneCSSRule(AddStylesToTop[i],doc);
		}
		top.document.cssAdded = true;
	}
  doc.body.appendChild(this.errorOverlay);
  doc.body.appendChild(this.errorSticker);
}

CustomAlertBox.prototype.alert = function (str,confirm,confirm2) {
  str=str.toString().replace(/\n/g,'<br />');
  if(typeof(confirm) != 'undefined') {
    if(typeof(confirm2) != 'undefined') {
      this.msgs.push(new Array(str,confirm,confirm2));
    } else
      this.msgs.push(new Array(str,confirm));
  }
  else
    this.msgs.push(str);
  if(!this.visible) { this.show(); }

}

function LoginRegisterCancel(msg){
	alertBox.errorStickerButtons[0].value='Войти';
	alertBox.errorStickerButtons[1].value='Зарегистрироваться';
	alertBox.errorStickerButtons[1].style.display='inline';
	alertBox.errorStickerButtons[1].style.width='150px';
	alertBox.alert(msg,function logexec() {
		window.location.href='/pages/login/';
	},function regexec() {
		window.location.href='/pages/registration/';
	});
}

var alertBox= new CustomAlertBox();

if (top.document === document || !/(MSIE)\s+6\D+/i.test(navigator.userAgent)){
	window.alert = function(str) {
		alertBox.errorStickerButtons[0].value='OK';
		alertBox.alert(str);
	};
}

function SpoilerSaveState(nodeId, state) {
	var exdate = new Date();
	exdate.setDate(exdate.getDate() + 180);
	document.cookie = "spoiler_" + nodeId + "=" + escape(state) +
		";expires=" + exdate.toUTCString() + ";path=/";
}

function ExpandNode(nodeId, dspl) {

  dspl = dspl ? dspl : 'block';

  clickedElement=document.getElementById(nodeId).style;
	titNodeId = nodeId+'_title';

  if (!clickedElement)
    clickedElement=document.all.nodeId.style
  if (!clickedElement)
    return 1
  if (clickedElement.display == dspl){
    clickedElement.display="none";
		$('#'+titNodeId).removeClass(titNodeId + '_expanded').addClass(titNodeId + '_collapsed');
    if (document.getElementById('img_'+nodeId))
      document.getElementById('img_'+nodeId).src=document.getElementById('img_'+nodeId).src.replace('minus.gif',"plus.gif");
    state = 0;
  } else {
    if ((currentExpanded) && (collapsePrevious))
      currentExpanded.display = "none";
    currentExpanded=clickedElement;
    currentExpanded.display = dspl;
		$('#'+titNodeId).removeClass(titNodeId + '_collapsed').addClass(titNodeId + '_expanded');
    if (document.getElementById('img_'+nodeId))
    	document.getElementById('img_'+nodeId).src=document.getElementById('img_'+nodeId).src.replace("plus.gif",'minus.gif');
    state = 1;
  }
  if ($('#'+titNodeId).hasClass('persist_spoiler'))
	  SpoilerSaveState(nodeId, state);
  ToggledAlready=1;
}

function PurchaseBasket(User,HasMoney,CustomSet) {
	var PriceTotal = $('#total_qbasket_summ').text();
	PriceTotal = PriceTotal.replace(',','.');
	var NeedMoney = Math.ceil(PriceTotal * 1 - HasMoney);

	if (NeedMoney > 0) {
		if(NeedMoney<10) NeedMoney=10;
		var href = '/pages/put_money_on_account/?summ='+NeedMoney;
		var ref_url = '/pages/my_books/?action=do_order';
		if (CustomSet) ref_url += '&custom_set='+CustomSet;
		href += '&ref_url='+encodeURIComponent(ref_url);
		window.location.href = href;
		return;
	}

	var CMess=ConfirmPay1+RubPrice(PriceTotal)+ConfirmPay2+OneClickBasketBuyConfirm+ConfirmPay3;
	var CFunc = function exec() {
		var href = '/pages/my_books/?action=do_order';
		if (CustomSet) href += '&custom_set='+CustomSet;
		document.location.href=href;
	}
	alertBox.errorStickerButtons[0].value='OK';
	alertBox.alert(CMess,CFunc);
}

function TrendyWarnQuickBuy(Obj,Summ,PreOrder,Art,User,Price){
	var c_lass = Obj.className;
	var matches = c_lass.match(/free_get/); // free book download (gifts) class
	if (matches == null) {
		var Descr = 'Cразу после этого вы сможете скачивать эту книгу. ';
		if (PreOrder == 2){
			Descr = 'Сразу после этого вы сможете продолжить чтение. ';
		} else if (PreOrder){
			Descr = 'Сразу после этого ваш предзаказ будет принят и помещен в «Мои книги». ';
		}
		var CMess = ConfirmPay1+RubPrice(Summ)+ConfirmPay2+Descr+ConfirmPay3;
		var CFunc = function exec() {
			top.window.location.href=Obj.getAttribute('href');
		};
		// кто победит IE 6 в top.document.appendChild, дам конфетку
		if (top.document === document || !/(MSIE)\s+6\D+/i.test(navigator.userAgent)){
			alertBox.errorStickerButtons[0].value='OK';
			alertBox.alert(CMess,CFunc);
		} else if (confirm(CMess)) CFunc();
	}
	if ( $.browser.msie ) { event.returnValue=false; }
	return false;
}

function TrendyWarnGift(Obj,Art){
	var CMess = 'Cразу после этого у вас спишется 1 подарок и Вы сможете скачивать эту книгу.';
	var CFunc = function exec() {
		top.window.location.href=Obj.getAttribute('href');
	};
	// кто победит IE 6 в top.document.appendChild, дам конфетку
	if (top.document === document || !/(MSIE)\s+6\D+/i.test(navigator.userAgent)){
		alertBox.errorStickerButtons[0].value='OK';
		alertBox.alert(CMess,CFunc);
	} else if (confirm(CMess)) CFunc();
	return false;
}


var MetaCash = new Object;
function getMetaContents(mn){
	if (MetaCash[mn]) return MetaCash[mn];
	var m = document.getElementsByTagName('meta');
	for(var i in m){
		if (!MetaCash[mn]) MetaCash[mn] = m[i].content;
		if(m[i].name == mn) return m[i].content;
	}
	return '';
}

function decOfNum(number, titles)
{
    cases = [2, 0, 1, 1, 1, 2];
		number = number % 100 > 4 && number % 100 < 20 ? 2 : cases[Math.min(number % 10, 5)];
    return titles[number];
}

BodyEndFunc.push({'extinputs_init': function(){
/*default ref_url */
def_ref_url=$('#login-bubble input[name=ref_url]').val();
	$(".ext-input").wrap('<span class="ext-input-wrap" />');
	$(".ext-button").each(function(){
		var wrap=$('<span class="ext-button-wrap" />');
		if ($(this).is('.ext-button-green')) wrap.addClass('ext-button-wrap-green');
		if ($(this).is('.ext-button-gray')) wrap.addClass('ext-button-wrap-gray');
		$(this).wrap(wrap);
	});
	if(!placeholders_supported) {
		$(':input[placeholder]').each(function(){
			$(this).placeholder();
		});
	}
	$("input.inum").bind('keydown',function(event) {
		if( event.keyCode != 46 && event.keyCode != 8 && event.keyCode != 9 && event.keyCode != 37 && event.keyCode != 39 &&
			  (event.keyCode < 48 || (event.keyCode > 57 && event.keyCode < 96) || event.keyCode > 105) ) {
			event.preventDefault();
		}
	});
	$("#login-link, #login-link-car").overlay({
		fixed:false,
		effect: 'apple',
		speed:100,
		onClose: function() {
			$("#loginfailblock").hide();
			$("#div-quick-reg").hide();
			$("#div-quick-login").show();
			$('#login-link input[name=ref_url]').val(def_ref_url);
			$.mask.close();
		},
		onLoad:function() {
			$(document).mask({
				color: '#000',
				loadSpeed: 200,
				opacity: 0.7,
				onBeforeClose: function() {
					$("#login-link").data("overlay").close();
					$('#login-bubble input[name=ref_url]').val(def_ref_url);
					if (document.getElementById('login-link-car')) $("#login-link-car").data("overlay").close();
				}
			});
			if (!SocNet.services.fb) SocNet.push('fb',{InitCall: true});
			if (!SocNet.services.vk) SocNet.push('vk',{InitCall: true});
			if (!SocNet.services.mr) SocNet.push('mr',{InitCall: true});
		}
	});
	/*,  */
	if (document.getElementById('download_drm1')){
	$("#download_drm1").overlay({
		fixed:false,
		effect: 'apple',
		speed:100,
		onClose: function() {$.mask.close();},
		onLoad:function() {
			$(document).mask({
				color: '#000',
				loadSpeed: 200,
				opacity: 0.7,
				onBeforeClose: function() {
					$("#download_drm1").data("overlay").close();
				}
			});
		}
	});}
	if (document.getElementById('en_drm')){
	$("#en_drm").overlay({
		fixed:false,
		effect: 'apple',
		speed:100,
		onClose: function() {$.mask.close();},
		onLoad:function() {
			$(document).mask({
				color: '#000',
				loadSpeed: 200,
				opacity: 0.7,
				onBeforeClose: function() {
					$("#en_drm").data("overlay").close();
				}
			});
		}
	});}
	if (document.getElementById('lock_mini_drm')){
	$("#lock_mini_drm").overlay({
		fixed:false,
		effect: 'apple',
		speed:100,
		onClose: function() {$.mask.close();},
		onLoad:function() {
			$(document).mask({
				color: '#000',
				loadSpeed: 200,
				opacity: 0.7,
				onBeforeClose: function() {
					$("#lock_mini_drm").data("overlay").close();
				}
			});
		}
	});}

	/* readers main page */
	$('.filter_links > td > a').click(function(){
		$('#min_price').val("");
		$('#max_price').val("");
		if ($(this).index() == 0) $('#max_price').val('3000');
		else if ($(this).index() == 1) { $('#min_price').val('3000'); $('#max_price').val('5000'); }
		else if ($(this).index() == 2) $('#min_price').val('5000');
	});
	
	/* buy free books */
	var free_data, free_price;
	$('a.free_get').click(function(){
		$('#hg-pop-tooltip').addClass('free_book_get');
		free_data = stars_data[$(this).attr('rel')];
		free_price = $(this).parents('.book_info').children('.nb_price').children('.simple_price').html();
		$('#hg-pop-tooltip').css({left:$(this).offset().left-79,top:$(this).offset().top+10}).show();
		if (free_price == null) {
			free_price = $('.book_descr_links').children('.td').children('.simple_price').html();
			$('#hg-pop-tooltip').css({left:$(this).offset().left-15,top:$(this).offset().top+40}).show();
		}
		var free_amount_text = ["книгу", "книги", "книг"][free_data.free_amount%10 == 1 && free_data.free_amount%100 != 11 ? 0 : free_data.free_amount%10 >= 2 && free_data.free_amount%10 <= 4 
			&& (free_data.free_amount%100 < 10 || free_data.free_amount%100 >= 20) ? 1 : 2];
		$('#hg-pop-tooltip .close').show();
		$('#hg-content').html('<div id="free-download">'+
				'<a href="'+free_data.href2+'" class="coolbtn pay_now_btn"><span class="cb1"><span class="cb2"><span class="value">Скачать бесплатно</span></span></span></a>'+
				'<p class="free-d-text'+(free_data.free_amount>99?" free_alt":"")+'"><span>'+free_data.free_amount+'</span>'+free_amount_text+' еще можно<br/>скачать бесплатно</p>'+
				'<p class="free-d-text2">Не хотите по подписке?</p>'+
				'<a href="'+$(this).attr('href')+'" onclick="'+$(this).attr('onclick')+'" class="buy-book">Купить за '+free_price+'</a>'+
			'</div>');
		$('#hg-overlay').show();
		return false;
	});

	/* stars */
	var art, tooltip, mark, i;
	genstars = function(t, mark) {
		t.html("");
		art = stars_data['a_'+t.attr('id')];
		if (mark) {
			art.votes[mark-1]++;
			if (art.voted) art.votes[art.voted-1]--;
			else art.vote_amount++;
			if (art.mid_vote == 0 && art.vote_amount == 1) art.mid_vote = mark;
			else {
				var tmp = 0;
				for(i=1;i<=5;i++) tmp += art.votes[i-1]*i;
				art.mid_vote = (tmp/art.vote_amount).toFixed(2);
			}
			art.voted = mark;
		}
		var tmp2 = art.mid_vote;
		tmp2 = tmp2.toString().substr(2);
		tmp2 = tmp2.length == 1?tmp2+'0':tmp2;
		for(i=1;i<=5;i++) {
			var a_class = "";
			if (art.mid_vote < i && art.mid_vote > i-1 && tmp2 >= 26 && tmp2 <= 75) a_class = " voted-half";
			else if ((art.mid_vote >= i && ((art.voted > 0 && art.vote_amount > 1) || (art.voted == 0 && art.vote_amount > 0))) ||
				(art.voted >=i && art.vote_amount == 1) ||
				(art.mid_vote < i && art.mid_vote > i-1 && tmp2 >= 76)) a_class = " voted";
			t.append('<a href="javascript:void(0);" class="star'+a_class+'" id="'+i+'"><span></span></a>');
		}
		if (!t.hasClass('bigstars')) t.children('a:last').css("padding-right", "4px");
	};

	// $('.stars_book').each(function() {
		// stars_data[stars_data.length]=this.a
	// });
	$('.stars_book').each(function() {
		genstars($(this));
	});

	$('.stars_book a').live('click', function() {
		var parent = $(this).parent();
		var id = parent.attr('id');
		art = stars_data['a_'+id];
		mark = $(this).attr('id');
		if (art.logined == 0) {
			$("#loginfailblock").html('Для того чтобы поставить оценку Вы должны авторизоваться').show();
			$("#login-link").data("overlay").load();
			$('input[name=ref_url]').val($('input[name=ref_url]').val() + ($('input[name=ref_url]').val().match("/\?/")?'':'?')+'action=votestars&vart='+id+'&mark='+mark+'&rand='+Math.random());
			return false;
		} else {
			if (mark != art.voted) {
				if (mark >= 1 || mark <= 5 || id) {
					var Request = {
						url: '/pages/ajax_epmty/',
						OnData:function(Data) {
							if (Data == 'ok') {
								genstars(parent, mark);
							} else if (/already_voted/.test(Data[0])) alert("Вы уже голосовали за это произведение.");
							else alert("Произошла ошибка: "+Data[0]);
						},
						params: {action:'votestars', vart:id, mark:mark, rand:Math.random()}
					};
					GUJ.PutRequest(Request);
				}
			} else return false;
		}
	});

	$('.stars_book a').live('mouseenter', function() {
		$("#hg-pop_close").hide();
		$(this).prevAll().andSelf().addClass('star-hover');
		var parent = $(this).parent();
		art = stars_data['a_'+parent.attr('id')];
		var max_vote = Math.max.apply(null, art.votes);
		var vote_amount_text = ["оценка", "оценки", "оценок"][art.vote_amount%10 == 1 && art.vote_amount%100 != 11 ? 0 : art.vote_amount%10 >= 2 && art.vote_amount%10 <= 4 && (art.vote_amount%100 < 10 || art.vote_amount%100 >= 20) ? 1 : 2];
		tooltip = (art.voted==0?'<p class="vote-info">Оценить книгу на '+$(this).attr('id')+'!</p>':'')+
			'<p class="voted-info">Всего '+art.vote_amount+' '+vote_amount_text+'.<br />Средняя оценка '+art.mid_vote+'.</p>'
			+(art.voted?'<p class="old-vote-info">Моя оценка '+art.voted+'.</p>'+(art.voted != $(this).attr('id') ? '<p class="vote-info">Изменить на '+$(this).attr('id')+'!</p>' : '<p class="vote-info">Оставить оценку</p>') :'');
		var table = '<dl>';
		for(i=5;i>0;i--)
			table += '<dt'+(art.voted==i?' class="alt"':"")+'>'+i+'</dt>'+
				'<dd'+(art.voted==i?' class="alt"':"")+'><div style="width:'+(art.votes[i-1]==0?0:Math.floor(100*art.votes[i-1]/max_vote))+'px;"></div><span>('+art.votes[i-1]+')</span></dd>';
		table += '</dl>';
		$('#hg-content').addClass('votestars').html(tooltip+table);
		if ($(this).parent().hasClass('bigstars')) $('#hg-pop-tooltip').css({left:parent.offset().left-41,top:parent.offset().top+18}).show();
		else $('#hg-pop-tooltip').css({left:parent.offset().left-57,top:parent.offset().top+15}).show();
	});

	$('.stars_book a').live('mouseleave', function() {
		$(this).prevAll().andSelf().removeClass('star-hover');
		$('#hg-pop-tooltip').hide();
		$('#hg-content').removeClass('votestars');
	});

	/* buy and download register button */
	$('.escho_oplat_popup a').click(function(){
		$("#buy_book_data").slideUp(200,function(){
			$("#login-link").data("overlay").load();
			$("#div-quick-login").hide();
			$("#div-quick-reg").show();
			$(".kykyru-footer-add-alt").addClass('ie7-fix-left-side');
		});
		return false;
	});
	
	$('#buy_book_data a.close').click(function(){
		$("#buy_book_link").data("overlay").close();
		$.mask.close();
	});
	
	/* book page */
	if (document.getElementById('buy_book_link')){
		$("#buy_book_link").overlay({
			fixed:false,
			effect: 'apple',
			speed:100,
			// onClose: function() {$.mask.close();},
			onLoad:function() {
				$(document).mask({
					color: '#000',
					loadSpeed: 200,
					opacity: 0.7,
					onBeforeClose: function() {
						$("#buy_book_link").data("overlay").close();
						$("#login-link").data("overlay").close();
					}
				});
			}
		});
	}
	
	$('#buy_book_link').click(function(){
		$("#buy_book_link").data('overlay').load();
	});
	
	$('#book_intro').click(function(){
		$("#hg-pop-tooltip").css({left:$(this).offset().left+30, top:$(this).offset().top+30});
		$('#hg-pop-tooltip, #hg-pop_close, #hg-overlay').show();
		$("#hg-content").html($('#book_intro_data').html());
		return false;
	});
	
	$("a[href*='/pages/registration/']").click(function() {ShowRegPopup();return false;});

	/* liters_touch lister */
	$('.okno .cell:first').addClass('c_current').addClass('a_active');
	$('.rakurs .arrow_down').click(function(){
		var cur = $('.okno .c_current');
		tmp = (cur.index()+1)*81;
		if (tmp == 324 || !cur.next().size()) {
			num = 0;
			$('.okno .cell:first').addClass('c_current');
			cur.removeClass('c_current');
		} else if (cur.next().size()) {
			cur.removeClass('c_current').next().addClass('c_current');
			num = tmp;
		}
		$('.okno .inner').css("margin-top", "-"+num+"px");
		return false;
	});

	rotate = function(){
		var act = $('.okno .a_active');
		act.removeClass('a_active');
		if (act.next().size())
			a_next = act.next().addClass('a_active');
		else
			a_next = $('.okno .cell:first').addClass('a_active');
		$('.device img').fadeOut(200, function(){
			$('.device img').attr("src", "/static/new/i/litres_touch/device_"+a_next.index()+".jpg").fadeIn(300, function(){});
		});

	};

	var gg = setInterval('rotate()', 3000);
	$('.okno, .pic').hover(function(){
		gg = window.clearInterval(gg);
	}, function(){
		gg = setInterval('rotate()', 3000);
	});

	$('.rakurs .arrow_up').click(function(){
		var cur = $('.okno .c_current');
		tmp = (cur.index()-1)*81;
		if (tmp == 0) {
			num = 0;
			cur.removeClass('c_current').prev().addClass('c_current');
		} else if (!cur.prev().size()) {
			num = 243;
			cur.removeClass('c_current');
			$('.okno .cell:eq(3)').addClass('c_current');
		} else if (cur.prev().size()) {
			num = tmp;
			cur.removeClass('c_current').prev().addClass('c_current');
		}
		$('.okno .inner').css("margin-top", "-"+num+"px");
		return false;
	});

	$('.okno .cell').click(function(){
		$('.okno .cell').removeClass('a_active');
		$(this).addClass('a_active');
		$('.device img').attr("src", "/static/new/i/litres_touch/device_"+$(this).index()+".jpg");
		return false;
	});

	if (document.getElementById('youtube-popup')){
		$("#youtube-popup").overlay({
			fixed:false,
			effect: 'apple',
			speed:100,
			onClose: function() {$.mask.close();},
			onLoad:function() {
				$(document).mask({
					color: '#000',
					loadSpeed: 200,
					opacity: 0.7,
					onBeforeClose: function() {
						$("#youtube-popup").data("overlay").close();
					}
				});
			}
		});
	}

	$('#youtube-popup').click(function(){
		$("#youtube-popup").data('overlay').load();
	});

	if (document.getElementById('instruction-popup')){
		$("#instruction-popup").overlay({
			fixed:false,
			effect: 'apple',
			speed:100,
			onClose: function() {$.mask.close();},
			onLoad:function() {
				$(document).mask({
					color: '#000',
					loadSpeed: 200,
					opacity: 0.7,
					onBeforeClose: function() {
						$("#instruction-popup").data("overlay").close();
					}
				});
			}
		});
	}

	$('#instruction-popup').click(function(){
		$("#instruction-popup").data('overlay').load();
	});

}});

function ShowRegPopup() {
	$("#div-quick-login").hide();
	$("#div-quick-reg").show();
	$("#login-link").data("overlay").load();
}

var ContactOK = undefined;
var FBOk = undefined;
function popup_social(){

	var container = '#soc_group';
	if ($(container).html()) return true;

	var node = '#download_file_popup';

	$(node).overlay({
		fixed:false,
		effect: 'apple',
		speed:100,
		load: false,
		onClose: function() {
			$.mask.close();
			GUJ.PutRequest({
				url: '/pages/ajax_epmty/',
				params: { action:'set_socnet_reminder', rand:Math.random() }
			});
		},
		onLoad:function() {
			$(document).mask({
				color: '#000',
				loadSpeed: 200,
				opacity: 0.7,
				onBeforeClose: function() {
					$(node).overlay().close();
				}
			});
		}
	});

	function CkeckAllDoneAndGo(){
		if (FBOk == undefined || ContactOK == undefined) return false;
		if(FBOk == 0 && ContactOK != 1){
				$(node).overlay().load();
				$(container).html('<noindex><iframe src="//www.facebook.com/plugins/likebox.php?href=http%3A%2F%2Fwww.facebook.com%2Fmylitres&amp;width=518&amp;colorscheme=light&amp;show_faces=true&amp;border_color&amp;stream=false&amp;header=true&amp;height=290" scrolling="no" frameborder="0" style="border:none; overflow:hidden; width:518px; height:290px;" allowTransparency="true"></iframe></noindex>');
			}else if(FBOk != 1 && ContactOK == 0){
				$(node).overlay().load();
				$(container).html('<div id="vk_groups2"></div>');
				VK.Widgets.Group("vk_groups2", {mode: 0, width: "518", height: "290"}, 23482323);
			}
	}
	CheckSNGroups(CkeckAllDoneAndGo);
	return true;
}

function CheckSNGroups(f) {
	if(getCookie('ingroup_vk')) {
		ContactOK=getCookie('ingroup_vk');
		if(typeof f=='function') f();
	} else {
		// Тупой ВКонтакт не умеет сам правильно определять авторизован ли пользователь
		// будем через try
		try {
			VK.api('groups.isMember',{gid: 23482323},function(k) {
				if (k == undefined){
					ContactOK = -1;
				} else {
					ContactOK = k.response == undefined ? -1 : k.response;
					setCookie('ingroup_vk',ContactOK,0,'/',2);
				}
				if(typeof f=='function') f();
			});
		} catch(e) {
			ContactOK = -1;
			if(typeof f=='function') f();
		}
	}
	if(getCookie('ingroup_fb')) {
		FBOk=getCookie('ingroup_fb');
		if(typeof f=='function') f();
	} else {
		if (FB.getAuthResponse() != null){
		FB.api({method: 'pages.isFan', page_id: 'mylitres'},function(k){
			FBOk = k == undefined ? -1 : k == 1 ? 1 : 0;
			FBOk_out=k.error_code;
			if(FBOk_out==104) FBOk=-1;
			setCookie('ingroup_fb',FBOk,0,'/',2);
			if(typeof f=='function') f();
		});
		} else {
			FBOk=-1;
			if(typeof f=='function') f();
		}
	}
}

jQuery.fn.placeholder = function() {
	$(this)
	.focusout(function() {
		if (this.value == '') this.value = $(this).attr('placeholder');
		if (this.value == $(this).attr('placeholder'))
			$(this).addClass('def_txt');
		else $(this).removeClass('def_txt');
	})
	.focus(function(event) {
		event.stopImmediatePropagation();
		if (this.value == $(this).attr('placeholder')) {
			$(this).val('').removeClass('def_txt');
		}
	})
	.mousedown(function() {
		$(this).focus();
	})
	.triggerHandler('focusout');
}

function NewOpenPassToggle(prefix) {
	var passopen=document.getElementById('show_pass'+prefix).checked;
	var opwf=$('#open_pwd'+prefix+'_inp');
	var cpwf=$('#pwd'+prefix+'_inp');
	if(passopen) {
		opwf.val(cpwf.val());
		opwf.triggerHandler('focusout');
	} else {
		var value = (!placeholders_supported && opwf.val()==opwf.attr('placeholder'))?'':opwf.val();
		cpwf.val(value);
	}
	$('#open_pwd'+prefix).css('display',passopen?'block':'none');
	$('#pwd'+prefix).css('display',passopen?'none':'block');
}

var bubbleTimeout;
var bubbleIndex = null;

BodyEndFunc.push({'bubbles_init': function(){
/* top menu */

$('#bubble_menu a[class!="nobub"]').attr('href','javascript:;');
var m_width=$("#bubble_menu").width()-30;
$("#sub-menu-r").css("marginLeft",m_width);
$('#bubble_menu a[class!="nobub"]').each(function(index) {
	$(this).mouseenter(function(){
		$(this).addClass('bubble-triggers-hoverfix');
		if(bubbleIndex == index) return;
		bubbleIndex = index;
		clearTimeout(bubbleTimeout);
		bubbleTimeout = setTimeout(function(){
			$("#bubble_menu a").eq(bubbleIndex).click();
		},1000);
	}).mouseleave(function(){
			$(this).removeClass('bubble-triggers-hoverfix');
		setBubbleCloseTO()
	}).click(function(){
		  clearTimeout(bubbleTimeout);
			var isself=$("#top_bubble_area .top_bubble").eq(index).is(":visible");
			$("#bubble_menu a.thisbubble").removeClass('thisbubble');
			$("#top_bubble_area .top_bubble:visible").hide();
			if(!isself) {
				bubbleIndex = index;
				$(this).addClass('thisbubble');
				$("#top_bubble_area .top_bubble").eq(index).slideDown('fast');
			} else bubbleIndex = null;
	});
});

$("#top_bubble_area .top_bubble .top_bubble_close").each(function(){
	$(this).click(function(){
		$("#bubble_menu a.thisbubble").removeClass('thisbubble');
		$("#top_bubble_area .top_bubble:visible").hide();
		bubbleIndex = null;
	});
});

$("#top_bubble_area .top_bubble").each(function(){
	$(this).mouseleave(function(){
		setBubbleCloseTO(bubbleIndex)
  }).mouseenter(function() {
		clearTimeout(bubbleTimeout);
  });
});

$(document).click(function(event) {
    if (bubbleIndex!=null && !$(event.target).is('#bubble-triggers *, #bubble_menu *') && !$(event.target).is('#top_bubble_area *')) {
         $("#top_bubble_area .top_bubble .top_bubble_close").eq(bubbleIndex).click();
    }
});
$('#hg-overlay, #hg-pop_close').click(function(){
	$("#hg-pop-tooltip").hide();
	$('.dwnl_splr_btn').removeClass('dwnl_splr_btn_active');
	$('#hg-pop-tooltip').removeClass('free_book_get');
	$('#hg-overlay').hide();
	$('#hg-content').html(' ');
	$('#hg-t').removeAttr("style");
});



/* tab search  tab-all*/
/* not ie6 or ie7 */
if (($.browser.msie) && ($.browser.version == '6.0') || ($.browser.msie) && ($.browser.version == '7.0')){
$(".result-top").hide();
}else{
if($('.result-top > a').size()<=2){
$(".result-top > a.t0").hide();
$(".result-top > span").hide();
}
/* Если страница поиска то выполняем скрипты */
if(document.getElementById('searchresults')) {

/* Переменные для выяснения существования определенного типа книг */
var type0 = $(".t6 .newbook").has(".covertype0"); // Электронная книга
var type1 = $(".t6 .newbook").has(".covertype1"); // аудиокнига
var type2 = $(".t6 .newbook").has(".covertype2"); // медиакнига
var type4 = $(".t6 .newbook").has(".covertype4"); // pdf книга
var type11 = $(".t6 .newbook").has(".covertype11"); // drm книга
var hide=$(".t6 .newbook");
$('.result-top .t0').click(function(){$(".newbook").show();});

/* функция поиска максимальной высоты
$.fn.equalizeHeights = function() {
  var maxHeight = this.map(function(i,e) {
	return $(e).height();
  }).get();
  return this.height( Math.max.apply(this, maxHeight) );
};

$('.result-series .item').equalizeHeights(); // применить стиль, поиск максимальной высоты для блока серия - пока не решил правильно в js или в xslt сделать.
$('.result-book-author .book_row .item .img').equalizeHeights(); // применить стиль, поиск максимальной высоты для автора где книг меньше 4.
*/
	if(document.getElementById('type0')) {
		$('#type0').click(function(){hide.hide(); type0.show();});
	}
	if(document.getElementById('type1')) {
		$('#type1').click(function(){hide.hide(); type1.show();});
	}
	if(document.getElementById('type2')) {
		$('#type2').click(function(){hide.hide(); type2.show();});
	}
	if(document.getElementById('type4')) {
		$('#type4').click(function(){hide.hide(); type4.show();});
	}
	if(document.getElementById('type11')) {
		$('#type11').click(function(){hide.hide(); type11.show();});
	}

/* tab для навигации по поиску */
$('#searchresults .result-top a').click(function(){
	var thisClass = this.className.slice(0,2);
	$('#searchresults .tab-item').hide();
	$('#searchresults .tab-item.' + thisClass).show();
	$('.result-top a').removeClass('active');
	$(this).addClass('active');
	//alert(thisClass);
	if(thisClass=='t0'){
		$('#searchresults .tab-item').show();
	}else {
		$(this).addClass('active');
	}
});

}}
}});

function getAssocArrayLength(tempArray) { // функция возращает размер массива...
	var result = 0;
	for (tempValue in tempArray) result++;
	return result;
}

/* popup скачать для миникарточки */
function popup_download_type(obj,art,fid,filename,sid,formats){
	$('.dwnl_splr_btn').removeAttr("href");
	var offleft=$(obj).offset().left-30;
	var pd=offleft+$("#hg-pop-tooltip").width();
	var body=$("body").width();
	//alert(tt+'_'+body+'_'+(body-offleft));
	$('#hg-pop-tooltip, #hg-pop_close, #hg-overlay').show();

	if(pd>=body)
	$("#hg-pop-tooltip").css({left:body-offleft-30, top:$(obj).offset().top+20});
	else{
		$("#hg-pop-tooltip").css({left:offleft, top:$(obj).offset().top+20});
		$("#hg-t").css('marginLeft', 50);
		$("#hg-t i").css({width:50, left:-50});
		$("#hg-t b").css('width', 6);
	}
	$('.dwnl_splr_btn').removeClass('dwnl_splr_btn_active');
	$(obj).addClass('dwnl_splr_btn_active');
	
	// названия длы вывода
	var format_names = {"fb2.zip":"FB2", "epub":"EPUB", "txt.zip":"TXT.ZIP", "rtf.zip":"RTF", "a4.pdf":"PDF A4", "html.zip":"HTML.ZIP", "a6.pdf":"PDF A6",
		"mobi.prc":"MOBI", "txt":"TXT", "java":"JAVA", "lrf":"LRF", "rb":"RB", "isilo3.pdb":"ISILO3", "lit":"LIT", "doc.prc.zip":"DOC.PRC"};
	var format_subnames = {"mobi.prc":" (Kindle)", "lrf":" (Sony)", "rb":" (Rocket)", "lit":" (Microsoft Reader)", "doc.prc.zip":" (Palm)"};
	var tmp = ""; // пустая переменая в которую генерится весь контент поп-апа
	var arr = {1:[], 2:[], 3:[], 4:[], 5:[]}; // пустой многомерный массив
	for (var i = 0; i < formats.length; i++) { // группируем
		if (formats[i] == 'fb2.zip' || formats[i] == 'epub')
			arr[1][arr[1].length] = formats[i];
		if (formats[i] == 'a6.pdf' || formats[i] == 'mobi.prc')
			arr[2][arr[2].length] = formats[i];
		if (formats[i] == 'lrf' || formats[i] == 'rb' || formats[i] == 'isilo3.pdb' || formats[i] == 'lit' || formats[i] == 'doc.prc.zip')
			arr[3][arr[3].length] = formats[i];
		if (formats[i] == 'txt.zip' || formats[i] == 'rtf.zip' || formats[i] == 'a4.pdf' || formats[i] == 'html.zip')
			arr[4][arr[4].length] = formats[i];
		if (formats[i] == 'txt') {
			arr[5][arr[5].length] = formats[i];
			arr[5][arr[5].length] = 'java';
		}
	}
	for (var i = 1; i <= getAssocArrayLength(arr); i++) { // делаем списки
		if (getAssocArrayLength(arr[i]) > 0) {
			tmp2 = arr[i];
			if (i == 1) tmp += '<ul class="pdt1"><li class="title">Удобные</li>';
			if (i == 2) tmp += '<ul class="pdt2"><li class="title">Для ридеров</li>';
			if (i == 3) tmp += '<ul class="pdt3"><li class="title">Другие</li>';
			if (i == 4) tmp += '<ul class="pdt4"><li class="title">Для компьютера</li>';
			if (i == 5) tmp += '<ul class="pdt5"><li class="title">Для телефона</li>';
			for (var g = 0; g < tmp2.length; g++) {
				tmp += '<li><a href="/download_my_book/'+art+'/'+fid+'/'+filename+'.'+tmp2[g]+'?sid='+sid+'" onclick="_gap.push([\'_trackEvent\', \'Download #0\',\''+tmp2[g]+'\','+art+']);">'+format_names[tmp2[g]]+'</a>'
					+(format_subnames[tmp2[g]]?format_subnames[tmp2[g]]:"")+'</li>';
			}
			tmp += '</ul>';
		}
	}
	$("#hg-content").html('<div class="pdt-content">'+tmp+'</div>');
}



function setBubbleCloseTO() {	clearTimeout(bubbleTimeout);
	bubbleTimeout = setTimeout(function(){
		if(bubbleIndex!=null) $("#top_bubble_area .top_bubble .top_bubble_close").eq(bubbleIndex).click();
	},3000);
}

function LoginFormCheck(the_form) {
	if (the_form && the_form.id == 'frm_login') {
		AppendUtcOffsetInput2Form('frm_login');
		return true;
	} else {
		AppendUtcOffsetInput2Form('frm_quick_login');
	};

	if($('#login_fast_inp').val()=='' || (!placeholders_supported && $('#login_fast_inp').val()==$('#login_fast_inp').attr('placeholder'))) {
		$('#login_fast_inp').removeClass('def_txt').focus();
		return false;
	}
	var el=$('#'+($('#show_pass_fast').is(":checked")?'open_':'')+'pwd_fast input');
	if(el.val()=='' || (!placeholders_supported && el.val()==el.attr('placeholder') )) {
		el.removeClass('def_txt').focus();
		return false;
	}
	return true;
}

function PutMoneyBasketAddArt(Obj,Summ){
	var CMess='На вашем счету недостаточно средств для покупки, не хватает '+RubPrice(Summ)+' руб.\nХотите отложить книгу и пополнить счет сейчас?';
	var CFunc = function exec() {
		if(Summ<10) Summ=10;
		window.location.href='/pages/put_money_on_account/?summ='+RubPrice(Summ)+'&ref_url='+encodeURIComponent(Obj.getAttribute('href'));
	};
	alertBox.errorStickerButtons[0].value='OK';
	alertBox.alert(CMess,CFunc);
	return false;
}

var AJAXOFF = 0;
var RootStarted = 0;
function PutArtToBasketAjax(ArtID,AddPrice,Type){
	if (AJAXOFF || RootStarted){
		return true;
	}

	var Mode = 'root';
	RootStarted = 1;
	if ($('#fast_basket_spl').length > 0){
		Mode = 'child';
		RootStarted = 0;
	} else if ($('#right_col_private').length > 0){
		Mode = 'semiroot';
	}

	var ToBasAjaxRequest = {
		url: '/pages/ajax_tobasket/',
		params : {art: ArtID, mode: Mode, action: 'add_art_to_basket'},
		OnHTML:function(HTML){
			var TargetElement = $('#fast_basket_spl');
			if (this.params.mode == 'semiroot'){
				TargetElement = $('#right_col_private');
			} else if (this.params.mode == 'root'){
				TargetElement = $('#right_content_cell');
			}
			TargetElement.prepend(HTML);
			var ElToSlide = 0;
			if (this.params.mode == 'root'){
				ElToSlide = 'right_col_private';
			} else if (this.params.mode == 'semiroot'){
				ElToSlide = 'fast_basket_block';
			}
			if (ElToSlide){
				$('#'+ElToSlide).hide();
				// $('#fast_basket_spl .price').html($('.book_descr_links .td').html());
				// $('#fast_basket_spl .price div').children('.discount').remove();
				$('#'+ElToSlide).slideDown('fast').addClass('gray-corners').addClass('corners');
			}
			var basket_items=$('div[id^="basketitem_"]').length;
			$('#fast_basket_spl_title_num').html('('+basket_items+')');
			$('#header_basket_spl_title_num').html(basket_items+' '+decOfNum(basket_items,['товар','товара','товаров']));
			if (this.params.mode == 'child'){
				$('#total_qbasket_summ').html(RubPrice(DerubPrice('total_qbasket_summ') + this.AddPrice));
			}
			$('*[class~="tobasket_'+this.ArtID+'_out"]').show();
			$('*[class^="tobasket1_'+this.ArtID+'"]').remove();
			RootStarted = 0;
		},
		OnHTMLFail: function(fake1,fake2){
			AJAXOFF = 1;
			alert('Ошибка при добавлении книги в корзину. Попробуйте, пожалуйста, добавить эту книгу в корзину еще раз');
			$('*[class~="tobasket1_'+this.ArtID+'"]').remove();
			this.ToBasElems().show();
		},
		ArtID: ArtID,
		AddPrice: AddPrice,
		ToBasElems: function(){return $('*[class~="tobasket_'+this.ArtID+'_in"]')}
	};

	var ToBasElems = ToBasAjaxRequest.ToBasElems();
	ToBasElems.before('<img alt="" src="/static/new/i/ajax_progress.gif" class="tobasket1_'+ArtID+' progress_gif" width="16" height="16"/>');
	ToBasElems.hide();
	GUJ.PutRequest(ToBasAjaxRequest);
	return false;
}

function DropArtFromBasketAjax(BasketID,PriceToDecr,ArtID){
	if (AJAXOFF){
		return true;
	}
	var Request = {
		url: '/pages/ajax_epmty/',
		params : {action: 'del_art_from_basket', itm: BasketID},
		BasketID: BasketID,
		PriceToDecr: PriceToDecr,
		OnData: function(Data){
			if (Data === 'ok'){
				var basket_items = $('div[id^="basketitem_"]').length - 1;
				$('#fast_basket_spl_title_num').html('('+basket_items+')');
				$('#header_basket_spl_title_num').html(basket_items+' '+decOfNum(basket_items,['товар','товара','товаров']));
				$('#total_qbasket_summ').html(RubPrice(DerubPrice('total_qbasket_summ') - this.PriceToDecr));
				$('#basketitem_'+this.BasketID).slideUp('fast',function(){
					$(this).remove();
					if ($('div[id^="basketitem_"]').length == 0){
						$('#fast_basket_block').remove();
						if ($('#right_col_hr_divider').length == 0){
							$('#right_col_private').remove();
						} else {
							$('#right_col_hr_divider').remove();
						}
					} else if ($('#fast_basket_hided_link_d').length > 0 && $('div[id^="basketitem_"]').length - $('#fast_basket_hided div[id^="basketitem_"]').length < 3){
						OpenFastBasketSpoiler();
						$('#fast_basket_hided_link_d').remove();
					}
				});
				$('*[class~="tobasket_'+this.ArtID+'_in"]').show();
				$('*[class~="tobasket_'+this.ArtID+'_out"]').hide();
			} else {
				this.OnDataFail(0,0);
			}
		},
		ArtID: ArtID,
		OnDataFail: function(fake1,fake2){
			AJAXOFF = 1;
			alert('При удалении из корзины произошла ошибка. Попробуйте, пожалуйста, удалить товар из корзины еще раз');
			$('#frombasket_'+this.BasketID).remove();
		}
	}
	$('#basketitem_'+BasketID).prepend('<span style="position:absolute"><img alt="" src="/static/new/i/ajax_progress.gif" id="frombasket_'+BasketID+'" class="frombasket_'+BasketID+' rm_progress_gif" width="16" height="16"/></span>');
	GUJ.PutRequest(Request);
	return false;
}

function DerubPrice(ElementID){
	var CurRubPrice = $('#'+ElementID).text();
	CurRubPrice = CurRubPrice.replace(',','.') * 1;
	return CurRubPrice;
}

// Хакообразная подгонка правого столбца по высоте к высоте основной страницы
var mhnns_cnt = 0;
var WorkingWidth = 0;
var WorkingWidth = 0;
var FixWidthOn = 1600;
function MakeHotNewNormalSize(){
  if (mhnns_cnt > 0){
    mhnns_cnt = 2;
    return;
  }
  mhnns_TID = 1;

	if (document.getElementById('main-div')) MainDivResize(false);
	if (document.getElementById('master_page_div')){
		AdoptInScreenBlocks();
		var HotNewDiv = document.getElementById('ratings');
		if (!HotNewDiv){
			return;
		}
		var HeightLimit = document.getElementById('master_page_div').offsetHeight;
		if (HeightLimit < 700) HeightLimit = 700;

		var CropElementTo = FindFinalElement(HotNewDiv,HeightLimit - HotNewDiv.offsetTop);
		HotNewDiv.style.overflow='hidden';
		HotNewDiv.style.height = (CropElementTo + 3)+'px';
	}
	if (mhnns_cnt > 1) {
		mhnns_cnt = 0;
		MakeHotNewNormalSize();
	}
  mhnns_TID = 0;
}

function FindFinalElement(TopDiv,Limit){
  var CurPos = 0;
  for (var i=0;i < TopDiv.childNodes.length && CurPos < Limit;i++){
    var Child = TopDiv.childNodes[i];
    var ChildClass = Child.className+'';
    if (ChildClass.match(/right_col_title|extender/)){
      CurPos = Child.offsetTop;
    } else {
      CurPos = FindFinalElement(Child,Limit - CurPos);
    }
  }
  return CurPos;
}



var Padding = 20;
var BlockWidth = 0;
var TitleWidth = 0;
var BlockCSS;
var TitleCSS1;
var TitleCSS2;
var MainDivCSS;
var TopBubbleCSS;

if (getCSSRule('.newbook')){
  BlockCSS = getCSSRule('.newbook').style;
  if (BlockCSS && BlockCSS.width){
    BlockWidth = parseInt(BlockCSS.width) + Padding;
  }
  TitleCSS1 = getCSSRule('.newbook .booktitle').style;
  if (TitleCSS1 && TitleCSS1.width){
    TitleWidth = (TitleCSS1.width + '').replace('px','') * 1;
  }
  TitleCSS2 = getCSSRule('.newbook .booksubtitle').style;
}

if(getCSSRule('div#main-div')) {
	MainDivCSS=getCSSRule('div#main-div').style;
	TopBubbleCSS=getCSSRule('.top_bubble').style;
}

function AdoptInScreenBlocks(){
  if (no_adopt) return;
  if (BlockWidth){
    WorkingWidth = 0;
    if (document.getElementById('master_page_div')){
      // Документ уже загружен, можно фактический размер поля смотреть
      WorkingWidth = document.getElementById('master_page_div').offsetWidth;
    } else {
			var gpad = GetPadding();
			WorkingWidth = Math.min(document.body.clientWidth,FixWidthOn+22)
				- gpad*2 - 208 - 22 - 32;
      if (WorkingWidth < 351){
        WorkingWidth = 351;
      }
    }
    var BlocksPerLine = Math.floor(WorkingWidth/BlockWidth);
    var CanAddPixels = Math.floor((WorkingWidth - BlockWidth * BlocksPerLine)/BlocksPerLine);
    BlockCSS.width=(BlockWidth + CanAddPixels - Padding) + 'px';
    TitleCSS2.width=TitleCSS1.width=(TitleWidth + CanAddPixels) + 'px';
  }

}

function FindMaxWH( all_elements ) {
    var el = all_elements.filter(":first");
    var maxH = el.parent().height();
    var maxW = el.parent().width();

    var text;
    var oldtext = el.attr('title') || el.html();
    var newtext = "ЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖ";
    var real_max_w;
    var real_max_h;

    if ( !el.length ) return;

    el.html( newtext );
    var start = el.outerWidth() < maxW;
    do {
      text = newtext;
      if ( start ) {
	newtext = newtext + "Ж";
      } else {
	newtext = newtext.substring( 0, text.length - 1 );
      }
      el.html( newtext );
    } while ( ( el.outerWidth() < maxW ) == start );

    real_max_w = text.length;
    real_max_h = 0;
    newtext = text;

    do {
      text = newtext;
      real_max_h++;
      newtext = newtext + " " + newtext;
      el.html( newtext );
    } while ( el.outerHeight() < maxH );

    el.html( oldtext );
    return { 'maxH': maxH, 'maxW': maxW, 'real_max_h': real_max_h, 'real_max_w': real_max_w };
}

function MakeEllipsis(){
  var ellipsis_elements = new Array(
    jQuery(".ell_new").not(".ellE1").not(".ellA1").not(".ellT1").find("a"),
    jQuery(".ellE1").not(".ellA1").not(".ellT1").find("a")
  );

  if(jQuery().ellipsis) {
    for ( var i = 0; i < ellipsis_elements.length; i++ ) {
      var all_elements = ellipsis_elements[i];
      var size = FindMaxWH( all_elements );

      if ( size && size.maxW && size.maxH && size.real_max_w && size.real_max_h ) {
	all_elements.ellipsis( size.maxW, size.maxH, size.real_max_w, size.real_max_h );
      }
    }
  }
  //jQuery(".ellP4 a").ellipsis(65,16);
}

function GetPadding(){
  var gwidth = document.body.clientWidth;
  var gpad = (gwidth>=FixWidthOn)?50:5*(gwidth-980)/62;
  gpad = (gpad>0)?parseInt(gpad):0;
	return gpad;
}

function MainDivResize(init) {
  var gpad = GetPadding();
  var maxwidth = FixWidthOn-gpad*2;

  MainDivCSS.maxWidth=maxwidth + 'px';
  MainDivCSS.paddingLeft=gpad + 'px';
  MainDivCSS.paddingRight=gpad + 'px';

  TopBubbleCSS.width=100-parseInt(gpad*3/5)+'%';

  //$("#main-div").css({'max-width':maxwidth+'px','padding-left':gpad+'px','padding-right':gpad+'px'});
  //$(".top_bubble").css({'width':100-parseInt(gpad*3/5)+'%'});
  if (!init && $.browser.msie && $.browser.version.substr(0,1)<7 && $("#main-div").width()>maxwidth) {$("#main-div").width(maxwidth);} //awesome!
  $("#dynamics_padd").css("paddingLeft", MainDivCSS.paddingLeft);

}

BodyEndFunc.push({
  'za_MHNNS': MakeHotNewNormalSize,
  'zb_ellipsis': MakeEllipsis
});

WinResizeFunc.push({'zz_resize_MHNNS': function(){MakeHotNewNormalSize(); MakeEllipsis();}});

BodyLoadFunc.push({
  'menuscroll': function(){ var menuscroll = new SimpleScroller;},
  'za_HNNS': MakeHotNewNormalSize
});


var sfac_delay=false;
var sfac_tdelay=false;
var sfac_sel=-1;
var sfac_pps;
var sfac_timeout;

BodyLoadFunc.push({
  'sfac_init': function(){
		jQuery("#q").keydown(function(e) {
			if(e.keyCode==13&&document.getElementById("sfac").style.display!='none'&&!sfac_keyEvent(e.keyCode)) {
				e.preventDefault();
				return false;
			}
		}).keyup(function(e) {
			if((e.keyCode==38||e.keyCode==40)&&document.getElementById("sfac").style.display!='none'&&!sfac_keyEvent(e.keyCode)) {
				e.preventDefault();
				return false;
			}
			if(sfac_pps==undefined) {
				sfac_request();
			} else sfac_delay=true;
			clearTimeout(sfac_pps);
			sfac_pps=setTimeout(function(){sfac_pps=undefined; if(sfac_delay) sfac_request();},200);
		}).blur(function() {
			sfac_delay=false;
			sfac_tdelay=false;
			sfac_sel=-1;
			clearTimeout(sfac_pps);
			clearTimeout(sfac_timeout);
			setTimeout(function(){document.getElementById("sfac").style.display='none';},200);
		}).attr({"autocomplete":"off"});
		jQuery('<div id="sfac_cont" id="srch_popup"><div id="sfac"/></div>').insertAfter("#q");
  }
});

function sfac_request(value) {
	sfac_delay=false;
	var typedesc = new Array(['книга','книги','книг'],['аудиокнига','аудиокниги','аудиокниг'],['мультимедиа-книга','мультимедиа-книги','мультимедиа-книг'],['устроиство','устроиства','устроиств'],null,null,['база','базы','баз'],['фильм','фильма','фильмов'],['игра','игры','игр'],['программа','программы','программ']);
	var val=document.getElementById("q").value;
	if(sfac_timeout==undefined) {
		sfac_tdelay=false;
		clearTimeout(sfac_timeout);
		if(val.length > 2) {
			GUJ.PutRequest({
				url: '/pages/ajax_search/',
				params : {q: val},
				HttpRType: 'json',
				OnData:function(data){
					if(val!=document.getElementById("q").value) return;
					var out='';
					for (i in data.results) {
						elem=data.results[i];
						if(typeof(elem)!='object') continue;
						if(typeof(elem.atype)==undefined || elem.atype==4 || elem.atype==11) elem.atype=0;
						var FixedStr = data.word.replace(/[еэё]/i,'[еэё]');
						FixedStr = FixedStr.replace(/[ий]/i,'[ий]');
						var text=elem.txt.replace(new RegExp("^("+FixedStr+")","i"),"<b>$1</b>");
						switch(elem.type) {
							case 'author':href='/pages/biblio_authors/?subject='+elem.id;hint='автор, '+elem.totalbooks+' '+decOfNum(elem.totalbooks,typedesc[elem.atype]);break;
							case 'sequence':href='/pages/biblio_series/?id='+elem.id;hint='серия, '+elem.totalbooks+' '+decOfNum(elem.totalbooks,typedesc[elem.atype]); if (elem.author) hint+=', автор '+elem.author;break;
							case 'book':href='/pages/biblio_book/?art='+elem.id;hint=typedesc[elem.atype][0]+(elem.atype<2&&elem.author!=''?' '+elem.author:'');break;
						}
						out+='<li><a href="'+href+'" title="'+elem.txt+'">'+text+'<span> &mdash; '+hint+'</span></a></li>';
					}
					if(out!='') {
						jQuery('#sfac').html('<ul>'+out+'</ul>').slideDown(200);
						jQuery('#sfac a').click(function(){document.getElementById("q").value=$(this).attr('title');});
					}
					else
						jQuery('#sfac').hide();
				}
			});
			sfac_timeout=setTimeout(function(){sfac_timeout=undefined; if(sfac_tdelay) sfac_request();},100);
		} else jQuery("#q").triggerHandler('blur');
	} else sfac_tdelay=true;
}

function sfac_keyEvent(keyCode) {
	var aList=document.getElementById("sfac").getElementsByTagName('a');
	if(keyCode==13) {
		if(sfac_sel==-1) return true;
		document.location.href=aList[sfac_sel].href;
	}
	if((keyCode==38 && sfac_sel>=0)|| (keyCode==40 && sfac_sel<aList.length-1)) {
		for(i in aList) {	aList[i].className="";}
		sfac_sel+=(keyCode==38?-1:1);
		if(sfac_sel>=0 && sfac_sel<aList.length) aList[sfac_sel].className="sfacSelected";
	}
	return false;
}

/*socnet*/
var SocNetInit = function (p){
	var T = this;
	this.services = new Object;

	this.push = function(s,p){
		if(!s) return false;
		T.services[s] = T.services[s] || {};
		T.services[s].el_id = p && p.el_id ? p.el_id : T.services[s].el_id || null;
		T.services[s].onLoad = T.services[s].onLoad || [];
		if (p){
			if (p.onLoad) T.services[s].onLoad.push(p.onLoad);
			if (p.InitCall) T.InitCall(s);
		}
		return T;
	};

	this.WaitLoadJS = function(src, target, waitme, func){
			var T = this;
			var e = document.createElement('script'); e.async = true;
			e.src = src;
			document.getElementById(target).appendChild(e);

			var dc = 0;
			var checker = function(){
				if (window[waitme] !== undefined){
					func.call();
				} else if(dc++ < 100) {
					setTimeout(function(){ checker.call(); },500);
				}
			};
			checker.call();
	};

	this.InitCall = function(s){
		if (T.services.fb && (!s || s == 'fb')){
			window.fbAsyncInit = function() {
				FB.init({appId: '148369558555542', status: true, cookie: true, xfbml: true});
				for (var i=0; i<T.services.fb.onLoad.length; i++) T.services.fb.onLoad[i].call();
			};
			var e = document.createElement('script'); e.async = true;
			e.src = document.location.protocol +
				'//connect.facebook.net/ru_RU/all.js';
			document.getElementById(T.services.fb.el_id || 'fb-root').appendChild(e);
		}
		if (T.services.vk && (!s || s == 'vk')){
			window.vkAsyncInit = function() {
				VK.init({
					apiId: 2243292,
					onlyWidgets: true
				});
				for (var i=0; i<T.services.vk.onLoad.length; i++) T.services.vk.onLoad[i].call();
			};
			var el = document.createElement("script");
			el.type = "text/javascript";
			el.src = document.location.protocol+"//vkontakte.ru/js/api/openapi.js";
			el.async = true;
			document.getElementById(T.services.vk.el_id || 'vk_api_transport').appendChild(el);
		}

		if (T.services.tw && (!s || s == 'tw')){
			var el = document.createElement("script");
			el.type = "text/javascript";
			el.id = "twitter-wjs";
			el.onload = function(){
				for (var i=0; i<T.services.tw.onLoad.length; i++) T.services.tw.onLoad[i].call();
			};
			el.src = document.location.protocol+"//platform.twitter.com/widgets.js";
			el.async = true;
			document.getElementById(T.services.tw.el_id || 'tw_init').appendChild(el);
		}

		if (T.services.mr && (!s || s == 'mr')){
			if(document.location.protocol=='https:') return;
			T.WaitLoadJS(
				'//cdn.connect.mail.ru/js/loader.js',
				T.services.mr.el_id || 'mr_init',
				'mailru',
				function(){
					mailru.loader.require('api', function() {
						mailru.connect.init(611986, '8f071e6a8bb671e07673f19b21f9c755');
					});
					for (var i=0; i<T.services.mr.onLoad.length; i++) T.services.mr.onLoad[i].call();
				}
			);
		}

		if (T.services.ok && (!s || s == 'ok')){
			if(document.location.protocol=='https:') return;
			var el = document.createElement("link");
			el.rel = "stylesheet";
			el.href = "http://stg.odnoklassniki.ru/share/odkl_share.css";
			el.async = true;
			document.getElementById(T.services.ok.el_id || 'ok_init').appendChild(el);
			T.WaitLoadJS(
				'http://stg.odnoklassniki.ru/share/odkl_share.js',
				T.services.ok.el_id || 'ok_init',
				'ODKL',
				function(){
					ODKL.init();
/*
					mailru.loader.require('api', function() {
						mailru.connect.init(611986, '8f071e6a8bb671e07673f19b21f9c755');
					});
//*/
					for (var i=0; i<T.services.ok.onLoad.length; i++) T.services.ok.onLoad[i].call();
				}
			);
		}
	};

	this.LikeClick = {
		send: function(p){
			var Request = {
				url: '/pages/ajax_epmty/',
				OnData:function(Data) {
					if ( Data == 'ok' ) {
						window.location.reload();
					}
				},
				params: { action:'i_like_this', rand:Math.random() }
			};
			GUJ.PutRequest(Request);
			return false;
		},
		ok: function(){
			setTimeout(T.LikeClick.send, 1000);
		}
	};

	// google+ хочет определение функции в области window
	window['LikeClickGoogle'] = function(p){
		if (p && p.state == 'on') T.LikeClick.send();
	};

	BodyLoadFunc.push({'zzza_socnetinit': function(){
		for (var i in T.services) {
			T.InitCall(i);
		}
		SNLoadCheck();
	}});
};

function SNLoadCheck() {
	if(typeof VK !="undefined" && typeof FB != "undefined")
		CheckSNGroups();
	else
		setTimeout('SNLoadCheck()',3000);
}

var SocNet = new SocNetInit();

function SNRedirect(params){
	var href = window.location.toString();
	var nh = new Array;
	var rgx = new Array;
	for (var p in params){
		rgx.push(p);
		nh.push(p +'='+ params[p]);
	}
	rgx = new RegExp('\\b('+rgx.join('|')+')=[^&]*&?', "gi");
	href = href.replace(rgx,'');
	if (nh.length > 0){
		href += (window.location.search ? /[&?]$/.test(href) ? '' : '&' : '?') + nh.join('&');
	}
	//alert(href);
	window.location.href = href;
}
function FBLoginClick(perms){
	if (typeof(FB) == 'undefined'){
		alert('Facebook API not initialized');
	} else {
		FB.login(function(r) {
			if (r.authResponse) {
				SNRedirect({pre_action: 'socnet', socnet: 'fb', access_token: r.authResponse.accessToken});
			} else {
				//alert('Вы не зарегистрированы на facebook');
			}
		}, {'scope':perms});
	}
};

function VKLoginClick(perms){
	if (typeof(VK) == 'undefined'){
		alert('Vkontakte API not initialized');
	} else {
		VK.Auth.login(function(r) {
			if (r.session) {
				SNRedirect({pre_action: 'socnet', socnet: 'vk', access_token: r.session.sid, uids: r.session.user.id});
				/* Пользователь успешно авторизовался */
				if (r.settings) {
					/* Выбранные настройки доступа пользователя, если они были запрошены */
				}
			} else {
				/* Пользователь нажал кнопку Отмена в окне авторизации */
				//alert('Вы не зарегистрированы vkontakte');
			}
		},perms);
	}
}

function MRLoginClick(perms){
	if (typeof(mailru) == 'undefined'){
		alert('mailru API not initialized');
	} else {
		mailru.events.listen(mailru.connect.events.login, function(s){
			if (s){
				SNRedirect({pre_action: 'socnet', socnet: 'mr', access_token: s.session_key, uids: s.oid, exp: s.exp});
			} else {
				//alert('Вы не авторизованы на Mail.ru');
			}
		});
		mailru.connect.login(perms);
	}
}

function TWLoginClick(){
	SNRedirect({pre_action: 'socnet', socnet: 'tw'});
}

function OILoginClick(id,host){
	var oi = document.getElementById(id);
	if (oi) oi = oi.value;
	if (/^[\w-@.\/:]+$/.test(oi)){
		if (host){
			var r = new RegExp('\.'+host.replace(/\./g,'\.'),"i");
			if (!r.test(oi)) oi += '.'+host;
		}
		SNRedirect({pre_action: 'socnet', socnet: 'oi', user_open_id: oi});
	} else {
		alert('Неверный формат OpenID');
	}
	return false;
}

function ShowOIForm(id,eid){
	var a = ['openid_form', 'lj_form'];
	for (var i = 0; i < a.length; i++){
		var f = document.getElementById(a[i]+'_'+eid);
		if (f){
			if (a[i] == id){
				f.style.display = f.style.display == 'block' ? 'none' : 'block';
			} else {
				f.style.display = 'none';
			}
		}
	}
}


/*paginator*/
var Paginator = function(paginatorHolderId, pagesTotal, pagesSpan, pageCurrent, baseUrl, moreSettings){
	if(!document.getElementById(paginatorHolderId) || !pagesTotal || !pagesSpan) return false;
//
	this.inputData = {
		paginatorHolderId: paginatorHolderId,
		pagesTotal: pagesTotal,
		pagesSpanOrig: pagesSpan,
		pagesSpan: pagesSpan < pagesTotal ? pagesSpan : pagesTotal,
		pageCurrent: pageCurrent,
		baseUrl: baseUrl ? baseUrl : '/pages/',
		align: 'justify',
		scrollBtn: 'none',
		scrollBtnCaptionL: '«',
		scrollBtnCaptionR: '»'
	};
	for (var i in moreSettings){
		this.inputData[i] = moreSettings[i];
	}
	if (pagesSpan > pagesTotal) this.inputData.scrollBtn = 'none';
	else this.inputData.align = 'justify';

	this.html = {
		holder: null,

		table: null,
		trPages: null,
		trScrollBar: null,
		tdsPages: null,

		scrollBar: null,
		scrollThumb: null,

		pageCurrentMark: null
	};


	this.prepareHtml();

	this.initScrollThumb();
	this.initPageCurrentMark();
	this.initEvents();

	this.scrollToPageCurrent();
}

/*
	Set all .html properties (links to dom objects)
*/
Paginator.prototype.prepareHtml = function(){

	this.html.holder = document.getElementById(this.inputData.paginatorHolderId);
	this.html.holder.innerHTML = this.makePagesTableHtml();

	this.html.table = this.html.holder.getElementsByTagName('table')[0];

	var trPages = this.html.table.getElementsByTagName('tr')[0];

	this.html.tdsPages = new Array;
	this.html.skeepedTds = new Array;
	var tds = trPages.getElementsByTagName('td');
	for (var i=0; i < tds.length; i++){
		if (tds[i].className.match(/scrollBtn/)){
			var tmp = tds[i].getElementsByTagName('a')[0];
			if			(tmp.className.match(/scrollBtnL/)) this.html.scrollBtnL = tds[i];
			else if	(tmp.className.match(/scrollBtnR/)) this.html.scrollBtnR = tds[i];
			continue;
		}
		if (tds[i].style.visibility == 'hidden') {
			this.html.skeepedTds.push(tds[i]);
			continue;
		}
		this.html.tdsPages.push(tds[i]);
	}

	this.html.scrollBar = getElementsByClassName(this.html.table, 'div', 'scroll_bar')[0];
	this.html.scrollThumb = getElementsByClassName(this.html.table, 'div', 'scroll_thumb')[0];
	this.html.pageCurrentMark = getElementsByClassName(this.html.table, 'div', 'current_page_mark')[0];

	// hide scrollThumb if there is no scroll (we see all pages at once)
	if(this.inputData.pagesSpan == this.inputData.pagesTotal){
		addClass(this.html.holder, 'fullsize');
	}
}

/*
	Make html for pages (table)
*/
Paginator.prototype.makePagesTableHtml = function(){
	var tdWidth = (100 / ((this.inputData.align == 'justify' ? this.inputData.pagesSpan : this.inputData.pagesSpanOrig) + (this.inputData.scrollBtn.match(/left|right/) ? 1 : this.inputData.scrollBtn == 'both' ? 2 : 0))) + '%';

	var html = '' +
	'<table>' +
		'<tr>' +
			(this.inputData.align.match(/right|center/) ? '<td style="visibility: hidden;"></td>' : '') +
			(this.inputData.scrollBtn.match(/left|both/) ? '<td class="scrollBtn" width="' + tdWidth + '"><a href="#" class="scrollBtnL">'+this.inputData.scrollBtnCaptionL+'</a></td>' : '');
			for (var i=1; i<=this.inputData.pagesSpan; i++){
				html += '<td width="' + tdWidth + '" class="paginator_cell"></td>';
			}
			html += '' +
			(this.inputData.scrollBtn.match(/right|both/) ? '<td class="scrollBtn" width="' + tdWidth + '"><a href="#" class="scrollBtnR">'+this.inputData.scrollBtnCaptionR+'</a></td>' : '') +
			(this.inputData.align.match(/left|center/) ? '<td style="visibility: hidden;"></td>' : '')+
		'</tr>' +
		'<tr>' +
			(this.inputData.align.match(/right|center/) ? '<td style="visibility: hidden;"></td>' : '') +
			'<td colspan="' + (this.inputData.pagesSpan +
													(this.inputData.scrollBtn.match(/left|right/) ? 1 : this.inputData.scrollBtn == 'both' ? 2 : 0)
													) + '">' +
				'<div class="scroll_bar">' +
					'<div class="scroll_trough"></div>' +
					'<div class="scroll_thumb">' +
						'<div class="scroll_knob"></div>' +
					'</div>' +
					'<div class="current_page_mark"></div>' +
				'</div>' +
			'</td>' +
			(this.inputData.align.match(/left|center/) ? '<td style="visibility: hidden;"></td>' : '')+
		'</tr>' +
	'</table>';

	return html;
}

/*
	Set all needed properties for scrollThumb and it's width
*/
Paginator.prototype.initScrollThumb = function(){
	this.html.scrollThumb.widthMin = '8'; // minimum width of the scrollThumb (px)
	this.html.scrollThumb.widthPercent = this.inputData.pagesSpan/this.inputData.pagesTotal * 100;

	this.html.scrollThumb.xPosPageCurrent = (this.inputData.pageCurrent - Math.round(this.inputData.pagesSpan/2))/this.inputData.pagesTotal * (this.html.table.offsetWidth - this.skeepWidth());
	this.html.scrollThumb.xPos = this.html.scrollThumb.xPosPageCurrent;

	this.html.scrollThumb.xPosMin = 0;
	this.html.scrollThumb.xPosMax;

	this.html.scrollThumb.widthActual;

	this.setScrollThumbWidth();

}

Paginator.prototype.skeepWidth = function(){
	var w = 0;
	for (var i = 0; i < this.html.skeepedTds.length; i++){
		w += this.html.skeepedTds[i].offsetWidth;
	}
	return w;
}

Paginator.prototype.setScrollThumbWidth = function(){
	// Try to set width in percents
	this.html.scrollThumb.style.width = this.html.scrollThumb.widthPercent + "%";

	// Fix the actual width in px
	this.html.scrollThumb.widthActual = this.html.scrollThumb.offsetWidth;

	// If actual width less then minimum which we set
	if(this.html.scrollThumb.widthActual < this.html.scrollThumb.widthMin){
		this.html.scrollThumb.style.width = this.html.scrollThumb.widthMin + 'px';
	}

	this.html.scrollThumb.xPosMax = this.html.table.offsetWidth - this.skeepWidth() - this.html.scrollThumb.widthActual;
}

Paginator.prototype.moveScrollThumb = function(){
	this.html.scrollThumb.style.left = this.html.scrollThumb.xPos + "px";
}


/*
	Set all needed properties for pageCurrentMark, it's width and move it
*/
Paginator.prototype.initPageCurrentMark = function(){
	this.html.pageCurrentMark.widthMin = '3';
	this.html.pageCurrentMark.widthPercent = 100 / this.inputData.pagesTotal;
	this.html.pageCurrentMark.widthActual;

	this.setPageCurrentPointWidth();
	this.movePageCurrentPoint();
}

Paginator.prototype.setPageCurrentPointWidth = function(){
	// Try to set width in percents
	this.html.pageCurrentMark.style.width = this.html.pageCurrentMark.widthPercent + '%';

	// Fix the actual width in px
	this.html.pageCurrentMark.widthActual = this.html.pageCurrentMark.offsetWidth;

	// If actual width less then minimum which we set
	if(this.html.pageCurrentMark.widthActual < this.html.pageCurrentMark.widthMin){
		this.html.pageCurrentMark.style.width = this.html.pageCurrentMark.widthMin + 'px';
	}
}

Paginator.prototype.movePageCurrentPoint = function(){
	if(this.html.pageCurrentMark.widthActual < this.html.pageCurrentMark.offsetWidth){
		this.html.pageCurrentMark.style.left = (this.inputData.pageCurrent - 1)/this.inputData.pagesTotal * (this.html.table.offsetWidth - this.skeepWidth()) - this.html.pageCurrentMark.offsetWidth/2 + "px";
	} else {
		this.html.pageCurrentMark.style.left = (this.inputData.pageCurrent - 1)/this.inputData.pagesTotal * (this.html.table.offsetWidth - this.skeepWidth()) + "px";
	}
}



/*
	Drag, click and resize events
*/
Paginator.prototype.initEvents = function(){
	var _this = this;

	this.html.scrollThumb.onmousedown = function(e){
		if (!e) var e = window.event;
		e.cancelBubble = true;
		if (e.stopPropagation) e.stopPropagation();

		var dx = getMousePosition(e).x - this.xPos;
		document.onmousemove = function(e){
			if (!e) var e = window.event;
			_this.html.scrollThumb.xPos = getMousePosition(e).x - dx;

			// the first: draw pages, the second: move scrollThumb (it was logically but ie sucks!)
			_this.moveScrollThumb();
			_this.drawPages();


		}
		document.onmouseup = function(){
			document.onmousemove = null;
			_this.enableSelection();
		}
		_this.disableSelection();
	}

	this.html.scrollBar.onmousedown = function(e){
		if (!e) var e = window.event;
		if(matchClass(_this.paginatorBox, 'fullsize')) return;

		_this.html.scrollThumb.xPos = getMousePosition(e).x - getPageX(_this.html.scrollBar) - _this.html.scrollThumb.offsetWidth/2;

		_this.moveScrollThumb();
		_this.drawPages();


	}

	if (this.html.scrollBtnL){
		this.html.scrollBtnL.getElementsByTagName('a')[0].onclick = function(){
			_this.html.scrollThumb.xPos -=
				(
					(_this.html.table.offsetWidth - _this.skeepWidth()) /
					_this.inputData.pagesTotal * (_this.inputData.pagesSpan)
				);
			_this.moveScrollThumb();
			_this.drawPages();
			return false;
		}
	}
	if (this.html.scrollBtnR){
		this.html.scrollBtnR.getElementsByTagName('a')[0].onclick = function(){
			_this.html.scrollThumb.xPos +=
				(_this.html.scrollThumb.xPos == 0 ? 2 : 0) +
				(
					(_this.html.table.offsetWidth - _this.skeepWidth()) /
					_this.inputData.pagesTotal * (_this.inputData.pagesSpan)
				);
			_this.moveScrollThumb();
			_this.drawPages();
			return false;
		}
	}

	// Comment the row beneath if you set paginator width fixed
	//	addEvent(window, 'resize', function(){Paginator.resizePaginator(_this)});
	WinResizeFunc.push({'resizePaginator': function(){Paginator.resizePaginator(_this);}});
}

/*
	Redraw current span of pages
*/
Paginator.prototype.drawPages = function(){
	var percentFromLeft = this.html.scrollThumb.xPos/(this.html.table.offsetWidth - this.skeepWidth());
	var cellFirstValue = Math.round(percentFromLeft * this.inputData.pagesTotal);

	var html = "";
	// drawing pages control the position of the scrollThumb on the edges!
	if(cellFirstValue < 1){
		cellFirstValue = 1;
		this.html.scrollThumb.xPos = 0;
		this.moveScrollThumb();
	} else if(cellFirstValue >= this.inputData.pagesTotal - this.inputData.pagesSpan) {
		cellFirstValue = this.inputData.pagesTotal - this.inputData.pagesSpan + 1;
		this.html.scrollThumb.xPos = this.html.table.offsetWidth - this.skeepWidth() - this.html.scrollThumb.offsetWidth;
		this.moveScrollThumb();
	}
	if (this.html.scrollBtnL){
		if (cellFirstValue == 1) {
			if (this.html.scrollBtnL && !this.html.scrollBtnL.className.match(/\s*disable/i))
				this.html.scrollBtnL.className += ' disable';
		} else this.html.scrollBtnL.className = this.html.scrollBtnL.className.replace(/\s*disable/gi,'');
	}
	if (this.html.scrollBtnR){
		if (cellFirstValue == this.inputData.pagesTotal - this.inputData.pagesSpan + 1){
			if (this.html.scrollBtnR && !this.html.scrollBtnR.className.match(/\s*disable/i))
				this.html.scrollBtnR.className += ' disable';
		} else this.html.scrollBtnR.className = this.html.scrollBtnR.className.replace(/\s*disable/gi,'');
	}

	for(var i=0; i<this.html.tdsPages.length; i++){
		var cellCurrentValue = cellFirstValue + i;
		if(cellCurrentValue == this.inputData.pageCurrent){

			html = "<span><span class='line'></span>" + "<strong>" + cellCurrentValue + "</strong>" + "</span>";
		} else {
			var Url = this.inputData.baseUrl;
			if(cellCurrentValue==1) Url = Url.replace(/\&?pagenum=[^&]+/,'');			
			html = "<span>" + "<a href='" + Url.replace("%7Bcurrent_page%7D",cellCurrentValue) + "'>" + cellCurrentValue + "</a>" + "</span>";
		}
		this.html.tdsPages[i].innerHTML = html;
	}
}

/*
	Scroll to current page
*/
Paginator.prototype.scrollToPageCurrent = function(){
	this.html.scrollThumb.xPosPageCurrent = (this.inputData.pageCurrent - Math.round(this.inputData.pagesSpan/2))/this.inputData.pagesTotal * (this.html.table.offsetWidth - this.skeepWidth());
	this.html.scrollThumb.xPos = this.html.scrollThumb.xPosPageCurrent;

	this.moveScrollThumb();
	this.drawPages();

}



Paginator.prototype.disableSelection = function(){
	document.onselectstart = function(){
		return false;
	}
	this.html.scrollThumb.focus();
}

Paginator.prototype.enableSelection = function(){
	document.onselectstart = function(){
		return true;
	}
}

/*
	Function is used when paginator was resized (window.onresize fires it automatically)
	Use it when you change paginator with DHTML
	Do not use it if you set fixed width of paginator
*/
Paginator.resizePaginator = function (paginatorObj){

	paginatorObj.setPageCurrentPointWidth();
	paginatorObj.movePageCurrentPoint();

	paginatorObj.setScrollThumbWidth();
	paginatorObj.scrollToPageCurrent();
}




/*
	Global functions which are used
*/
function getElementsByClassName(objParentNode, strNodeName, strClassName){
	var nodes = objParentNode.getElementsByTagName(strNodeName);
	if(!strClassName){
		return nodes;
	}
	var nodesWithClassName = [];
	for(var i=0; i<nodes.length; i++){
		if(matchClass( nodes[i], strClassName )){
			nodesWithClassName[nodesWithClassName.length] = nodes[i];
		}
	}
	return nodesWithClassName;
}


function addClass( objNode, strNewClass ) {
	replaceClass( objNode, strNewClass, '' );
}

function removeClass( objNode, strCurrClass ) {
	replaceClass( objNode, '', strCurrClass );
}

function replaceClass( objNode, strNewClass, strCurrClass ) {
	var strOldClass = strNewClass;
	if ( strCurrClass && strCurrClass.length ){
		strCurrClass = strCurrClass.replace( /\s+(\S)/g, '|$1' );
		if ( strOldClass.length ) strOldClass += '|';
		strOldClass += strCurrClass;
	}
	objNode.className = objNode.className.replace( new RegExp('(^|\\s+)(' + strOldClass + ')($|\\s+)', 'g'), '$1' );
	objNode.className += ( (objNode.className.length)? ' ' : '' ) + strNewClass;
}

function matchClass( objNode, strCurrClass ) {
	return ( objNode && objNode.className.length && objNode.className.match( new RegExp('(^|\\s+)(' + strCurrClass + ')($|\\s+)') ) );
}


function addEvent(objElement, strEventType, ptrEventFunc) {
	if (objElement.addEventListener)
		objElement.addEventListener(strEventType, ptrEventFunc, false);
	else if (objElement.attachEvent)
		objElement.attachEvent('on' + strEventType, ptrEventFunc);
}
function removeEvent(objElement, strEventType, ptrEventFunc) {
	if (objElement.removeEventListener) objElement.removeEventListener(strEventType, ptrEventFunc, false);
		else if (objElement.detachEvent) objElement.detachEvent('on' + strEventType, ptrEventFunc);
}


function getPageY( oElement ) {
	var iPosY = oElement.offsetTop;
	while ( oElement.offsetParent != null ) {
		oElement = oElement.offsetParent;
		iPosY += oElement.offsetTop;
		if (oElement.tagName == 'BODY') break;
	}
	return iPosY;
}

function getPageX( oElement ) {
	var iPosX = oElement.offsetLeft;
	while ( oElement.offsetParent != null ) {
		oElement = oElement.offsetParent;
		iPosX += oElement.offsetLeft;
		if (oElement.tagName == 'BODY') break;
	}
	return iPosX;
}

function getMousePosition(e) {
	if (e.pageX || e.pageY){
		var posX = e.pageX;
		var posY = e.pageY;
	}else if (e.clientX || e.clientY) 	{
		var posX = e.clientX + document.body.scrollLeft + document.documentElement.scrollLeft;
		var posY = e.clientY + document.body.scrollTop + document.documentElement.scrollTop;
	}
	return {x:posX, y:posY}
}

/*ellipsis*/

jQuery.fn.ellipsis = function(
  maxW,       // element max width (px)
  maxH,       // element max height (px)
  orig_max_w, // element max length (chars)
  real_max_h, // element max height (lines)
  start
) {
	return this.each(function(){
		var el = $(this);
		var mH = maxH || parseInt(el.parent().css('maxHeight'));
		if (!mH || mH <= 0) mH = el.parent().height();
		var mW = maxW || parseInt(el.parent().css('maxWidth'));
		if (!mW || mW <= 0) mW = el.parent().width();

		var oT = el.attr('title') || el.html(); //text
		if (el.attr('title') == '') {
			el.not('.nott').attr('title', oT);
		} else el.html(oT);

		var ch = oT.length; //characters
		var s = start || parseInt(ch / 2); //step

		if ( ch < orig_max_w ) {
			el.attr('title','');
			return;
		}

		var real_max_w = Math.round( orig_max_w / 0.65 );
		var words = oT.split( /[ -]/ );
		var curr_line    = 0;
		var line_length  = 0;
		var total_length = 0;
		var need_dots    = 0;
		var i            = 0;
		while ( curr_line < real_max_h && i < words.length ) {
		  var w_len = words[i].length;

		  if ( w_len >= real_max_w ) {
		    total_length += real_max_w + 1;
		    break;
		  } else if ( line_length + w_len > real_max_w ) {
		    curr_line++;
		    if (curr_line < real_max_h) {
		      total_length += w_len + 1;
		      line_length   = w_len + 1;
		     } else {
		      total_length += real_max_w + 1 - line_length;
		     }
		  } else {
		    total_length += w_len + 1;
		    line_length  += w_len + 1;
		  }
		  i++;
		}

		if ( total_length < ch ) {
		  oT = oT.substring( 0, total_length - 2 );
		  oT = oT.replace( /[ -\:\,\.]+$/, "" );
		  oT += "…";
		}

		var first_try = 1;

		ch = oT.length;
		s = ch / 2;
		el.html( oT );

		var nT = oT; //newText
		while (s > 1) {
			el.html(nT);

			var oH = el.outerHeight(), oW = el.outerWidth();
			if ( oH <= mH && oW <= mW ) {
				if ( first_try ) {
					s = 0;
				} else if (oT.length == nT.length) {
					s = 0;
				} else {
					ch += s;
					nT = oT.substring(0, ch);
				}
			} else {
				ch -= s;
				nT = nT.substring(0, ch);
			}
			s = parseInt(s / 2);
			first_try = 0;
		}

		if (oT.length > nT.length) {
			nT = nT.substring(0, nT.length - 2);
			el.html(nT + "…");
		} else if (el.attr('title').length == nT.length){
			el.attr('title','');
		}
	});
};


/* jQuery Tools 1.2.5 - The missing UI library for the Web */
(function(a){function t(d,b){var c=this,j=d.add(c),o=a(window),k,f,m,g=a.tools.expose&&(b.mask||b.expose),n=Math.random().toString().slice(10);if(g){if(typeof g=="string")g={color:g};g.closeOnClick=g.closeOnEsc=false}var p=b.target||d.attr("rel");f=p?a(p):d;if(!f.length)throw"Could not find Overlay: "+p;d&&d.index(f)==-1&&d.click(function(e){c.load(e);return e.preventDefault()});a.extend(c,{load:function(e){if(c.isOpened())return c;var h=q[b.effect];if(!h)throw'Overlay: cannot find effect : "'+b.effect+
'"';b.oneInstance&&a.each(s,function(){this.close(e)});e=e||a.Event();e.type="onBeforeLoad";j.trigger(e);if(e.isDefaultPrevented())return c;m=true;g&&a(f).expose(g);var i=b.top,r=b.left,u=f.outerWidth({margin:true}),v=f.outerHeight({margin:true});if(typeof i=="string")i=i=="center"?Math.max((o.height()-v)/2,0):parseInt(i,10)/100*o.height();if(r=="center")r=Math.max((o.width()-u)/2,0);h[0].call(c,{top:i,left:r},function(){if(m){e.type="onLoad";j.trigger(e)}});g&&b.closeOnClick&&a.mask.getMask().one("click",
c.close);b.closeOnClick&&a(document).bind("click."+n,function(l){a(l.target).parents(f).length||c.close(l)});b.closeOnEsc&&a(document).bind("keydown."+n,function(l){l.keyCode==27&&c.close(l)});return c},close:function(e){if(!c.isOpened())return c;e=e||a.Event();e.type="onBeforeClose";j.trigger(e);if(!e.isDefaultPrevented()){m=false;q[b.effect][1].call(c,function(){e.type="onClose";j.trigger(e)});a(document).unbind("click."+n).unbind("keydown."+n);g&&a.mask.close();return c}},getOverlay:function(){return f},
getTrigger:function(){return d},getClosers:function(){return k},isOpened:function(){return m},getConf:function(){return b}});a.each("onBeforeLoad,onStart,onLoad,onBeforeClose,onClose".split(","),function(e,h){a.isFunction(b[h])&&a(c).bind(h,b[h]);c[h]=function(i){i&&a(c).bind(h,i);return c}});k=f.find(b.close||".close");if(!k.length&&!b.close){k=a('<a class="close"></a>');f.prepend(k)}k.click(function(e){c.close(e)});b.load&&c.load()}a.tools=a.tools||{version:"1.2.5"};a.tools.overlay={addEffect:function(d,
b,c){q[d]=[b,c]},conf:{close:null,closeOnClick:true,closeOnEsc:true,closeSpeed:"fast",effect:"default",fixed:!a.browser.msie||a.browser.version>6,left:"center",load:false,mask:null,oneInstance:true,speed:"normal",target:null,top:"10%"}};var s=[],q={};a.tools.overlay.addEffect("default",function(d,b){var c=this.getConf(),j=a(window);if(!c.fixed){d.top+=j.scrollTop();d.left+=j.scrollLeft()}d.position=c.fixed?"fixed":"absolute";this.getOverlay().css(d).fadeIn(c.speed,b)},function(d){this.getOverlay().fadeOut(this.getConf().closeSpeed,
d)});a.fn.overlay=function(d){var b=this.data("overlay");if(b)return b;if(a.isFunction(d))d={onBeforeLoad:d};d=a.extend(true,{},a.tools.overlay.conf,d);this.each(function(){b=new t(a(this),d);s.push(b);a(this).data("overlay",b)});return d.api?b:this}})(jQuery);
(function(h){function k(d){var e=d.offset();return{top:e.top+d.height()/2,left:e.left+d.width()/2}}var l=h.tools.overlay,f=h(window);h.extend(l.conf,{start:{top:null,left:null},fadeInSpeed:"fast",zIndex:9999});function o(d,e){var a=this.getOverlay(),c=this.getConf(),g=this.getTrigger(),p=this,m=a.outerWidth({margin:true}),b=a.data("img"),n=c.fixed?"fixed":"absolute";if(!b){b=a.css("backgroundImage");if(!b)throw"background-image CSS property not set for overlay";b=b.slice(b.indexOf("(")+1,b.indexOf(")")).replace(/\"/g,
"");a.css("backgroundImage","none");b=h('<img src="'+b+'" class="overlayfix"/>');b.css({border:0,display:"none"}).width(m);h("body").append(b);a.data("img",b)}var i=c.start.top||Math.round(f.height()/2),j=c.start.left||Math.round(f.width()/2);if(g){g=k(g);i=g.top;j=g.left}if(c.fixed){i-=f.scrollTop();j-=f.scrollLeft()}else{d.top+=f.scrollTop();d.left+=f.scrollLeft()}b.css({position:"absolute",top:i,left:j,width:0,zIndex:c.zIndex}).show();d.position=n;a.css(d);b.animate({top:a.css("top"),left:a.css("left"),width:m},
c.speed,function(){a.css("zIndex",c.zIndex+1).fadeIn(c.fadeInSpeed,function(){p.isOpened()&&!h(this).index(a)?e.call():a.hide()})}).css("position",n)}function q(d){var e=this.getOverlay().hide(),a=this.getConf(),c=this.getTrigger();e=e.data("img");var g={top:a.start.top,left:a.start.left,width:0};c&&h.extend(g,k(c));a.fixed&&e.css({position:"absolute"}).animate({top:"+="+f.scrollTop(),left:"+="+f.scrollLeft()},0);e.animate(g,a.closeSpeed,d)}l.addEffect("apple",o,q)})(jQuery);
(function(b){function k(){if(b.browser.msie){var a=b(document).height(),d=b(window).height();return[window.innerWidth||document.documentElement.clientWidth||document.body.clientWidth,a-d<20?d:a]}return[b(document).width(),b(document).height()]}function h(a){if(a)return a.call(b.mask)}b.tools=b.tools||{version:"1.2.5"};var l;l=b.tools.expose={conf:{maskId:"exposeMask",loadSpeed:"slow",closeSpeed:"fast",closeOnClick:true,closeOnEsc:true,zIndex:9998,opacity:0.8,startOpacity:0,color:"#fff",onLoad:null,
onClose:null}};var c,i,e,g,j;b.mask={load:function(a,d){if(e)return this;if(typeof a=="string")a={color:a};a=a||g;g=a=b.extend(b.extend({},l.conf),a);c=b("#"+a.maskId);if(!c.length){c=b("<div/>").attr("id",a.maskId);b("body").append(c)}var m=k();c.css({position:"absolute",top:0,left:0,width:m[0],height:m[1],display:"none",opacity:a.startOpacity,zIndex:a.zIndex});a.color&&c.css("backgroundColor",a.color);if(h(a.onBeforeLoad)===false)return this;a.closeOnEsc&&b(document).bind("keydown.mask",function(f){f.keyCode==
27&&b.mask.close(f)});a.closeOnClick&&c.bind("click.mask",function(f){b.mask.close(f)});b(window).bind("resize.mask",function(){b.mask.fit()});if(d&&d.length){j=d.eq(0).css("zIndex");b.each(d,function(){var f=b(this);/relative|absolute|fixed/i.test(f.css("position"))||f.css("position","relative")});i=d.css({zIndex:Math.max(a.zIndex+1,j=="auto"?0:j)})}c.css({display:"block"}).fadeTo(a.loadSpeed,a.opacity,function(){b.mask.fit();h(a.onLoad);e="full"});e=true;return this},close:function(){if(e){if(h(g.onBeforeClose)===
false)return this;c.fadeOut(g.closeSpeed,function(){h(g.onClose);i&&i.css({zIndex:j});e=false});b(document).unbind("keydown.mask");c.unbind("click.mask");b(window).unbind("resize.mask")}return this},fit:function(){if(e){var a=k();c.css({width:a[0],height:a[1]})}},getMask:function(){return c},isLoaded:function(a){return a?e=="full":e},getConf:function(){return g},getExposed:function(){return i}};b.fn.mask=function(a){b.mask.load(a);return this};b.fn.expose=function(a){b.mask.load(a,this);return this}})(jQuery);

