var ss = {
  fixAllLinks: function() {
    var allLinks = document.getElementsByTagName('a');
    for (var i=0;i<allLinks.length;i++) {
      var lnk = allLinks[i];
      if ((lnk.href && lnk.href.indexOf('#') != -1) && ( (lnk.pathname == location.pathname) || ('/'+lnk.pathname == location.pathname) ) && (lnk.search == location.search)) {
        ss.addEvent(lnk,'click',ss.smoothScroll);
      }
    }
  },
  smoothScroll: function(e) {
    if (window.event) {
      target = window.event.srcElement;
    } else if (e) {
      target = e.target;
    } else return;
    if (target.nodeName.toLowerCase() != 'a') {
      target = target.parentNode;
    }
    if (target.nodeName.toLowerCase() != 'a') return;
    anchor = target.hash.substr(1);
    var allLinks = document.getElementsByTagName('a');
    var destinationLink = null;
    for (var i=0;i<allLinks.length;i++) {
      var lnk = allLinks[i];
      if (lnk.name && (lnk.name == anchor)) {
        destinationLink = lnk;
        break;
      }
    }
    if (!destinationLink) destinationLink = document.getElementById(anchor);
    if (!destinationLink) return true;
    var destx = destinationLink.offsetLeft; 
    var desty = destinationLink.offsetTop;
    var thisNode = destinationLink;
    while (thisNode.offsetParent && 
          (thisNode.offsetParent != document.body)) {
      thisNode = thisNode.offsetParent;
      destx += thisNode.offsetLeft;
      desty += thisNode.offsetTop;
    }
    clearInterval(ss.INTERVAL);
    cypos = ss.getCurrentYPos();
    ss_stepsize = parseInt((desty-cypos)/ss.STEPS);
    ss.INTERVAL = setInterval('ss.scrollWindow('+ss_stepsize+','+desty+',"'+anchor+'")',10);
    if (window.event) {
      window.event.cancelBubble = true;
      window.event.returnValue = false;
    }
    if (e && e.preventDefault && e.stopPropagation) {
      e.preventDefault();
      e.stopPropagation();
    }
  },
  scrollWindow: function(scramount,dest,anchor) {
    wascypos = ss.getCurrentYPos();
    isAbove = (wascypos < dest);
    window.scrollTo(0,wascypos + scramount);
    iscypos = ss.getCurrentYPos();
    isAboveNow = (iscypos < dest);
    if ((isAbove != isAboveNow) || (wascypos == iscypos)) {
      window.scrollTo(0,dest); 
      clearInterval(ss.INTERVAL); 
      location.hash = anchor; 
    }
  },
  getCurrentYPos: function() {
    if (document.body && document.body.scrollTop)
      return document.body.scrollTop;
    if (document.documentElement && document.documentElement.scrollTop)
      return document.documentElement.scrollTop;
    if (window.pageYOffset)
      return window.pageYOffset;
    return 0;
  },
  addEvent: function(elm, evType, fn, useCapture) {
    if (elm.addEventListener){
      elm.addEventListener(evType, fn, useCapture);
      return true;
    } else if (elm.attachEvent){
      var r = elm.attachEvent("on"+evType, fn);
      return r;
    } else {
      alert("Handler could not be removed");
    }
  } 
}
ss.STEPS = 30;
ss.addEvent(window,"load",ss.fixAllLinks);
var counter = 0;
var display = false;
var margin = 10;
var padding = 15;
var def = 'zoom';
var image = 'detail';
var text = 'plot';
function decrease(arr,num)
{
  var fst = arr[0] - num;
  var scd = arr[1] - num;
  return [fst,scd]
}
function objectPosition(obj)
{
  var curleft = curtop = 0;
  if (obj.offsetParent)
  {
    do
    {
      curleft += obj.offsetLeft;
      curtop += obj.offsetTop;
    }while (obj = obj.offsetParent);
  }
  return [curleft,curtop];
}
function increaseCounter()
{
  counter = counter + 1;
  return true;
}
function zoom(e,obj)
{
  var href = obj.href;
  var post = obj.className.substr(obj.className.lastIndexOf(" ")+1);
  var object = decrease(objectPosition(obj),10);
  if(display) forceDrop(def + counter);
  if(!increaseCounter()) return false;
  var alt = document.getElementById('alt-' + post).innerHTML; 
  var title = document.getElementById('title-' + post).innerHTML;
  var content = document.getElementById('desc-' + post).innerHTML;
  var graph = append(def + counter);
  graph.className = 'zoom';
  graph.style.width = '167px';
  graph.style.height = '109px';
  graph.style.left = object[0] + 'px';
  graph.style.top = object[1] + 'px';
  graph.innerHTML = '<img id="' + image + counter + '"' +
                    'src="' + href + '"' +
                    'alt="' + alt + '"' +
                    'tiptitle="' + title + '" ' +
                    'onmouseover="tooltip.show(this.getAttribute(\'tiptitle\'))"' +
                    'onmouseout="tooltip.hide()" />' +
                    '<p id="' + text + counter + '">' + content + '</p>';
  graph.style.display = 'block';
  graph.onclick = niceDrop;
  return grow(graph.id,counter,'320','320',object[0],object[1],'280','211');
}
function grow(id,counter,width,height,left,top,mimgw,mimgh)
{
  var obj = document.getElementById(id);
  var obr = document.getElementById(image + counter);
  var curX = obj.style.width.replace('px','');
  var curY = obj.style.height.replace('px','');
  var posX = obj.style.left.replace('px','');
  var posY = obj.style.top.replace('px','');
  if((width - curX) < 2 && (height - curY) < 2) 
  {
    obj.style.width = width + 'px';
    obj.style.height = height + 'px';
    obr.style.width = (mimgw > (width-2*padding)) ? (width-2*padding) + 'px' : mimgw + 'px';
    obr.style.height = (mimgh > (height-2*padding)) ? (height-2*padding) + 'px' : mimgh + 'px';
    come((text + counter),1); 
    return true; 
  }
  var difX = Math.ceil((width - curX)/10);
  var difY = Math.ceil((height - curY)/10);
  curX = difX + curX*1;
  curY = difY + curY*1;
  left = (left -  Math.floor(difX/2) < margin) ? margin : left -  Math.floor(difX/2);
  top = (top -  Math.floor(difY/2) < margin) ? margin : top -  Math.floor(difY/2);
  obj.style.width = curX + 'px';
  obj.style.height = curY + 'px';
  obj.style.left = left + 'px';
  obj.style.top = top + 'px';
  obr.style.width = (mimgw > (curX-2*padding)) ? (curX-2*padding) + 'px' : mimgw + 'px';
  obr.style.height = (mimgh > (curY-2*padding)) ? (curY-2*padding) + 'px' : mimgh + 'px';
  setTimeout("grow('"+id+"','"+counter+"',"+width+","+height+","+left+","+top+","+mimgw+","+mimgh+")",12);
  display = true;
  return false;
}
function append(id)
{
  var zoom = document.createElement('div');
  var body = document.getElementsByTagName('body');
  zoom.id = id;
  body[0].appendChild(zoom);
  return zoom;
}
function hide(id)
{
  document.getElementById(id).style.display = 'none';
  return false;
}
function drop(id)
{
  var thing = document.getElementById(id);
  var body = document.getElementsByTagName('body');
  document.getElementById(image + id.replace(def,'')).onmouseout();
  body[0].removeChild(thing);
  display = false;
  return true;
}
function forceDrop(id)
{
  setTimeout("drop('"+id+"')",90);
  return fade(id,9);
}
function niceDrop()
{
  return forceDrop(this.id);
}
function fade(id,lvl)
{
  if(lvl >= 1) setTimeout("fade('"+id+"',"+(lvl-1)+")",20);
  return !visibility(id,lvl/10);
}
function come(id,lvl)
{
  if(lvl <= 9) setTimeout("come('"+id+"',"+(lvl+1)+")",20);
  if(!document.getElementById(id)) return false;
  document.getElementById(id).style.display = 'block';
  return visibility(id,lvl/10);
}
function visibility(id,opacity)
{
  if(thing = document.getElementById(id))
  {
    thing.style["-khtml-opacity"] = opacity;
    thing.style.opacity = opacity;
    thing.style.filter = "alpha(opacity="+Math.round(100*opacity)+")";
    return true;
  }
  return false;
}
var form = false; 
var rss = false;
function hideForm(id)
{
  setTimeout("hide('"+id+"')",90);
  return fade(id,10);
}
function switchForm()
{
  var id = 'contact';
  form = (form) ? hideForm(id) : come(id,1);
  return true;
}
function switchRss()
{
  var id = 'rss';
  rss = (rss) ? hideForm(id) : come(id,1);
  return true;
}
function urlencode(str)
{
  return escape(encodeURI(str));
}
function trim(str)
{
  return str.replace(/^\s+|\s+$/g, '');
}
function mailcheck(addr)
{
  if(addr.indexOf('@') == -1 || addr.indexOf('@') == 0 || addr.indexOf('@') == addr.length) return false;
  else if(addr.indexOf('.') == -1 || addr.indexOf('.') == 0 || addr.indexOf('.') == addr.length) return false;
   else return true;          
}
function saveMessage(lang)
{
  var xmlhttp = createXmlhttp();
  var data = 'lang=' + lang + '&js=on&name=' + urlencode(getValue('name')) + '&mail=' + urlencode(getValue('mail')) + '&web=' + urlencode(getValue('web')) + '&text=' + urlencode(getValue('text')) + '&spam=' + urlencode(getValue('spam')) + '&check=' + urlencode(getValue('check'));
  if(!checkMessage(lang)) return true;
  switchMessage();
  if(sendXmlhttp(xmlhttp,data,lang)) return true;
  return false;
}
function checkMessage(lang)
{
  if(lang == 'cz')
  {
    if(trim(getValue('name')).length < 3) return myAlert('Zadané jméno je příliš krátké.','name');
    if(!mailcheck(trim(getValue('mail')))) return myAlert('E-mailová adresa není v korektním tvaru.','mail');
    if(trim(getValue('text')).length < 4) return myAlert('Zadaný text zprávy je příliš krátký.','text');
  }
  else
  {
    if(trim(getValue('name')).length < 3) return myAlert('Name filled in is too short.','name');
    if(!mailcheck(trim(getValue('mail')))) return myAlert('E-mail address is not valid.','mail');
    if(trim(getValue('text')).length < 4) return myAlert('Message filled in is too short.','text');
  }
  return true;
}
function myAlert(str,id)
{
  document.getElementById(id).focus();
  alert(str);
  return false;
}
function switchMessage(vyprazdnit)
{
  if(document.getElementById('formulary').style.display == 'none')
  {
    hide('response');
    if(vyprazdnit) resetMessage();
    come('formulary',1);
  }
  else
  {
    hide('formulary');
    come('response',1);
  }
  return true;
}
function resetMessage()
{
  document.getElementById('name').value = '';
  document.getElementById('mail').value = '@';
  document.getElementById('web').value = 'http://';
  document.getElementById('text').value = '';
  document.getElementById('spam').value = '';
  return true;
}
function createXmlhttp()
{
  var xmlhttp;
  try
  {
    xmlhttp = new XMLHttpRequest();
  }
  catch(e)
  {
    try
    {
      xmlhttp = new ActiveXObject('Microsoft.XMLHTTP');
    }
    catch(e){}
  }
  if(!xmlhttp) return false;
  else return xmlhttp;
}
function sendXmlhttp(xmlhttp,content,lang)
{
  if(!xmlhttp) return !problemFound(lang,false);
  else try
  {
    xmlhttp.open('POST','/message.php',true);
    xmlhttp.onreadystatechange = function () { handleXmlhttp(xmlhttp,lang); };
    xmlhttp.setRequestHeader('Content-Type','application/x-www-form-urlencoded'); 
    xmlhttp.send(content);
  }
  catch(e)
  {
    return false;
  }
  return true;
}
function handleXmlhttp(xmlhttp,lang)
{
  var result = '';
  if(xmlhttp.readyState == 4 && xmlhttp.status == 200)
  {
    try
    {
      var arr = xmlhttp.responseText.split('~');
      if(arr.length != 4) return problemFound(lang,true);
      changeSpamCheck(arr[1],arr[2]);
      if(arr[0] == 'SUC' && lang == 'cz') result = arr[3] + '<br /><br /><input class="submit" type="button" onclick="switchMessage(true)" value="Poslat další zprávu" />';
      else if(arr[0] == 'SUC') result = arr[3] + '<br /><br /><input class="submit" type="button" onclick="switchMessage(true)" value="Send another message" />';
      else if(lang == 'cz') result = arr[3] + '<br /><br /><input class="submit" type="button" onclick="switchMessage(false)" value="Zkusit poslat znovu" />';
      else result = arr[3] + '<br /><br /><input class="submit" type="button" onclick="switchMessage(false)" value="Try sending again" />';
    }
    catch(e)
    {
      return problemFound(lang,false);
    }
  }
  else result = '<img src="/image/functional/load.gif" alt="Image loading" />';
  return show(result);
}
function show(text)
{
  document.getElementById('response').innerHTML = '<table cellspacing="8" cellpadding="0"><tr><th>' + text + '</th></tr></table>';
  return true;
}
function problemFound(lang,again)
{
  if(again && lang == 'cz') return show('Nastal problém s odesláním zprávy. Zkuste prosím znova.<br /><br /><input class="submit" type="button" onclick="switchMessage(false)" value="Zkusit poslat znovu" />');
  else if(again) return show('There was an error while sending. Try again.<br /><br /><input class="submit" type="button" onclick="switchMessage(false)" value="Try sending again" />');
  else if(lang == 'cz') return show('Nastal problém s odesláním zprávy. Zkuste stránku aktualizovat.');
  return show('There was an error while sending. Try refreshing the page.');
}
function changeSpamCheck(task,check)
{
  document.getElementById('task').innerHTML = task;
  document.getElementById('check').value = check;
  return true;
}
function getValue(id)
{
  return document.getElementById(id).value;
}
var qTipTag = "a,span"; 
var qTipX = -20; 
var qTipY = 25; 
tooltip = {
  name : "qTip",
  offsetX : qTipX,
  offsetY : qTipY,
  tip : null
}
tooltip.init = function () {
  var tipNameSpaceURI = "http://www.w3.org/1999/xhtml";
  if(!tipContainerID){ var tipContainerID = "qTip";}
  var tipContainer = document.getElementById(tipContainerID);
  if(!tipContainer) {
    tipContainer = document.createElementNS ? document.createElementNS(tipNameSpaceURI, "div") : document.createElement("div");
    tipContainer.setAttribute("id", tipContainerID);
    document.getElementsByTagName("body").item(0).appendChild(tipContainer);
  }
  if (!document.getElementById) return;
  this.tip = document.getElementById (this.name);
  if (this.tip) document.onmousemove = function (evt) {tooltip.move (evt)};
  var a, sTitle, elements;
  var elementList = qTipTag.split(",");
  for(var j = 0; j < elementList.length; j++)
  {  
    elements = document.getElementsByTagName(elementList[j]);
    if(elements)
    {
      for (var i = 0; i < elements.length; i ++)
      {
        a = elements[i];
        sTitle = a.getAttribute("title");        
        if(sTitle)
        {
          a.setAttribute("tiptitle", sTitle);
          a.removeAttribute("title");
          a.removeAttribute("alt");
          a.onmouseover = function() {tooltip.show(this.getAttribute('tiptitle'))};
          a.onmouseout = function() {tooltip.hide()};
        }
      }
    }
  }
}
tooltip.move = function (evt) {
  var x=0, y=0;
  if (document.all) {
    x = (document.documentElement && document.documentElement.scrollLeft) ? document.documentElement.scrollLeft : document.body.scrollLeft;
    y = (document.documentElement && document.documentElement.scrollTop) ? document.documentElement.scrollTop : document.body.scrollTop;
    x += window.event.clientX;
    y += window.event.clientY;
  } else {
    x = evt.pageX;
    y = evt.pageY;
  }
  this.tip.style.left = (x + this.offsetX) + "px";
  this.tip.style.top = (y + this.offsetY) + "px";
}
tooltip.show = function (text) {
  if (!this.tip) return;
  this.tip.innerHTML = text;
  this.tip.style.display = "block";
}
tooltip.hide = function () {
  if (!this.tip) return;
  this.tip.innerHTML = "";
  this.tip.style.display = "none";
}
window.onload = function () {
  tooltip.init();
}
