var winDim = new winDimensions();
window.onresize = function() { winDim = new winDimensions(); }

var mousePos = new Object; // Position of the Mouse 
document.onmousemove = function(event) { mousePosition(event); }
document.onmouseup   = function(event) { mouseUp(event); }

var dragObj = null; // Object that is moved using the mouse
var resizeY = null; // resizing an object's Height
var resizeX = null; // resizing an object's Width

var doNotRequireWASM = true; // flag to see if WASM status is checked when Ajax calls are made.
var ROOT_DIR = "/arts/artsdigital/";
var tinyMCE; // called when tinyMCE is used

// Ajax functions
function getAjax(URL, post, noWait) { // Ajax call to get basic Text.  Will not do XML.  XML requires synchronous call.
  testWASMStatus(URL);
  if (!ajaxGood) return;
  var sendType = (post) ? "post" : "get";
  var response = "";
 
  if (!noWait) waiting(true);
  var xhr = new createXMLHttpRequest();
  try {
    xhr.open(sendType, URL, false);
    if (post) xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
    xhr.send(post);
    response = xhr.responseText;
    xhr.close;
  } catch(e) {}
  if (response.match(/^\s+$/)) response = "";
  waiting(false);
  return response;
}
function getAsyncAjax(URL, post, processFXN, noWait) { // Ajax call to make an Asynchronous call.  If !noWait, need to make sure something in processFXN switches waiting off
  testWASMStatus(URL);
  if (!ajaxGood) return;
  if (!noWait) waiting(true);
  var sendType = (post) ? "post" : "get";
  var xhr = new createXMLHttpRequest();
  try {
    xhr.onreadystatechange = function() {
      if (xhr.readyState==4) {
        if (xhr.status==200) {
          if (typeof(processFXN)=="function") {
            if (xhr.responseXML) processFXN(xhr.responseXML);
            else if (xhr.responseText) processFXN(xhr.responseText);
            else if (xhr.responseText!==null) processFXN(xhr.responseText);
          }
        }
      }
    }
    xhr.open(sendType, URL, true);
    if (post) xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
    xhr.send(post);
    xhr.close;
  } catch(e) {}
  return null;
}
var ajaxGood = true; // variable to allow me to switch off Ajax calls if a wasm session's dropped off.
function testWASMStatus(URL) { // Function to checkwhether there a WASM session is required to continue
  if (doNotRequireWASM) {
    ajaxGood = true;
    return;
  }
  URL = URL.replace(/\?.*$/, "");
  var xhr = new createXMLHttpRequest();
  var headers;
  xhr.onreadystatechange = function() {
    try {
      if (xhr.readyState>2) {
        if (!xhr.getAllResponseHeaders()) {
          ajaxGood = false;
          if (confirm("Your session has expired.\n\nDo you wish to log back into the system?")) {
            waiting();
            overlay(true);
          
            var iframe = document.createElement("iframe");
            iframe.src = URL;
            iframe.style.width = "90%"; iframe.style.height = "90%"; iframe.style.position = "absolute"; iframe.style.top = "5%"; iframe.style.left = "5%"; 
            iframe.style.background = "#FFF"; iframe.style.border = "0";
            _("_SPACE_").appendChild(iframe);
            var check = function() {
              try { // if the page is off server (aka WASM) won't have access to the iframe source 
                if (iframe.contentDocument.body.textContent) { 
                  overlay(); 
                  ajaxGood = true; 
                  return; 
                }
              } catch(e) {} 
              setTimeout(check, 200);
            }
            iframe.onload = function() { check(); }
          } else window.location = "http://sydney.edu.au/arts/artsdigital/";
          return;
        }
      }
    } catch (e) {}
  }
  xhr.open("HEAD", URL, true);
  xhr.send(null);
  xhr.close;
  return;
}
function createXMLHttpRequest() {
  try { return new ActiveXObject("Msxml2.XMLHTTP") } catch (e) {}
  try { return new ActiveXObject("Microsoft.XMLHTTP"); } catch (e) {}
  try { return new XMLHttpRequest(); } catch (e) {}
  alert ("XMLHttpRequest not Supported!");
  return null;
}
function getURLVar(key) {
  var what; var val;
  var vars = document.location.href.replace(/^.*\?/, "").split(/&/);
  for (x=0; x<vars.length; x++) {
    if (key==vars[x].replace(/=.*$/, "")) return vars[x].replace(/^.*=/, "");
  }
  return "";
}

function waiting(on) {
  if (!document.body) return; // Avoiding errors on an onload
  if (!_("_WAITING_")) {
    var wait = document.createElement("div");
    wait.style.position = "fixed"; wait.style.width="100%"; wait.style.height="100%"; wait.style.left = "0px"; wait.style.top = "0px"; 
    wait.style.opacity = ".8"; wait.style.background = "#FFF"; wait.style.zIndex = "200";
    wait.id = "_WAITING_";
    document.body.appendChild(wait);

    var img = document.createElement("img");
    img.src = ROOT_DIR+"images/icons/ajax-loader.gif";
    img.style.left = "50%"; img.style.top = "50%"; img.style.position = "absolute";
    wait.appendChild(img);
  }

  if (on) _("_WAITING_").style.visibility = "visible";
  else _("_WAITING_").style.visibility = "hidden";
  return;
}
 
function _(id) { return obj = document.getElementById(id); }

// Overlay functions
function overlay(onoff) {
  if (onoff) {
    if (document.all) { // IE hacks
      document.body.parentNode.scrollTop = 0;
      document.body.parentNode.style.overflow = "hidden";
      
    } else document.body.style.overflow = "hidden";

    if (!_("OVERLAY")) {
      var ws = document.createElement("div");
      ws.id = "OVERLAY";
      ws.style.position = "fixed"; ws.style.left = "0px"; ws.style.top = "0px"; ws.style.background = "#000"; ws.style.width = "100%"; ws.style.height = "100%";
      if (document.all) ws.style.position = "absolute";
      ws.style.filter = "alpha(opacity=60)";  ws.style.zOpacity = "0.6"; ws.style.KhtmlOpacity = "0.6"; ws.style.opacity = "0.6";
      ws.style.zIndex = "100";
      document.body.appendChild(ws);

      var space = document.createElement("div");
      space.id = "_SPACE_";
      space.style.position = "fixed"; space.style.left = "0px"; space.style.top = "0px"; space.style.width = "100%"; space.style.height = "100%";
      if (document.all) space.style.position = "absolute";
      space.style.zIndex = "101"; 
      document.body.appendChild(space);

      var close = document.createElement("a");
      close.id = "_closeOverlayButton";
      close.onclick = function() { overlay(); }
      close.innerHTML = "<img src='"+ROOT_DIR+"images/icons/cancel_40x40.png' style='border: 0px' />";
      close.style.position = "absolute"; close.style.top = "10px"; close.style.right = "10px";
      space.appendChild(close);
    } 
  } else {
    if (document.all) { // IE hack
      document.body.parentNode.style.overflow = "auto";
    } else document.body.style.overflow = "auto";

    if (_("OVERLAY")) {
      _("OVERLAY").parentNode.removeChild(_("OVERLAY"));
      _("_SPACE_").parentNode.removeChild(_("_SPACE_"));
    }
  }
  return;
}

function dragObject(ev, obj) {
  ev = ev ? ev : window.event;
  if (ev && obj) {
// Cheating way of doing it but wth;
    if (ev.type=="mousedown") dragObj = obj
  }
  return;
}
function centreObject(obj, dim, limit) { // Centres an object on a page.  limit is either null, height or width - identifies what to leave out;
  var dimensions = Array("height", "width");
  if (!dim) { // grabbing object style data if not supplied
    dim = new Object;
    for (x=0; x<dimensions.length; x++) {
      var axis = dimensions[x];
      if (obj.style[axis]) {
        if (typeof(obj.style[axis].replace(/(px){0,1}$/, "")*1)=="number") dim[axis] = obj.style[axis].replace(/(px){0,1}$/, "");
        else if (obj.style[axis].match(/em$/)) dim[axis] = obj.style[axis].replace(/em$/, "")*10;
        else if (obj.style[axis].match(/%$/)) dim[axis] = obj.style[axis].replace(/%$/, "")/100*winDim[axis];
        else dim[axis] = 500;
      }
    }
  }
  
  var attr;
  for (x=0; x<dimensions.length; x++) {
    if (dimensions[x]!=limit) {
      switch (dimensions[x]) {
        case "height" : attr = "top"; break;
        case "width"  : attr = "left"; break;
      }
      var wo = (Math.ceil((winDim[dimensions[x]] - dim[dimensions[x]]) / 2) > 0) ? Math.ceil((winDim[dimensions[x]] - dim[dimensions[x]]) / 2) : 0;
      obj.style[attr] = wo+"px"; // Everything else
    } 
  }
  obj.style.position = "absolute";
  return;
}


// Function to generate a caption based on mouseovers and such
var captionTimeout; var killCaptionTimeout;
var captionClone = caption; // cloning the caption function so we can call it from within caption itself.
function caption(text, objStyle, delay) { //objStyle is Object with properties to be placed in the caption style.  delay measured in ms.
  if (text && typeof(text)=="string") {
    if (delay) { 
      captionTimeout = setTimeout(
        function() { captionClone(text, objStyle); },
        delay
      );
      return;
    }

    var CAPTION;
    if (!_("_CAPTION_")) {
      CAPTION = document.createElement("div");
      CAPTION.id = "_CAPTION_";
      document.body.appendChild(CAPTION);
    } else CAPTION = _("_CAPTION_");

    CAPTION.innerHTML = text;
    CAPTION.style.backgroundColor = "#FDF0A3"; CAPTION.style.padding = "5px"; CAPTION.style.border = "1px #000 solid"; CAPTION.style.textAlign = "left"; CAPTION.style.maxWidth = "60%";
    CAPTION.style.zIndex = "102"; CAPTION.style.position = "fixed"; CAPTION.style.visibility = "visible"; 

    if (mousePos.longitude) {
      CAPTION.style.right = (winDim.width - mousePos.x*1+10)+"px";
      CAPTION.style.left = null;
    } else {
      CAPTION.style.left = (mousePos.x*1+10)+"px";
      CAPTION.style.right = null;
    }
    if (mousePos.latitiude) {
      CAPTION.style.top = (mousePos.y*1+10)+"px";
      CAPTION.style.bottom = null;
    } else {
      CAPTION.style.bottom = (winDim.height - mousePos.y*1+10)+"px"; 
      CAPTION.style.top = null;
    }

    if (objStyle) {
      for (x in objStyle) {
        CAPTION.style[x] = objStyle[x];
        switch(x) { // Deals with position setting
          case "left" : CAPTION.style.right = null; break;
          case "right" : CAPTION.style.left = null; break;
          case "top" : CAPTION.style.bottom = null; break;
          case "bottom" : CAPTION.style.top = null; break;
        }
      }
    }
    clearTimeout(captionTimeout);
    clearTimeout(killCaptionTimeout);
  } else {
    if (delay) { 
      killCaptionTimeout = setTimeout(
        function() { caption(); },
        delay
      );
      return;
    }

    if (_("_CAPTION_")) _("_CAPTION_").parentNode.removeChild(_("_CAPTION_"));
    clearTimeout(captionTimeout);
    clearTimeout(killCaptionTimeout);
  }
  return;
}

var DELAYED = new Object;
function delay(id, fxn, delay) { // Sets a timer for something.  Kills the timer if delay(id) is called
  if (DELAYED[id]) clearTimeout(DELAYED[id]);
  DELAYED[id] = setTimeout(fxn, delay);
  return;
}

function winDimensions() { // Object setting the Browser dimensions
  if (typeof(window.innerHeight)=="number") {
    this.height = window.innerHeight;
    this.width = window.innerWidth;
  } else if (document.documentElement && document.documentElement.clientWidth) {
    this.height = document.documentElement.clientHeight;
    this.width = document.documentElement.clientWidth;
  } else if (document.body && document.body.clientWidth) {
    this.height = document.body.clientHeight;
    this.width = document.body.clientWidth;
  }
  if (typeof(this.height)=="string") this.height = this.height.replace(/^(\d+)[a-z]*$/i, "$1")*1;
  if (typeof(this.width)=="string") this.width = this.width.replace(/^(\d+)[a-z]*$/i, "$1")*1;

  if (screen && typeof(screen.height)=="number") {
    this.screenHeight = screen.height;
    this.screenWidth = screen.width;
  }
}  
function clearSelection() {
  try {
    if (window.getSelection()) window.getSelection().clear;
    else if (document.selection) document.selection.clear()
    else if (document.getSelection()) document.getSelection().clear;
  } catch(e) { }
  return;
}
// Mouse Position objects and settings
function mousePosition(evt) {
  evt = evt ? evt : window.event;

  if (dragObj || resizeY || resizeX) {
    clearSelection();
    mousePos.origX = mousePos.x;
    mousePos.origY = mousePos.y;
  }

  if (evt.pageX && evt.pageY) { // Working out mouse position in relation to page
    mousePos.pageX = evt.pageX; 
    mousePos.pageY = evt.pageY;
  } else if (evt.clientX) {
    mousePos.pageX = evt.clientX + (document.documentElement.scrollLeft ? document.documentElement.scrollLeft : window.pageXOffset);
    mousePos.pageY = evt.clientY + (document.documentElement.scrollTop  ? document.documentElement.scrollTop  : window.pageYOffset);
  }

  if (evt.clientX && evt.clientY) { // working out mousePosition in relation to screen
    mousePos.x = evt.clientX;
    mousePos.y = evt.clientY;
  }
  mousePos.longitude = (mousePos.x > (winDim.width/2)) ? true : false; // right is true
  mousePos.latitiude = (mousePos.y < (winDim.height/2)) ? true : false; // top is true

  if (dragObj) { if (dragObj.style) {
    dragObj.style.left = (dragObj.style.left.replace(/px$/, "") - (mousePos.origX - mousePos.x)) + "px";
    dragObj.style.top  = (dragObj.style.top.replace(/px$/, "")  - (mousePos.origY - mousePos.y)) + "px";
  } }
  if (resizeX) { // works as right is getting bigger
    if (resizeX.length) {
      for (x=0; x<resizeX.length; x++) { 
        if (resizeX[x].style.width.match(/%$/)) resizeX[x].style.width = Math.ceil((resizeX[x].style.width.replace(/%$/, "") * winDim.width / 100))+"px";
        resizeX[x].style.width = (resizeX[x].style.width.replace(/px$/, "")*1 - mousePos.origX + mousePos.x) + "px";
      }
    } else {
      if (resizeX.style.width.match(/%$/)) resizeX.style.width = Math.ceil((resizeX.style.width.replace(/%$/, "") * winDim.width / 100))+"px";
      resizeX.style.width = (resizeX.style.width.replace(/px$/, "")*1 - mousePos.origX + mousePos.x) + "px";
    }
  }
  if (resizeY) { // always works as down as getting bigger
    if (resizeY.length) {
      for (x=0; x<resizeY.length; x++) resizeY[x].style.height = (resizeY[x].style.height.replace(/px$/, "")*1 - mousePos.origY + mousePos.y) + "px";

    } else resizeY.style.height = (resizeY.style.height.replace(/px$/, "")*1 - mousePos.origY + mousePos.y) + "px";
  }
}
function mouseUp(evt) { 
  dragObj = null; 
  resizeX = null;
  resizeY = null;
  mousePos.origX = null; mousePos.origY = null;
  clearSelection();
}

// Form Processing
function processForm(formObj, processFile, rewriteObj, processResults) { //returnss the feed from processing the file if no rewriteObj.  
  if (tinyMCE) tinyMCE.triggerSave();
//rewriteObj can also be a function which runs based on response
  var ERROR = "";
  var result = new Object;
// if (formObj.onsubmit!==this) formObj.onsubmit();

  if (formObj.elements) { 
    for (x=0; x<formObj.elements.length; x++) {
      try{
        if (formObj.elements[x].tagName.match(/^(textarea|input|select)$/i) && formObj.elements[x].name) {
// Determining if a required field is empty
          if (formObj.elements[x].type=="checkbox") {
            result[formObj.elements[x].name] = formObj.elements[x].checked ? (formObj.elements[x].value ? formObj.elements[x].value : "1") : "";

          } else if (formObj.elements[x].type=="radio") {
            if (formObj.elements[x].checked) result[formObj.elements[x].name] = formObj.elements[x].value ? formObj.elements[x].value : "1";

          } else if (!formObj.elements[x].value || formObj.elements[x].getAttribute("origValue")==formObj.elements[x].value || formObj.elements[x].getAttribute("default")==formObj.elements[x].value) {
            if (formObj.elements[x].getAttribute("mandatory")) ERROR+= formObj.elements[x].name+" is missing!\n";
            else result[formObj.elements[x].name] = "";

          } else if (formObj.elements[x].getAttribute("ERROR")) {
            ERROR+= formObj.elements[x].getAttribute("ERROR")+"\n";
         
          } else {
            if (formObj.elements[x].name.match(/email/i)) {
              if (formObj.elements[x].value.match(/^(\w\W*)+@(\w+\W*)+\.(\w+\W*)+$/)) result[formObj.elements[x].name] = sanitise(formObj.elements[x].value);
              else ERROR+= "Please supply a legitimate Email!\n";
            } else {
              if (formObj.elements[x].value!=="NULL") result[formObj.elements[x].name] = sanitise(formObj.elements[x].value);
            }
          }
        }
      }catch(e){}
    }

    var res;  
    if (processResults && !ERROR) {
       res = processResults(result);
       if (typeof(res)=="string") ERROR+= "\n\n"+res;
       else if (typeof(res)=="object") result = res;
    }
    if (ERROR) ARTS.alert(ERROR+"\nPlease correctly complete these fields before continuing.");
    else {
      res = "";
      for (x in result) res+= (res.length ? "&" : "")+x+"="+(typeof(result[x])=="string" ? sanitise(result[x]) : "null");
      res = getAjax(processFile, res);
      if (rewriteObj) {
        if (typeof(rewriteObj)=="function") rewriteObj(res);
        else if (typeof(rewriteObj)=="object") rewriteObj.innerHTML = res;
      } else return res;
    }
  } else ARTS.alert("Form "+formObj.id+" has no inputs!!");
  return false;
}
function sanitise(str) {
  if (str.match(/[#\&\?=]/)) { 
    str = str.replace(/\?/g, "|_QUESTIONMARK_|");
    str = str.replace(/\&/g, "|_AMPERSAND_|");
    str = str.replace(/#/g, "|_HASH_|");
    str = str.replace(/=/g, "|_EQUAL_|");
  }       
  return str;
}
function dummyVal() { //create a dummy string.  For IE Ajax callsS
  var NOW = new Date;
  var dummy = NOW.valueOf();
  return dummy;
}
function clearEntry(obj, str) {
  if (!obj.tagName.match(/^(INPUT|TEXTAREA)$/)) return; // makes sure only input and textareas are affected
  if (!str) {
    if (obj.getAttribute("origValue"))		str = obj.getAttribute("origValue"); /* legacy */
    else if (obj.getAttribute("default"))	str = obj.getAttribute("default");
  }
  if (obj.value==str) { 
    obj.value = "";
    obj.className = obj.className.replace(/\bdefaultText\b/g, ""); 
  }
  if (str) {
    if (!obj.getAttribute("default")) obj.setAttribute("default", str);
    obj.onblur = function() {
      if (this.value.match(/^\s*$/)) {
        this.value = this.getAttribute("default");
        this.className = this.className+" defaultText";
      }
      this.onblur = function() {}
    }
  }
  return;
}
function clearRadio(contObj) { //clears all the values in a container with radio objects
  for (x=0; x<contObj.childNodes.length; x++) {
    try{
      if (contObj.childNodes[x].tagName.match(/^input$/i) && contObj.childNodes[x].type.match(/radio/i)) {
        if (contObj.childNodes[x].checked) contObj.childNodes[x].checked = null;
      } 
    }catch(e){}
  }
  return;
}
// function to display text after an onchange or a click on a checkbox.
function chooseOne(targetURL, val, obj) {
  if (!targetURL) return;
  if (!obj) return;
  if (val==false) val = "";
  obj.innerHTML = getAjax(targetURL+val+"&dummy="+dummyVal());
}
// Funtions to show or hide objects
function show(obj, on) { 
  if (obj.style.visibility) obj.style.visibility = on ? "visible" : "hidden"; 
  if (obj.style.display) obj.style.display = on ? "inherit" : "none";
}

function _print(content, noPrint) { // noPrint allows the content to go into the "print area" but does not force the browser to go begin printing process
  var _print;
  if (!_("_print")) {
    _print = document.createElement("div");  
    _print.id = "_print";  
  } else _print = _("_print");

  _print.style.position = "absolute"; _print.style.width = "100%"; _print.style.minHeight = "100%";
  _print.style.left = "0px"; _print.style.top = "0px"; _print.style.background = "#FFF";
  _print.innerHTML = content;

  document.body.appendChild(_print);
  if (!noPrint) window.print();
  return;
}

/* Cookie Based Functions */
function getCookies(wot) { // returns an object with all the cookies
  var cookie = new Object;
  var bits = document.cookie.split("; ");
  for (x=0; x<bits.length; x++) {
    if (wot) {
      if (wot==bits[x].replace(/=.*$/, "")) return bits[x].replace(/^.*=/, "");
    } else cookie[bits[x].replace(/=.*$/, "")] = bits[x].replace(/^.*=/, "");
  }
  if (wot) return "";
  else return cookie;
}
function setCookie(wot, val, expire) {
  document.cookie = wot+"="+val+";"+(expire ? "expires="+expire.toGMTString() : "");
  return;
}

function sortObjsByProperty(arr, prop, reverse) {
  if (typeof(arr)!=="Array") return;
  var result = new Array;
  var toSort = new Array;
  for (x=0; x<arr.length; x++) {
    if (typeof(arr[x])!=="Object") return "Index "+x+" not an object.";
    if (arr[x][prop])	toSort.push(arr[x][prop]+" [["+x+"]]");
    else 		toSort.push(" [["+x+"]]");
  }
  toSort.sort();
  if (reverse) toSort.reverse();
  for (x=0; x<toSort.length; x++) result.push(arr[toSort[x].replace(/^.* \[\[(\d+)\]\]$/, "$1")]);
  return result;
}

/* Making sure indexOf is an Array method */
if (!Array.indexOf) {
  Array.prototype.indexOf = function(obj) {
    var x;
    for (x=0; x<this.length; x++) {
      if (obj===this[x]) return x;
    }
    return -1;
  }
}
/*
String.prototype.URLsanitise = function() {
  var str = ""; var x;
  for (x=0; x<this.length; x++) str+= this[x];
  return str.replace(/\?/g, "[[QU]]").replace(/&/, "[[AND]]").replace(/=/, "[[EQ]]");
}*/
String.prototype.trim = function() {
  var str = this.replace(/(^\s*|\s*$)/, "");
  return str;
}

/* Preselect text in a textarea or Input */
function selectInputText(obj, begin, end) {
  if (obj.tagName=="INPUT" || obj.tagName=="TEXTAREA") {
    begin = typeof(begin)=="number" ? begin : 0;
    end = end && end>=begin ? end : obj.value.length;
    if (obj.setSelectionRange) { // Mozilla
      obj.focus();
      obj.setSelectionRange(begin, end);
    } else if (obj.createTextRange) {
      var range = obj.createTextRange();
      range.collapse();
      range.moveEnd("character", end);
      range.moveStart("character", begin);
      range.select();
    }
  }
}
/* Limit text to certain count */
function limitWords(obj, limit, noShowCount, onLimit) {
  if (obj.tagName.match(/^(input|textarea)$/i)) {
    if (!onLimit) onLimit = function() { ARTS.alert("You have exceeded the word limit of "+limit+"!"); }

    var words = obj.value.replace(/(^\s*|\s*$)/g, "").split(/\s+/);
    if (words.length>limit) {
      onLimit();
      obj.value = obj.value.replace(/\s+\S+$/, "");
      return;
    }
    if (!noShowCount) {
      var show; var noInput = true;
      if (obj.nextSibling) {
        if (obj.nextSibling.childNodes[0]) {
          if (obj.nextSibling.childNodes[0].nodeValue.match(/^\d+ remaining words allowed.$/)) noInput = false;
        }
      }
      if (noInput) {
        show = document.createElement("p");
        show.style.fontStyle = "italic"; show.style.color = "#999";
        if (obj.nextSibling) obj.parentNode.insertBefore(show, obj.nextSibling);
        else obj.parentNode.appendChild(show);
      } else show = obj.nextSibling;
      while (show.childNodes[0]) show.removeChild(show.childNodes[0]);
      show.appendChild(document.createTextNode((limit - words.length)+" remaining words allowed."));
    }
  }
}
function limitChars(obj, limit, noShowCount, onLimit) {
  if (obj.tagName.match(/^(input|textarea)$/i)) {
    if (!onLimit) onLimit = function() { ARTS.alert("You have exceeded the character limit of "+limit+"!"); }

    var chars = obj.value.replace(/(^\s*|\s*$)/g, "").split(/\s+/);
    if (chars.length>limit) {
      onLimit();
      obj.value = obj.value.replace(/\s+\S+$/, "");
      return;
    }
    if (!noShowCount) {
      var show; var noInput = true;
      if (obj.nextSibling) {
        if (obj.nextSibling.childNodes[0]) {
          if (obj.nextSibling.childNodes[0].nodeValue.match(/^\d+ remaining words allowed.$/)) noInput = false;
        }
      }
      if (noInput) {
        show = document.createElement("p");
        show.style.fontStyle = "italic"; show.style.color = "#999";
        if (obj.nextSibling) obj.parentNode.insertBefore(show, obj.nextSibling);
        else obj.parentNode.appendChild(show);
      } else show = obj.nextSibling;
      while (show.childNodes[0]) show.removeChild(show.childNodes[0]);
      show.appendChild(document.createTextNode((limit - words.length)+" remaining characters allowed."));
    }
  }
}

function addLineBreaks(txt) {
  if (typeof(txt)!=="string") return;
  return "<p>"+txt.replace(/\n\s+\n/g, "</p><p>").replace(/\n/g, "<br/>")+"</p>";
}
function stripLineBreaks(txt) {
  if (typeof(txt)!=="string") return;
  return txt.replace(/(<|&lt;)p(><|&lt;&gt;)\/p(>|&gt;)/ig, ""). /* clears out any browser inserted p tags due to bad DOM */
    replace(/(<|&lt;)br(\/){0,1}(>|&gt;)/ig, "\n"). /* straight forward replace of line breaks */
    replace(/(<|&lt;)\/p(><|&gt;&lt;)p(>|&gt;)/ig, "\n\n"). /* clears out p tags */
    replace(/(^(<|&lt;)p(>|&gt;)|(<|&lt;)\/p(>|&gt;)$)/ig, ""). /* clears out the opening and ending p tag */
    replace(/(<|&lt;)\/{0,1}p(>|&gt;)/ig, "\n"); /* any remaining errant p tags */
}
function addKeyPressToButtons(target) { /* Allows all the buttons to have a keypress and be part of the tab settings */
  if (!target) target = document;
  for (x=0; x<target.getElementsByTagName("div").length; x++) {
    if (target.getElementsByTagName("div")[x].className && target.getElementsByTagName("div")[x].className.match(/\b(submit|report|function)Button\b/)) {
      target.getElementsByTagName("div")[x].setAttribute("tabindex", "0");
      target.getElementsByTagName("div")[x].onkeypress = function(e) {
        e = window.event ? window.event : e;
        var t = e.srcElement ? e.srcElement : e.target;
        var key = e.keyCode ? e.keyCode : e.charCode;
        if (key==13 || key==32) {
          if (t.onclick) t.onclick();
          else if (t.childNodes[0].onclick) t.childNodes[0].onclick();
        }
      }
    }
  }
}
function allowEnterEqualClick(e) {
  e = window.event ? window.event : e;
  var t = e.srcElement ? e.srcElement : e.target;
  var key = e.keyCode ? e.keyCode : e.charCode;
  if (key==13 || key==32) { // allows enter and spacebar to submit
    if (t.onclick) t.onclick();
  }
}

// Alert replacing functions
function artsFunctions() { 
  this.popup = function() {
    this.onclose = null;
    this.window = null;
    this.style = {
      zIndex: 500,
      minWidth: Math.ceil(.1 * winDim.width)+"px",
      minHeight: Math.ceil(.1 * winDim.height)+"px",
      width: Math.ceil(.4 * winDim.width)+"px",
      height: Math.ceil(.3 * winDim.height)+"px",
      backgroundColor: "#f9f9f9",
      color: "#000",
      borderRadius: "10px",
      padding: "10px 10px 10px 10px",
      textAlign: "left",
      verticalAlign: "top",
      border: "3px solid #66f",
      overflow: "auto"
    }
    this.open = function() {
      var guard;
      document.body.appendChild(guard = document.createElement("div"));
      guard.style.height = winDim.height+"px"; guard.style.width = winDim.width+"px"; guard.style.position = "fixed"; guard.style.top = "0px"; guard.style.left = "0px";
      guard.style.backgroundColor = "#000"; guard.style.opacity = ".5"; guard.style.zIndex = this.style.zIndex;

      document.body.appendChild(this.window = document.createElement("div"));
      for (x in this.style) this.window.style[x] = this.style[x];
      this.window.style.position = "absolute"; 
      this.window.style.top = Math.ceil((winDim.height - this.style.height.replace(/px$/, "")) /2)+"px";
      this.window.style.left = Math.ceil((winDim.width - this.style.width.replace(/px$/, "")) /2)+"px";
      document.body.parentNode.scrollTop = 0;
    }
    this.close = function() {
      if (this.window.parentNode==document.body){
        document.body.removeChild(this.window.previousSibling);
        document.body.removeChild(this.window);
      }
      window.onkeydown = function() {}
      if (!("ondblclick" in window)) document.onkeydown = window.onkeydown;
      if (this.onclose) this.onclose();
    }
  }
  this.POPUP = new this.popup();
// Replace the browser functions
  this.alert = function(str) {
/*    var tmp;
    ARTS.POPUP.open();
    ARTS.POPUP.window.appendChild(tmp = document.createElement("div"));
    tmp.innerHTML = addLineBreaks(str);

    if (ARTS.POPUP.window.childNodes[0].offsetHeight > ARTS.POPUP.window.offsetHeight) {
      ARTS.POPUP.window.style.height = (
        ARTS.POPUP.window.childNodes[0].offsetHeight + 40 < winDim.height ?
          ARTS.POPUP.window.childNodes[0].offsetHeight + 40 :
          winDim.height
      )+"px";
      ARTS.POPUP.window.style.top = Math.ceil((winDim.height - ARTS.POPUP.window.style.height.replace(/px$/, "")) /2)+"px";
      ARTS.POPUP.window.style.left = Math.ceil((winDim.width - ARTS.POPUP.window.style.width.replace(/px$/, "")) /2)+"px";
    }

    tmp = document.createElement("div");
    tmp.className = "submitButton"; tmp.style.position = "absolute"; tmp.style.bottom = "15px"; tmp.style.right = "15px";
    tmp.onclick = function() { ARTS.POPUP.close(); }
    ARTS.POPUP.window.appendChild(tmp);
    tmp.appendChild(tmp = document.createElement("a"));
    tmp.appendChild(document.createTextNode("close"));

    window.onkeydown = function(e) {
      e = window.event ? window.event : e;
      var key = e.keyCode ? e.keyCode : e.charCode;
      if (key==13) ARTS.POPUP.close();
    }
    if (!("ondblclick" in window)) document.onkeydown = window.onkeydown;
*/
    alert(str);
  }
}
var ARTS = new artsFunctions();

