var siteroot = '/cms/';
var jsdir = siteroot + 'js/';

// inArray Prototype Array object by EmbiMedia
// http://www.embimedia.com/resources/labs/js-inarray.html
// Returns true if the passed value is found in the
// array.  Returns false if it is not.
// Modified to return index, or -1 if not found
Array.prototype.inArray = function (value) {
    var i;
    var len = this.length;
    for (i=0; i < len; i++) {
        // Matches identical (===), not just similar (==).
        if (this[i] === value) {
            return i;
        }
    }
    return -1;
};

function mycreateElement(element) {
  if (typeof document.createElementNS != 'undefined') {
    return document.createElementNS('http://www.w3.org/1999/xhtml', element);
  }
  if (typeof document.createElement != 'undefined') {
    return document.createElement(element);
  }
  return false;
}

function insertAfter(parent, node, referenceNode) {
    parent.insertBefore(node, referenceNode.nextSibling);
}
function prependChild(parent, node) {
    parent.insertBefore(node, parent.firstChild);
}

function getNode(parentnode,tag) {
  var nodeobj = parentnode.firstChild;
  if (nodeobj) {
    while (nodeobj) {
      if (nodeobj.tagName) {
        if(nodeobj.tagName.toLowerCase() == tag) {
          return nodeobj;
        }
      }
      var nodeobj = nodeobj.nextSibling;
    }
  }
  return false;
}
function getNextNode(siblingnode,tag) {
  var nodeobj = siblingnode.nextSibling;
  if (nodeobj) {
    while (nodeobj) {
      if (nodeobj.tagName) {
        if(nodeobj.tagName.toLowerCase() == tag) {
          return nodeobj;
        }
      }
      var nodeobj = nodeobj.nextSibling;
    }
  }
  return false;
}
function getLastNode(parentnode,tag) {
//alert(parentnode.childNodes.length);
  var nodeobj = parentnode.lastChild;
  if (nodeobj) {
    var i = 0;
    for (i=parentnode.childNodes.length-1; i>=0; i--) {
      var nodeobj = parentnode.childNodes[i];
//      alert(nodeobj.nodeType);
//      if (nodeobj.nodeType ==3) {
//        alert(nodeobj.data);
//      }
      if (nodeobj.tagName) {
        if(nodeobj.tagName.toLowerCase() == tag) {
          return nodeobj;
        }
      }
      //alert(nodeobj.nodeType);
      //var nodeobj = nodeobj.prevSibling;
      //alert(nodeobj.nodeType);
    }
  }
  return false;
}

// See these pages - where the addEvent function came from
//http://www.scottandrew.com/weblog/articles/cbs-events
//http://www.onlinetools.org/articles/unobtrusivejavascript/chapter4.html
// Sitepoint's book DHTML Utopia, Ch3 pg 54 (available in sample chapters)
// http://www.sitepoint.com/blog-post-view.php?id=171578
function addEvent(obj, evType, fn, useCapture){
  if (!obj) { alert(fn); return false; }
  if (obj.addEventListener) { 
    obj.addEventListener(evType, fn, useCapture); 
    return true; 
  }
  else if (obj.attachEvent) { 
    var r = obj.attachEvent("on"+evType, fn); 
    return r; 
  }
  else { 
    var oldevent = elm['on' + evType];
    if (typeof elm['on' + evType] != 'function') {
      elm['on' + evType] = fn;
    }
    else {
      elm['on' + evType] = function() {
        oldevent();
        fn();
      }
    }
  } 
}


// taken from http://simon.incutio.com/archive/2004/05/26/addLoadEvent
function addLoadEvent(func) {
  //alert(func);
  var oldonload = window.onload;
  if (typeof window.onload != 'function') {
    window.onload = func;
  } else {
    window.onload = function() {
      oldonload();
      func();
    };
  }
}

function addClass (elem,classtoadd) {
  var classarr = new Array();
  if (elem && classtoadd) {
    if (elem.className) {
      classarr = elem.className.split(" ");
      if (classarr.inArray(classtoadd)<0) {
        classarr.push(classtoadd);
        elem.className = classarr.join(" ");
      }
    }
    else {
      elem.className = classtoadd;
    }
    return true;
  }
  return false;
}

function remClass (elem,classtorem) {
  var classarr = new Array();
  var ind = 0;
  if (elem && classtorem) {
    if (elem.className) {
      classarr = elem.className.split(" ");
      if ((ind = classarr.inArray(classtorem))>=0) {
        classarr.splice(ind,1);
        elem.className = classarr.join(" ");
      }
    }
    else {
      elem.className = '';
    }
    return true;
  }
  return false;
}


var jsprint=false;
function printPage(mode) {
  var ret = 0;
  if (ret = switchStyle('print')) {
    if ((ret==1) && (mode!='full')) {
      jsprint=true;
      window.print();
    }
    return !(jsprint);
  }
  else {
    return true;
  }
}

function switchStyle(stylename) {
  pagestyleid='pagestyle';
  printstyleid='printstyle';
  if (document.getElementById && document.getElementsByTagName && stylename) {
    if (document.getElementById(printstyleid)) {
      var printstyleobj = document.getElementById(printstyleid);
      // hack for IE - doesn't refresh global style
      var stylelink = document.getElementById(pagestyleid);
      printstyleobj.setAttribute('href', stylelink.href);
      // end hack for IE
      var parentobj = printstyleobj.parentNode;
      var oldobj = parentobj.removeChild(printstyleobj);
      return 2;
    }
    else {
      var stylelink = document.getElementById(pagestyleid);
      var headobj = document.getElementsByTagName('head')[0];
      var printstyleobj = mycreateElement('link');
      var stylere = new RegExp("(style=).*$", "i");
      oldstylelinkstr = new String(stylelink.href);
      printstyleobj.setAttribute('type', 'text/css');
      printstyleobj.setAttribute('href', oldstylelinkstr.replace(stylere,"$1" + escape(stylename)));
      printstyleobj.setAttribute('id', printstyleid);
      printstyleobj.setAttribute('rel', 'stylesheet');
      //stylelink.href = oldstylelinkstr.replace(stylere,"$1" + escape(stylename));
      headobj.appendChild(printstyleobj);
    }
    return true;
  }
  else {
    return false;
  }
}

function addStyle(stylename) {
  pagestyleid='pagestyle';
  if (document.getElementById && stylename) {
    var stylelink = document.getElementById(pagestyleid);
    var stylere = new RegExp("(style=).*$", "i");
    oldstylelinkstr = new String(stylelink.href);
    stylelink.href = oldstylelinkstr.replace(stylere,"$1" + escape(stylename));
    return true;
  }
  else {
    return false;
  }
}

//  Based on function and comments here: http://htmldog.com/ptg/archives/000063.php
// and on Mary's code here: http://www.christian-web-masters.com/forums/index.php?showtopic=4999

function mail_to() {
  var a;
  var i;
  var mailto;
  var address;
  var name;
  var titlestart = 'send an email to ';
  if (!document.getElementsByTagName("a")) {
    return;
  }
  
  a = document.getElementsByTagName("a");
  // loop through each anchor tag
  for (i = 0; i < a.length; i++) {
    // is this an encoded email address?
    nolinktext = false;
    if (a[i].className && a[i].className.indexOf("encemail")>=0) {
      mailto = a[i].firstChild;
      if ((mailto.nodeValue == null) || (mailto.nodeValue.indexOf("{at}")<0))  {
        if (a[i].getAttribute('title')) {
          address = new String(a[i].getAttribute('title'));
          nolinktext = true;
        }
        else {
          continue;
        }
      }
      else {
        address = new String(mailto.nodeValue);
      }
      rawaddress = address;
      address = address.replace(/ {at} /g, '@');
      address = address.replace(/ {dot} /g, '.');
      
      name = a[i].getAttribute('title').slice(titlestart.length);
      //mailto.nodeValue = address;
      if (name == rawaddress) {
        name = address;
      }
      if (!nolinktext) {
        mailto.nodeValue = name;
      }
      
      a[i].setAttribute('title', 'Send an email to ' + address);
      a[i].setAttribute('href', 'mailto:' + address);
    }
  }
}

function pluginPopup(linkobj) {
  if ((linkobj) && (linkobj.href)) {
    properties = '';
    return popup(linkobj,properties);
  }
  else {
    return false;
  }
}

function popup(linkobj,properties) {
  if (!properties) {
    properties = '';
  }
  if (linkobj.href) {
    window.open(linkobj.href,'popup',properties);
  }
  return false;
}




function includejs(scriptname) {
  var head;
  var script;
  
  if (scriptname && document.getElementsByTagName && document.getElementById) {
    head = document.getElementsByTagName('head').item(0);
    script = document.createElement('script');
    script.setAttribute('src', scriptname);
    script.setAttribute('type', 'text/javascript');
    script.setAttribute('defer', true);
    void(head.appendChild(script));
    return true;
  }
  return false;
}

function myRemoveChildNodes() {
    while (this.childNodes.length > 0) {
        this.removeChild(this.childNodes[0]);
    }
}

//function IEinit() {
/* See ieonly.js for IE-only Javascript */
//}

function testIEOnlyLoaded() {
  if (ieonlyloaded2) {
    IEinit();
    clearInterval(stopit);
  }
}

var stopit = "";

function addBehaviours() {
  try {
    Node.prototype.removeChildNodes = myRemoveChildNodes;
  }
  catch (e) {
    stopit = setInterval(testIEOnlyLoaded, 50);
  }
}

// these global variables allow checking that the appropriate library has been loaded
var ieonlyloaded = false;
var ieonlyloaded2 = false;

function loadJSIncludes() {
  //xmlrequestloaded = includejs(jsdir + 'xmlrequest.js');
  if (document.all) {
    ieonlyloaded = includejs(jsdir + 'ieonly.js');
  }
}

function textarearesize(taobj,moreless) {
  if (taobj && taobj.tagName && (taobj.tagName.toLowerCase()=='textarea')) {
    if (moreless == 'less') {
      taobj.setAttribute('rows',Math.max(1,Math.floor(0.8*taobj.getAttribute('rows'))));
      taobj.setAttribute('cols',Math.max(1,Math.floor(0.8*taobj.getAttribute('cols'))));
    }
    else {
      taobj.setAttribute('rows',Math.max(1,Math.ceil(1.2*taobj.getAttribute('rows'))));
      taobj.setAttribute('cols',Math.max(1,Math.ceil(1.2*taobj.getAttribute('cols'))));
    }
    return false;
  }
}

function sizeabletextareas_addevents(ta,pluslink,minuslink) {
  if (ta && pluslink && minuslink) {
    addEvent(pluslink,'click',function (e) { if (e.preventDefault) { e.preventDefault(); } textarearesize(ta,'more'); return false;}, false);
    addEvent(minuslink,'click',function (e) { if (e.preventDefault) { e.preventDefault(); } textarearesize(ta,'less'); return false;}, false);
  }
}

function sizeabletextareas() {
  var ti=0;
  if (document.getElementsByTagName('textarea')) {
    var textareas = document.getElementsByTagName('textarea');
    //ORIG: for (var ti=0; ti < textareas.length; ti++) {
    // make use of tip from here: http://calculist.blogspot.com/2005/12/gotchagotcha.html
    // prevents problems with mutating/overwriting the ta variable, since it becomes 
    // declared inside it's own function call
    (function loop(ti) {
      if (ti < textareas.length) {
        //textareas[ti].setAttribute('rows',100);
        var ta = textareas[ti];
        if (! ta.getAttribute('id')) {
          ta.setAttribute('id','textarea-' + (ti+1));
        }
        var taid = ta.getAttribute('id');
        var newdiv = mycreateElement('div');
        var pluslink = mycreateElement('a');
        var minuslink = mycreateElement('a');
        var pluslinktext = document.createTextNode('(+)');
        var minuslinktext = document.createTextNode('(-)');
        pluslink.appendChild(pluslinktext);
        minuslink.appendChild(minuslinktext);
        pluslink.setAttribute('href','#' + taid);
        minuslink.setAttribute('href','#' + taid);
        newdiv.appendChild(pluslink);
        newdiv.appendChild(minuslink);
        /*
        addEvent(pluslink,'click',function (e) { if (e.preventDefault) { e.preventDefault(); } textarearesize(ta,'more'); return false;}, false);
        addEvent(minuslink,'click',function (e) { if (e.preventDefault) { e.preventDefault(); } textarearesize(ta,'less'); return false;}, false);
        */
        sizeabletextareas_addevents(ta,pluslink,minuslink);
        insertAfter(ta.parentNode, newdiv, ta);
        loop(ti + 1);
      }
    })(0);
  }
}



addLoadEvent(loadJSIncludes);
addLoadEvent(addBehaviours);
addLoadEvent(mail_to);
addLoadEvent(sizeabletextareas);

