var notSaved = false; // Tracks whehter changes have been made to a page before closing _SPACE_
var winDim;
document.onload = function() { winDim = winDimensions(); }

var mousePos = { x:0, y:0 }
document.onmousemove = mousePosition;
document.onmouseup = mouseUp;
var dragObj = new Object;
var resizeY = new Object;
var resizeX = new Object;

var hoveredTimeout;

// Ajax functions
function getAjax(URL, post) { // Ajax call to get basic Text.  Will not do XML.  XML requires synchronous call.
  var sendType = (post) ? "post" : "get";
  var response;
 
  if (post) waiting(true);
  var xhr = new createXMLHttpRequest();

  xhr.open(sendType, URL, false);
  if (post) xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
  xhr.send(post);
  response = xhr.responseText;
  xhr.close;

  if (response.match(/^\s*$/)) response = null;
  waiting(false);
  return response;
}
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) { // returns GET variables
  var what; var val;
  var vars = document.location.href.replace(/^.*\?/, "").split(/&/);
  for (x in vars) {
    if (key==vars[x].replace(/=.*$/, "")) return vars[x].replace(/^.*=/, "");
  }
}

function waiting(on) {
  if (document.body) {
    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 = "2500";
      wait.setAttribute("id", "_WAITING_"); wait.id = "_WAITING_";
      document.body.appendChild(wait);
    
      var img = document.createElement("img");
      img.src = "/artsdigital/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";

    if (document.all) { // something to deal with the FIXED position not working for IE
      document.body.parentNode.style.overflow = (on) ? "hidden" : "auto";
    }
  }
  return;
}
 
function _(id) { return obj = document.getElementById(id); }

// Overlay functions
function overlay(onoff) {
  if (onoff) {
    if (document.all) { // IE hack
      document.body.parentNode.style.overflow = "hidden";
    }
    if (!_("OVERLAY")) {
      var ws = document.createElement("div");
      ws.setAttribute("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 = "1000";
      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 = "1001"; 
      document.body.appendChild(space);

      var close = document.createElement("a");
      close.id = "_closeOverlayButton";
      close.href = "javascript:overlay()";
      close.innerHTML = "<img src='/artsdigital/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";
    }
    if (_("OVERLAY")) {
      _("OVERLAY").parentNode.removeChild(_("OVERLAY"));
      _("_SPACE_").parentNode.removeChild(_("_SPACE_"));
    }
  }
  return;
}

function framedWindowOverlay(content, heading, allProp, movable, onClose) {
  var name = heading ? heading.replace(/[\s"']+/g, "_") : "_POPUP_";
    var frameWidth = 15; // Frame widths
    var headingHeight = (heading) ? 30 : 5; 

  if (content) { // creating the window in the firstplace
    overlay(true);

    var all = document.createElement("div");
    all.id = name;
    for (x in allProp) all.style[x] = allProp[x];
 
    var head = document.createElement("div"); // heading  
    head.className = "windowHeading";
    head.id = "head_"+name;
    head.setAttribute("onselectstart", "return null"); head.onselectstart = "return null";
    head.innerHTML = heading;

    if (movable) { // Making an object movable from the head bar  
      if (document.all) head.onemousedown = "dragObject(event, _('"+name+"'))";
      else head.setAttribute("onmousedown", "dragObject(event, _('"+name+"'))");
    }
    all.appendChild(head);

    var kill = document.createElement("a"); // kill button 
    kill.href = "javascript:framedWindowOverlay(null, '"+name+"'"+(onClose ? ", null, null, '"+onClose+"'" : "")+")";
    kill.innerHTML = "<img src='/artsdigital/images/tabs/close_btn.png' style='border: 0px' />";
    kill.style.position = "absolute"; kill.style.right = "5px"; kill.style.top = "5px";
    all.appendChild(kill);
    if (_("_closeOverlayButton")) _("_closeOverlayButton").style.visibility = "hidden";

    var cont = document.createElement("div"); // Actual Content 
    all.appendChild(cont);
    cont.className = "cont";
    cont.style.height = (all.style.height.replace(/px$/, "")*1-2*frameWidth-headingHeight)+"px";
    cont.style.width = (all.style.width.replace(/px$/, "")*1-(2*frameWidth))+"px";
    cont.style.position = "absolute"; cont.style.left = frameWidth+"px"; cont.style.bottom = cont.style.left;
    cont.style.overflow = "auto";
    cont.id = "cont_"+name;
    cont.innerHTML = content;

    var resize = document.createElement("div");
    resize.style.backgroundImage = "url(/artsdigital/images/corners/pop_br.png)"; resize.style.backgroundRepeat = "no-repeat";
    all.appendChild(resize); 
    resize.className = "unselectable";
    resize.style.cursor = "se-resize"; resize.style.position = "absolute"; resize.style.right = "-16px"; resize.style.bottom = "-16px"; 
    resize.style.width = "16px"; resize.style.minWidth = "16px"; resize.style.height = "16px"; resize.style.minHeight = "16px";
    resize.onmousedown = "resizeFramedWindow(event, _('"+name+"'))"; resize.setAttribute("onmousedown", "resizeFramedWindow(event, _('"+name+"'))");
    resize.onselectstart = "return null"; resize.setAttribute("onselectstart", "return null");
// Inserting the round corners and borders
    var tl = document.createElement("div"); tl.style.backgroundImage = "url(/artsdigital/images/corners/pop_tl.png)"; tl.style.position = "absolute"; tl.style.left = "-16px"; tl.style.top = "-16px"; all.appendChild(tl);
    tl.style.width = "16px"; tl.style.minWidth = "16px"; tl.style.height = "16px"; tl.style.minHeight = "16px";
    var tr = document.createElement("div"); tr.style.backgroundImage = "url(/artsdigital/images/corners/pop_tr.png)"; tr.style.position = "absolute"; tr.style.right = "-16px"; tr.style.top = "-16px"; all.appendChild(tr);
    tr.style.width = "16px"; tr.style.minWidth = "16px"; tr.style.height = "16px"; tr.style.minHeight = "16px";
    var bl = document.createElement("div"); bl.style.backgroundImage = "url(/artsdigital/images/corners/pop_bl.png)"; bl.style.position = "absolute"; bl.style.left = "-16px"; bl.style.bottom = "-16px"; all.appendChild(bl);
    bl.style.width = "16px"; bl.style.minWidth = "16px"; bl.style.height = "16px"; bl.style.minHeight = "16px";
    var tt = document.createElement("div"); tt.style.backgroundImage = "url(/artsdigital/images/corners/pop_top.png)"; tt.style.backgroundRepeat = "repeat-x"; tt.style.position = "absolute"; tt.style.top = "-16px"; tt.style.minHeight = "16px"; tt.style.height = "16px"; tt.style.width = "100%"; all.appendChild(tt); 
    var bb = document.createElement("div"); bb.style.backgroundImage = "url(/artsdigital/images/corners/pop_btm.png)"; bb.style.backgroundRepeat = "repeat-x"; bb.style.position = "absolute"; bb.style.bottom = "-16px"; bb.style.minHeight = "16px"; bb.style.height = "16px"; bb.style.width = "100%"; all.appendChild(bb);  all.appendChild(bb);
    var ll = document.createElement("div"); ll.style.backgroundImage = "url(/artsdigital/images/corners/pop_left.png)"; ll.style.backgroundRepeat = "repeat-y"; ll.style.position = "absolute"; ll.style.left = "-16px"; ll.style.width = "16px"; ll.style.height = "100%"; ll.style.minHeight = "100%"; ll.style.top = "0px"; all.appendChild(ll); 
    var rr = document.createElement("div"); rr.style.backgroundImage = "url(/artsdigital/images/corners/pop_right.png)"; rr.style.backgroundRepeat = "repeat-y"; rr.style.position = "absolute"; rr.style.right = "-16px"; rr.style.width = "16px"; rr.style.height = "100%"; rr.style.minHeight = "100%"; rr.style.top = "0px"; all.appendChild(rr); 

    _("_SPACE_").appendChild(all);
    if (!all.style.top && !all.style.bottom) centreObject(all, null, "width");
    if (!all.style.left && !all.style.right) centreObject(all, null, "height");
    if (!all.style.background && !all.style.backgroundColor) all.style.backgroundColor = "#000";
  } else {
    if (notSaved) {
      var goAhead = confirm( ((typeof(notSaved)=="string") ? notSaved : "Changes have been made without saving.\n\nDo you wish to continue without saving?") );
      if (!goAhead) return;
    }
    if (_(name)) _('_SPACE_').removeChild(_(name));
    var die = true;
    if (_('_SPACE_')) {
      for (x in _('_SPACE_').childNodes) {
        if (_('_SPACE_').childNodes[x]) { if (_('_SPACE_').childNodes[x].tagName) { if (_('_SPACE_').childNodes[x].tagName.match(/div/i)) {
          die = false;
        } } }
      }
    }
    if (die) { overlay(); notSaved= false; }
    if (onClose) eval(onClose);
  }
  return;
}
function resizeFramedWindow(ev, obj) {
  if (!obj) return;
  ev = ev ? ev : window.event;
  if (ev.type=="mousedown") {
     var id = obj.id;
     resizeX = Array(obj, _("cont_"+id));
     resizeY = Array(obj, _("cont_"+id));
  }
}
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 in dimensions) {
      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 in dimensions) {
    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
function caption(text, objStyle, delay) { //objStyle is Object with properties to be placed in the caption style.  delay measured in ms.
  if (text) {
    if (delay) { 
      var definedStyle = "";
      for (x in objStyle) definedStyle+= x+": "+objStyle+", ";
      hoveredTimeout = setTimeout("caption('"+text+"', { "+definedStyle.replace(/, $/, "")+" } )", delay);
      return;
    }

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

    if (objStyle) {
      for (x in objStyle) caption.style[x] = objStyle[x];
    }

    caption.innerHTML = text;
    caption.style.zIndex = 1002; ; caption.style.position = "fixed"; caption.style.visibility = "visible"; 
    caption.style.left = mousePos.x+"px" ; caption.style.top = mousePos.y+"px";
  } else {
    if (_("_CAPTION_")) _("_CAPTION_").style.visibility = "hidden";
    clearTimeout(hoveredTimeout);
  }
  return;
}

// Mouse Position objects
function winDimensions() {
  if (typeof(window.innerHeight)=="number") {
    this.height = window.innerHeight;
    this.width = window.innerWidth;
  } else if (document.body && typeof(document.body.offsetHeight)=="number") {
    this.height = document.body.offsetHeight;
    this.width = document.body.offsetWidth;
  }

  if (screen && typeof(screen.height)=="number") {
    if (screen.height < this.height) this.height = screen.height;
    if (screen.width < this.width) this.width = screen.width;
  }
}  
function clearSelection() {
  if (document.selection) refresh = document.selection.clear()
  else if (document.getSelection()) refresh = document.getSelection().clear;
  else if (window.getSelection()) refresh = window.getSelection().clear;
  return;
}
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) { // Bit that actually calcultes the cursor position
    mousePos.x = evt.pageX; mousePos.y = evt.pageY;
  } else if (evt.clientX) {
    mousePos.x = evt.clientX + (document.documentElement.scrollLeft ? document.documentElement.scrollLeft : document.body.scrollLeft);
    mousePos.y = evt.clientY + (document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop);
  } 

  if (dragObj) { if (dragObj.style) { // for moving objects around
    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 in resizeX) { 
        if (resizeX[x]) { if (resizeX[x].style) {
          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) { if (resizeX.style) {
        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 in resizeY) {
        if (resizeY[x]) { if (resizeY[x].style) {
          resizeY[x].style.height = (resizeY[x].style.height.replace(/px$/, "")*1 - mousePos.origY + mousePos.y) + "px";
        } }
      }
    } else {
      if (resizeY) { if (resizeY.style) {
        resizeY.style.height = (resizeY.style.height.replace(/px$/, "")*1 - mousePos.origY + mousePos.y) + "px";
      } }
    }
  }
}
function mouseUp(evt) { // clears objects used for resize and dragging
  dragObj = null; 
  resizeX = null;
  resizeY = null;
  mousePos.origX = null; mousePos.origY = null;
  clearSelection();
}
function mouseCoord(evt) { // Object to determine mouse Coordinates
  evt = evt ? evt : window.event;
  if (evt.pageX && evt.pageY) {
    this.x = evt.pageX; this.y = evt.pageY;
  } else if (evt.clientX) {
    this.x = evt.clientX + (document.documentElement.scrollLeft ? document.documentElement.scrollLeft : document.body.scrollLeft);
    this.y = evt.clientY + (document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop);
  } 
}

// Form Processing
function processForm(formObj, processFile, req_fields, rewriteObj) { //returnss the feed from processing the file if no rewriteObj
  var ERROR = "";
  var result = "";

  if (formObj.elements) { 
    for (bit in formObj.elements) {
      if (formObj.elements[bit]) { if (formObj.elements[bit].tagName) { if (formObj.elements[bit].tagName.match(/^(textarea|input|select)$/i)) { if (formObj.elements[bit].name) {
// Determining if a required field is empty
        if (!formObj.elements[bit].value) {
          if (req_fields) {
            for (req in req_fields) {
              if (req_fields[req]==formObj.elements[bit].name) {
                ERROR+= formObj.elements[bit].name+" is missing!\n";
                formObj.elements[bit].style.border = "2px solid #D55";
              }
            }
          } else { // Putting something in the input/textarea etc to control what's manadatory but no need for req_fields
            if (formObj.elements[bit].getAttribute("mandatory")) ERROR+= formObj.elements[bit].name+" is missing!\n";
          }
        } else {
          if (formObj.elements[bit].type=="checkbox") {
            if (formObj.elements[bit].checked) result+= formObj.elements[bit].name+"=1&";
          } else if (formObj.elements[bit].name.match(/email/i)) {
            if (formObj.elements[bit].value.match(/^(\w\W*)+@(\w+\W*)+\.(\w+\W*)+$/)) result+= formObj.elements[bit].name+"="+sanitise(formObj.elements[bit].value)+"&";
            else ERROR+= "Please supply a legitimate Email!\n";
          } else {
            if (formObj.elements[bit].value!="NULL") result+= formObj.elements[bit].name+"="+sanitise(formObj.elements[bit].value)+"&";
          }
        }
      } } } }
    } 
  
    if (ERROR) { alert(ERROR+"\nPlease correctly complete these fields before continuing."); return;
    } else {
      var returnMsg = getAjax(processFile, result);
      if (rewriteObj) rewriteObj.innerHTML = returnMsg;
      else return returnMsg;
    }
  } else alert("Form "+formObj.id+" has no inputs!!");
  return;
}
function sanitise(string) {
  if (string.match(/[#\&\?=]/)) { 
    string = string.replace(/\?/g, "|_QUESTIONMARK_|");
    string = string.replace(/\&/g, "|_AMPERSAND_|");
    string = string.replace(/#/g, "|_HASH_|");
    string = string.replace(/=/g, "|_EQUAL_|");
  }       
  return string;
}
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.value==str) obj.value = "";
  if (!obj.origValue && !obj.getAttribute("origValue")) obj.setAttribute("origValue", str);
  return;
}
function clearRadio(contObj) { //clears all the values in a container with radio objects
  for (x in contObj.childNodes) {
    if (contObj.childNodes[x]) { if (contObj.childNodes[x].tagName) { if (contObj.childNodes[x].tagName.match(/^input$/i)) { if (contObj.childNodes[x].type) { if (contObj.childNodes[x].type.match(/radio/i)) {
      if (contObj.childNodes[x].checked) contObj.childNodes[x].checked = null;
    } } } } }
  }
  return;
}
// functoin 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 = "";
  var response = getAjax(targetURL+val+"&dummy="+dummyVal());
  obj.innerHTML = response;

  return;
}
// Funtions to show or hide objects
function show(obj, on) { obj.style.visibility = (on ? "visible" : "hidden"); }

