// tools.js - function library
// (c) 2005 Q42 BV

var userAgent    = navigator.userAgent.toLowerCase();
var appVersion   = navigator.appVersion.toLowerCase();
var appName      = navigator.appName.toLowerCase();

// operating system and browser information
var isWin        = (appVersion.indexOf('windows') != -1);
var isOpera      = (userAgent.indexOf('opera') != -1);
var isIE         = (appName.indexOf('internet explorer') != -1) && !isOpera;
var isSafari     = (userAgent.indexOf('applewebkit') != -1);
var isMozilla    = (appName.indexOf('netscape') != -1) && !isSafari;

// build versionString
if (isSafari)
  var versionString = appVersion.substr(v.lastIndexOf("safari/") + 7, 3);
else if (isIE || isOpera)
  var versionString = appVersion.substring(appVersion.indexOf('msie') + 5);
else if (isMozilla)
{
  var versionString = userAgent.substring(userAgent.indexOf('rv:')+3, userAgent.indexOf('rv:') + 6);
  Node.prototype.selectSingleNode = function(xpath)
  {
    var xpe = new XPathEvaluator();
    return xpe.evaluate(xpath, this, xpe.createNSResolver(this), 
      XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;
};
  
  Node.prototype.selectNodes = function(xpath)
{
  var xpe = new XPathEvaluator();
  var result = xpe.evaluate(xpath, this, xpe.createNSResolver(this), 
    XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
  var a = [];
  for( var i = 0; i < result.snapshotLength; i++) 
   a[i] = result.snapshotItem(i);
  return a;
};     
  
}
else
  var versionString = appVersion;

// cast version to numeric
var version = parseFloat(versionString);
var ie50 = isWin && isIE && (version <= 5.01);


// array push and pop support for IE50 and others
if (!Array.prototype.push)
  Array.prototype.push = function(el)
  {
    this[this.length] = el;
  };

if (!Array.prototype.pop)
  Array.prototype.pop = function()
  {
    var el = this[this.length-1];
    this.length--;
    return el;
  };

function getXMLDOM()
{
  if (isMozilla)
    return document.implementation.createDocument("text/xml", "", null);
  if (isIE)
    try
    {
      return new ActiveXObject("MSXML2.DOMDocument.6.0");
    }
    catch (e)
    {
      try
      {
        return new ActiveXObject("MSXML2.DOMDocument.5.0");
      }
      catch (e)
      {
        try
        {
          return new ActiveXObject("MSXML2.DOMDocument.4.0");
        }
        catch (e)
        {
          try
          {
            return new ActiveXObject("MSXML2.DOMDocument.3.0");
          }
          catch (e)
          {
            alert("Xml Parser not found");
          }
        }
      }
    }
}
function getXMLHTTP()
{
  if (isMozilla)
    return new XMLHttpRequest();
  if (isIE)
    return new ActiveXObject("Msxml2.XMLHTTP");
}

// isValidEmail, email check
function isValidEmail(e)
{
  charsOk = "1234567890qwertyuiop[]asdfghjklzxcvbnm.@-_QWERTYUIOPASDFGHJKLZXCVBNM";

  // first check if all characters in e exist in charsOk
  for(i=0; i < e.length ;i++){
    if(charsOk.indexOf(e.charAt(i))<0){ 
      return (false);
    } 
  } 

  // then check if it's an email adress
  if (document.images) {
    re = /(@.*@)|(\.\.)|(^\.)|(^@)|(@$)|(\.$)|(@\.)/;
    re_two = /^.+\@(\[?)[a-zA-Z0-9\-\.]+\.([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/;
    if (!e.match(re) && e.match(re_two)) {
      return (-1);    
    } 
  }
};

// make xml document from xmlString
// use: Document xmlDoc = initXml("<apen />");
function initXml(xmlString)
{
  // msxml.domdocument.4.0
  if (typeof (ActiveXObject) != "undefined") {
    var xml = getXMLDOM();
    xml.validateOnParse = false;
    xml.async = false;
    xml.loadXML(xmlString);
  } else if (DOMParser) {
    var xml = (new DOMParser()).parseFromString(xmlString, "text/xml");
  }
  return xml;
};

// make xml document from xmlFilePath
// use: Document xmlDoc = loadXml("/data/xsl/object.xsl");
function loadXmlFile(filepath)
{
  // msxml.domdocument.4.0
  if (typeof (ActiveXObject) != "undefined") {
    var xml = getXMLDOM();
    xml.async = false;
    xml.resolveExternals = true;
    xml.load(filepath);
  } else if (DOMParser) {
    alert('IE only');
  }
  return xml;
};

// add new element to Xml DOM
function addToXmlDom(xmldom, element, value)
{
  var element = xmldom.createElement(element);
  xmldom.documentElement.appendChild(element);
  var valueNode = xmldom.createTextNode(value);
  element.appendChild(valueNode);
};

function attachEventHandler(theEl, theEvent, theHandler, theScope)
{   
  if (theScope)
    theHandler = theHandler.closure(theScope);
  if(typeof(theEl) == 'string')
    theEl = document.getElementById(el);
      
  theEvent = theEvent.toLowerCase();
  if (isIE)
    theEl.attachEvent(theEvent, theHandler);
  else
  {
    if (theEl == document.body)
      theEl = document;
    if (theEvent == "ondragstart")
      theEvent = "ondraggesture";

    theEl.addEventListener(theEvent.substring(2), theHandler, true);
  }
};

function getVisibleElementsByTagName(ancestorEl, tagName)
{
 if (ancestorEl == null)
    return;

  var els = [];
  var a = ancestorEl.getElementsByTagName(tagName);
  for (var i=0; i<a.length; i++)
  {
    var el = a[i];
    if (el.style.display != "none" && el.style.visibility != "hidden")
      els.push(el)
  }
  return els;
};

function getPreviousSiblingByTagNameAttributeValues(currEl, tagName, attrName, attrValue)
{
  if (currEl == null)
    return null;
  
  if (typeof(attrValue) == "undefined")
    attrValue = null;
  
  var prevSib = currEl.previousSibling;
  if (prevSib == null)
    return null;
  
  if (prevSib.tagName.toLowerCase() == tagName.toLowerCase())
  {
    if (attrName == "class" || attrName.toLowerCase() == "classname")
    {
      try
      {
        if (ClassNameAbstraction.contains(prevSib,attrValue))
          return prevSib;
      }
      catch(ex)
      {
        if (prevSib.className.indexOf(attrValue) != -1)
          return prevSib;
      }
    }
    if (prevSib.getAttribute(attrName) == attrValue)
      return prevSib;
  }
  
  return getPreviousSiblingByTagNameAttributeValues(prevSib, tagName, attrName, attrValue);
};

function getElementsByTagNameAttributeValue(ancestorEl, tagName, attrName, attrValue) {
  if (ancestorEl == null)
    return;

  if (typeof(attrValue) == "undefined")
    attrValue = null;

  var els = [];
  var a = ancestorEl.getElementsByTagName(tagName);
  for (var i=0; i<a.length; i++)
  {
    var el = a[i];
    switch (attrName)
    {
      case "className":
      case "classname":
      case "class":
        try
        {
          if (ClassNameAbstraction.contains(el,attrValue))
            els.push(el);
        }
        catch(ex)
        {
          if (el.className.indexOf(attrValue) != -1)
            els.push(el);
        }
        break;
      default:
        var val = el.getAttribute(attrName);
        if ((val != null) && ((attrValue == null) || (val == attrValue)))
          els.push(el);
    }
  }
  return els;
};


function getParentElementByTagName(el, tagName) {
  tagName = tagName.toLowerCase();

  while (el && el.getAttribute && el.parentNode)
  {
    if (el.tagName && (el.tagName.toLowerCase() == tagName))
      return el;
    el = el.parentNode;
  }

  return null;
};

function getParentElementByTagNameAttributeValue(el, tagName, attrName, attrValue) {
  if (typeof(attrValue) == 'undefined')
    attrValue = null;

  tagName = tagName.toLowerCase();

  while (el && el.getAttribute && el.parentNode)
  {
    if (el.tagName && (el.tagName.toLowerCase() == tagName))
    {
      switch (attrName)
      {
        case "className":
        case "class":
          if (el.className.indexOf(attrValue) != -1)
            return el;
        default:
          var val = el.getAttribute(attrName);
          if ((val != null) && ((attrValue == null) || (val == attrValue)))
            return el;
      }
    }
    el = el.parentNode;
  }

  return null;
};

function trim(s)
{
    return (s+"").replace(/^\s*([^\s]*)\s$/g,"$1");
}

function replaceAll(checked, replaced, replacedWith)
{
  var i = checked.indexOf(replaced);
  while (i > -1)
  {
    checked = checked.replace(replaced, replacedWith);
    i = checked.indexOf(replaced);
  }
  return checked;
}

// sets the classname of an element
function setClass(el,classname)
{
  if(typeof(el) == 'string')
    el  = document.getElementById(el);

  try {
    el.className = classname;
  } catch(e) {
    //alert("global.js: \nsetClass()\nname:" + e.name + "\ncode:" + (e.number & 0xFFFF) + "\nmessage:" + e.message);
  }
}

function swapClass(el,classname1,classname2)
{
  if (el.className == classname1)
    el.className = classname2;
  else
    el.className = classname1;
}

// does a value exist in an array?
function inArray(value, array)
{
  for(i=0;i<array.length;i++)
  {
    if(array[i] == value)
    {
      return true;
    }
  }
  return false;
}

// gets value of selected option in <select>
function getOptionValue(elname)
{
  try
  {
    var el = document.getElementById(elname);
  } catch(e) {
    alert("global.js\ngetOptionValue()\nelname\t :"+elname);
  }
  try
  {
    var value = el.options[el.selectedIndex].value;
  } catch(e) {
    alert("global.js\ngetOptionValue()\nvalue\t :"+value);
  }
  return value;
}

// create a popup in the center of the screen
function popup(url, h, w) 
{
  var t = (parseInt(self.screen.height)/2) - h/2;
  var l = (parseInt(self.screen.width)/2) - w/2;
  var popup = window.open(url, "popup", "top="+t+",left="+l+",width="+w+",height="+h+",resizable=yes");
  if (popup) 
    popup.focus();
}

// sets a date
function newdate(year,month,day,hour,minute,second,milliseconds)
{
  var d = new Date();
  if(year)    d.setYear(year);
  if(month)   d.setMonth(month);
  if(day)     d.setDate(day);
  if(hour)    d.setHours(hour);
  if(minute)  d.setMinutes(minute);
  if(second)  d.setSeconds(second);
  if(milliseconds) d.setMilliseconds(milliseconds);
  return d;
}

// writes a readable date
function writeDateTime(when, time) //when = date ('' = now), time = boolean to show time
{
  function zeroBefore(number,characters) // adds an amount of zero's to 'number' to make number.length = 'characters'
  {
    var result = number.toString();
    for (; result.length<characters; )
      result = "0" +result;
    return result;
  }
  var monthNameShort = new Array("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec");

  if (when.indexOf("T")!=-1)
  {
    //maak datum uit database amerikaans formaat
    var when_array = when.split("T");
    var when_date = when_array[0].split("-");
    when = when_date[1] + "-" + when_date[2] + "-" + when_date[0] + " " + when_array[1];
  }
  
  if (when == '')
  {
    var d = new Date();
    result = d.getDate() + ' ';
    result += monthNameShort[d.getMonth()] + ' ';
    result += d.getFullYear();
    if (time='true')
    {
      result += ' ' + zeroBefore(d.getHours(),2);
      result += ':' + zeroBefore(d.getMinutes(),2);
    }
  }
  else
  {
    var d = new Date(when);
    result = d.getDate(when) + ' ';
    result += monthNameShort[d.getMonth(when)] + ' ';
    result += d.getFullYear(when);
    if (time='true')
    {
      result += ' ' + zeroBefore(d.getHours(),2);
      result += ':' + zeroBefore(d.getMinutes(),2);
    }
  }
  return result;
}

// gets a parameter from the querystring
function getParameter(name, defaultValue)
{
  var qa = document.location.search.substring(1).split("&");
  for (var i=0; i<qa.length; i++)
  {
    if (qa[i].indexOf(name + "=") == 0)
      return unescape(qa[i].substring(name.length+1, qa[i].length));
  }
  return defaultValue ? defaultValue : null;
}

//function for reading a cookie or userdata
function readQ42Cookie(theName, theDefault) 
{
  try {
    var theCookie = document.cookie + "|;";
    var p = theCookie.indexOf("Q42=");
    if (p == -1) return theDefault;
    theCookie = theCookie.substring(p, theCookie.indexOf("|;", p)) + "|";
    var pos = theCookie.indexOf(theName + ":");
    if (pos == -1) return theDefault;
    var theValue = unescape(theCookie.substring(pos+theName.length+1, theCookie.indexOf("|", pos)));
    if (theValue == "") theValue = theDefault;

    //check type
    if (typeof(theDefault) == "number") {
      theValue = 1*theValue;
      if (isNaN(theValue)) theValue = theDefault;
    }
    return theValue;
  } catch (e) {
    return theDefault;
  }
};

//function for writing a cookie or userdata
function writeQ42Cookie(theName, theValue) 
{
  try {
    //get the cookie
    var theCookie = document.cookie;

    //get the content of the cookie
    if (theCookie != "") var theContent = theCookie.substring(theCookie.indexOf("=") + 2, theCookie.length - 1);
    else var theContent = "";

    //split the content into name:value pairs
    var cArray = theContent.split("|");

    //make an associative name value array of them
    var nvs = new Object();
    for (var i=0; i<cArray.length; i++) {
      if (cArray[i].substring(0, cArray[i].indexOf(":")) != "") {
        nvs[cArray[i].substring(0, cArray[i].indexOf(":"))] = cArray[i].substring(cArray[i].indexOf(":") + 1, cArray[i].length);
      }
    }

    //add the new cookie name/value pair
    nvs[theName] = theValue;

    //serialize it again
    var s = "";
    for (var n in nvs) s += "|" + n + ":" + nvs[n];

    //write the cookie
    var nextYear = new Date();
    nextYear.setFullYear(nextYear.getFullYear()+1);
    var c = "Q42=" + s + "|; expires=" + nextYear.toGMTString() + "; path=/;";

    document.cookie = "Q42=";
    document.cookie = c;
  } catch (e) {}
};

//function for reading a cookie or userdata
function readCookie(theName, theDefault) 
{
  try {
    var nameEQ = theName + "=";
    var ca = document.cookie.split(';');
    for(var i=0;i < ca.length;i++)
    {
      var c = ca[i];
      while (c.charAt(0)==' ') c = c.substring(1,c.length);
      if (c.indexOf(nameEQ) == 0) 
        return c.substring(nameEQ.length,c.length);
    }
  } catch (e) {}
  return theDefault;
};

//function for writing a cookie or userdata
function writeCookie(theName, theValue) 
{
  try {
    var nextYear = new Date();
    nextYear.setFullYear(nextYear.getFullYear()+1);
    document.cookie = theName + "=" + theValue + "; expires=" + nextYear.toGMTString() + "; path=/";
  } catch (e) {}
};

// escaping and unescaping text
function escapeText(textin)
{
  var post = textin;

  var post2 = '';
  for (var i=post.length-1; i>=0; i--) {
    var cc = post.charCodeAt(i);
    if (cc > 126) {
      post2 = '&#' + cc + ';' + post2;
    } else {
      post2 = post.charAt(i) + post2;
    }
  }
  return post2;
}
function unescapeText(textin)
{
  return textin.replace(/\&\#([^;]+);/g, function (all, code) 
  { 
    code = code.toLowerCase();
  
    if (code.indexOf("x") == 0)
    {
      code = code.substr(1);
      return String.fromCharCode(parseInt(code, 16));   
    }
    else
      return String.fromCharCode(parseInt(code));
  });
}

function urlEncode(url)
{
  return url.replace(/\//g,"%2F").replace(/\:/g,"%3A");
}

function loadIframe(elementId, url, params)
{
  var iframe = document.getElementById(elementId);
  if (!iframe)
    return;
  
  if (url.indexOf("?") == -1)
    url += "?";
  else
    url += "&";

  for (var param in params) 
    url += param + "=" + params[param] + "&";
  
  url += "anticache=" + new Date().getTime();
  
  iframe.setAttribute("src", url);
}

function loadXML(url, params, showError) 
{
  var xmlhttp = getXMLHTTP();
  var paramXml = null;
  var type = "get";

  if (params != null)
  {
    paramXml = initXml("<params />");
    for (var param in params)
    {
      var child = paramXml.createElement(param);
      child.text = params[param];
      paramXml.documentElement.appendChild(child);
    }
    type = "post";
  }
  
  xmlhttp.open(type, url, false);
  xmlhttp.send(paramXml);
  
  var xmldom = initXml(xmlhttp.responseText);
  
  if (showError)
  {
    if (!xmldom.documentElement) 
    {
      alert("Invalid XML. url:" + url + "\n\n" + xmldom.parseError.line + "\n" + xmldom.parseError.reason + "\n\n" + xmlhttp.responseText);
      return null;
    }

    if (xmldom.selectSingleNode("/error")) 
    {
      alert(xmldom.selectSingleNode("/error").text);
      return null;
    }
  }
  
  if (xmldom && xmldom.documentElement)
    return xmldom;
  else
    return xmlhttp.responseText;
};




/**
* Add node serialization support. (.xml for firefox)
*/
if(typeof Node != "undefined")
Node.prototype.__defineGetter__("xml", function() {
   switch (this.nodeType)
   {
     case 1:
       // Workaround for Mozilla bug.
       var n = this;
       if (n.parentNode == n.ownerDocument)
         n = n.parentNode;
       return new XMLSerializer().serializeToString(n);
     case 9:
       return new XMLSerializer().serializeToString(this);
     case 2:
       return this.nodeName + "=\"" + this.nodeValue + "\"";
     case 3:
     case 4:
       return this.nodeValue;
     case 7:
       return "<?" + this.nodeName + " " + this.nodeValue + "?>";
     case 11:
       var res = "";
       for (var i = 0; i < this.childNodes.length; i++)
         res += this.childNodes[i].xml;
       return res;
     default:
       throw new Error("Type: " + this.nodeType + " not supported!");
   }
});

function getRandom(max)
{
  return Math.round(Math.random()*max);
}

function getXmlDoc(keuze, multi,swish)
  {    
    var url = "/admin/actions/getSuggests.aspx?keuze="+keuze;
    
    if (multi == 1)
      url += "&multi="+1;   
      
    if (swish == 1)
      url += "&swish="+1;   
    
    var xmlhttp = getXMLHTTP();
    var suggests = getXMLDOM();
    
    try {
      xmlhttp.open("GET", url, false);
      xmlhttp.send(null);
    }catch (e) {
      // geen contact!      
      suggests.loadXML("<suggests/>");
      return;
    }    
    suggests.loadXML(xmlhttp.responseText);
    return suggests;
  }
  
  function showSuggest(el,who)
  {    
     // de droplist
     var droplist = document.getElementById(who+"-"+el.id+"-drop");          
     droplist.className = "show";
     
    // load the list    
    var xmlNode = obj[el.id].selectNodes("/suggests/suggest");    
    var aantal = 0;
    
    var startRange = document.selection.createRange();         
    
    switch (event.keyCode)
    {      
      case 13:
        droplist.className = "hide";                        
        el.focus;
        break;      
      case 46:
        return true;
        break;
      case 40:
      case 38:
        // key up en down
          var divs = droplist.getElementsByTagName('div');
          var current = 0;
          for (i=0; i<divs.length; i++)
          {            
            if (divs[i].className == "chosen")              
              current = i;                      
            divs[i].className = "";              
          }

          if (event.keyCode == 40 && (current+1) < divs.length )
          { 
            divs[current+1].className = "chosen";
            divs[current+1].scrollIntoView();
            el.value = divs[current+1].innerText;
          }
          else if (event.keyCode == 38 && (current-1) >= 0 )
          {
            divs[current-1].className = "chosen";            
            divs[current-1].scrollIntoView();
            el.value = divs[current-1].innerText;
          }
          else
            divs[current].className = "chosen";          
            
          return true;
        break;      
      case 9:
        // tab
          droplist.className = "hide";
          el.focus();
          return true;
        break;
      case 8:
      default:
        if (el.value == "")
          return true;
          
        droplist.innerHTML = "";
        var first = "";
        for (z=0; z<xmlNode.length-1; z++)
        {             
          if(xmlNode[z].text.toLowerCase().indexOf(el.value.toLowerCase()) == 0)
          {     
            droplist.innerHTML += "<div>"+xmlNode[z].text+"</div>";   
            if (first == "")
              first = xmlNode[z].text;
           }       
        }
        
        if (first != "")
        {
          var endRange = startRange.duplicate(); 
          var buffer = el.value.substring(0,el.value.indexOf(startRange.text));            
          var endRange = startRange.duplicate();
          endRange.text = first.substring(el.value.length);
          startRange.setEndPoint("EndToEnd", endRange);
          startRange.select();
        }                    
        break;
    }        
  }