
// 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 isChrome     = (userAgent.indexOf('chrome') != -1);
var isIE         = (appName.indexOf('internet explorer') != -1) && !isOpera;
var isSafari     = !isChrome && userAgent.indexOf('applewebkit') != -1;
var isMozilla = (appName.indexOf('netscape') != -1) && !isSafari;
var isSafariMobile = isSafari && userAgent.indexOf('mobile') != -1;

// background image cache fix, from http://www.mister-pixel.com/
try { document.execCommand("BackgroundImageCache", false, true); } catch(err) { }


// build versionString
if (isSafari)
  var versionString = appVersion.substr(appVersion.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);
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)
        {
          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)
{		
  //verify the variables
  theEvent = theEvent.toLowerCase();
  if (theEvent.substring(0,2) == "on")
    theEvent = theEvent.substring(2);
  if (theScope)
    theHandler = theHandler.closure(theScope);
  if(typeof(theEl) == 'string')
    theEl = document.getElementById(el);

  // attach for IE or firefox
  if (isIE)
  {
    theEl.attachEvent("on" + theEvent, theHandler);
  }
  else
  {
    if (theEl == document.body)
      theEl = document;
    if (theEvent == "ondragstart")
      theEvent = "ondraggesture";

    theEl.addEventListener(theEvent, 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, paramsXml)
{
  var xmlhttp = getXMLHTTP();
  var paramXml = null;
  var type = "get";

  if (paramsXml != null)
  {
    paramXml = paramsXml;
    type = "post";
  }
  else 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 (typeof(xmldom.selectSingleNode) == 'function' && 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" && isMozilla)
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 loadZoemToel(url) {
  if (isSafariMobile) {
    window.location.href = url;
    return;
  }
  url = escape(url);
  var w = window.open("/global/zoemtoel2/zoom.htm?img=" + url, "zoom", "directories=no,location=no,menubar=no,resizable=yes,scrollbars=no,status=no,toolbar=no,fullscreen=yes", false);
  if (!w)
    alert("Please disable your popup blocker in order to use the zoom feature.");
}

function XmlHttp(){}
XmlHttp.prototype =
{
  request: function(url, send)
  {
    if (window.XMLHttpRequest)
      req = new XMLHttpRequest();
    else if (window.ActiveXObject)
      req = new ActiveXObject("Microsoft.XMLHTTP");
    if (req == null) return;        
    req.open("GET", url, false);
    req.send(send);
    return req;
  }
}
var xmlhttp = new XmlHttp();


if (top.gui)
  top.gui.hideLoadingMessage();
  
  
Function.prototype.closure = function(obj)
{
  // Init object storage.
  if (!window.__objs)
  {
    window.__objs = [];
    window.__funs = [];
  }

  // For symmetry and clarity.
  var fun = this;

  // Make sure the object has an id and is stored in the object store.
  var objId = obj.__objId;
  if (!objId)
    __objs[objId = obj.__objId = __objs.length] = obj;

  // Make sure the function has an id and is stored in the function store.
  var funId = fun.__funId;
  if (!funId)
    __funs[funId = fun.__funId = __funs.length] = fun;

  // Init closure storage.
  if (!obj.__closures)
    obj.__closures = [];

  // See if we previously created a closure for this object/function pair.
  var closure = obj.__closures[funId];
  if (closure)
    return closure;

  // Clear references to keep them out of the closure scope.
  obj = null;
  fun = null;

  // Create the closure, store in cache and return result.
  return __objs[objId].__closures[funId] = function ()
  {
    return __funs[funId].apply(__objs[objId], arguments);
  };
};



function AddBrowserClassname() {
  el = document.body;
  if (!el) return;

  if (isSafariMobile)
    ClassNameAbstraction.add(el, "safarimobile");

  if (isSafari)
    ClassNameAbstraction.add(el, "safari");
  else if (isChrome)
    ClassNameAbstraction.add(el, "chrome");
  else if (isMozilla)
    ClassNameAbstraction.add(el, "mozilla");
}
attachEventHandler(document, "load", AddBrowserClassname);
