var mainUrlLookup = null;
var prevUrlSearch = "";
var urlsFound = new Array();
var mainurl = "";
var mainUrlValid = false;
var lookingUpDate = false;
var lookingUpDateFinishFn = null;
var mainLinkManager = null;

var userTouchedInput = false;

function testTouchForwardLink(link)
  {
  if (userTouchedInput)
    {
    var fn = function(result)
      {
      if (result)
        {
        window.location = link;
        }
      }
    csConfirm('You have made changes. Are you sure you want to go back to editing the introduction page and loose changes?', fn);
    return;
    }
  window.location = link;
  }

var hasLocationBeenLookedUp = false;

function setLocationLookupValue(value)
  {
  hasLocationBeenLookedUp = value;
  if (hasLocationBeenLookedUp)
    {
    document.getElementById('submit_button').value = "Submit";
    }else
    {
    document.getElementById('submit_button').value = "Lookup Webpage";
    }
  document.getElementById('submit_button').disabled = false;
  }

function submitData()
  {
  if (!hasLocationBeenLookedUp)
    {
    document.getElementById('submit_button').disabled = true;
    finishedEnteringUrl();
    return;
    }
  if (!mainUrlValid)
    {
    alert("The location entered does not appear to be valid. If the sub-links are still being looked up, please wait untill we have validated your location.");
    return;
    }
  if (lookingUpDate)
    {
    alert("Please wait while we validate your date.");
    return;
    }
  if (!usingCustomIntroductionPage && document.getElementById('subjectinput').value == "")
    {
    alert("Please fill in the headline field.")
    return;
    }
  document.getElementById('mainForm').submit();
  var sb = document.getElementById('submit_button');
  sb.disabled = true;
  sb.value = "Please wait while we make local copies of pages.";
  document.getElementById('subjectinput').disabled = true;
  document.getElementById('urlinput').disabled = true;
  document.getElementById('dateinput').disabled = true;
  }


function finishedEnteringDate()
  {
  lookingUpDate = true;

  this.readReturnedDate = function(date)
    {
    this.value = date;
    lookingUpDate = false;
    if (lookingUpDateFinishFn != null)
      {
      lookingUpDateFinishFn.run();
      lookingUpDateFinishFn = null;
      }
    }

  this.errorReadingDate = function(id, error)
    {
    lookingUpDateFinishFn = null;
    if (id == 1)
      {
      alert(error);
      }
    if (id == 2)
      {
      alert('Unable to make sence of given date.');
      if (defaultDate == null)
        {
        this.value = error['date'];
        }else
        {
        this.value = defaultDate;
        }
      }
    lookingUpDate = false;
    }

  var fn = new phpRequest(new objfn('readReturnedDate', this), 'parseDate', 'pageinfo', 'responder.php');
  fn.setErrorHandler(new objfn('errorReadingDate', this));
  fn.run(this.value);
  }


function finishedEnteringUrl()
  {
  var input = document.getElementById('urlinput').value;//this.value;

  if (input == "")
    {
    document.getElementById('urlinput').value = "http://";
    input = "http://"
    }

  if (input == "http://")
    {
    alert("Please enter a url in the 'Location' field.");
    setLocationLookupValue(false);
    return;
    }

  if (input.indexOf('://') == -1)
    {
    input = 'http://' + input;
    }
  if (input.lastIndexOf('/') == (input.indexOf('://')+2))
    {
    input = input + '/';
    }
  if (input == 'http:///')
    {
    input = 'http://';
    }
  document.getElementById('urlinput').value = input;
  if (prevUrlSearch == input)
    {
    setLocationLookupValue(true);
    return;
    }
  prevUrlSearch = input;
  mainurl = input;
  mainUrlValid = true;
  urlsFound = new Array();
  if (mainLinkManager == null)
    {
    mainLinkManager = new URLManager(document.getElementById('linkLocation'));
    }
//  new expandableUrl(document.getElementById('linkLocation'), input, null, 1);
  mainLinkManager.setParentURL(input);

  var helpTable = document.getElementById('helpTable');
  if (helpTable != null)
    {
    helpTable.style['visibility'] = "visible";
    helpTable.style['display'] = "block";
    }

  return;
  }

function URLManager(root)
  {
  while(root.childNodes.length != 0)
    {
    root.removeChild(root.childNodes[0]);
    }

  this.root = root;
/*
Hash Of urls:
url = {'obj':expandableURL, 'state':[0=live|1=archive|2=disabled]};
*/
  this.directParentChildren = null;
  this.links = null;
  this.cachedURLResults = new Array();
  this.parentURL = null;
  this.frameLinkNodes = {};
  }

URLManager.prototype.colorSelect = function(select)
  {
  if (select.value == 0)
    {
    select.className = "sublinkdd_live";
    }else if(select.value == 1)
    {
    select.className = "sublinkdd_archived";
    }else if(select.value == 2)
    {
    select.className = "sublinkselect";
    }
  }

URLManager.prototype.setUrlState = function(url, state)
  {
//alert(state+url);
  if (this.links[url] == null)
    {
    this.addURL(url, state);
    }

  this.links[url]['state'] = state;

  if (state == 1)
    {
    if (this.links[url]['obj'] == null)
      {
      this.links[url]['obj'] = new expandableURL(this, url);
      }
    this.links[url]['obj'].showChildren();
    }

  var removedLink = false;
  if (state != 1 && this.links[url]['obj'] != null)
    {
    if (url != this.parentURL)
      {
      this.links[url]['obj'].unlink();
      this.links[url]['obj'] = null;
      }else
      {
      this.links[url]['obj'].hideChildren();
      }
    removedLink = true;
    }

  for(var i in this.links)
    {
    if (this.links[i]['obj'] != null)
      {
      this.links[i]['obj'].setURLOption(url, state);
      }
    }

  if (removedLink)
    {
    this.removeUnlinked();
    }
  }

URLManager.prototype.reset = function()
  {
  for(var i in this.links)
    {
    if (this.links[i]['obj'] != null && this.links[i]['obj'].unlink != null)
      {
      this.links[i]['obj'].unlink();
      }
    }
  this.links = new Array();
  this.directParentChildren = new Array();
  }

URLManager.prototype.setParentURL = function(url)
  {
  this.reset();
  this.parentURL = url;
  this.addURL(url, 1);

  if (window.urlStates != null)
    {
    this.links[url]['autoLoading'] = true;
    for (var i in window.urlStates)
      {
      if (window.urlStates[i] == 1)
        {
        this.links[i] = {'obj':null, 'state':0, 'onLinkableLoad':true};
        }else
        {
        this.links[i] = {'obj':null, 'state':window.urlStates[i]};
        }
      }
    }
  }

URLManager.prototype.addURL = function(url, state)
  {
  this.links[url] = {'obj':null, 'state':state};
  if (state == 1)
    {
    this.links[url]['obj'] = new expandableURL(this, url);
    this.links[url]['obj'].showChildren();
    }
  }

URLManager.prototype.setLinkIsFrame = function(url)
  {
  var node = this.frameLinkNodes[url];
  while (node.childNodes.length != 0)
    {
    node.removeChild(node.childNodes[0]);
    }
  node.appendChild(document.createTextNode('[Contains Frames] '));
  }

URLManager.prototype.createURLLabel = function(url, isFrame, isMainLink)
  {
  var mainLinkRoot = document.createElement('div');
  mainLinkRoot.className = "sublinks";
  var urlText;
  if (this.parentURL == url && usingCustomIntroductionPage)
    {
    mainLinkRoot.appendChild(document.createTextNode(" "));
    var cl = document.createElement('span');
    cl.className = 'sublnk_frame';
    cl.appendChild(document.createTextNode("[Custom Introduction]"));
    mainLinkRoot.appendChild(cl);
    mainLinkRoot.appendChild(document.createTextNode(" ["));
    }else
    {
    mainLinkRoot.appendChild(document.createTextNode(" "));
    if (isFrame)
      {
      var frameNode = document.createElement('span');
      frameNode.className = "sublnk_frame";
      frameNode.appendChild(document.createTextNode('[Frame] '));
      mainLinkRoot.appendChild(frameNode);
      }
    if (isMainLink)
      {
      var frameNode = document.createElement('span');
      this.frameLinkNodes[url] = frameNode;
      frameNode.className = "sublnk_frame";
      mainLinkRoot.appendChild(frameNode);
      }
    mainLinkRoot.appendChild(document.createTextNode(url + ' ['));
    }
  var urlViewLink = document.createElement('a');
  if (window.archivedLinks != null && window.archivedLinks[url] != null)
    {
    urlViewLink.href = window.archivedLinks[url];
    urlViewLink.appendChild(document.createTextNode('View Archived'));
    }else
    {
    urlViewLink.href = url;
    urlViewLink.appendChild(document.createTextNode('View'));
    }


  urlViewLink.target = '_blank';
  var urlTextFin = document.createTextNode(']');
  mainLinkRoot.appendChild(urlViewLink);
  mainLinkRoot.appendChild(urlTextFin);

  return mainLinkRoot;
  }

URLManager.prototype.createURLOptionDD = function(url)
  {
  var linkOptions = document.createElement('select');
  linkOptions.url = url;
  linkOptions.name = "links[" + url + "]";
  linkOptions.className = "sublinkselect";
  var option;

  if (this.parentURL != url || !usingCustomIntroductionPage)
    {
    option = document.createElement('option');
    option.appendChild(document.createTextNode('Live'));
    option.value = 0;
    option.className = "sublinkopt_normal";
    linkOptions.appendChild(option);
    }

  option = document.createElement('option');
  option.appendChild(document.createTextNode('Archived'));
  option.value = 1;
  option.className = "sublinkopt_normal";
  linkOptions.appendChild(option);

  if (this.parentURL != url && (!usingCustomIntroductionPage || !this.directParentChildren[url]))
    {
    option = document.createElement('option');
    option.appendChild(document.createTextNode('Disabled'));
    option.value = 2;
    option.className = "sublinkopt_normal";
    linkOptions.appendChild(option);
    }

  if (this.links[url] != null)
    {
    linkOptions.value = this.links[url]['state'];
    }else
    {
    linkOptions.value = 2;
    if (linkOptions.value != 2)
      {
      linkOptions.value = 0;
      }
    }

  var parent = this;

  this.colorSelect(linkOptions);

  linkOptions.onchange = function()
    {
    userTouchedInput = true;
    parent.setUrlState(this.url, this.value);
    }

  return linkOptions;
  }

URLManager.prototype.getURLLinks = function(url, retCB, errCB)
  {
  if (this.cachedURLResults[url] != null)
    {
    retCB.run(this.cachedURLResults[url]);
    return;
    }
  var fn = new phpRequest(retCB, 'getLinks', 'pageinfo', 'responder.php');
  fn.setErrorHandler(errCB);
  fn.run(url, (window.articleID==null?"":window.articleID));
  }

URLManager.prototype.setURLResult = function(url, result)
  {
  this.cachedURLResults[url] = result;
  }

URLManager.prototype.removeUnlinked = function()
  {
  for(var i in this.links)
    {
    if (this.links[i]['state'] == 1 && this.links[i]['obj'] != null)
      {
      if (!this.pathExists(this.parentURL, i))
        {
        this.links[i]['obj'].unlink();
        this.links[i]['obj'] = null;
        if (this.parentURL != i && (!usingCustomIntroductionPage || !this.directParentChildren[i]))
          {
          this.links[i]['state'] = 2;
          }else if((this.parentURL != i || !usingCustomIntroductionPage))
          {
          this.links[i]['state'] = 0;
          }else
          {
          this.links[i]['state'] = 1;
          }
        }
      }
    }
  }

URLManager.prototype.pathExists = function(from, to)
  {
  if (from == to)
    {
    return true;
    }

  if (this.links[from] == null)
    {
    return false;
    }

  if (this.links[from]['state'] != 1)
    {
    return false;
    }

  if (this.links[from]['obj'] != null)
    {
    return this.links[from]['obj'].pathExistsTo(to);
    }

  return false;
  }

function expandableURL(manager, url)
  {
  this.manager = manager;
  this.url = url;
  this.rootNode = document.createElement('div');
  this.manager.root.appendChild(this.rootNode);
  this.childLinkObjs = new Array();
  this.showingChildren = false;

  var titleDiv = document.createElement('div');
  this.rootNode.appendChild(titleDiv);
  this.optionSelect = this.manager.createURLOptionDD(this.url);
  titleDiv.appendChild(this.optionSelect);
  titleDiv.appendChild(this.manager.createURLLabel(this.url, false, true));

  var clearDiv = document.createElement('div');
  clearDiv.style['clear'] = "both";
  this.rootNode.appendChild(clearDiv);

  this.childLocation = document.createElement('div');
  this.rootNode.appendChild(this.childLocation);
  this.childLocation.className = "sublinks";

  clearDiv = document.createElement('div');
  clearDiv.style['clear'] = "both";
  this.rootNode.appendChild(clearDiv);
  }

expandableURL.prototype.pathExistsTo = function(url)
  {
  if (this.runningPathExists)
    {
    return false;
    }
  this.runningPathExists = true;
  if (this.url == url)
    {
    this.runningPathExists = false;
    return true;
    }
  for(var i in this.childLinkObjs)
    {
    if (this.manager.pathExists(i, url))
      {
      this.runningPathExists = false;
      return true;
      }
    }
  this.runningPathExists = false;
  return false;
  }


expandableURL.prototype.hideChildren = function()
  {
  this.showingChildren = false;
  while (this.childLocation.childNodes.length != 0)
    {
    this.childLocation.removeChild(this.childLocation.childNodes[0]);
    }
  this.childLinkObjs = new Array();
  }

expandableURL.prototype.showChildren = function()
  {
  if (this.showingChildren)
    {
    return;
    }
  this.showingChildren = true;
  while (this.childLocation.childNodes.length != 0)
    {
    this.childLocation.removeChild(this.childLocation.childNodes[0]);
    }
  var div = document.createElement('div');
  div.className = 'message';
  div.appendChild(document.createTextNode('Looking up "' + this.url +'", please wait...'));
  this.childLocation.appendChild(div);
  this.manager.getURLLinks(this.url, new objfn('readSubChildren', this), new objfn('errorReadSubChildren', this));
  }

expandableURL.prototype.errorReadSubChildren = function(code, message)
  {
  if (this.manager.links[this.url] != null && this.manager.links[this.url]['state'] != 1)
    {
    return;
    }

  while(this.childLocation.childNodes.length != 0)
    {
    this.childLocation.removeChild(this.childLocation.childNodes[0]);
    }
  var div = document.createElement('div');
  div.className = 'fatal';
  div.appendChild(document.createTextNode(message));
  this.childLocation.appendChild(div);
  if (this.url == this.manager.parentURL)
    {
    prevUrlSearch = "";
    setLocationLookupValue(false);
    }
  }

expandableURL.prototype.readSubChildren = function(result)
  {
//  document.title = result['title'];
  this.manager.setURLResult(this.url, result);
  if (this.manager.links[this.url] != null && (this.manager.links[this.url]['state'] != 1 && !this.manager.links[this.url]['onLinkableLoad']))
    {
    return;
    }
  while(this.childLocation.childNodes.length != 0)
    {
    this.childLocation.removeChild(this.childLocation.childNodes[0]);
    }

  if (this.url == this.manager.parentURL)
    {
    setLocationLookupValue(true);
    var titleNode = document.getElementById('subjectinput');
    if (titleNode.manuallyChanged == null/*titleNode.value == ""*/)
      {
      titleNode.value = result['title'];
      }
    }

  if (result['badContentType'] == "1")
    {
    while(this.childLocation.childNodes.length != 0)
      {
      this.childLocation.removeChild(this.childLocation.childNodes[0]);
      }
    var div = document.createElement('div');
    div.className = 'fatal';
    div.appendChild(document.createTextNode("Unsupported content type. (" + result['contentType'] + ")"));
    this.childLocation.appendChild(div);

    return;
    }

  var links = result['links'];
  var frames = result['frames'];

  if (frames.length != 0)
    {
    this.manager.setLinkIsFrame(this.url);
    }
  var frameHash = {};
  for(var i = 0; i < frames.length; i++)
    {
    frameHash[frames[i]] = true;
    }
  this.childLinkObjs = new Array();
  for(var i = 0; i < links.length; i++)
    {

    if (this.url == this.manager.parentURL)
      {
      this.manager.directParentChildren[links[i]] = true;
      }


    var linkRoot = document.createElement('div');
    var linkOpt = this.manager.createURLOptionDD(links[i]);
    this.childLinkObjs[links[i]] = linkOpt;
    linkRoot.appendChild(linkOpt);

    linkRoot.appendChild(this.manager.createURLLabel(links[i], frameHash[links[i]]));

    linkRoot.style['clear'] = "both";
    this.childLocation.appendChild(linkRoot);

    if (this.manager.links[links[i]] != null && this.manager.links[links[i]]['onLinkableLoad'])
      {
      this.manager.links[links[i]]['onLinkableLoad'] = false;
      this.manager.links[links[i]]['autoLoading'] = true;
      this.manager.setUrlState(links[i], 1);
      }

    if (frameHash[links[i]] && !this.manager.links[this.url]['autoLoading'])
      {
      this.manager.setUrlState(links[i], 1);
      }

    }

  this.manager.links[this.url]['autoLoading'] = false;
  }

expandableURL.prototype.unlink = function()
  {
  if (this.rootNode != null)
    {
    this.rootNode.parentNode.removeChild(this.rootNode);
    }
  }

expandableURL.prototype.setURLOption = function(url, value)
  {
  if (url == this.url)
    {
    this.optionSelect.value = value;
    this.manager.colorSelect(this.optionSelect);
    }

  if (this.childLinkObjs[url] != null)
    {
    this.childLinkObjs[url].value = value;
    this.manager.colorSelect(this.childLinkObjs[url]);
    }
  }







