function BigCover(ID){
  document.getElementById('bookcover_'+ID).style.display = 'block';
}

function CloseCover(ID){
  document.getElementById('bookcover_'+ID).style.display = 'none';
}

currentExpanded=0;
collapsePrevious=0;

function ExpandNode(nodeId){
  clickedElement=document.getElementById(nodeId).style;
  if (!clickedElement)
    clickedElement=document.all.nodeId.style
  if (!clickedElement)
    return 1
  if (clickedElement.display=="block")
  {
    clickedElement.display="none";
    if (document.getElementById('img_'+nodeId))
      document.getElementById('img_'+nodeId).src=document.getElementById('img_'+nodeId).src.replace('minus.gif',"plus.gif");
  }
  else {
    if ((currentExpanded) && (collapsePrevious))
      currentExpanded.display="none"
    currentExpanded=clickedElement;
    currentExpanded.display="block";
    if (document.getElementById('img_'+nodeId))
    document.getElementById('img_'+nodeId).src=document.getElementById('img_'+nodeId).src.replace("plus.gif",'minus.gif');
  }
  ToggledAlready=1;
}

function chkgrp(itemname){
    SubItems=document.getElementById(itemname)
    for (i=0;i != SubItems.getElementsByTagName("input").length;i++){
      SubItems.getElementsByTagName("input").item(i).checked = document.getElementById('genre_'+itemname).checked
    }
}

function UnchPrnt(name){
  document.getElementById('genre_'+name).checked=0
}

function ShowHide(id)
{
  var itm = null;
  if (document.getElementById) {
    itm = document.getElementById(id);
  } else if (document.all){
    itm = document.all[id];
  } else if (document.layers){
    itm = document.layers[id];
  }

  if (!itm)
  {
    // do nothing
  }
  else if (itm.style)
  {
	if (itm.style.display == "none")
	{
	  itm.style.display = "";
	}
    else
	{
	  itm.style.display = "none";
	}
  }
  else
  {
    itm.visibility = "show";
  }
}

function AddAuth()
{
  document.subscribe_form.author_list.value=document.subscribe_form.author_list.value + document.subscribe_form.author_choose.value + '\n';
}

function ExpandSubscribeForm(val)
{
  document.getElementById('subscribe_options').style.display=val>0?'block':'none';
  document.getElementById('genres').style.display=val==2?'block':'none';
  document.getElementById('genres_text').style.display=val==2?'block':'none';
  document.getElementById('pattern').style.display=val==2?'block':'none';
  document.getElementById('pattern_text').style.display=val==2?'block':'none';
  document.getElementById('authors').style.display=val==2?'block':'none';
  document.getElementById('authors_text').style.display=val==2?'block':'none';

  if (document.getElementById('email'))
  {
    document.getElementById('email').style.display=val>0?'block':'none';
  }
}

function ChkLanguage(val)
{
  if (val == 2) {
		document.getElementById('langs').style.display = 'inline';
  } else {
		document.getElementById('langs').style.display = 'none';
  }
}

function switchVisibility (id) {
  el = document.getElementById (id).style;
	im = document.getElementById ('ei_' + id);

  if (el.display == "block") {
		el.display = "none";
		im.src = "/static/img/expand.gif";
	} else {
		el.display = "block";
		im.src = "/static/img/collapse.gif";
	}
}

function HideNavigation (e_pos,id) {
	e_pos.innerHTML = '<a href="DrawNavigation (this.parentNode,'+id+')">Папки</a>';
}

function DrawConfig (id,capt) {
	document.getElementById ("div_conf").style.display = "block";
	document.getElementById ("create_input").value = id;
	document.getElementById ("ren_input").value = id;
	document.getElementById ("ren_input_txt").value = capt;
	document.getElementById ("span_capt").innerHTML = capt;
	if (id == 0) {
		document.getElementById ("ren_input_txt").disabled = true;
	} else {
		document.getElementById ("ren_input_txt").disabled = false;
	}
}

function InsertOptInCombo (el,id) {
	el.innerHTML = '<option value="0" selected>Перенести в…</option>' + combo_text;
//  document.getElementById ("submit_move_" + id).style.display = "block";
}

function DrawSubmitButton (id,v) {
  document.getElementById ("submit_move_" + id).style.display = (v!=0)?"block":"none";
}

function CoolClk(id){
  document.getElementById(id).click();
}
function DButn(id){
  document.getElementById(id).disabled=true;
}

function ShowFrame (path, medium) {
  if (medium) {
    window.open (path, '', 'scrollbars=1,resizable=1,width=900,height=700');
  } else {
    window.open (path, '', 'scrollbars=1,resizable=1,width=500,height=300');
  }
}

function SelAvatar (id,img) {
  window.opener.document.getElementById ('avatar_img').src = '/static/users/' + img;
  window.opener.document.getElementById ('avatar_id').value = img;
  window.opener.document.getElementById ('id_avatar').value = id;
  self.close ();
}

function AddRecArt (id,capt) {
	var art_id_input = window.opener.document.getElementById ('art_id');

	if (art_id_input.value.search (id) >= 0) {
		return;
	}

	window.opener.document.getElementById ('art_name_div').innerHTML += '<h2>«' + capt + '»</h2>';
	art_id_input.value += id + ';';
	self.close ();
}

function switchDisplay (el_capt,link_capt,vis_txt,unvis_txt) {
  var el = document.getElementById (el_capt);
  var link = document.getElementById (link_capt);
  if (el.style.display == 'none') {
    el.style.display = 'block';
    link.innerHTML = vis_txt;
  } else {
    el.style.display = 'none';
    link.innerHTML = unvis_txt;
  }
}

function TextAreaMaxLength(Object, MaxLen) {
  Object.value = Object.value.substring(0,MaxLen);
}


function SearchResultsHL(hlstrings){
  var HLStrings=hlstrings.split(' ');
	var Changed = 0;
	var Hcode = document.getElementById('searchresults').innerHTML
  for (i=0;i < HLStrings.length;i++){
		if (HLStrings[i].length > 2 && HLStrings[i] != 'quot'){
			HLStrings[i]=HLStrings[i].replace('.','\.');
			HLStrings[i]=HLStrings[i].replace(/[&<>]/,'.');
			HLStrings[i]='(>[^<>]*)('+HLStrings[i]+')';
			var SearchToReplace=new RegExp(HLStrings[i],'gi');
			Hcode =	Hcode.replace(SearchToReplace,'$1<span class="searchresults">$2</span>');
			Changed = 1;
		}
  }
	if (Changed) {
		document.getElementById('searchresults').innerHTML = Hcode;
	}
}

function init() {
  SlidesInit();
}

// ================== SLIDEIMAGES ====================
var Slides = {};

function SlidesAppend (id,big_src) {
  Slides[id] = {};

  Slides[id]['imgsize'] = {sw: 0, sh: 0, bw: 0, bh: 0};
  Slides[id]['pos'] = 0;
  Slides[id]['timer'] = null;
  Slides[id]['img'] = null;
  Slides[id]['div'] = null;
  Slides[id]['big_img'] = null;
  Slides[id]['big_src'] = big_src;
  Slides[id]['sml_src'] = '';
}

function SlidesInit () {
  for (var id in Slides) {
    img = __el(id);

    Slides[id]['img'] = img;
    Slides[id]['sml_src'] = img.src;
    Slides[id]['imgsize'].sw = img.width;
    Slides[id]['imgsize'].sh = img.height;

    Slides[id]['big_img'] = document.createElement ('img');
    Slides[id]['big_img'].src = Slides[id]['big_src'];

    var div = document.createElement('div');
    div.style.width = Slides[id]['imgsize'].sw + 'px';
    div.style.height = Slides[id]['imgsize'].sh + 'px';
    div.style.textAlign = 'left';
    div.className = 'cover_div';
    var imgparent = img.parentNode;
    var imgitem = img;
    if (imgparent.nodeName == 'A') {
      imgitem = imgparent;
      imgparent = imgparent.parentNode;
    }
    imgparent.insertBefore (div,imgitem);
    div.appendChild (imgitem);

    Slides[id]['div'] = div;

    img.onmouseover = SlideImageIn;
    img.onmouseout = SlideImageOut;
    img.style.zIndex = 1000;

    setTimeout('SlideImage (-100,"'+id+'")',1);
  }
  setTimeout ('_slides_wait_preload()',100);
}

var wait_cycles = 0;
function _slides_wait_preload () {
  var completed = 1;
  for (var id in Slides) {
    if (Slides[id]['big_img'].width > 36.6) {
      Slides[id]['imgsize'].bw = Slides[id]['big_img'].width;
      Slides[id]['imgsize'].bh = Slides[id]['big_img'].height;
    } else {
      completed = 0;
    }
  }

  if (!completed) {
    wait_cycles++;
    setTimeout ('_slides_wait_preload()',(wait_cycles>30)?3000:100);
  }
}

function SlideImageIn () {
  SlideImage (+14,this.id);
}

function SlideImageOut () {
  SlideImage (-20,this.id);
}

function SlideImage (step,id) {
  if (Slides[id]['timer']) clearTimeout (Slides[id]['timer']);
  if (!Slides[id]['imgsize'].bw) {
    if ((''+Slides[id]['img'].src).match('loading')) {}
    else {
      Slides[id]['img'].src = '/static/img/loading.gif';
    }
  } else {

  Slides[id]['pos'] += step;
  if (Slides[id]['pos'] > 100) Slides[id]['pos'] = 100;
  if (Slides[id]['pos'] < 0) Slides[id]['pos'] = 0;

  if (Slides[id]['img'].style.position != 'absolute') {
    Slides[id]['img'].src = Slides[id]['big_src'];
    Slides[id]['divOffset'] = _getOffset(Slides[id]['div']);
    Slides[id]['img'].style.position = 'absolute';
  }

  var dx = Slides[id]['pos']*(Slides[id]['imgsize'].bw-Slides[id]['imgsize'].sw)/100;
  var dy = Slides[id]['pos']*(Slides[id]['imgsize'].bh-Slides[id]['imgsize'].sh)/100;

  var cwidth = Math.floor(Slides[id]['imgsize'].sw + dx);
  var cheight = Math.floor(Slides[id]['imgsize'].sh + dy);
  var cleft = Math.floor(Slides[id]['divOffset'].X - dx/2);
  var ctop = Math.floor(Slides[id]['divOffset'].Y - dy/2);

  var bodySize = getBodySize();
  var minx = bodySize.left - Slides[id]['divOffset'].fullX + Slides[id]['divOffset'].X;
  var miny = bodySize.top  - Slides[id]['divOffset'].fullY + Slides[id]['divOffset'].Y;
  var maxx = minx + parseInt(bodySize.width) - cwidth;
  var maxy = miny + parseInt(bodySize.height) - cheight;

  if (cleft < minx) cleft = minx;
  if (cleft > maxx) cleft = maxx;
  if (ctop < miny) ctop = miny;
  if (ctop > maxy) ctop = maxy;

  Slides[id]['img'].width = cwidth;
  Slides[id]['img'].height = cheight;
  Slides[id]['img'].style.left = cleft + 'px';
  Slides[id]['img'].style.top = ctop + 'px';
  }

  if (Slides[id]['pos'] < 100 && step > 0 || Slides[id]['pos'] > 0 && step < 0) {
    Slides[id]['timer'] = setTimeout ('SlideImage('+step+',"'+id+'")',20);
  }
  if (step < 0 && Slides[id]['pos'] == 0) {
    Slides[id]['img'].style.position = 'static';
    Slides[id]['img'].style.top = 'auto';
    Slides[id]['img'].style.left = 'auto';
    Slides[id]['img'].src = Slides[id]['sml_src'];
  }
}


// Elements. Sobakka.framework.1.0 (c) russel

function __el (id) {
  return document.getElementById (id);
}

function __el_of (el,tag) {
  return el.getElementsByTagName (tag);
}

/*
function _getX (el,toBody) {
  if (el.style && parseInt (getCurrentStyle(el).left) && getCurrentStyle(el).position == 'absolute') return parseInt (el.style.left);
  var x = 0;
  //while (el) {
  while (el && (getCurrentStyle(el).position != 'relative' || toBody)) {
    x += parseInt (el.offsetLeft);// + parseInt (el.clientLeft);
    el = el.offsetParent;
  }
  return x;
}

function _getY (el,toBody) {
  if (el.style && parseInt (getCurrentStyle(el).top) && getCurrentStyle(el).position == 'absolute') return parseInt (el.style.top);
  var y = 0;
  //while (el) {
  while (el && (getCurrentStyle(el).position != 'relative' || toBody)) {
    y += parseInt (el.offsetTop);// + parseInt (el.clientTop);
    el = el.offsetParent;
  }
  return y;
}
//*/

function _getOffset (el) {
  var elStyle = getCurrentStyle(el);
  if (elStyle && parseInt (elStyle.left) && elStyle.position == 'absolute')
    return {X: elStyle.left,
            Y: elStyle.top,
            fullX: elStyle.left,
            fullY: elStyle.top};

  var out = {X: 0, Y: 0, fullX: 0, fullY: 0};
  var b=true;
  var b_getFull=true;
  if (el.getBoundingClientRect){
    var tmp = getOffsetRect(el);
    out.fullX = tmp.left;
    out.fullY = tmp.top;
    b_getFull = false;
  }
  while (el && (b || b_getFull)) {
    if(b && getCurrentStyle(el).position == 'relative'){
      if(b_getFull){
        out.fullX = out.X;
        out.fullY = out.Y;
        b=false;
      } else {
        break;
      }
    }
    if(b){
      out.X += parseInt (el.offsetLeft);
      out.Y += parseInt (el.offsetTop);
    } else {
      out.fullX += parseInt (el.offsetLeft);
      out.fullY += parseInt (el.offsetTop);
    }
    el = el.offsetParent;
  }
  if(b && b_getFull){
    out.fullX = out.X;
    out.fullY = out.Y;
  }
  return out;
}

function _width (obj) {
  if (obj.style && parseInt (obj.style.width)) return parseInt (obj.style.width);
  return obj.offsetWidth;
}

function _height (obj) {
  if (obj.style && parseInt (obj.style.height)) return parseInt (obj.style.height);
  return obj.offsetHeight;
}

function debug (el) {
  var str = '';
  for (k in el) {
    str += k + ' = ' + el[k] + '<br/>';
  }
  __el ('debug_div').innerHTML = str;
}

function WarnQuickBuy(Summ,PreOrder){
	var Descr = 'Cразу после этого вы сможете скачивать эту книгу';
	if (PreOrder){
		Descr = 'Сразу после этого ваш предзаказ будет принят и помещен в «Мои книги»';
	}
	return confirm('Сейчас с вашего счета в книжном магазине будет списана сумма '+Summ+'р.\n'+Descr+'. Продолжить?')
}


//#########################################################
function getCurrentStyle(el){
  if(!el) return null;
  var s=el.currentStyle;
  if(!s) s=document.defaultView.getComputedStyle(el,null); // Для FireFox
  return s;
}

/*
function getOffset(elem) {
    if (elem.getBoundingClientRect) {
        // "правильный" вариант
        return getOffsetRect(elem)
    } else {
        // пусть работает хоть как-то
        return getOffsetSum(elem)
    }
}

function getOffsetSum(elem) {
    var top=0, left=0
    while(elem) {
        top = top + parseInt(elem.offsetTop)
        left = left + parseInt(elem.offsetLeft)
        elem = elem.offsetParent
    }

    return {top: top, left: left}
}
//*/
function getOffsetRect(elem) {
    // (1)
    var box = elem.getBoundingClientRect()

    // (2)
    var body = document.body
    var docElem = document.documentElement

    // (3)
    var scrollTop = window.pageYOffset || docElem.scrollTop || body.scrollTop
    var scrollLeft = window.pageXOffset || docElem.scrollLeft || body.scrollLeft

    // (4)
    var clientTop = docElem.clientTop || body.clientTop || 0
    var clientLeft = docElem.clientLeft || body.clientLeft || 0

    // (5)
    var top  = box.top +  scrollTop - clientTop
    var left = box.left + scrollLeft - clientLeft

    return { top: Math.round(top), left: Math.round(left) }
}
//*/
function getBodySize(){
  var docElem = document.documentElement;
  var docBody = document.body;
  return { top:    self.pageYOffset || (docElem && docElem.scrollTop) || (docBody && docBody.scrollTop),
           left:   self.pageXOffset || (docElem && docElem.scrollLeft) || (docBody && docBody.scrollLeft),
           height: (document.compatMode=='CSS1Compat' && !window.opera && docElem && docElem.clientHeight) ||
                   (docBody && docBody.clientHeight),
           width:  (document.compatMode=='CSS1Compat' && !window.opera && docElem && docElem.clientWidth) ||
                   (docBody && docBody.clientWidth)
  }
}

/*---------------------- bookmarks --------------------------------------*/
function getBrowserInfo() {
 var t,v = undefined;
 if (window.opera) t = 'Opera';
 else if (document.all) {
  t = 'IE';
  var nv = navigator.appVersion;
  var s = nv.indexOf('MSIE')+5;
  v = nv.substring(s,s+1);
 }
 else if (navigator.appName) t = 'Netscape';
 return {type:t,version:v};
}

function bookmark(a){
 var url = window.document.location;
 var title = window.document.title;
 var b = getBrowserInfo();
 if (b.type == 'IE' && 7 > b.version && b.version >= 4) window.external.AddFavorite(url,title);
 else if (b.type == 'Opera') {
  a.href = url;
  a.rel = "sidebar";
  a.title = url+','+title;
  return true;
 }
 else if (b.type == "Netscape") window.sidebar.addPanel(title,url,"");
 else alert("Нажмите CTRL-D, чтобы добавить страницу в закладки.");
 return false;
}
/*-----------------------------------------------------------------------*/
/*-------------------------- элемент по центру окна ---------------------*/
var CenterELs = new Array;


function CenterElement(id){
  var el = document.getElementById(id);
  var st = getCurrentStyle(el);
  var p = _getOffset(el.offsetParent);
  var bodySize = getBodySize();
  var tmp = st.height.match(/\d+/);
  var ctop = tmp?tmp[0]:0;
  tmp = st.width.match(/\d+/);
  var cleft = tmp?tmp[0]:0;
  ctop = Math.floor(bodySize.top - p.fullY + p.Y + (bodySize.height - ctop)/2);
  cleft = Math.floor(bodySize.left - p.fullX + p.X + (bodySize.width - cleft)/2);
  el.style.position = 'absolute';
  el.style.top = ctop + 'px';
  el.style.left = cleft + 'px';
}//*/

/*-----------------------------------------------------------------------*/

var bookmarks_xml;
var bookmarks_page_title = 'Без названия';
function ReloadBookmarks (xml) {
  if (xml) {
    bookmarks_xml = xml;
    return;
  }

  sendQRequest ('fetch_bookmark',{},function (result) {
    if (result) {
      (''+result).replace (/<bookmarks>(.*?)<\/bookmarks>/i,function ($1,$2) { bookmarks_xml = $2; });
      ShowBookmarks (1);
    }
  });
}

function ShowBookmarks (internal) {
  if (__el('bookmarks_div').style.display == 'none' || internal) {
    var html = '';
    var ok = 1;
    (''+bookmarks_xml).replace (/<bookmark ([^>]+?)>/ig,function ($1,$2) {
      var bi = ''+$2;
      var id,pt,pu;
      bi.replace (/id="(\d+)"/i,function ($1,$2) { id = $2; });
      bi.replace (/page_title="([^"]+)"/i,function ($1,$2) { pt = $2; });
      bi.replace (/page_url="([^"]+)"/i,function ($1,$2) { pu = $2; });
      
      if (document.location.href == pu) {
        ok = 0;
      }
      html += '<nobr><a href="'+pu+'">'+pt+'</a><a class="delbm" href="javascript:DelBookmark('+id+')" title="Удалить">[х]</a></nobr>';
    });
    if (ok) {
      html = '<nobr><a href="javascript:AddBookmark()"><b>+ Добавить страницу в закладки</b></a></nobr>' + html;
    }
    
    __el('bookmarks_div').innerHTML = html;
    if (internal) {} else { __el('bookmarks_div').style.display = 'block'; }
  } else {
    __el('bookmarks_div').style.display = 'none';
  }
}

function AddBookmark () {
  sendQRequest ('add_bookmark',{title: bookmarks_page_title, url: document.location.href},function () {
    ReloadBookmarks ();
  });
}

function DelBookmark (id) {
  sendQRequest ('del_bookmark',{id: id},function () {
    ReloadBookmarks ();
  });
}
