initMenu();

//inicjalizacja menu kategorii roślin
function initMenu() {
  var req = extractReqParams(window.location);
  if(req && req.plantCategory) {
    var now = new Date();
    fixDate(now);
    now.setTime(now.getTime() + 30*24*60*60*1000);
    setCookie('plantCategory', req.plantCategory, now, '');
    menuIdString = req.plantCategory;
  } else {
    menuIdString = getCookie('plantCategory');
  }
  if(!menuIdString) {
    menuIdString = 1;
    setCookie('plantCategory', '1', now, '');
  }
}

//typ pozycji obiektu
function ObjectPosition(x, y) {
  this.x=x;
  this.y=y;
}

//dodawanie funcji do wywoał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;
}

//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) {
var p = new ObjectPosition(o.offsetLeft, o.offsetTop);
  while(o.offsetParent) {
    o = o.offsetParent;
    p.x += o.offsetLeft;
    p.y += o.offsetTop;
  }
  return p;
}

//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 : "") +
      ((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";
  }
}

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;");
}

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();");
}

function searchTextField(f, p, v) {
  eval("document."+f+"."+p+".value = '"+v+"';");
  eval("document."+f+".submit();");
}

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();
}

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();
}

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;
}

//objekt request
function Request() {}

//wyciąganie parametrów z urla
function extractReqParams(s) {
  try {
    var anch = document.createElement("a");
    anch.href = s;
    if(anch.search != '') {
      var retArr = anch.search.replace('?', '').split('&');
      var req = new Request();
      for(var i = retArr.length - 1; i >= 0 ; i--)
        if(retArr[i].indexOf('=') != -1) {
          var attr = retArr[i].split('=', 2);
          eval('Request.prototype.'+attr[0]+'=null;');
          eval('req.'+attr[0]+'="'+attr[1]+'";');
        } else {
          retArr.splice(i, 1);
        }
      if(retArr.length > 0)
        return req;
      return null;
    } else {
      return null;
    }
  } catch(ex) {
    return null;
  }
}

//zmiana panela w opisie preparatu
function showPreparationPanel(n, id) {
  try {
    if(document.getElementById('preparationPanel'+n).innerHTML == '') {
      if(n == 2) {
       advAJAX.get ({
        url: 'index.php?page=komentarze_do_preparatow'
        , parameters: {
          'id' : id
        }
        , tag : n
        , onSuccess: function(obj) {
          try {
            document.getElementById('preparationPanel'+obj.tag).innerHTML = obj.responseText;
          } catch(ex) {}
        }
        , onError: function(obj) { alert("Błąd: " + obj.status); }
      });
      } else if(n == 3) {
       advAJAX.get ({
        url: 'index.php?page=lista_podobnych_preparatow'
        , parameters: {
          'id' : id
        }
        , tag : n
        , onSuccess: function(obj) {
          try {
            document.getElementById('preparationPanel'+obj.tag).innerHTML = obj.responseText;
          } catch(ex) {}
        }
        , onError: function(obj) { alert("Błąd: " + obj.status); }
      });
      } else if(n == 4) {
       advAJAX.get ({
        url: 'index.php?page=lista_powiazanych_tresci'
        , parameters: {
          'id' : id
        }
        , tag : n
        , onSuccess: function(obj) {
          try {
            document.getElementById('preparationPanel'+obj.tag).innerHTML = obj.responseText;
          } catch(ex) {}
        }
        , onError: function(obj) { alert("Błąd: " + obj.status); }
      });
      }
    }
    for(var i = 1; i <=8; i++) {
      try {
        document.getElementById('preparationPanel'+i).className = (i == n ? '' : 'undisplayed');
      } catch(ex) {}
      try {
        document.getElementById('preparationPanelButton'+i).className = (i == n ? 'preparationPanelButton clicked' : 'preparationPanelButton');
      } catch(ex) {}
    }
  } catch(ex) {}
}

//pokazywanie i ukrywanie formularza dodawania komentarza preparatu
function togglePreparationComment() {
  try {
    var d = document.getElementById('addCommentBox');
    if(d.style.height != '140px') {
      d.style.height = '140px';
      var req = extractReqParams(window.location);
      var f = document.createElement('iframe');
      f.allowTransparency = 'true';
      f.frameBorder = '0';
      f.border = '0';
      f.marginHeight = '0';
      f.marginWidth = '0';
      f.scrolling = 'no';
      f.src = 'http://www.ochronaroslin.agro.pl/forum/cms/add_comment_preparations.php?id='+req.id;
      d.appendChild(f);
    } else {
      d.style.height = '0px';
      d.removeChild(d.childNodes[0]);
    }
  } catch(ex) {}
}

//pokazywanie i ukrywanie formularza dodawania komentarza agrofaga
function togglePestComment() {
  try {
    var d = document.getElementById('addCommentBox');
    if(d.style.height != '140px') {
      d.style.height = '140px';
      var req = extractReqParams(window.location);
      var f = document.createElement('iframe');
      f.allowTransparency = 'true';
      f.frameBorder = '0';
      f.border = '0';
      f.marginHeight = '0';
      f.marginWidth = '0';
      f.scrolling = 'no';
      f.src = 'http://www.ochronaroslin.agro.pl/forum/cms/add_comment_pests.php?id='+req.id;
      d.appendChild(f);
    } else {
      d.style.height = '0px';
      d.removeChild(d.childNodes[0]);
    }
  } catch(ex) {}
}

addOnLoad('resizeIframes');

function resizeIframes() {
  if(document.getElementById('forumFrame'))
    resizeCaller();
}

function resizeCaller() {
//Input the IDs of the IFRAMES you wish to dynamically resize to match its content height:
//Separate each ID with a comma. Examples: ["myframe1", "myframe2"] or ["myframe"] or [] for none:
  var iframeids=["forumFrame"]
//Should script hide iframe from browsers that don't support this script (non IE5+/NS6+ browsers. Recommended):
  var iframehide="no"
  var dyniframe=new Array()
  for (i=0; i<iframeids.length; i++){
    if (document.getElementById)
      resizeIframe(iframeids)
    //reveal iframe for lower end browsers? (see var above):
    if ((document.all || document.getElementById) && iframehide=="no"){
      var tempobj=document.all? document.all[iframeids] : document.getElementById(iframeids)
      tempobj.style.display="block"
    }
  }
}

function resizeIframe(frameid){
  var extraHeight = 20;
  var currentfr=document.getElementById(frameid)
  var getFFVersion=navigator.userAgent.substring(navigator.userAgent.indexOf("Firefox")).split("/")[1]
  var FFextraHeight=parseFloat(getFFVersion)>=0.1? 10 : 0 //extra height in px to add to iframe in FireFox 1.0+ browsers
  if (currentfr && !window.opera){
    currentfr.style.display="block"
    if (currentfr.contentDocument && currentfr.contentDocument.body.offsetHeight) //ns6 syntax
      currentfr.height = extraHeight+currentfr.contentDocument.body.offsetHeight+FFextraHeight; 
    else if (currentfr.Document && currentfr.Document.body.scrollHeight) //ie5+ syntax
      currentfr.height = extraHeight+currentfr.Document.body.scrollHeight;
    if (currentfr.addEventListener)
      currentfr.addEventListener("load", readjustIframe, false)
    else if (currentfr.attachEvent){
      currentfr.detachEvent("onload", readjustIframe) // Bug fix line
      currentfr.attachEvent("onload", readjustIframe)
    }
  }
}

function readjustIframe(loadevt) {
  var crossevt=(window.event)? event : loadevt
  var iframeroot=(crossevt.currentTarget)? crossevt.currentTarget : crossevt.srcElement
  if (iframeroot)
    resizeIframe(iframeroot.id);
}

function loadintoIframe(iframeid, url){
  if (document.getElementById)
    document.getElementById(iframeid).src=url
}
