
  var selectedObjects = new Array
  
  function prepareForm(form) {
    if(selectedObjects.length < 1) {
      alert('Please select at least one criteria from the matrix.')
      return false
    }
    jurisdictions = new Array()
    sectors = new Array()
    for (i in selectedObjects) {
      valarray = selectedObjects[i].split('_')
      if(! inArray(valarray[0], jurisdictions)) {
        jurisdictions.push(valarray[0])
      }
      if(! inArray(valarray[1], sectors)) {
        sectors.push(valarray[1])
      }
    }
    for (i in jurisdictions) {
      addHiddenInputField(form, 'jurisdiction', jurisdictions[i])  
    }
    for (i in sectors) {
      addHiddenInputField(form, 'sector', sectors[i])  
    }
    
    return true
  }

  function addHiddenInputField(formElement, fieldName, fieldValue) {
     var inputElement = document.createElement("input")
     inputElement.setAttributeNode(createHtmlAttribute("type", "hidden"))
     inputElement.setAttributeNode(createHtmlAttribute("name", fieldName))
     inputElement.setAttributeNode(createHtmlAttribute("value", fieldValue))
     formElement.appendChild(inputElement)
  }

  function createHtmlAttribute(name, value) {
     var attribute = document.createAttribute(name)
     attribute.nodeValue = value
     return attribute
  }
  
  function cellRollover(tdobject) {
    highlightrow(tdobject, 'matrixcellhighlight', 'matrixrowhighlight')
  } 

  function cellClick(tdobject) {
    // if this object is already selected
    if(inArray(tdobject.id, selectedObjects)) { 
      // remove it from the selected array
      while (i < selectedObjects.length) {
        if (selectedObjects[i] == tdobject.id) {
          selectedObjects.splice(i, 1);
        } else {
          i++;
        }
      }
      // and set the image back to a cross.
      tdobject.style.backgroundImage = 'url(/blankdot.gif)'
    } else {
      // add it to the list
      selectedObjects.push(tdobject.id)
      //  and do the highlight thing.
      tdobject.style.backgroundImage = 'url(/tick.gif)'
    }
  }
  
  function highlightrow(tdobject, tdclass, rowclass) {
   
    var alltds = document.getElementsByTagName('td')
    var trparent = tdobject.parentNode;
  
    for (var i=0; i< alltds.length; i++) { 
      // those that are in the same column shoudl be updated.
      // those that have the same row parent should be updated.
      if((alltds[i].cellIndex == tdobject.cellIndex) || (alltds[i].parentNode == trparent)) {
        // make sure we should not be overiding this
	alltds[i].className = rowclass
      } else {
        alltds[i].className = 'matrixcelldefault' 
	
      }
    }
    tdobject.className = tdclass
  }
  
  function inArray(objectid, array) {
    for (i in array) {
      if(array[i] == objectid) {
        return true
      }
    } 
    return false
    
  }

  function debugoutput (message) {
    outputbox = document.getElementById('debugoutput')
    outputbox.value = outputbox.value + '\n' + message
  } 
