//--- Eerste element in een formulier focussen ---

function focusForm() {
   if (document.forms && document.forms[0]) {
      var f = document.forms[0], e;
      if (f.elements && f.elements[0])
         for (var i = 0; i < f.elements.length; i++) {
            e = f.elements[i];
            if ((e.tagName == "INPUT" && e.type == "text") || e.tagName == "SELECT" || e.tagName == "TEXTAREA") {
               if (e.focus && !e.disabled) e.focus();
               if (e.select && e.tagName != "TEXTAREA") e.select();
               break;
            }
         }
   }
}

//--- <abbr> tags vervangen door iets netters ---

function replaceAbbrTags() {
   var abbrs = document.getElementsByTagName("abbr"), stopTimeout = null;

   for (var i = 0; i < abbrs.length; i++) {
      var span = abbrs[i].firstChild, span2 = abbrs[i].nextSibling, title, hasSpan, id = "tooltip" + i, tt;

      //oude tooltip opzoeken
      hasSpan = (span && span.nodeType == 1 && span.tagName.toLowerCase() == "span");
      if (!hasSpan) {
         hasSpan = (span2 && span2.nodeType == 1 && span2.tagName.toLowerCase() == "span");
         if (hasSpan) span = span2;
      }
   
      if (!hasSpan) span = abbrs[i];
      title = span.getAttribute("title");
   
      //oude tooltip verwijderen
      span.setAttribute("title", "");
      span.removeAttribute("title");
   
      //MSIE handelt positie van een span aan het begin van de regel niet goed af, vandaar deze workaround
      if (navigator.appName.toLowerCase() == "microsoft internet explorer") {
         var text = span.firstChild, abbrtext = new String();
         if (text) {
            abbrtext = text.nodeValue;
            span.removeChild(text);
            span.appendChild(document.createTextNode(abbrtext.substr(0, 1)));
         }
         if (abbrtext.length > 1) {
            var iespan = document.createElement("span");
            iespan.appendChild(document.createTextNode(abbrtext.substr(1, 1)));
            span.appendChild(iespan);
            if (abbrtext.length > 2)
               span.appendChild(document.createTextNode(abbrtext.substr(2)));
         }
      }

      //events voor nieuwe tooltip alvast instellen
      span.onmouseover = new Function("popoverMouseover(this, '" + id + "');");
      span.onmouseout = new Function("popoverMouseout('" + id + "');");
   
      //nieuwe tooltip aanmaken
      tt = document.createElement("div");
      tt.style.position = "absolute";
      tt.style.display = "none";
      tt.className = "popover";
      tt.appendChild(document.createTextNode(title));
      tt.onmouseover = new Function("stopHidingPopover('" + id + "');");
      tt.onmouseout = new Function("popoverMouseout('" + id + "');");
      tt.id = id;
              
      document.body.appendChild(tt);
   }
}

//--- Een element met clear:both onder iedere <code>/<div class="example"> zetten en de hoogte fixen ---

function updateCodeTags() {
   var codes = document.getElementsByTagName("code"), divs = document.getElementsByTagName("div"), len = codes.length,
       h = getBodyHeight(), maxh = h / 2 + h * 0.05, newh = h / 2;
   for (var i = 0; i < divs.length; i++)
      if (divs[i].className.indexOf("example") >= 0)
         codes[len++] = divs[i];
   for (var i = 0; i < len; i++) {
      var c = codes[i], p = c.parentNode;
      if (p) {
         //firstChild en lastChild opzoeken
         var firstChild = p.firstChild, lastChild = p.lastChild;
         while (firstChild && firstChild.nodeType == 3) firstChild = firstChild.nextSibling;
         while (lastChild && lastChild.nodeType == 3) lastChild = lastChild.previousSibling;

         //Fix voor opera
         if (c == firstChild)
            p.insertBefore(document.createElement("p"), c);

         //Als de code hoger is dan de helft van het scherm, dan insluiten in een div en scrollbaar maken
         if (c.offsetHeight > maxh) {
            c.style.height = newh + "px";
            c.style.maxHeight = c.style.height;
            var div = document.createElement("div");
            div.style.overflow = "auto";
            div.style.height = "100%";
            div.innerHTML = c.innerHTML;
            c.innerHTML = "";
            c.appendChild(div);
         }  

         //Een clear:both element onder de code toevoegen
         var next = document.createElement("div");
         next.style.margin = "0";
         next.style.clear = "both";
         if (navigator.userAgent.toLowerCase().indexOf("gecko") >= 0)
            c.style.marginBottom = "1em";
         if (p.lastChild == c)
            p.appendChild(next);
         else
            p.insertBefore(next, c.nextSibling);

         //Eventuele tevele marge weghalen
         var nextnext = next.nextSibling;
         while (nextnext && nextnext.nodeType == 3) nextnext = nextnext.nextSibling;
         if (nextnext) nextnext.style.marginTop = "0";
      }
   }
}

//--- News-items inkorten ---

function shortenNewsItems() {
   var deleteRemaining;
   var maxLength = 100;
   var ellipsis = "...";

   function trimEnd(s) {
      return s.replace(/[ ]+?$/, "");
   }

   function shortenElement(o, currentPosition) {
      var position = 0, ch = o.firstChild;
      while (ch != null) {
         if (deleteRemaining) {
            var nextch = ch.nextSibling;
            o.removeChild(ch);
            ch = nextch;
         }
         else if (ch.nodeType == 1 && ch.tagName == "BR") {
            var nextch = ch.nextSibling;
            o.insertBefore(document.createTextNode(" "), ch);
            o.removeChild(ch);
            ch = nextch;
         }
         else {
            switch(ch.nodeType) {
               case 1: //Element node
                  position += shortenElement(ch, currentPosition + position);
                  break;
               case 3: //Text node
                  if (ch.nodeValue.length + currentPosition >= maxLength) {
                     ch.nodeValue = trimEnd(ch.nodeValue.substr(0, maxLength - currentPosition - position)) + (ellipsis? ellipsis: "");
                     deleteRemaining = true;
                  }
                  else if (position + currentPosition + ch.nodeValue.length >= maxLength) {
                     ch.nodeValue = trimEnd(ch.nodeValue) + (ellipsis? ellipsis: "");
                     deleteRemaining = true;
                  }
                  position += ch.nodeValue.length;
                  break;
            }
            ch = ch.nextSibling;
         }
      }
      return position;
   }

   var descriptions = document.getElementById("news").getElementsByTagName("td");
   for (var i = 0; i < descriptions.length; i++)
      if (descriptions[i].className == "description") {
         deleteRemaining = false;
         shortenElement(descriptions[i], 0);
      }
}

//--- Het mouseover-event van elke popover repliceren naar z'n child-elementen ---

function replicatePopoverMouseovers() {
   var popovers = document.getElementsByTagName("div");
   for (var i = 0; i < popovers.length; i++)
      if (popovers[i].className == "popover")
         replicatePopoverMouseover(popovers[i]);
}

function replicatePopoverMouseover(popover) {
   if (typeof(popover) == "string")
      popover = document.getElementById(popover);
   var mouseover = popover.onmouseover, child = popover.firstChild;
   if (mouseover) {
      while (child) {
         if (child.nodeType == 1) {
            child.onmouseover = mouseover;
            replicatePopoverMouseover(child);
         }
         child = child.nextSibling;
      }
   }
}

//--- Test-functies (voor test-knoppen, niet voor debug-doeleinden) ---

function testURL(url) {
   if (url.substr(0, 7).toLowerCase() != "http://" && url.substr(0, 8).toLowerCase() != "https://")
      url = "http://" + url;
   window.open(url, "_blank", "location=yes");
}

function testMail(mail) {
   window.location.href = "mailto:" + mail;
}

//--- Functies t.b.v. pop-overs en DHTML-tooltips ---

var stopPopoverTimeout = null, alreadyPopoverTiming = false;

function popoverMouseover(element, popover, position) {
   var elementtop, elementleft;
   if (typeof(element) != "object")
      element = document.getElementById(element);
      
   //Workaround voor positie-bug in MSIE
   if (navigator.appName.toLowerCase() == "microsoft internet explorer") {
      var subelm = element.firstChild;
      while (subelm && subelm.nodeName != "SPAN")
         subelm = subelm.nextSibling;
      if (subelm)
         elementtop = findPosY(subelm)
      else
         elementtop = findPosY(element);
   }
   else
      elementtop = findPosY(element);
   
   elementleft = findPosX(element);
   
   removePopovers();
   if (typeof(popover) != "object")
   	  popover = document.getElementById(popover);

   if (popover != null) {
      stopPopoverTimeout = popover.id;

      position = (position) ? position.toLowerCase() : "auto";
      if (position == "auto")
         position = (elementleft > getBodyWidth() / 2) ? "right" : "left";

      if (position == "right")
         popover.style.right = getBodyWidth() - (elementleft + element.offsetWidth) - 2 + "px";
      else if (position == "left")
         popover.style.left = elementleft - 2 + "px";

      popover.style.top = elementtop + element.offsetHeight + 1 + "px";
      popover.style.display = "block";
   }
}

function popoverMouseout(popover) {
   stopPopoverTimeout = null;
   if (!alreadyPopoverTiming) {
      alreadyPopoverTiming = true;
      if ((popover != null) && (typeof(popover) == "object"))
         setTimeout("popoverMouseoutDelayed('" + popover.id + "');", 500);
      else
         setTimeout("popoverMouseoutDelayed('" + popover + "');", 500);
   }
}

function popoverMouseoutDelayed(popover) {
   if (stopPopoverTimeout != popover) {
      popover = document.getElementById(popover);
      popover.style.display = "none";
   }
   alreadyPopoverTiming = false;
}

function removePopovers(e) {
   //fix voor MSIE, die event.target niet kent
   if (e && !e.target)
      e.target = e.srcElement;
   
   if (!e || !e.target || !e.target.onclick) {
      var divs = document.getElementsByTagName("div");
      for (var i = 0; i < divs.length; i++) {
         if (new String(divs[i].className).indexOf("popover") >= 0) {
            divs[i].style.display = "none";
         }
      }
      alreadyPopoverTiming = false;
   }
}

function stopHidingPopover(popover) {
   if (typeof(popover) == "object")
      stopPopoverTimeout = popover.id;
   else
      stopPopoverTimeout = popover;
}

//--- Easy-access functies ---

function getBodyWidth() {
   var width1 = (window.innerWidth? window.innerWidth: 0);
   var width2 = (document.body.clientWidth? document.body.clientWidth: 0);
   if (width2 < width1 && width2 > 0 || width1 == 0)
      width1 = width2;
   return width1;
}

function getBodyHeight() {
   var height1 = (window.innerHeight? window.innerHeight: 0);
   var height2 = (document.body.clientHeight? document.body.clientHeight: 0);
   if (height2 < height1 && height2 > 0 || height1 == 0)
      height1 = height2;
   return height1;
}

function findPosX(obj) {
   var curleft = 0;
   if (obj.offsetParent) {
      while (obj.offsetParent) {
         curleft += obj.offsetLeft;
         obj = obj.offsetParent;
      }
   } else if (obj.x)
      curleft += obj.x;
   return curleft;
}

function findPosY(obj) {
   var curtop = 0;
   if (obj.offsetParent) {
      while (obj.offsetParent) {
         curtop += obj.offsetTop;
         obj = obj.offsetParent;
      }
   } else if (obj.y)
      curtop += obj.y;
   return curtop;
}

//--- Script voor clientside cookies gebruiken ---

function setCookie(name, value, expires, path, domain, secure) {
   document.cookie =
      name + "=" + value +
      ((expires)? "; expires=" + expires.toGMTString(): "") +
      ((path)? "; path=" + path: "") +
      ((domain)? "; domain=" + domain: "") +
      ((secure)? "; secure": "");
}


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));
}

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";
   }
}

//--- className includen en excluden ---

function includeClassName(currentClassNames, className) {
   var classNameArray = currentClassNames.split(" ");
   for (var i = 0; i < classNameArray.length; i++)
      if (classNameArray[i] == className)
         return classNameArray.join(" ");
   return classNameArray.join(" ") + " " + className;
}

function excludeClassName(currentClassNames, className) {
   var classNameArray = currentClassNames.split(" ");
   for (var i = 0; i < classNameArray.length; i++)
      if (classNameArray[i] == className)
         classNameArray.splice(i, 1);
   return classNameArray.join(" ");
}

//--- Syntax-highlighters registeren

function registerHighlighters() {
   var divs = document.getElementsByTagName("div"), highlighters = new Array();
   for (var i = 0; i < divs.length; i++)
      if (divs[i].className == "__highlighter")
         highlighters[highlighters.length] = divs[i];
   for (var i = 0; i < highlighters.length; i++)
      dp.sh.HighlightElement(highlighters[i], highlighters[i].id.replace(/^([a-z]+)_highlighter_[0-9]{3}$/, "$1"));
}

//Laatstbezochte PIN-cookie instellen

function setLastVisitedPinCookie() {
   var qs = window.location.search;
   if (qs.substr(0, 1) == "?")
      qs = qs.substr(1);
   var a = qs.split("&"), pin = 0;
   for (var i = 0; i < a.length; i++) {
      if (a[i].length > 4 && a[i].substr(0, 4) == "pin=") {
         pin = a[i].substr(4);
         break;
      }
   }
   if (pin > 0) {
      var c = getCookie("aintlogin");
      if (c != null) {
         a = c.split("&");
         var found = a.length;
         for (var i = 0; i < a.length; i++) {
            if (a[i].length > 8 && a[i].substr(0, 8) == "lastpin=") {
               found = i;
               break;
            }
         }
         a[found] = "lastpin=" + pin;
         var expires = new Date(new Date().valueOf() + 86400000); //Morgen
         setCookie("aintlogin", a.join("&"), expires);
      }
   }
}

setLastVisitedPinCookie();
