USER_CLIENT = 0;
USER_PACKAGER = 1;
USER_CONTACT = 2;
USER_ADMIN = 5;
USER_ROOT = 10;

/**
 * Attaches an onclick event to each link with rel="external" that opens the
 * link in a new window.
 */
function initExternalLinks() {
  var as = document.getElementsByTagName("a");
  for (var i = 0; i < as.length; i++) {
    if (as[i].getAttribute("rel") == "external") {
      as[i].onclick = openNewWindow;
    }
  }

  function openNewWindow() {
    window.open(this.href);
    return false;
  }
}

/**
 * Attaches submit handlers to text inputs of the given form, to compensate for
 * pretent submit buttons (i.e. <a> elements).
 *
 * @param form form to attach submit handlers to
 */
function attachSubmitHandlers(form) {
  // find all text-like inputs
  var inputs = form.getElementsByTagName("input");
  for (var i = 0; i < inputs.length; i++) {
    var inputType = inputs[i].getAttribute("type").toLowerCase();
    if (!(inputType == "text" || inputType == "password")) {
      continue;
    }

    attachHandler(inputs[i], form);
  }

  /**
   * Attaches the enter key handler (that submits the given form) to the
   * given input. Uses mootools Event class.
   */
  function attachHandler(i, f) {
    i.onkeypress = function(e) {
      var event = new Event(e);
      if (event.key == "enter") {
        return validateForm(f);
      }
    }
  }
}

function launchScanWindow(url) {  
  newWindow(url, 'scan', 600, 720);
  //document.getElementById('launchButton').style.display = 'none';
  //document.getElementById('proceedDeliveryButton').style.display = 'block';
  
  return false;
}

function launchFtpDownload(url) {  
  window.open(url);
  //document.getElementById('ftpButton').style.display = 'none';
  //document.getElementById('deliveryCompleteButton').style.display = 'block';
  
  return false;
}

function agreeTermsConditions() {
  document.getElementById('downloadButton').style.display = 'block';
  document.getElementById('appRequestFormContainer').style.display = 'none';
  
  return false;
}

function newWindow(url, name, width, height) {
  try {
    photoWindow = window.open(url, name,"location=no,directories=no,menubar=no,status=no,toolbar=no,scrollbars=yes,height=" +height+ ",width=" +width+ ",resizable=yes");
    photoWindow.resizeTo(width,height);
    photoWindow.focus();
  } catch (e) {}
  
  return false;
}

function firePasswordReminder(frm) {
  frm.entity.value='security';
  frm.command.value='login';
  
  if (frm.username.value == '') {
    frm.username.focus();
    alert('Please enter your username in the username field first.');
  } else {
    frm.entity.value='user';
    frm.command.value='forgotPassword';
    frm.submit();
  }
  
  return false;
}

function processPackageFormat(frm) {
  var elem = document.getElementById('deploymentToolHolder');
  
  if (elem != null) {
    if (frm.packageFormat.options[frm.packageFormat.selectedIndex].value == 'Softgrid') {
      elem.style.display = 'none';
    } else {
      elem.style.display = 'block';
    }
  }
}

function processOther(fld, fldTarget) {
  if (fldTarget == null) {
    var elem = document.getElementById(fld.name + 'Other');
  } else {
    var elem = document.getElementById(fldTarget);
  }
  
  if (fld.options[fld.selectedIndex].value == '') {
    elem.style.display = 'block';
  } else {
    elem.style.display = 'none';
  }
}

function processInvoiceStatus(fld) {
  if (fld.options[fld.options.selectedIndex].value == 'Invoiced') {
    document.getElementById('invoiceIdHolder').style.display = 'block';
    document.getElementById('invoiceDateHolder').style.display = 'block';
  } else if (fld.options[fld.options.selectedIndex].value == 'Paid') {
    document.getElementById('invoiceIdHolder').style.display = 'block';
    document.getElementById('invoiceDateHolder').style.display = 'block';
    document.getElementById('invoicePaidDateHolder').style.display = 'block';
  }
}

function processLabourStatus(fld) {
  if (fld.options[fld.options.selectedIndex].value == 'Invoiced') {
    document.getElementById('labourInvoiceIdHolder').style.display = 'block';
    document.getElementById('labourInvoiceDateHolder').style.display = 'block';
  } else if (fld.options[fld.options.selectedIndex].value == 'Paid') {
    document.getElementById('labourInvoiceIdHolder').style.display = 'block';
    document.getElementById('labourInvoiceDateHolder').style.display = 'block';
    document.getElementById('labourInvoicePaidDateHolder').style.display = 'block';
  }
}

/**
 * Constructor for an Entity.
 * Used for cache
 */
function Entity (id, title) {
  this.id = id;
  this.title = title;
}

/**
 * Refresh entity select box
 */
function refreshEntities(targetUrl, paramString, targetElem, sId, filterUnique) {
  //window.status = "Refreshing cache...";
  var req = newXMLHttpRequest();

  var handlerFunction = getReadyStateHandler(req, function(xml) { _updateEntities(targetElem, xml, sId, filterUnique); });
  req.onreadystatechange = handlerFunction;  
  req.open("POST", targetUrl, true);
  req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");

  req.send(paramString);
}

/**
 * AJAX - populate list via returned XML
 */
function _updateEntities(targetElem, inputXML, sId, selectOther) {
  var rootNode = inputXML.getElementsByTagName("root")[0];

  var list = rootNode.getElementsByTagName("entity");
  var tmpList = new Array();
  var lookup = new Array(); // use as HashMap
  
  for (var i=0; i<list.length; i++) {
    var entity = list[i];

    var id = entity.getElementsByTagName("id")[0].firstChild.nodeValue;
    var tmpNode = entity.getElementsByTagName("name")[0].firstChild;
    var title = (tmpNode != null) ? tmpNode.nodeValue : "";
    
    if (filterUnique == true && lookup[title] != null) {
      // don't add to cache
    } else {    
      // update cache
      tmpList.push(new Entity(id, title));
    }
    lookup[title] = 1;
    
  }

  entityCache = tmpList;
    
  window.status = "Done.";
  drawEntityList(targetElem, sId, selectOther);

  if (tmpList.length == 0) {
    //window.status = "Cache is empty.";
  }
}

/**
 * Draws select box of entities drawn from cache.
 */
function drawEntityList(targetElem, sId, selectOther) {
  // get contents
  var contents = targetElem;

  // clear list
  removeChildren(contents);
  contents.options[0] = new Option("Please choose ...", "");
  
  for (var i=0; i<entityCache.length; i++) {
    tmpEntity = entityCache[i];

    // populate list
    contents.options[i+1] = new Option(tmpEntity.title, tmpEntity.id);
    
    if (tmpEntity.id == sId && !selectOther) {
      contents.options.selectedIndex = i+1;
    }
  }
  
  contents.options[i+1] = new Option("(other)", "");
  if (selectOther) { 
    contents.options[i+1].selected = true;
  }
}

/**
 * Removes the child nodes of the specified element.
 */
function removeChildren(el) {
  while (el.firstChild) {
    el.removeChild(el.firstChild);
  }
}
 
/**
 * Toggles the display of input elements based on the type of user.
 */
function toggleUser(userType) {
  liArr = document.getElementById('theForm').getElementsByTagName("li");
  
  for (i=0; i < liArr.length; i++) {
    if ((userType == USER_PACKAGER || userType == USER_ADMIN || userType == USER_ROOT) && liArr[i].className != "allUsers") {
      liArr[i].style.display = "none";
      inpArr = liArr[i].getElementsByTagName("input");
      for (j=0; j < inpArr.length; j++) {
        if (liArr[i].className != "noValid") {
          if (inpArr[j].value.indexOf("PASSWORD") == -1) { // ignore password
            inpArr[j].value = inpArr[j].value.replace(/_YES/, "_NO");
          }
        }
      }
    } else {
      liArr[i].style.display = "block";
      inpArr = liArr[i].getElementsByTagName("input");
      for (j=0; j < inpArr.length; j++) {
        if (liArr[i].className != "noValid") {
          if (inpArr[j].value.indexOf("PASSWORD") == -1) { // ignore password
            inpArr[j].value = inpArr[j].value.replace(/_NO/, "_YES");
          }
        }
      }
    }
  }
}