/**
 * Web in de Wijk
 *
 * (C) 2006, Q42 Internet BV - http://q42.nl
 */
 
// check which browser is running
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(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);

function getBoxObjectFor(el)
{
  if (el.getBoundingClientRect)
  {
    var bcr = el.getBoundingClientRect();
    return {
      x: bcr.left + document.documentElement.scrollLeft,
      y: bcr.top + document.documentElement.scrollTop,
      width: bcr.right - bcr.left,
      height: bcr.bottom - bcr.top
    };
  }
  else if (el.ownerDocument.getBoxObjectFor)
  {
    var box = el.ownerDocument.getBoxObjectFor(el);
    var bcr = {
      x:box.x,
      y:box.y,
      width:box.width,
      height:box.height
    };
    for (var pel = el.parentNode; pel != document.documentElement; pel = pel.parentNode)
    {
      bcr.x -= pel.scrollLeft;
      bcr.y -= pel.scrollTop;
    }
    return bcr;
  }
  else
    aler("getBoxObjectFor is not implemented for this browser");
}

function getElementsByTagNameAttributeValue(ancestorEl, tagName, attrName, attrValue)
 {
  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 "class":
        //if (el.className.indexOf(attrValue) != -1)
        if (Spif.ClassNameAbstraction.contains(el,attrValue))
          els.push(el);
        break;
      default:
        var val = el.getAttribute(attrName);
        if ((val != null) && ((attrValue == null) || (val == attrValue)))
          els.push(el);
    }
  }
  return els;
};

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 (Spif.ClassNameAbstraction.contains(el,attrValue))
            return el;
        default:
          var val = el.getAttribute(attrName);
          if ((val != null) && ((attrValue == null) || (val == attrValue)))
            return el;
      }
    }
    el = el.parentNode;
  }

  return null;
};

function getParametersFromElement(el)
{
  // Will extract a hashTable of name/value pairs from a className:
  // class="... params-name1_value1-name2_value2... ..."

  var params = {};
  var matches = el.className.match(/params-(.+[^\s$])/);
  if (matches)
  {
    var s = matches[1];
    var a = s.split("-");
    for (var i=0; i<a.length; i++)
    {
      var nv = a[i].split("_");
      params[nv[0]] = nv[1];
    }
  }
  
  return params;
}

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 getXMLDOM(url)
{
  var xmlDoc;

  if (window.ActiveXObject)
    xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
  else
    xmlDoc = document.implementation.createDocument("text/xml", "", null);

  xmlDoc.async=false;
  xmlDoc.load(url);

  return xmlDoc;
};

function getXSLTStylesheet(xslFileName)
{
  //ophalen van alle verschillende soorten websites.
  if (window.ActiveXObject)
  {
    var xslDoc = new ActiveXObject("Msxml2.FreeThreadedDOMDocument");
    xslDoc.async = false;
    xslDoc.resolveExternals = true;
    xslDoc.load(xslFileName);

    var xslt = new ActiveXObject("Msxml2.XSLTemplate");
    xslt.stylesheet = xslDoc;

    return xslt.createProcessor();
  }
  else
  {
    var xslDoc = getXMLDOM(xslFileName);
    var xsltProc = new XSLTProcessor();
    xsltProc.importStylesheet(xslDoc);

    return xsltProc;
  }
};

function initXML(xmlString)
{
  if (window.ActiveXObject)
  {
    var doc=new ActiveXObject("Microsoft.XMLDOM");
    doc.async="false";
    doc.loadXML(xmlString);
    return doc;
  }
  else
  {
    var parser=new DOMParser();
    var doc=parser.parseFromString(xmlString,"text/xml");
    return doc;
  }
};

function loadXMLFile (file)
{
  var xmlDoc;
  //ophalen van alle verschillende soorten websites.
  if (document.implementation && document.implementation.createDocument)
    xmlDoc = document.implementation.createDocument("", "", null);
  else if (window.ActiveXObject)
  {
    xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
    xmlDoc.async="false";
  }
  xmlDoc.load(file);
  
  return xmlDoc;
}

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();

function removeDoubles(array)
{
  var newArray = new Array();
  var aantal = 0;
  for (i=0; i<array.length; i++)
  {
    var vergelijk = array[i];

    for (y=0; y<newArray.length; y++)
    {
      var vergelijkmet = newArray[y];
      if (vergelijk == vergelijkmet)
        aantal++
    }

    if (aantal == 0)
      newArray.push(vergelijk)
    aantal = 0;
  }
  return newArray;
}


function setFocus(el)
{
  if (el)
    setTimeout(function() {el.select(); },20)
}

function findPos(obj)
 {
  var curleft = curtop = 0;
  if (obj.offsetParent)
   {
    curleft = obj.offsetLeft
    curtop = obj.offsetTop
    while (obj = obj.offsetParent)
     {
      curleft += obj.offsetLeft
      curtop += obj.offsetTop
    }
  }
  return [curleft,curtop];
}

// only IE probably!
// transforms xmlDom using xslTemplate and parameters
// define params as var params = new Array( {name:"currentAssetId", value:currentAssetId} );
function transformXml(xmlDoc, xslProc, destEl, parameters) {

  var preXslPath = "/_xslt/";
  if (isMozilla)
  {
    //create processor
    var processor = new XSLTProcessor();
    
    //get and import xsl
    var xslDom = xmlhttp.request(preXslPath + xslProc).responseXML;
    processor.importStylesheet(xslDom);
    
    //add parameters if there are any
    if (parameters)
      for (var i = 0; i < parameters.length; i++)
        processor.setParameter("", parameters[i]["name"], parameters[i]["value"]);
        
    
    //transform and show result
    var result = processor.transformToDocument(xmlDoc);
    if(result.documentElement)
    {
      destEl.innerHTML = "";

      //needed like this for event dialog
      while (result.documentElement.firstChild)
        destEl.appendChild(result.documentElement.firstChild);
        
      return;
    } 
  } 
  else if (isIE)
  {
    xslProc = getXSLTStylesheet(preXslPath+xslProc);
    var endResult = null;
    if (xslProc.transformToDocument)
    {
      if (parameters)
        for (var i = 0; i < parameters.length; i++)
          xslProc.setParameter("", parameters[i].name, parameters[i].value);

      var result = xslProc.transformToDocument(xmlDoc);

      if (parameters)
        for (var i = 0; i < parameters.length; i++)
          xslProc.removeParameter("", parameters[i].name);

      endResult = result;
    }
    else
    {
      xslProc.input = xmlDoc;
      if (parameters)
        for (var i = 0; i < parameters.length; i++)
          xslProc.addParameter(parameters[i].name, parameters[i].value);

      xslProc.transform();
      endResult = xslProc.output;
    }
    
    //draw endresult
    destEl.innerHTML = "";
    destEl.innerHTML = serializeXMLDoc(endResult);
  }
}

function serializeXMLDoc(xmlDoc)
{
  if (window.XMLSerializer)
    var html = new XMLSerializer().serializeToString(xmlDoc);
  else
    var html = "" + xmlDoc;

  html = html.replace(/(<iframe[^>]+)\/>/gi, "$1></iframe>");

  return html;
}
  
function selectSingleNode(node, xpath)
{
  if (typeof(node.selectSingleNode) != "undefined")
    return node.selectSingleNode(xpath);
  else
  {
    var xpe = new XPathEvaluator();
    return xpe.evaluate(xpath, node, xpe.createNSResolver(node), XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;
  }
}

// check for XPath implementation 
if( document.implementation.hasFeature("XPath", "3.0") ) 
{ 
  // prototying the XMLDocument 
  XMLDocument.prototype.selectSingleNode = function(cXPathString, xNode) 
  { 
    if( !xNode ) { xNode = this; }
    var xItems = this.selectNodes(cXPathString, xNode);
    
    if( xItems.length > 0 )  
      return xItems[0];
    else 
      return null;
  } 
  
  // prototying the Element 
  Element.prototype.selectSingleNode = function(cXPathString) 
  {
    if(this.ownerDocument.selectSingleNode) 
      return this.ownerDocument.selectSingleNode(cXPathString, this); 
    else
      throw "For XML Elements Only";
  } 
} 

if( document.implementation.hasFeature("XPath", "3.0") ) 
{ 
  // prototying the XMLDocument 
  XMLDocument.prototype.selectNodes = function(cXPathString, xNode) 
  { 
    if( !xNode ) { xNode = this; }
    var oNSResolver = this.createNSResolver(this.documentElement) 
    var aItems = this.evaluate(cXPathString, xNode, oNSResolver,
                 XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null) 
    var aResult = [];
    for( var i = 0; i < aItems.snapshotLength; i++) 
    { 
      aResult[i] = aItems.snapshotItem(i);
    } 
    return aResult;
  } 

  // prototying the Element 
  Element.prototype.selectNodes = function(cXPathString) 
  { 
    if(this.ownerDocument.selectNodes) 
    { 
      return this.ownerDocument.selectNodes(cXPathString, this);
    } 
    else{throw "For XML Elements Only";} 
  } 
} 