var ckWen = 'wen';
var ckTopRibbon = 'topRibbon';
var currWen = getCookie(ckWen) ? getCookie(ckWen) : -1;
var rbPanel = null, rbStarsPos = null, rbStars = null;
var rbStarsNumber = 5, rbStarWidth = 16;
var rbcWidth = null, rbcHeight = null;
var bPlacesToInit = ['Left', 'Right'];
var acStack = new Array();
var acStackProcessing = false;
var naviCols = 7;
var scrollStep = 50;
var tplAlert = '<div><div><text/></div></div><div class="anchor">&#160;</div>';
var tplAlertClosable = '<div><div><div class="close" onclick="hideAlert(this.parentNode.parentNode.parentNode);">&#160;</div><text/></div></div><div class="anchor">&#160;</div>';
var showAllTxt = 'pokaż wszystko';
var topRibbonReady = false;

addOnLoad('initEbooks');
addOnLoad('initTopRibbon');
addOnLoad('initBanners');
addOnLoad('initAjaxContentsNoReload');

//typ pozycji obiektu
function ObjectPosition(x, y) {
  this.x=x;
  this.y=y;
}

//dodawanie funcji do wywołania przy body onload
function addOnLoad(f) {
  var currentEvent = window.onload==undefined?undefined:window.onload.toString();
  if(currentEvent == undefined) {
    window.onload = new Function('event', f+'();\n');
  } else {
    if(currentEvent.lastIndexOf('}') != -1)
      window.onload = new Function('event', currentEvent.substring(currentEvent.indexOf('{')+1, currentEvent.lastIndexOf('}')-1)+'\n'+f+'();\n');
    else
      window.onload = new Function('event', f+'();\n');
  }
}

//dodaje dynamicznie bibliotekę javascript
function loadLibJS(f) {
  var s = document.createElement('script');
  s.type = 'text/javascript';
  s.src = f;
  try {
    document.getElementsByTagName('head')[0].appendChild(s);
  } catch(ex) {}
}

//parent tag 'tag' obiektu o
function getOuterTag(o, tag) {
  if(o == null || o.parentNode == undefined) return null;
  o = o.parentNode;
  while(o.parentNode != undefined && o.nodeName.toUpperCase() != tag.toUpperCase())
    o = o.parentNode;
  return (o.nodeName != undefined && o.nodeName.toUpperCase() == tag.toUpperCase()) ? o : null;
}

//array children tagów 'tag' obiektu o (bezpśrednie)
function getInnerTags(o, tag) {
  var r = new Array();
  if(o == null) return r;
  for(var i = 0; i < o.childNodes.length; i++)
    if(o.childNodes[i].nodeName.toUpperCase() == tag.toUpperCase())
      r.push(o.childNodes[i]);
  return r;
}

//next sibling tag 'tag' dla obiektu o
function getNextTag(o, tag) {
  if(o == null || o.nextSibling == undefined) return null;
  o = o.nextSibling;
  while(o.nextSibling != undefined && o.nodeName.toUpperCase() != tag.toUpperCase())
    o = o.nextSibling;
  return (o.nodeName != undefined && o.nodeName.toUpperCase() == tag.toUpperCase()) ? o : null;
}

//previous sibling tag 'tag' dla obiektu o
function getPreviousTag(o, tag) {
  if(o == null || o.previousSibling == undefined) return null;
  o = o.previousSibling;
  while(o.previousSibling != undefined && o.nodeName.toUpperCase() != tag.toUpperCase())
    o = o.previousSibling;
  return (o.nodeName != undefined && o.nodeName.toUpperCase() == tag.toUpperCase()) ? o : null;
}

//pobieranie z obiektu o tagów tag o className cn
function getTagsByClassName(o, tag, cn) {
  var re = new RegExp('(^| )' + cn + '($| )', '');
  var ts = o.getElementsByTagName(tag);
  var r = new Array();
  for(var i = ts.length - 1; i >= 0; i--) {
    if(ts[i].className && re.test(ts[i].className))
      r.push(ts[i]);
  }
  return r;
}

//znajduje dla obiektu o, parent tag "tag" o className "cn"
function getParentByClassName(o, tag, cn) {
  if(o == null) return null;
  var re = new RegExp('(^| )' + cn + '($| )', '');
  while(o.parentNode && (o.nodeName.toUpperCase() != tag.toUpperCase() || !o.className || !re.test(o.className)))
    o = o.parentNode;
  return (o.nodeName.toUpperCase() == tag.toUpperCase() && o.className && re.test(o.className) ? o : null);
}


//next sibling dla obiektu o, tag "tag" o className "cn"
function getNextTagByClassName(o, tag, cn, exc) {
  if(exc) {
    if(o == null) return null;
    o = o.nextSibling;
  }
  if(o == null) return null;
  var re = new RegExp('(^| )' + cn + '($| )', '');
  while(o.nextSibling && (o.nodeName.toUpperCase() != tag.toUpperCase() || !o.className || !re.test(o.className)))
    o = o.nextSibling;
  return (o.nodeName.toUpperCase() == tag.toUpperCase() && o.className && re.test(o.className) ? o : null);
}

//previous sibling dla obiektu o, tag tag o className cn
function getPreviousTagByClassName(o, tag, cn) {
  if(o == null || o.previousSibling == undefined) return null;
  var re = new RegExp('(^| )' + cn + '($| )', '');
  while(o.previousSibling && (o.nodeName.toUpperCase() != tag.toUpperCase() || !o.className || !re.test(o.className)))
    o = o.previousSibling;
  return (o.nodeName.toUpperCase() == tag.toUpperCase() && o.className && re.test(o.className) ? o : null);
}

//zwraca pozycję obiektu od id i
function getObjectPositionById(i) {
  try {
    return getObjectPosition(document.getElementById(i));
  } catch(ex) {
    return null;
  }
}

//zwraca pozycję obiektu o
function getObjectPosition(o) {
  try {
    var p = new ObjectPosition(o.offsetLeft, o.offsetTop);
    while(o.offsetParent) {
      o = o.offsetParent;
      p.x += o.offsetLeft;
      p.y += o.offsetTop;
    }
    return p;
  } catch(ex) {
    return null;
  }
}

//naprawiacz daty dla cookies
function fixDate(date) {
  base = new Date(0);
  skew = base.getTime();
  if(skew > 0) date.setTime(date.getTime() - skew);
}

//zapisanie cookie
function setCookie(name, value, expires, path, domain, secure) {
  var curCookie = name + '=' + escape(value) +
      ((expires) ? '; expires=' + expires.toGMTString() : '') +
      ((path) ? '; path=' + path : '; path=/') +
      ((domain) ? '; domain=' + domain : '') +
      ((secure) ? '; secure' : '');
  document.cookie = curCookie;
}

//odczytanie nazw cookies
function getCookiesNames(prefix) {
  var dc = document.cookie;
  var cookieName;
  var stack = new Array();
  var offset = 0;
  while(dc.indexOf(prefix, offset) != -1) {
    cookieName = prefix;
    offset = dc.indexOf(prefix, offset)+prefix.length;
    while(dc.charAt(offset)>='0' && dc.charAt(offset)<='9')
      cookieName += dc.charAt(offset++);
    if(dc.charAt(offset)=='=')
      stack.push(cookieName);
  }
  return stack.length!=0?stack:null;
}

//odczytanie cookie
function getCookie(name) {
  var dc = document.cookie;
  var prefix = name + '=';
  var begin = dc.indexOf('; ' + prefix);
  if (begin == -1) {
    begin = dc.indexOf(prefix);
    if (begin != 0) return null;
  } else
    begin += 2;
  var end = document.cookie.indexOf(';', begin);
  if (end == -1)
    end = dc.length;
  return unescape(dc.substring(begin + prefix.length, end));
}

//usunięcie cookie
function deleteCookie(name, path, domain) {
  if (getCookie(name)) {
    document.cookie = name + '=' +
    ((path) ? '; path=' + path : '') +
    ((domain) ? '; domain=' + domain : '') +
    '; expires=Thu, 01-Jan-70 00:00:01 GMT';
  }
}

//ustawienie selecta
function setSelect(f, p, v) {
  for(var i = 0; i < eval('document.'+f+'.'+p+'.options.length'); i++)
    if(eval('document.'+f+'.'+p+'.options['+i+'].value') == v)
      eval('document.'+f+'.'+p+'.options['+i+'].selected = true;');
}

//przeszukiwanie selecta
function searchSelectField(f, p, v, c) {
  try {
    if(c != undefined && c)
      for(var i = 0; i < eval('document.'+f+'.length'); i++)
        if(eval('document.'+f+'['+i+'].type') == 'text')
          eval('document.'+f+'['+i+'].value = \'\';');
        else if(eval('document.'+f+'['+i+'].type') == 'select-one')
          eval('document.'+f+'['+i+'].selectedIndex = 0;');
        else if(eval('document.'+f+'['+i+'].type') == 'checkbox')
          eval('document.'+f+'['+i+'].checked = false;');
  } catch(ex) {}
  for(var i = 0; i < eval('document.'+f+'.'+p+'.options.length'); i++)
    if(eval('document.'+f+'.'+p+'.options['+i+'].value') == v)
      eval('document.'+f+'.'+p+'.options['+i+'].selected = true;');
  eval('document.'+f+'.submit();');
}

//przeszukiwanie pola tekstowego
function searchTextField(f, p, v) {
  eval('document.'+f+'.'+p+'.value = \''+v+'\';');
  eval('document.'+f+'.submit();');
}

//validacja NIPu
function checkNip(n){
  var nipRE=/^\d{10}$/;
  n = n.replace(/[ \-]/g, '');
  if(!nipRE.test(n)) return false;
  if(((6*n.charAt(0)+5*n.charAt(1)+7*n.charAt(2)+2*n.charAt(3)+3*n.charAt(4)+4*n.charAt(5)+5*n.charAt(6)+6*n.charAt(7)+7*n.charAt(8))%11)%10 == n.charAt(9)) return true;
  return false;
}

//otwarcie obrazka w popupie
function popImage(l) {
  var popImage=window.open('','popImage', (document.all?'width=150,height=150,':'')+'scrollbars=no,resizable=yes,toolbar=no,userbar=no,location=no,status=no,menubar=no,screenX=100,screenY=100');
  popImage.document.writeln('<html><head><title>Obrazek</title></head>');
  popImage.document.writeln('<body style="background-color: #ffffff; margin: 0px;" onLoad="autoSize();">');
  popImage.document.writeln('<img style="border: 0px; cursor: pointer;" id="image" src="'+l+'" onclick="window.close();">');
  popImage.document.writeln('<script language="JavaScript" type="text/javascript" ><!--');
  popImage.document.writeln('function autoSize(o,l) {');
  if(document.all) {
    popImage.document.writeln('window.resizeBy(document.getElementById("image").offsetWidth-document.body.clientWidth, document.getElementById("image").offsetHeight-document.body.clientHeight);');
  } else {
    popImage.document.writeln('window.resizeTo(2000, 150);');
    popImage.document.writeln('window.resizeBy(document.getElementById("image").offsetWidth-window.innerWidth, document.getElementById("image").offsetHeight-window.innerHeight);');
  }
  popImage.document.writeln('window.focus();');
  popImage.document.writeln('}');
  popImage.document.writeln('/'+'/-'+'-></script>');
  popImage.document.writeln('</body></html>');
  popImage.document.close();
}

//otwarcie popupa
function popUp(l,w,h,s) {
  var popUp = window.open(l,'popUp', 'width='+w+',height='+h+',scrollbars='+(s==1?'yes':'no')+',resizable=yes,toolbar=no,userbar=no,location=no,status=no,menubar=no');
  popUp.document.close();
  popUp.focus();
}

//przejście do linka
function linkGo(l,t) {
  if(t == undefined) {
    window.location = l;
  } else if(t == '_blank') {
    window.open(l);
  } else {
    window.open(l, t);
  }
}

//nawigacja - przejdź do pozycji na liście
function naviListGo(n) {
  var h = window.location.href.replace('show_all=1', 'show_all=0');
  if(h.indexOf('?offset=') != -1)
    h = h.replace(/\?offset=[0-9]*/, '?offset='+n);
  else if(h.indexOf('&offset=') != -1)
    h = h.replace(/&offset=[0-9]*/, '&offset='+n);
  else if(h.indexOf('?') == -1)
    h = h.replace(/\#.*/, '')+'?offset='+n;
  else
    h = h.replace(/\#.*/, '')+'&offset='+n;
  window.location = h;
}

//nawigacja - pokaż całą listę
function naviShowAll() {
  var h = window.location.href;
  if(h.indexOf('?show_all=') != -1)
    h = h.replace(/\?show_all=[0-9]*/, '?show_all=1');
  else if(h.indexOf('&show_all=') != -1)
    h = h.replace(/&show_all=[0-9]*/, '&show_all=1');
  else if(h.indexOf('?') == -1)
    h = h.replace(/\#.*/, '')+'?show_all=1';
  else
    h = h.replace(/\#.*/, '')+'&show_all=1';
  window.location = h;
}

//wyciągnięcie słowa
function getWord(n) {
  if(n <= 1)
    return n;
  else if((n >= 2 && n <= 4) || (n%100 > 20 && n%10 >= 2 && n%10 <= 4))
    return 2;
  return 3;
}

//przykrycie strony (dezaktywacja)
function coverPage(bc, cn) {
  var o = document.getElementById('lid');
  if(!o) {
    o = document.createElement('div');
    o.id = 'lid';
    o.innerHTML = '&#160;';
    document.body.appendChild(o);
  }
  o.className = cn ? cn : '';
  o.style.backgroundColor = bc ? bc : 'transparent';
  o.style.width = document.body.clientWidth + 'px';
  o.style.height = document.body.clientHeight + 'px';
}

//pokazanie oczekiwania
function showLidHourglass(bc, cn) {
  var o = document.getElementById('lidHourglass');
  if(!o) {
    o = document.createElement('div');
    o.id = 'lidHourglass';
    o.innerHTML = '&#160;';
    document.body.appendChild(o);
  }
  centerObjectOnScreen(o);
}

function hideLidHourglass() {
  var o = document.getElementById('lidHourglass');
  if(o)
    o.parentNode.removeChild(o);
}

//odkrycie strony (aktywacja)
function uncoverPage() {
  var o = document.getElementById('layerImage');
  if(o)
    o.parentNode.removeChild(o);
  o = document.getElementById('lidHourglass');
  if(o)
    o.parentNode.removeChild(o);
  o = document.getElementById('lid');
  if(o)
    o.parentNode.removeChild(o);
}

//kapitalizacja
function capitalize(s) {
  return s != null && s.length > 1?s.substr(0,1).toUpperCase()+s.substr(1):s;
}

//aktualizacja formularza
function updateForm(form, field, value) {
  try {
    field = document.forms[form].elements[field];
    if(field.nodeName.toUpperCase() == 'SELECT') {
      for(var i = 0; i < field.options.length; i++)
        if(field.options[i].value == value)
          field.selectedIndex = i;
    } else if(field.nodeName.toUpperCase() == 'INPUT') {
      if(field.type.toUpperCase() == 'CHECKBOX') {
        if(field.value == value)
          field.checked = 'checked';
      } else if(field.type.toUpperCase() == 'HIDDEN' || field.type.toUpperCase() == 'TEXT') {
        field.value = value;
      }
    }
  } catch(ex) {}
}

//pokazuje okienko rekomendacji
function recommendShow(o, url, title) {
  var pos = getObjectPosition(o);
  var panel = document.getElementById('recommendPanel');
  if(!panel) {
    panel = document.createElement('div');
    panel.id = 'recommendPanel';
    document.body.appendChild(panel);
  }
  if(panel.innerHTML.toLowerCase().indexOf('<input') == -1) {
    advAJAX.post ({
      url: '/index.php?page=polec_znajomemu',
      parameters: {
        'title': title,
        'url': url
      },
      tag: panel,
      onSuccess: function(obj) {
        obj.tag.innerHTML = obj.responseText;
        obj.tag.style.left = (pos.x - obj.tag.offsetWidth + o.offsetWidth) + 'px';
        obj.tag.style.top = (pos.y - obj.tag.offsetHeight) + 'px';
        obj.tag.style.visibility = 'visible';
      },
      onError: function(obj) { alert('Błąd: ' + obj.status); }
    });
  } else if(panel.style.visibility == 'visible') {
    panel.style.visibility = 'hidden';
  } else {
    panel.style.visibility = 'visible';
  }
}

//poleć znajomemu
function recommendSubmit(alrt) {
  var emailRE = /^([0-9a-zA-Z]([-.\w]*[0-9a-zA-Z])*@(([0-9a-zA-Z])+([-\w]*[0-9a-zA-Z])*\.)+[a-zA-Z]{2,9})$/;
  if(document.forms['formRecommend'] != undefined) {
    if(!emailRE.test(document.forms['formRecommend'].elements['emailFrom'].value) || emailRE.test(document.forms['formRecommend'].elements['emailTo'].value == ''))
      alert(alrt);
    else
      advAJAX.submit(document.forms['formRecommend'], {
        onSuccess: function(obj) {
          document.getElementById('recommendPanel').innerHTML = obj.responseText;
          setTimeout('document.getElementById("recommendPanel").style.visibility = "hidden";', 3000);
        },
        onError: function(obj) { alert('Błąd: ' + obj.status); }
      });
  }
}

//zapisanie konfiguracji
function saveConfig() {
  advAJAX.submit(document.forms['formConfig'], {
    onSuccess: function(obj) {
      if(obj.responseText != '')
        alert(obj.responseText);
    },
    onError: function(obj) { alert('Błąd: ' + obj.status); }
  });
}

//zapisanie danych
function savePersonalData() {
  if(shpFormValidate(document.forms['formCustomer'], true)) {
    advAJAX.submit(document.forms['formCustomer'], {
      onSuccess: function(obj) {
        if(obj.responseText != '')
          alert(obj.responseText);
      },
      onError: function(obj) { alert('Błąd: ' + obj.status); }
    });
  }
}

//inicjalizacja danych
function initPersonalData() {
  document.getElementById('formOrder').style.display = 'inline';
  document.getElementById('sectionForm2').style.visibility = 'visible';
  if(shpUserData != undefined)
    shpFormFill(shpUserData, document.forms['formCustomer']);
  if(document.forms['formCustomer'].elements['addInvStreet'].value != '') {
    document.getElementById('invoiceAddress').style.visibility = 'hidden';
    document.getElementById('invoiceAddress').style.position = 'absolute';
  } else {
    document.getElementById('sectionForm6').style.visibility = 'hidden';
    document.getElementById('sectionForm6').style.position = 'absolute';
  }
}

//pokazuje okienko oceny i komentarza książki
function commentBookShow(o, id) {
  var pos = getObjectPosition(o.parentNode);
  var panel = document.getElementById('commentPanel');
  if(panel != undefined)
    document.body.removeChild(panel);
  if(rbPanel == o) {
    rbPanel = null;
  } else {
    rbPanel = o;
    panel = document.createElement('div');
    panel.id = 'commentPanel';
    document.body.appendChild(panel);
    advAJAX.post ({
      url: '/index.php?page=recenzuj_ksiazke',
      tag: [o.parentNode, pos],
      parameters: {
        'id': id
      },
      onSuccess: function(obj) {
        panel.innerHTML = obj.responseText;
        panel.style.left = (obj.tag[1].x - panel.offsetWidth + obj.tag[0].offsetWidth) + 'px';
        panel.style.top = (obj.tag[1].y + obj.tag[0].offsetHeight) + 'px';
        panel.style.visibility = 'visible';
        if(document.getElementById('cartPanel').className == 'opened')
          shpCartOpen();
        activateRating();
      },
      onError: function(obj) { alert('Błąd: ' + obj.status); }
    });
  }
}

//oceń i komentuj książki
function commentBookSubmit(alrt1, alrt2, alrt3) {
  if(document.forms['formCommentBook'] != undefined) {
    if(document.forms['formCommentBook'].elements['rating'].value == 0)
      alert(alrt1);
    else if(document.forms['formCommentBook'].elements['comment'].value.length == 0)
      alert(alrt2);
    else if(document.forms['formCommentBook'].elements['comment'].value.length > 2000)
      alert(alrt3);
    else
      advAJAX.submit(document.forms['formCommentBook'], {
        onSuccess: function(obj) {
          var o = document.getElementById('commentPanel');
          o.style.left = (o.offsetLeft + o.offsetWidth - 300 - 12) + 'px';
          o.style.width = '300px';
          o.innerHTML = obj.responseText;
          setTimeout('document.body.removeChild(document.getElementById("commentPanel")); rbPanel = null;', 7000);
        },
        onError: function(obj) { alert('Błąd: ' + obj.status); }
      });
  }
}

//inicjacja bannerów
function initBanners() {
  var bp;
  var h = document.all
            ? Math.max(document.body.clientHeight, document.documentElement.offsetHeight)
            : document.body.clientHeight==window.innerHeight
              ? Math.max(document.body.clientHeight, document.documentElement.offsetHeight)
              : Math.max(document.body.clientHeight, window.innerHeight);
  if(bPlacesToInit.length > 0) {
    bp = bPlacesToInit.shift();
    try {
      if(document.getElementById('banners' + bp) && eval('b' + bp + '[0]') != 0)
        insertBanners('banners' + bp, 'b' + bp, h, 0);
      else
        initBanners();
    } catch(ex) {}
  }
}

//wypisywanie bannerów
function insertBanners(oName, lName, h, i) {
  var l = eval(lName);
  var ch = (document.body.clientHeight==window.innerHeight?document.documentElement.offsetHeight:document.body.clientHeight);
  var o = document.getElementById(oName);
  if(ch > h) {
    if(o.childNodes.length > 1)
      o.removeChild(o.childNodes[o.childNodes.length - 1]);
    i = -1;
  } else if(i < l.length && l[i] != 0) {
    if(l[i] == 'i') {
      var ban0 = document.createElement('div');
      var ban1 = document.createElement('a');
      ban1.href = l[i+5];
      var ban2 = document.createElement('img');
      ban2.alt = l[i+1];
      ban2.title = l[i+1];
      ban2.src = l[i+2];
      ban2.width = l[i+3];
      ban2.height = l[i+4];
      ban1.appendChild(ban2);
      ban0.appendChild(ban1);
      o.appendChild(ban0);
      insertBanners(oName, lName, h, (i+6));
    } else if(l[i] == 'f') {
      var ban0 = document.createElement('div');
      var ban1 = document.createElement('div');
      ban1.id = oName+'_'+i;
      ban0.appendChild(ban1);
      o.appendChild(ban0);
      var flashvars = {};
      var params = {};
      params.quality = 'autohigh';
      params.menu = 'false';
      params.scale = 'noscale';
      params.wmode = 'transparent';
      params.bgcolor = '#ffffff';
      var attributes = {};
      attributes.id = oName + '_' + i;
      swfobject.embedSWF(l[i + 1], oName + '_' + i, l[i + 2], l[i + 3], '9.0.0', '/flash/expressinstall.swf', flashvars, params, attributes);
      insertBanners(oName, lName, h, i+4);
    }
  } else {
    i = -1;
  }
  if(i < 0) {
    i = 0;
    while(i < o.childNodes.length)
      o.childNodes[i++].style.visibility = 'visible';
    initBanners();
  }
}

//inicjowanie formularza wyszukiwania
function initFormSearch(st, sa) {
  var h = window.location.hash;
  if(h) {
    h = h.substr(1).split(',');
    for(var i = 0; i < h.length; i += 2) {
      updateForm('formSearch', h[i], h[i + 1]);
      if(h[i] == 'searchType') {
        try {
          var cn = document.getElementById('searchTabs').childNodes;
          for(var j = 0; j < cn.length; j++)
            if(cn[j].nodeName.toUpperCase() == 'DIV' && ('' + cn[j].onclick).indexOf(', ' + h[i + 1] + ')') != -1)
              clickSearchTab(cn[j], h[i + 1]);
        } catch(ex) {}
      }
    }
  } else {
    finalizeSubmitFormSearch();
  }
}

//kliknięcie taba wyszukiwarki
function clickSearchTab(o, t) {
  var cn = o.parentNode.childNodes;
  for(var i = 0; i < cn.length; i++)
    if(cn[i].nodeName.toUpperCase() == 'DIV' && cn[i].className.indexOf('tabTitle') == -1)
      cn[i].className = (cn[i] == o ? 'tab tabOn' : 'tab');
  document.forms['formSearch'].elements['searchType'].value = t;
  for(var i = 1; i < 8; i++)
    document.getElementById('searchDescription'+i).className = (t != i ? 'undisplayed' : 'value');
  o.blur();
  document.forms['formSearch'].elements['searchTextBig'].focus();
  submitFormSearch();
}

//wyszukiwanie
function submitFormSearch() {
  var o = document.getElementById('searchResults');
  var url = getSearchUrl();
  if(o && url) {
    o.innerHTML = '<!--url[' + url + ']//-->';
    initAjaxContents(o, 'finalizeSubmitFormSearch');
  }
}

function getSearchUrl(h) {
  var ret = false;
  var f = document.forms['formSearch'];
  if(f) {
    var es = f.elements;
    if(es['searchText'].value != '') {
      if(h) {
        ret = '#' +
          'searchType,' + encodeURIComponent(es['searchType'].value) +
          ',searchText,' + encodeURIComponent(es['searchText'].value) +
          (es['searchAvailable'].checked ? ',searchAvailable,1' : '') + 
          (es['editionType'].selectedIndex != 0 ? ',editionType,' + encodeURIComponent(es['editionType'].options[es['editionType'].selectedIndex].value) : '') +
          (es['age'].selectedIndex != 0 ? ',age,' + encodeURIComponent(es['age'].options[es['age'].selectedIndex].value) : '');
        var o = document.getElementById('searchSortTabs');
        if(o) {
          var cn = o.childNodes;
          for(var i = 0; i < cn.length; i++)
            if(cn[i].nodeName.toUpperCase() == 'DIV' && cn[i].className && cn[i].className == 'tab tabOn') {
              var re = new RegExp('<!--([^/]+)//-->');
              var m = re.exec(cn[i].innerHTML);
              if(m.length > 1)
                ret += ',sort,' + (m[1]);
            }
        }
      } else {
        ret = '/szukaj_mini.html' +
          '?searchType=' + es['searchType'].value +
          '&searchText=' + es['searchText'].value +
          (es['searchAvailable'].checked ? '&searchAvailable=1' : '') + 
          (es['editionType'].selectedIndex != 0 ? '&editionType=' + es['editionType'].options[es['editionType'].selectedIndex].value : '') +
          (es['age'].selectedIndex != 0 ? '&age=' + es['age'].options[es['age'].selectedIndex].value : '');
      }
    }
  }
  return ret;
}

//finalizacja wyszukiwania
function finalizeSubmitFormSearch() {
  if(getSearchUrl(true))
    window.location = getSearchUrl(true);
  var o = document.getElementById('searchResults');
  if(o) {
    var re = new RegExp('<!--navi\[[0-9]+,0,[0-9]+\]//-->', '');
    if(re.test(o.innerHTML)) {
      try {
        var cn = document.getElementById('searchTabs').childNodes;
        for(var i = 0; i < cn.length; i++)
          if(cn[i].nodeName.toUpperCase() == 'DIV' && cn[i].className && cn[i].className == 'tab') {
            var re = new RegExp('this, ([0-9]+)');
            var m = re.exec('' + cn[i].onclick);
            if(m && m.length > 1)
              advAJAX.get ({
                url: getSearchUrl().replace(/&searchType=[0-9]+/, ''),
                parameters: {
                  'searchType': m[1],
                  'checkOnly': 1
                },
                tag: cn[i],
                onSuccess: function(obj) {
                  if(obj.responseText != 0)
                    showSearchHint(obj.tag, obj.parameters.searchType, obj.responseText);
                },
                onError: function(obj) { alert('Błąd: ' + obj.status); }
              });
          }
      } catch(ex) {}
    }
  }
}

//pokazanie podpowiedzi wyszukiwania
function showSearchHint(o, t, v) {
  var pos = getObjectPosition(o);
  var sh = document.createElement('div');
  sh.className = 'searchHint';
  var shc = document.createElement('div');
  shc.innerHTML = 'znaleziono ' + v + (v == 1 ? ' pozycję' : ((v < 10 || v > 20) && v%10 > 1 && v%10 < 5 ? ' pozycje' : ' pozycji'));
  sh.appendChild(shc);
  var sp = document.createElement('span');
  sp.innerHTML = '&#160;';
  sh.appendChild(sp);
  var tt = Math.abs(t - 4);
  var y = tt * 22 + o.offsetHeight + 5;
  sh.style.height = y + 'px';
/*
  var x = t - 4;
  x = Math.abs(x) * 5;
  sh.style.backgroundPosition = (10 + x) + 'px bottom';
  sp.style.marginLeft = (10 + x) + 'px';
*/
  var x = 0;
  sh.style.top = (pos.y - y) + 'px';
  sh.style.left = (pos.x - x) + 'px';
  try {
    if(o.lastChild.className == 'searchHint')
      o.removeChild(o.lastChild);
  } catch(ex) {}
  sh.style.zIndex = 20 - tt;
  o.appendChild(sh);
}

//ukrycie podpowiedzi wyszukiwania
function hideSearchHint() {
  try {
    var cn = document.getElementById('searchTabs').childNodes;
    for(var i = 0; i < cn.length; i++)
      if(cn[i].nodeName.toUpperCase() == 'DIV' && cn[i].className && (cn[i].className == 'tab' || cn[i].className == 'tab tabOn')) {
        try {
          if(cn[i].lastChild.className == 'searchHint')
            cn[i].removeChild(cn[i].lastChild);
        } catch(ex) {}
      }
  } catch(ex) {}
}


//rejestracja do newslettera
function registerNewsletter() {
  advAJAX.submit(document.forms['formNewsletterMini'], {
    onSuccess : function(obj) {
      if(obj.responseText != '')
        document.getElementById('emailRegBox').innerHTML = obj.responseText;
    },
    onError : function(obj) { alert("Error: " + obj.status); }
  });
  return false;
}

//pokazanie WEN
function showWen(force) {
  keepWen();
  if(force) {
    try {
      clearTimeout(wenShowTimeout);
    } catch(ex) {}
    var o = document.getElementById('wen');
    if(o) {
      o.className = 'over';
      var pos = getObjectPosition(o);
      for(var i = 0; i < o.childNodes.length; i++)
        if(o.childNodes[i].className == 'list') {
          o.childNodes[i].style.visibility = 'visible';
          o.childNodes[i].style.left = pos.x + 'px';
          o.childNodes[i].style.top = (pos.y + o.offsetHeight) + 'px';
        }
    }
  } else {
    wenShowTimeout = setTimeout('showWen(true);', 500);
  }
}

//podtrzymanie WEN
function keepWen() {
  try {
    clearTimeout(wenHideTimeout);
  } catch(ex) {}
}

//ukrycie WEN
function hideWen(force) {
  try {
    clearTimeout(wenShowTimeout);
  } catch(ex) {}
  if(force) {
    var o = document.getElementById('wen');
    if(o) {
      o.className = '';
      for(var i = 0; i < o.childNodes.length; i++)
        if(o.childNodes[i].className == 'list')
          o.childNodes[i].style.visibility = 'hidden';
    }
  } else {
    wenHideTimeout = setTimeout('hideWen(true);', 500);
  }
}

//zmiana WEN
function changeWen(o, id) {
  if(o && currWen != id) {
    setCookie(ckWen, id);
    var oo = document.getElementById('wen');
    if(oo) {
      hideWen(true);
      for(var i = 0; i < oo.childNodes.length; i++)
        if(oo.childNodes[i].className == 'current' && o.childNodes)
          oo.childNodes[i].innerHTML = o.childNodes[0].innerHTML;
        else if(oo.childNodes[i].className == 'list')
          for(var j = 0; j < oo.childNodes[i].childNodes.length; j++)
            oo.childNodes[i].childNodes[j].className = (oo.childNodes[i].childNodes[j] == o ? 'selected' : '');
      if(document.getElementById('menuCategories')) {
        document.getElementById('menuCategories').innerHTML = '<div>&#160;</div>';
        document.getElementById('menuCategories').className = 'hourglass';
      }
      advAJAX.get ({
        url: '/index.php?page=wen_kategorie&wen=1',
        onSuccess: function(obj) {
          if(document.getElementById('menuCategories')) {
            document.getElementById('menuCategories').className = '';
            document.getElementById('menuCategories').innerHTML = obj.responseText;
          }
          var o = document.getElementById('btnSeries');
          var oo = document.getElementById('seriesPanel');
          if(o && oo && oo.style.visibility != 'hidden') {
            showSeriesPanel(true);
            hideSeriesPanel();
          } else {
            if(oo)
              oo.parentNode.removeChild(oo);
            currWen = id;
          }
          initAjaxContents(null, null, null, new RegExp(',offset,[^,/]*', 'g'));
        },
        onError: function(obj) { alert('Błąd: ' + obj.status); }
      });
    }
  }
}

//pokazanie panelu serii
function showSeriesPanel(force) {
  keepSeriesPanel();
  if(force) {
    try {
      clearTimeout(seriesPanelShowTimeout);
    } catch(ex) {}
    var o = document.getElementById('btnSeries');
    if(o) {
      o.className = 'over';
      var wen = getCookie(ckWen);
      var oo = document.getElementById('seriesPanel');
      if(!wen)
        wen = 0;
      if(!oo || wen != currWen) {
        currWen = wen;
        if(!oo) {
          oo = document.createElement('div');
          oo.id = 'seriesPanel';
          oo.onmouseover = new Function('keepSeriesPanel();');
          oo.onmouseout = new Function('hideSeriesPanel();');
          document.body.appendChild(oo);
        }
        var pos = getObjectPosition(o);
        oo.innerHTML = '<div>&#160;</div>';
        oo.className = 'hourglass';
        oo.style.left = (pos.x + o.offsetWidth + 1) + 'px';
        oo.style.top = (pos.y) + 'px';
        oo.style.visibility = 'visible';
        advAJAX.get ({
          url: '/index.php?page=wen_serie',
          tag: [o, oo],
          onSuccess: function(obj) {
            var o = obj.tag[0];
            var oo = obj.tag[1];
            oo.className = '';
            oo.innerHTML = obj.responseText;
          },
          onError: function(obj) { alert('Błąd: ' + obj.status); }
        });
      } else {
        var pos = getObjectPosition(o);
        currWen = wen;
        oo.style.left = (pos.x + o.offsetWidth + 1) + 'px';
        oo.style.top = (pos.y) + 'px';
        oo.style.visibility = 'visible';
      }
    }
  } else {
    seriesPanelShowTimeout = setTimeout('showSeriesPanel(true);', 500);
  }
}

//podtrzymanie panelu serii
function keepSeriesPanel() {
  try {
    clearTimeout(seriesPanelHideTimeout);
  } catch(ex) {}
}

//ukrycie panelu serii
function hideSeriesPanel(force) {
  try {
    clearTimeout(seriesPanelShowTimeout);
  } catch(ex) {}
  if(force) {
    var o = document.getElementById('seriesPanel');
    if(o)
      o.style.visibility = 'hidden';
    o = document.getElementById('btnSeries');
    if(o)
      o.className = '';
  } else {
    seriesPanelHideTimeout = setTimeout('hideSeriesPanel(true);', 1700);
  }
}

//głosowanie
function rateBook(o, t, v, id) {
  showInfoHourglass(o);
  advAJAX.get({
    url: '/index.php?page=ocen&type=' + t + '&vote=' + v + '&id=' + id,
    tag: [o, v],
    onSuccess: function(obj) {
      try {
        var o = obj.tag[0];
        o.onclick = new Function('');
        o.className = '';
        var re = new RegExp('<!--(-?1),(-?[01]),([0-9]+)//-->', '');
        var m = re.exec(obj.responseText);
        if(m && m.length == 4) {
          try {
            if(m[1] != m[2]) {
              o = o.parentNode;
              for(var i = 0; i < o.childNodes.length; i++)
                if(o.childNodes[i].className == 'plus') {
                  var v = parseFloat(o.childNodes[i].innerHTML.replace(/[^0-9]/g, ''));
                  v += (m[1] == 1 ? 1 : 0) - (m[2] == 1 ? 1 : 0);
                  o.childNodes[i].innerHTML = '+' + v;
                } else if(o.childNodes[i].className == 'minus') {
                  var v = parseFloat(o.childNodes[i].innerHTML.replace(/[^0-9]/g, ''));
                  v += (m[1] == -1 ? 1 : 0) - (m[2] == -1 ? 1 : 0);
                  o.childNodes[i].innerHTML = '-' + v;
                }
            }
          } catch(ex) {}
        }
        showInfo(obj.tag[0], obj.responseText. replace(re, ''));
      } catch(ex) {}
    },
    onError: function(obj) {
      try {
        hideInfo();
        alert('Błąd: ' + obj.status);
      } catch(ex) {}
    }
  });
}

//pokaż alert
function showAlert(o, id, t, c) {
  var pos = getObjectPosition(o);
  var oo = document.getElementById(id);
  if(oo)
    oo.parentNode.removeChild(oo);
  oo = document.createElement('div');
  oo.id = id;
  oo.innerHTML = (c ? tplAlertClosable : tplAlert).replace('<text/>', t);
  document.body.appendChild(oo);
  oo.style.left = (pos.x + o.offsetWidth / 2 - 34) + 'px';
  oo.style.top = (pos.y - oo.offsetHeight) + 'px';
  oo.style.visibility = 'visible';
}

//ukryj alert
function hideAlert(o) {
  if(o)
    o.parentNode.removeChild(o);
}

//pokaż alert info
function showInfo(o, t, nh) {
  try {
    clearTimeout(timeoutInfo);
  } catch(ex) {}
  showAlert(o, 'alertInfo', t);
  if(!nh)
    timeoutInfo = setTimeout('hideInfo();', 3000);
}

//ukryj alert info
function hideInfo() {
  try {
    clearTimeout(timeoutInfo);
  } catch(ex) {}
  hideAlert(document.getElementById('alertInfo'));
}

//pokaż poczekajkę alert info
function showInfoHourglass(o) {
  showInfo(o, '<div class="hourglass">&#160;</div>', true);
}

//pokaż alert help
function showHelp(o, t, c) {
  try {
    clearTimeout(timeoutHelp);
  } catch(ex) {}
  showAlert(o, 'alertHelp', t, c);
  if(!c)
    timeoutHelp = setTimeout('hideHelp();', 3000);
}

//ukryj alert help
function hideHelp() {
  try {
    clearTimeout(timeoutHelp);
  } catch(ex) {}
  hideAlert(document.getElementById('alertHelp'));
}

//pokaż poczekajkę alert help
function showHelpHourglass(o) {
  showHelp(o, '<div class="hourglass">&#160;</div>', true);
}

//inicjalizacja ajaxowych contentów
function initAjaxContentsNoReload() {
  initAjaxContents(null, null, true);
}

//inicjalizacja ajaxowych contentów
function initAjaxContents(acs, doAfter, noReload, cleanRe) {
  var re = new RegExp('<!--url\\[([^\\]]+)\\]//-->', '');
  var m;
  if(acs) {
    if(acs instanceof Array)
      true;
    else
      acs = [acs];
  } else {
    acs = getTagsByClassName(document, 'div', 'ajaxContent');
    var acss = getTagsByClassName(document, 'span', 'ajaxContent');
    while(acss.length > 0)
      acs.push(acss.shift());
  }
  if(noReload) {
    for(var i = 0; i < acs.length; i++) {
      m = re.exec(acs[i].innerHTML);
      if(m)
        finalizeInitAjaxContent(acs[i], null, m[1]);
    }
    if(doAfter)
      eval(doAfter+'();');
  } else if(acs.length > 0) {
    for(var i = 0; i < acs.length; i++) {
      m = re.exec(acs[i].innerHTML);
      if(m)
        acStack.push(acs[i]);
    }
    if(!acStackProcessing)
      processAjaxContentsStack(doAfter, cleanRe);
  }
}

//przetwarzanie stosu ajaxowych contentów
function processAjaxContentsStack(doAfter, cleanRe) {
  var re = new RegExp('<!--url\\[([^\\]]+)\\]//-->', '');
  var m;
  acStackProcessing = true;
  var acs = acStack.shift();
  m = re.exec(acs.innerHTML);
  var ts = getPreviousTagByClassName(acs, 'div', 'tabs');
  if(ts) {
    for(var j = 0; j < ts.childNodes.length; j++)
      if(ts.childNodes[j].className && ts.childNodes[j].className.indexOf('tabOn') != -1) {
        sortRE = new RegExp('<!--([^/]+)//-->', '');
        var ms = sortRE.exec(ts.childNodes[j].innerHTML);
        if(ms.length == 2) {
          if(m[1].indexOf('?sort=') != -1)
            m[1] = m[1].replace(/\?sort=[^&]*/, '?sort=' + ms[1]);
          else if(m[1].indexOf('&sort=') != -1)
            m[1] = m[1].replace(/&sort=[^&]*/, '&sort=' + ms[1]);
          else if(m[1].indexOf('?') == -1)
            m[1] = m[1].replace(/\#.*/, '') + '?sort=' + ms[1];
          else
            m[1] = m[1].replace(/\#.*/, '') + '&sort=' + ms[1];
          j = ts.childNodes.length;
          window.location = '#sort,' + ms[1];
        }
      }
  }
  acs.className += ' hourglass';
  acs.innerHTML = '<div>&#160;</div>';
  if(cleanRe)
    m[1] = m[1].replace(cleanRe, '');
  advAJAX.get({
    url : urlSlicker(m[1]),
    tag : [acs, doAfter, cleanRe],
    unique : false,
    onSuccess : function(obj) {
      obj.tag[0].className = obj.tag[0].className.replace(' hourglass', '');
      finalizeInitAjaxContent(obj.tag[0], null, obj.url, obj.responseText);
      if(acStack.length == 0) {
        acStackProcessing = false;
        if(obj.tag[1])
          eval(obj.tag[1]+'();');
      } else {
        processAjaxContentsStack(obj.tag[1], obj.tag[2]);
      }
    },
    onError : function(obj) {
      alert('Błąd: ' + obj.status);
    }
  });
}

//finalizuje inicjalizację ajaxowego contentu
function finalizeInitAjaxContent(o, doAfter, url, content) {
  var t;
  var re = new RegExp('<!--navi\\[[0-9]+,[0-9]+,[0-9]+\\]//-->', '');
  if(content)
    o.innerHTML = (document.all ? '<span style="display: none;">a</span>' : '') + content;
  if(re.test(o.innerHTML))
    addAjaxNaviList(o, url, o.innerHTML.substring(o.innerHTML.indexOf('<!--navi[') + 9, o.innerHTML.indexOf(']//-->', o.innerHTML.indexOf('<!--navi['))).split(','));
  try {
    t = getPreviousTagByClassName(o, 'div', 'tabs');
    t = getTagsByClassName(t, 'div', 'tab');
    for(var i = 0; i < t.length; i++)
      if(!t[i].onclick)
        t[i].onclick = new Function('event', 'tabSortList(this);');
  } catch(ex) {}
  if(doAfter)
    eval(doAfter+'();');
  if(window.opera) {
    coverPage();
    uncoverPage();
  }
  initEbooks();
}

//dodawanie nawigacji do ajaxowej listy (offset, total, group)
function addAjaxNaviList(o, url, p) {
  for(var i = 0; i < p.length; i++)
    p[i] = parseFloat(p[i]);
  if(p[1] > p[2]) {
    var e, ee;
    var anl = document.createElement('div');
    anl.className = 'ajaxNaviList';
    if(p[0] > 0 && url.indexOf(',showAll,1') == -1) {
      e = document.createElement('div');
      e.innerHTML = '&lt;';
      e.className = 'prev';
      e.onclick = new Function('event', 'ajaxNaviListGo(this, "'+url+'", '+(p[0] - p[2] < 0 ? 0 : p[0] - p[2])+');');
      anl.appendChild(e);
    }
    if(p[0] < p[1] - p[2] && url.indexOf(',showAll,1') == -1) {
      e = document.createElement('div');
      e.innerHTML = '&gt;';
      e.className = 'next';
      e.onclick = new Function('event', 'ajaxNaviListGo(this, "'+url+'", '+(p[0] + p[2] >= p[1] ? p[1] - p[2] : p[0] + p[2])+');');
      anl.appendChild(e);
    }
    var f = document.createElement('div');
    f.className = 'pages';
    if(p[1] > 0) {
      var c = 0;
      e = document.createElement('div');
      for(var i = 0; i < p[1]; i += p[2]) {
        ee = document.createElement('a');
        ee.onclick = new Function('event', 'ajaxNaviListGo(this, "'+url+'", '+i+');');
        ee.innerHTML = i / p[2] + 1;
        ee.href = '#offset,' + i;
        if(p[0] == i && url.indexOf(',showAll,1') == -1)
          ee.className = 'selected';
        e.appendChild(ee);
        if(++c == naviCols) {
          c = 0;
          f.appendChild(e);
          e = document.createElement('div');
        } else if(i + p[2] >= p[1]) {
          f.appendChild(e);
        } else {
          ee = document.createTextNode(' ');
          e.appendChild(ee);
        }
      }
      e = document.createElement('div');
      ee = document.createElement('a');
      ee.onclick = new Function('event', 'ajaxNaviListGo(this, "'+url+'", -1);');
      ee.innerHTML = showAllTxt;
      if(url.indexOf(',showAll,1') != -1)
        ee.className = 'selected';
      e.appendChild(ee);
      f.appendChild(e);
      ee.href = '#showAll,1';
    }
    anl.appendChild(f);
    o.appendChild(anl);
  }
}

//ajaxowa nawigacja - przejdź do pozycji na liście
function ajaxNaviListGo(o, url, n) {
  var pos = getObjectPosition(document.getElementById('columns'));
  scrollPageUpTo(pos.y);
  var o = getParentByClassName(o, 'div', 'ajaxContent');
  if(n < 0) {
    url = url.replace(',showAll,0', ',showAll,1');
    url = url.replace(/,offset,[^,/]*/, ',offset,0');
    if(url.indexOf(',showAll,') == -1)
      url += (url.indexOf('?') == -1 ? '?' : '&') + 'showAll=1';
  } else {
    url = url.replace(',showAll,1', ',showAll,0');
    url = url.replace(/,offset,[^,/]*/, ',offset,' + n);
    if(url.indexOf(',offset,') == -1)
      url += (url.indexOf('?') == -1 ? '?' : '&') + 'offset=' + n;
  }
  if(o) {
    o.innerHTML = '&#160;<!--url['+url+']//-->' + o.innerHTML.replace(/<!--url\[([^\]]+)\]\/\/-->/, '');
    initAjaxContents(o);
  }
}

//scrollowanie strony w górę
function scrollPageUpTo(ty) {
  scrollPage(ty, -1);
}

//scrollowanie strony
function scrollPage(ty, d) {
  var sy = typeof(window.pageYOffset) == 'number'
    ? window.pageYOffset
    : (document.body && document.body.scrollTop
      ? document.body.scrollTop
      : (document.documentElement && document.documentElement.scrollTop
        ? document.documentElement.scrollTop
        : 0));
  if(sy <= ty || sy + (scrollStep * d) <= ty) {
    window.scroll(0, ty);
  } else {
    window.scroll(0, sy + (scrollStep * d));
    setTimeout('scrollPage(' + ty + ', ' + d + ');', 10);
  }
}

//tab sortujący
function tabSortList(o, s) {
  var re = new RegExp('<!--([^/]+)//-->', '');
  var m = re.exec(o.innerHTML);
  if(m && m.length == 2 && o.className.indexOf('tabOn') == -1) {
    var ts = getTagsByClassName(o.parentNode, 'div', 'tab');
    for(var i = 0; i < ts.length; i++)
      if(ts[i].className.indexOf('tabTitle') == -1)
        ts[i].className = 'tab' + (ts[i] == o ? ' tabOn' : '');
    o = getNextTagByClassName(o.parentNode, 'div', 'ajaxContent');
    if(s)
      submitFormSearch();
    else if(o)
      initAjaxContents(o);
  }
}

//litera filtrująca
function letterFilterList(o) {
  if(o.className.indexOf('selected') == -1) {
    var oo = o.parentNode;
    for(var i = 0; i < oo.childNodes.length; i++)
      oo.childNodes[i].className = oo.childNodes[i].className.replace(/ ?selected/, '') + (oo.childNodes[i] == o ? ' selected' : '');
    oo = getNextTagByClassName(oo, 'div', 'ajaxContent');
    if(oo) {
      oo.innerHTML = '&#160;<!--url[' + o.href.replace(',letter,', '_mini,letter,') + ']//-->' + oo.innerHTML.replace(/<!--url\[([^\]]+)\]\/\/-->/, '');
      initAjaxContents(oo);
    }
  }
  o.blur();
  return false;
}

//konwersja urla
function urlSlicker(url) {
  if(url.indexOf('index.html') == -1)
    return url;
  var re = new RegExp('\/(page,[^\/]+)\/', '');
  var m = re.exec(url);
  if(!m)
    return url;
  url = url.replace('#', url.indexOf('?') == -1 ? '?' : '&');
  var url = url.split('?');
  if(url.length == 1)
    return url[0];
  url[1] = url[1].replace(/&/g, ',').replace(/=/g, ',').split(',');
  for(var i = 0; i < url[1].length; i+=2)
    if(m[1].indexOf(',' + url[1][i] + ',') != -1) {
      re = new RegExp(',' + url[1][i] + ',[^,]*', '');
      m[1] = m[1].replace(re, ',' + url[1][i] + ',' + url[1][i + 1]);
    } else {
      m[1] += ',' + url[1][i] + ',' + url[1][i + 1];
    }
  url[0] = url[0].replace(m[0], '/' + m[1] + '/');
  return url[0];
}

//uruchomienie górnej wstęgi
function initTopRibbon() {
  var trId = getCookie(ckTopRibbon) ? getCookie(ckTopRibbon) : 0;
  var o = document.getElementById('ribbonTopTabs');
  var oo = document.getElementById('ribbonTopFlash');
  if(o && o.childNodes && trId >= 0 && oo.nodeName.toUpperCase() == 'DIV') {
    var i = 0;
    oo = null;
    while(i < o.childNodes.length && !oo) {
      if(o.childNodes[i].className && o.childNodes[i].className == 'selected')
        oo = o.childNodes[i];
      else
        i++;
    }
    if(oo) {
      var re = new RegExp('\(([0-9]+)\)', 'g');
      var m = re.exec((oo.onclick + '').replace('\n', ''));
      if(m) {
        var flashvars = {};
        flashvars.xmlPath = '/page,xml_ksiazki_na_wstege,contentType,xml,id,' + m[1] + '/index.html';
        var params = {};
        params.menu = 'false';
        params.quality = 'autohigh';
        params.scale = 'noscale';
        params.wmode = 'transparent';
        params.bgcolor = '#ffffff';
        params.salign = 'tl';
        var attributes = {};
        attributes.id = 'ribbonTopFlash';
        swfobject.embedSWF('/flash/ribbon_products.swf', 'ribbonTopFlash', '950', '194', '9.0.0', '/flash/expressinstall.swf', flashvars, params, attributes);
        setCookie(ckTopRibbon, m[1]);
        document.getElementById('ribbonTopFlash').onfocus = new Function('this.blur();');
      }
    }
  }
}

//najazd na fiszkę
function onRibbonProductOver(h) {
  document.getElementById('ribbonTop').childNodes[0].style.height = h + 'px';
  document.getElementById('ribbonTopFlash').style.height = h + 'px';
}

//zjazd z fiszki
function onRibbonProductOut(h) {
  document.getElementById('ribbonTop').childNodes[0].style.height = h + 'px';
  document.getElementById('ribbonTopFlash').style.height = h + 'px';
}

//rozwinięcie górnej wstęgi
function toggleTopRibbon() {
  hideSearchHint();
  var trId = getCookie(ckTopRibbon) ? getCookie(ckTopRibbon) : 0;
  trId = -trId;
  setCookie(ckTopRibbon, trId);
  document.getElementById('ribbonTop').className = (trId < 0 ? 'rolledUp' : '');
  document.getElementById('ribbonTopTabs').className = (trId < 0 ? 'rolledUp' : '');
  if(trId >= 0)
    initTopRibbon();
}

//informacja o załadowaniu listy
function onReadyTopRibbon() {
  topRibbonReady = true;
}


//przeładowanie górnej wstęgi we flashu
function setTopRibbonTab(o, id) {
  if(topRibbonReady)
    for(var i = 0; i < o.parentNode.childNodes.length; i++)
      if(o.parentNode.childNodes[i].nodeName.toUpperCase() == 'SPAN') {
        if(o.parentNode.childNodes[i] == o) {
          o.className = 'selected';
          setCookie(ckTopRibbon, id);
        } else {
          o.parentNode.childNodes[i].className = '';
        }
      }
}

//przeładowanie górnej wstęgi we flashu
function onReloadTopRibbon(id) {
  if(topRibbonReady) {
    topRibbonReady = false;
    document.getElementById('ribbonTopFlash').onReloadTopRibbon('/page,xml_ksiazki_na_wstege,contentType,xml,id,' + id + '/index.html');
  }
}

//ustawianie klasy dla wybranych pól
function setFieldsClass(fs, c) {
  if(fs) {
    if(fs instanceof Array)
      true;
    else
      fs = [fs];
    for(var i = 0; i < fs.length; i++)
      try {
        document.getElementById(fs[i]).className = c;
      } catch(ex) {}
  }
}

//wycentrowanie obiektu na ekranie
function centerObjectOnScreen(o) {
  var winW = document.all ? (document.documentElement&&document.documentElement.clientWidth) ? document.documentElement.clientWidth-20 : document.body.clientWidth-20:window.innerWidth-16;
  var winH = document.all ? (document.documentElement&&document.documentElement.clientHeight) ? document.documentElement.clientHeight-20 : document.body.clientHeight-20:window.innerHeight-16;
  o.style.position = 'fixed';
  o.style.left = Math.floor((winW - o.offsetWidth) / 2)+'px';
  o.style.top = Math.floor((winH - o.offsetHeight) / 2)+'px';
}

//otwarcie obrazka w warstwie
function popLayerImage(l, ct) {
  coverPage('#000000');
  showLidHourglass();
  var div = document.createElement('div');
  div.id = 'layerImage';
  var img = document.createElement('img');
  if(ct) {
    var a = document.createElement('a');
    a.className = 'close';
    a.innerHTML = ct;
    a.onclick = new Function('uncoverPage();');
    div.appendChild(a);
  }
  img.onclick = new Function('uncoverPage();');
  img.onload = new Function('showLayerImage(this);');
  img.src = l;
  div.appendChild(img);
  document.body.appendChild(div);
}

//pokazanie obrazka w warstwie
function showLayerImage(o) {
  hideLidHourglass();
  centerObjectOnScreen(o.parentNode);
  o.style.visibility = 'visible';
  document.getElementById('lid').onclick = new Function('uncoverPage();');
}

//aktywacja ratingu
function activateRating() {
  var o = document.getElementById('ratingOverlay');
  if(o)
    o.onmousemove = ratingMouseMove;
}

//obsługa jazdy po ratingu
function ratingMouseMove(evt) {
  var rNull = document.getElementById('ratingNull');
  var rOn = document.getElementById('ratingOn');
  var rOff = document.getElementById('ratingOff');
  var rActive = document.getElementById('ratingActive');
  var pos = rNull
  rOn.className = 'undisplayed';
  rOff.className = 'undisplayed';
  rNull.className = '';
  rActive.className = '';
  var pos = getObjectPosition(rNull);
  var mX = (evt ? evt.pageX : window.event.clientX) - pos.x - 1;
  mX = (1 + Math.floor(mX / (rNull.offsetWidth / 5))) * rNull.offsetWidth / 5;
  rActive.style.width = mX + 'px';
}

//obsługa zjazdu z ratingu
function ratingMouseOut() {
  var rNull = document.getElementById('ratingNull');
  var rOn = document.getElementById('ratingOn');
  var rOff = document.getElementById('ratingOff');
  var rActive = document.getElementById('ratingActive');
  if(document.forms['formCommentBook'].elements['rating'].value > 0) {
    rOn.style.width = (rNull.offsetWidth * document.forms['formCommentBook'].elements['rating'].value / 5) + 'px';
    rOn.className = '';
    rOff.className = '';
    rNull.className = 'undisplayed';
    rActive.className = 'undisplayed';
  } else {
    rOn.className = 'undisplayed';
    rOff.className = 'undisplayed';
    rNull.className = '';
    rActive.className = 'undisplayed';
  }
}

//obsługa kliknięcie ratingu
function ratingClick(o) {
  var rNull = document.getElementById('ratingNull');
  var rActive = document.getElementById('ratingActive');
  var v = rActive.offsetWidth / rNull.offsetWidth * 5;
  if(!isNaN(v))
    document.forms['formCommentBook'].elements['rating'].value = v;
}

//inicjowanie ebooków
function initEbooks() {
  var o = document.getElementById('colMid');
  if(o) {
    var bks = getTagsByClassName(o, 'div', 'book');
    for(var i = 0; i < bks.length; i++) {
      var info = getTagsByClassName(bks[i], 'div', 'info');
      if(info.length == 1) {
        var label = getTagsByClassName(info[0], 'span', 'typeLabel');
        var ib = getTagsByClassName(info[0], 'a', 'infobox');
        if(label.length == 1 && ib.length == 0) {
          switch(label[0].innerHTML) {
            case 'EBOOK pdf':
            case 'EBOOK epub':
              var cover = getTagsByClassName(bks[i], 'div', 'cover');
              if(cover.length == 0)
                cover = getTagsByClassName(bks[i], 'a', 'cover');
              if(cover.length == 1) {
                var img = document.createElement('img');
                img.src = '/img/layout/wrapper_ebook.png';
                img.className = 'wrapper';
                cover[0].appendChild(img);
              }
              ib = document.createElement('a');
              ib.innerHTML = 'Książka w wersji elektronicznej, żeby ją przeczytać musisz posiadać odpowiednie urządzenie.'
              ib.className = 'infobox';
              ib.href = '/pomoc_ebooki/info.html';
              info[0].appendChild(ib);
              break;
            case 'MP3 DO POBRANIA':
              var cover = getTagsByClassName(bks[i], 'div', 'cover');
              if(cover.length == 0)
                cover = getTagsByClassName(bks[i], 'a', 'cover');
              if(cover.length == 1) {
                var img = document.createElement('img');
                img.src = '/img/layout/wrapper_mp3.png';
                img.className = 'wrapper';
                cover[0].appendChild(img);
              }
              ib = document.createElement('a');
              ib.innerHTML = 'AUDIOBOOK w postaci plików MP3 do pobrania.'
              ib.className = 'infobox';
              ib.href = '/pomoc_ebooki/info.html';
              info[0].appendChild(ib);
              break;
          }
        }
      }
    }
  }
}
