
var baseform;
var default_year = '2000';
var default_time = '0000';
var true_char = 'Y';
var false_char = 'N';
var formHasChanged = false;
var ignoreSaveCheck = false;
var minDate = new Date(1970, 1, 1);
var maxDate = new Date(2079, 6, 6);

var validIniNum = true; //Ugh another global
var is_ready = true;
var sabhrs_ready = false

//See if the form has changed
function save_check(clickIt){
  var curElem;
  var baseform = document.getElementById("aspnetForm")
  
  if(aspElementById('btnSave').disabled == true){
    if(clickIt==false){
        return false;
    }
    else{
        return;
    }
  }
  /*
  if(aspElementById('cooperatorChanged').value == 'y'){
    formHasChanged = true
  }
  */

//Builds the available incidents table
  //
  
  if(!ignoreSaveCheck || (ignoreSaveCheck && clickIt==false)){
    if(!formHasChanged){
      for(var i=0; i<baseform.elements.length; i++){
        curElem = baseform.elements[i];
        //if(curElem.id != 'ctl00_PageContent_txtCooperator'){
            if((curElem.type == 'text' || curElem.type == 'textarea') && curElem.value!=null && curElem.defaultValue!=null && curElem.value!=curElem.defaultValue){
                formHasChanged = true;
                break;
            }
            else if(curElem.type == 'select-one' && curElem.selectedIndex!=null && has_cbo_changed(curElem,false)){
                formHasChanged = true;
                break
            } 
            else if(curElem.type == 'checkbox' && curElem.defaultChecked!=null && curElem.checked != curElem.defaultChecked){
                formHasChanged = true;
                break
            }
        //}
      }
    }
    if(formHasChanged && aspElementById('disabled').value != 'y'){
      if(confirm('Press OK to save your changes, Cancel to disregard changes.')){
            //cannot get around the ie/firefox dialog automatic pop-up, at least this will give them some 
            //info on whats going on. browsers do this to prevent someone from locking you onto their page
            if(validate_form() == false){
                return 'Could not save changes, click OK to continue and abandon your changes, or cancel to stay on the page/activity and fix the problem';          
            }
            if(clickIt==true){ 
                var v = aspElementById('btnSave').click();
                pausecomp(1500);
            }
            else{
                return true;
            }
      }
      else if(clickIt==false){
        return false;
      }
    }
    else if(clickIt==false){
        return false;
    }
  }
  return;
}
function toggleIncidentWarningDiv(){
    var theDiv = aspElementById('warningIncidentDiv');
    if(theDiv.style.display == "none"){
        theDiv.style.display = ""
        aspElementById('hlShowHide').innerHTML = "(Hide)"
    }
    else{
        theDiv.style.display = "none"
        aspElementById('hlShowHide').innerHTML = "(Show)"
    }
}
function toggleActivityWarningDiv(){
    var theDiv = aspElementById('warningActivityDiv');
    if(theDiv.style.display == "none"){
        theDiv.style.display = ""
        aspElementById('hlShowHideActivity').innerHTML = "(Hide)"
    }
    else{
        theDiv.style.display = "none"
        aspElementById('hlShowHideActivity').innerHTML = "(Show)"
    }
}
function has_cbo_changed(cbo,ignoreNoDefault){
  if(cbo.selectedIndex <= 0){
    return false;
  }
  var retval = !cbo.options[cbo.selectedIndex].defaultSelected;
  var cboHadDefaultSelection = false;
  // Make sure that the default selected value was set to start with
  if(retval){
    for(var i=0; i<cbo.options.length; i++){
      if(cbo.options[i].defaultSelected){
        cboHadDefaultSelection = true;
        break;
      }
    }
    if(!cboHadDefaultSelection && cbo.selectedIndex==0){
      retval = false;
    }
    if(!cboHadDefaultSelection && ignoreNoDefault == true){
      retval = false
    }
  }
  return retval;
}

function setIgnoreSaveCheck(){
  ignoreSaveCheck = true;
  return true;
}

function unSetIgnoreSaveCheck(){
    ignoreSaveCheck = false;
    return true;        
}

//Number validating functions
function get_boolean(textField){
  return (textField!=null && textField.value==true_char);
}

function get_decimal(textField, numDec){
  var newVal = 0;
  
  if(textField!=null){
    newVal = get_all(textField, parseFloat(textField.value), false)
    if(newVal!=0){
      var i;
      var decimals = '.';
      var curval = newVal.toString();
      var pos = curval.lastIndexOf('.');
      var maxNumDigitsBeforeDecimal = textField.maxLength - numDec - 1;

      for(i=0; i<numDec; i++){
        decimals += '0';
      }
      if(pos<0){
        if(curval.length > maxNumDigitsBeforeDecimal){   // Remove digits to the left of the decimal point if needed
          curval = curval.substr(curval.length - maxNumDigitsBeforeDecimal);
        }
        textField.value = curval + decimals;
      }
      else{
        if(pos > maxNumDigitsBeforeDecimal){   // Remove digits to the left of the decimal point if needed
          curval = curval.substr(pos-maxNumDigitsBeforeDecimal);
        }
        var maxlen = pos+numDec+1;
        if(maxlen<=curval.length){   //  Remove digits to the right of the decimal point if needed
          textField.value = curval.substr(0, maxlen);
        }
        else{
          textField.value = curval + decimals.substr(curval.length-pos);
        }
      }
      newVal = parseFloat(textField.value);
    }
  }
  return newVal;
}

function get_float(textField)
{
  var newVal = 0;
  if(textField!=null)
    newVal = get_number(textField, parseFloat(textField.value));
  return newVal
}

function get_int(textField){
  var newVal = 0;
  if(textField!=null)
    newVal = get_number(textField, parseInt(textField.value, 10));
  return newVal;
}


function get_date(textField){
  var retval = 0;
  var newDate;
  
  if(textField!=null) {
    // Fix the year as parse does not do a good job
    var d = new Date()
    default_year = d.getFullYear();
    default_year = default_year.toString()
    var curValue = textField.value;
    var lastSlash = curValue.lastIndexOf('/');
    if(curValue.length>2){
      if(lastSlash<3){
        curValue = curValue + '/' + default_year;
      }
      else{
        if(lastSlash == curValue.length-1){
          curValue = curValue + default_year;
        }
        else{
          var curYear = curValue.substr(lastSlash+1);
          curValue = curValue.substr(0, lastSlash+1) + 
                     default_year.substr(0, default_year.length - curYear.length) + 
                     curYear;
        }
      }
    }
    newDate = Date.parse(curValue);
    if(newDate < minDate || newDate > maxDate){
      newDate = NaN;
    }
    retval = get_all(textField, newDate, false);
    if(retval!=0) {
      var newDate = new Date(retval);
      var fullYear = newDate.getFullYear();
      textField.value = (newDate.getMonth()+1) + '/' + newDate.getDate() + '/' + fullYear;
      textField.defaultValue = textField.value;
    }
  }
  return retval;
}

//get a time field
function get_time(textField) {
  var retval = 0;
  if(textField!=null) {
    var intVal = parseInt(textField.value, 10)
    if(intVal >= 2400)
      intVal = NaN
    var retval = get_all(textField, intVal, false);
    if(retval!=0){
      textField.value = default_time.substr(0, default_time.length - textField.value.length) + textField.value;
      textField.defaultValue = textField.value;
    }
  }
  return retval;
}

//get a number
function get_number(textField, curValue) {
  return get_all(textField, curValue, true);
}

//See if anything on the current form has changed
function get_all(textField, curValue, overwriteVal){
  var retval = 0;
  if(textField!=null && textField.value != '') {
    if(isNaN(curValue)){
      if(textField.defaultValue==''){
        textField.value = '';
      }
      else {
        textField.value = textField.defaultValue;
        retval = textField.defaultValue;
        formHasChanged = true;
      }
    }
    else {
      retval = Math.abs(curValue);
      if(overwriteVal){
        textField.value = retval;
      }    
      textField.defaultValue = textField.value;
      formHasChanged = true;
    }
  }
  return retval;
}

//open the help window
function open_help()
{
  inline_help('','F300');
}

//Opens the inline help window
function inline_help(inanchortag, indocfile) {
  var anchortag = inanchortag;
  var docfile = indocfile;

  if(anchortag.length>0 && anchortag.substr(0,1)!='#'){
    anchortag = '#' + anchortag;
  }
  window.open("help/" + docfile + "_Doc.html" + anchortag, "help", "dependant=yes,width=750,height=550,menubar=no,personalbar=no,resizable=yes,scrollbars=yes,status=no,toolbar=no");     
}

//pops opene the printalbe report window
function PrintRpt() {
  window.open(this.document.location.href + "?print=Y", "f300print",
              "scrollbars=yes,resizable=yes,menubar=no,status=no,toolbar=yes,width=825,height=550");
}
function PrintF300() {
if(trim(aspElementById('incident_id').value) == ""){
    alert('Must save the record before you can print it!')
    return
}
window.open(this.document.location.href + "?print=Y&incident_id=" + trim(aspElementById('incident_id').value) + "&activity_id=" + trim(aspElementById('activity_id').value), "f300print",
              "scrollbars=yes,resizable=yes,menubar=no,status=no,toolbar=yes,width=825,height=550");
}

//pops open the activity change log
function openActivityLog(activityId,historyId){
  window.open("change_log.aspx?activity_id=" + activityId + "&history_id=" + historyId + "#" + historyId,"",
              "scrollbars=yes,menubar=no,status=yes,toolbar=no,location=no,width=800,height=230");
  return false;
}

//pops up the incident change log
function openIncidentLog(incidentId,historyId){
  window.open("change_log.aspx?incident_id=" + incidentId + "&history_id=" + historyId + "#" + historyId,"",
              "scrollbars=yes,menubar=no,status=yes,toolbar=no,location=no,width=800,height=230");
              return false;
}

//Trim trailing spaces
function rtrim(strVal) {
  var retval = strVal;
  if(strVal == null){
    return ''
  }
  if (strVal.length == 0){
    return ''
  }
  if(strVal.charAt(strVal.length - 1) == ' '){
    return ''
  }
  while(retval.charAt(retval.length-1)==' '){
    retval = retval.substr(0, retval.length-1);
  }
  
  return retval;
}

//trim leading spaces
function ltrim(strVal) {
  var retval = strVal;
  
  while(retval.charAt(0)==' '){
    retval = retval.substr(1, retval.length);
    if (retval == ' '){
        return '';
    }
  }
  return retval;
}

//left and right trim spaces from a string
function trim(strVal){
    return ltrim(rtrim(strVal))
}

//Trim leading zeros, gets around a javascript bug where it thinks 
//parseInt('00008')==parseInt('0') is true when doing a parseInt conversion
function ltrimZeros(strVal) {
  var retval = strVal;
  
  while(retval.charAt(0)=='0'){
    retval = retval.substr(1, retval.length);
    if (retval == '0'){
        return '0';
    }
  }
  return retval;
}

//open latlong_converter window
function latlong_converter() {
  window.open("latlong_converter.aspx", "",
              "scrollbars=yes,menubar=no,status=yes,toolbar=no,location=no,width=530,height=230");
}

//Functions to make javascript do a POST
function getNewSubmitForm(){
 var submitForm = document.createElement("FORM");
 document.body.appendChild(submitForm);
 submitForm.method = "POST";
 return submitForm;
}

//builds form elements on the fly 
function createNewFormElement(inputForm, elementName, elementValue){
 var newElement = document.createElement('INPUT');
 newElement.setAttribute('type', 'hidden');
 newElement.setAttribute('name', elementName);
 newElement.setAttribute('value', elementValue);
 
 inputForm.appendChild(newElement);
 newElement.value = elementValue;
 return newElement;
}

//POST the value over to user.aspx
function loadUser(userName) {
 var submitForm = getNewSubmitForm();
 createNewFormElement(submitForm, 'user_name',userName);
 submitForm.action= 'user.aspx';
 submitForm.submit();
}

//hack to make a link to a POST instead of redirecting via a GET
function loadReport(incidentNum) {
 var submitForm = getNewSubmitForm();
 createNewFormElement(submitForm, 'incident_id',incidentNum);
 submitForm.action= 'f300.aspx';
 submitForm.submit();
}

function typicalDownload(){
    var submitForm = getNewSubmitForm();
    createNewFormElement(submitForm, 'ids', aspElementById('ids').value)
    submitForm.action = 'download.aspx'
    submitForm.submit();
}

//hack to get all the cooperators to come across in the POST and not just the
//SELECTED one
function storeList(){
    /*
    var frm = document.getElementById("aspnetForm");
    var aspList = aspElementById('lstCooperator');
    var selectList = document.getElementById('saveList');
    selectList.name = "saveList";
    for(var i = 0; i < aspList.options.length; i++){
        var opt = document.createElement("option");
        opt.name = aspList.options[i].name;
        opt.value = aspList.options[i].value; 
        opt.selected = true;
        selectList.options.add(opt);
    }
    */
    var insertHere = aspElementById('activity_id');
	//insertHere.parentNode.insertBefore(selectList,insertHere);
    //store the incidents associated with a complex
    var incidentTable = aspElementById('incidenttable').getElementsByTagName("TBODY")[0];
    var incList = document.getElementById('incList');
    var incidents = incidentTable.getElementsByTagName("TR");
    incList.name = "incList";
    
    for(var j=1; j<incidents.length; j++){
        var val = incidents[j].id.replace("assoc","");
        val = val.replace("ctl00_PageContent_","");
        var opt = document.createElement("option");
        opt.name = val;
        opt.value = val;
        opt.selected= true;
        incList.options.add(opt);
    }
	insertHere.parentNode.insertBefore(incList,insertHere);
}

//displays the availabe incidents table
function showAva(){
        aspElementById('avaTable').style.display = '';
        var mytable=aspElementById('avaTable');
        myr=mytable.getElementsByTagName('tr');
        while(myr.length > 1){
                mytable.deleteRow(myr.length-1)
        } 

        getAvaIncidents();
        return false;
}

//AJAX call to get the Availavle incidents 
function getAvaIncidents(){
    var val = aspElementById('cboFires').value
    xmlHttp=GetXmlHttpObject()
	if (xmlHttp==null){
 	    alert ("Browser does not support HTTP Request")
 	    return false;
    }
	var url="json_activity.aspx"
	url=url+"?record_id="+val
	url=url+"&action=get_incident_by_area"
	url=url+"&sid="+Math.random()
	xmlHttp.onreadystatechange=loadAvaIncidents
	xmlHttp.open("GET",url,true)
	xmlHttp.send(null)
}

//Builds the available incidents table
function loadAvaIncidents() { 
    if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete"){ 
        if(xmlHttp.responseText!=""){
            if(xmlHttp.responseText!="NULL"){
                var incidentTable = aspElementById('incidenttable').getElementsByTagName("TBODY")[0];
                var incidentRows = incidentTable.getElementsByTagName("TR");
                
                var myObject =  JSON.parse(xmlHttp.responseText);
                var add = true;
                for(var i=0; i<myObject.length; i++){
                    add = true;
                    if(aspElementById('incident_id').value == myObject[i].incidentId){
                        add = false;
                    }
                    for(var j=0; j<incidentRows.length; j++){
                        var iId = incidentRows[j].id.replace("assoc","").replace("ctl00_PageContent_","");
                        if(iId == myObject[i].incidentId){
                           add = false;
                        }
                    }
                    if(add == true){
                        var assoc = aspElementById('avaTable').getElementsByTagName("TBODY")[0];
                        var assocRows = assoc.getElementsByTagName("TR");
                        for(var k=0; k<assocRows.length; k++){
                            var aId = assocRows[k].id.replace("pl","").replace("ctl00_PageContent_","");
                            if(aId == myObject[i].incidentId){
                                add = false;
                            }
                        }
                    }
                    if(add == true){ 
                        var tbody = aspElementById('avaTable').getElementsByTagName("TBODY")[0];
                        var row = document.createElement("TR")
                        row.id = "pl"+myObject[i].incidentId
                        if( i%2 == 0 ){
                            row.className = "item_alt"
                            row.onmouseover = function () {this.className = 'item_alt_hover';}
                            row.onmouseout = function () {this.className = 'item_alt';}
                        }
                        else{
                            row.className = "item"
                            row.onmouseover = function () {this.className = 'item_hover';}
                            row.onmouseout = function () {this.className = 'item';}
                        }
                        var td1 = document.createElement("TD")
                        td1.appendChild(document.createTextNode(myObject[i].state + "-" + trim(myObject[i].fnumber.substring(0,3)) + "-" + trim(myObject[i].fnumber.substring(3,10))))
                        var td2 = document.createElement("TD")
                        if (trim(myObject[i].reportedDtm) == '01/01/0001'){
                            td2.appendChild (document.createTextNode(""))
                        }
                        else{
                            td2.appendChild (document.createTextNode(myObject[i].reportedDtm))
                        }
                        var td3 = document.createElement("TD")
                        td3.appendChild (document.createTextNode(myObject[i].name))
                        td3.style.textAlign = "left"
                        var td4 = document.createElement("TD")
                        if(myObject[i].ownership != null && myObject[i].ownership != "null"){
                            td4.appendChild (document.createTextNode(myObject[i].ownership))
                        }
                        else{
                            td4.appendChild (document.createTextNode(""))
                        }
                        var td5 = document.createElement("TD")
                        td5.appendChild (document.createTextNode(myObject[i].acres))
                        var td6 = document.createElement("TD")
                        if(myObject[i].cause != null && myObject[i].cause != "null"){
                            td6.appendChild (document.createTextNode(myObject[i].cause))
                        }
                        else{
                            td6.appendChild (document.createTextNode(""))
                        }
                        var td7 = document.createElement("TD")
                        td7.style.textAlign = "center";
                        var plusImg = new Image();
                        plusImg.src = "images/plus_sign.gif";
                        plusImg.id = "plus" + myObject[i].incidentId;
                        plusImg.style.height = "20px";
                        plusImg.style.width = "20px";
                        plusImg.onclick = function(){ addIncidentToComplex(this); }
                        td7.appendChild (plusImg);
                     
                        row.appendChild(td1);
                        row.appendChild(td2);
                        row.appendChild(td3);
                        row.appendChild(td4);
                        row.appendChild(td5);
                        row.appendChild(td6);
                        row.appendChild(td7);
                      
                        tbody.appendChild(row);
                    }
                }
            }
        }
    }
}

//javascript to move an incident from the available table to the associated one
function addIncidentToComplex(img){
    var myTable=aspElementById('avaTable');
    var incidentTable=aspElementById('incidenttable').getElementsByTagName("TBODY")[0];
    var oldRow = img.parentNode.parentNode
    var newRow = document.createElement("TR");
    var oldCells = oldRow.getElementsByTagName("td");
    newRow.id = "assoc" + img.id.replace("plus","");
    for(var i=0; i<oldCells.length; i++){
        var cell = document.createElement("td");
        if(i != 6){
            cell.innerHTML = oldCells[i].innerHTML;
            if(i == 4){
                if(trim(aspElementById('txtTotalAcres').value) == 0){
                    aspElementById('txtTotalAcres').value = 0
                }
                aspElementById('txtTotalAcres').value = parseFloat(aspElementById('txtTotalAcres').value) + parseFloat(oldCells[i].innerHTML);
            }
        }
        else{
            var minusImg = new Image();
            minusImg.src = "images/minus_sign.gif";
            minusImg.id = "minus" + img.id.replace("plus","");
            minusImg.style.height = "20px";
            minusImg.style.width = "20px";
            minusImg.onclick = function(){ removeIncidentFromComplex(this); }
            cell.style.textAlign = "center";
            cell.appendChild (minusImg);
        }
        newRow.appendChild(cell); 
    }
    incidentTable.appendChild(newRow);
    myTable.deleteRow(img.parentNode.parentNode.rowIndex);
    styleTable(incidentTable);
    styleTable(myTable);
    if(aspElementById('incident_id').value > 0){
        ajaxIncidentToComplex(aspElementById('incident_id').value,img.id.replace("plus",""))
    }
    else{
    }
}

//AJAX call to save add an incident to a complex
function ajaxIncidentToComplex(cId,iId){
    xmlHttp=GetXmlHttpObject()
	if (xmlHttp==null){
 	    alert ("Browser does not support HTTP Request")
 	    return
    }
	var url="json_activity.aspx"
	url=url+"?record_id="+cId
	url=url+"&incident_id="+iId
	url=url+"&action=save_incident_to_complex"
	url=url+"&sid="+Math.random()
	xmlHttp.onreadystatechange=saveIncidentToComplexComplete
	xmlHttp.open("GET",url,true)
	xmlHttp.send(null)

}
function saveIncidentToComplexComplete(){
    if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete"){ 
        if(xmlHttp.responseText!=""){
            if(xmlHttp.responseText!="NULL"){
            }
            else{
                alert('Error adding incident to complex!')
            }
        }
    }
}

//ajax call to remove the incident from the complex in the database
function ajaxRemoveIncidentFromComplex(iId){
    xmlHttp=GetXmlHttpObject()
	if (xmlHttp==null)
 {
 	alert ("Browser does not support HTTP Request")
 	return
 }
	var url="json_activity.aspx"
	url=url+"?record_id="+iId
	url=url+"&action=remove_incident_from_complex"
	url=url+"&sid="+Math.random()
	xmlHttp.onreadystatechange=removeIncidentFromComplexComplete
	xmlHttp.open("GET",url,true)
	xmlHttp.send(null)
}

function removeIncidentFromComplexComplete(){
    if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete"){ 
        if(xmlHttp.responseText!=""){
            if(xmlHttp.responseText!="NULL"){
            }
            else{
                alert('Error removing incident from complex!')
            }
        }
    }
}

//removes an incident from a complex
function removeIncidentFromComplex(img){
    var removeId = img.id.replace("minus","").replace("ctl00_PageContent_","");
    var remRow = img.parentNode.parentNode
    aspElementById('txtTotalAcres').value = parseFloat(aspElementById('txtTotalAcres').value) - parseFloat(remRow.cells[4].innerHTML);
    var avaTable = aspElementById('avaTable');
    var incidentTable=aspElementById('incidenttable');
    incidentTable.deleteRow(remRow.rowIndex);
    ajaxRemoveIncidentFromComplex(removeId);
}

//re applies styles to the tables after a row is added or removed
function styleTable(tab){
     var rows = tab.getElementsByTagName("tr");
     var skipOne = 0;
     for(var i=1; i<rows.length; i++){
        if(rows[i].style.display == 'none'){
           if(skipOne == 0){
            skipOne = 1;
           }
           else{
            skipOne  = 0;
           } 
        }
        if( (i%2 == 1 && skipOne == 0) || (i%2==0 && skipOne == 1) ){
            rows[i].className = "item_alt"
            rows[i].onmouseover = function () {this.className = 'item_alt_hover';}
            rows[i].onmouseout = function () {this.className = 'item_alt';}
        }
        else{
            rows[i].className = "item"
            rows[i].onmouseover = function () {this.className = 'item_hover';}
            rows[i].onmouseout = function () {this.className = 'item';}
        }
     }
}

//toggle fieleds not needed for complexes and vice versa
function toggleComplexes(){
    var boxVal = aspElementById('chkComplex').checked;
    if(boxVal == true){
        aspElementById('cboCause').selectedIndex =  0;
        aspElementById('cboUnit').disabled = true;
        aspElementById('txtUnitNum').disabled = true;
        aspElementById('cboCause').disabled =  true;
        aspElementById('lat_deg').disabled =  true;
        aspElementById('lat_min').disabled =  true;
        aspElementById('long_deg').disabled =  true;
        aspElementById('long_min').disabled =  true;
        aspElementById('legal_qtr').disabled =  true;
        aspElementById('legal_sec').disabled =  true;
        aspElementById('legal_town').disabled =  true;
        aspElementById('legal_range').disabled =  true;
        //start here
        aspElementById('cboUnit').className = "disabled";
        aspElementById('txtUnitNum').className = "disabled";
        aspElementById('cboCause').className = "disabled";
        aspElementById('lat_deg').className = "disabled";
        aspElementById('lat_min').className = "disabled";
        aspElementById('long_deg').className = "disabled";
        aspElementById('long_min').className = "disabled";
        aspElementById('legal_qtr').className = "disabled";
        aspElementById('legal_sec').className = "disabled";
        aspElementById('legal_town').className = "disabled";
        aspElementById('legal_range').className = "disabled";
        
        aspElementById('activity').style.display = 'none';
        aspElementById('incidents').style.display = '';
        aspElementById('btnNewActivity').value = "Add New Incident (To this complex)";
    }
    else{
        aspElementById('cboUnit').disabled = false;
        aspElementById('txtUnitNum').disabled = false;
        aspElementById('txtCooperator').disabled = false;
        aspElementById('txtDate').disabled = false;
        aspElementById('txtTime').disabled = false;
        aspElementById('txtRemarks').disabled = false;
        aspElementById('chkISC209').disabled = false;
        aspElementById('chkBill').disabled = false;
        aspElementById('chkCostShare').disabled = false;
        
        aspElementById('cboCause').disabled =  false;
        aspElementById('lat_deg').disabled =  false;
        aspElementById('lat_min').disabled =  false
        aspElementById('long_deg').disabled =  false;
        aspElementById('long_min').disabled =  false
        aspElementById('legal_qtr').disabled =  false;
        aspElementById('legal_sec').disabled =  false;
        aspElementById('legal_town').disabled =  false;
        aspElementById('legal_range').disabled =  false;
        
        aspElementById('cboUnit').className = "";
        aspElementById('txtUnitNum').className = "";
        aspElementById('txtCooperator').className = "";
        aspElementById('txtDate').className = "";
        aspElementById('txtTime').className = "";
        aspElementById('txtRemarks').className = "";
        aspElementById('chkISC209').className = "";
        aspElementById('chkBill').className = "";
        aspElementById('chkCostShare').className = "";
        aspElementById('cboCause').className = "";
        aspElementById('lat_deg').className = "";
        aspElementById('lat_min').className = "";
        aspElementById('long_deg').className = "";
        aspElementById('long_min').className = "";
        aspElementById('legal_qtr').className = "";
        aspElementById('legal_sec').className = "";
        aspElementById('legal_town').className = "";
        aspElementById('legal_range').className = "";
        
        aspElementById('activity').style.display = '';
        aspElementById('incidents').style.display = 'none';
        aspElementById('btnNewActivity').value = "New Activity";
    }
}

//Sets the dispatch based on the user role selected, some roles are dispatch depenedend
//Some are not
function setDispatch() {
    var sIndex = aspElementById('rdoRole').selectedIndex;
    var roleListVal = aspElementById('rdoRole').options[sIndex].value;
    var dispatchList = aspElementById('office');
    var perDispatch = aspElementById('perDispatch')
    var foundIt = false;
    for (var i = 0; i< perDispatch.length; i++){
        if(perDispatch.options[i].value == roleListVal){
            dispatchList.selectedIndex = 0;
            dispatchList.disabled = true;
            dispatchList.className = "disabled"
            foundIt = true;
        }
    }
    if(foundIt == false){
        dispatchList.disabled = false;
        dispatchList.className = "";
    }
}

//Get a browser indepened XMLHTTP Object
function GetXmlHttpObject(){
var xmlHttp=null;
try {
 // Firefox, Opera 8.0+, Safari
 xmlHttp=new XMLHttpRequest();
 } catch (e) {
 //Internet Explorer
 try {
  xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
  } catch (e) {
  xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
 }
return xmlHttp;
}

//AJAX call to get the activity they click on and load it 
function loadActivity(id) { 
	xmlHttp=GetXmlHttpObject()
	if (xmlHttp==null){
 	    alert ("Browser does not support HTTP Request")
 	    return
    }
	var url="json_activity.aspx"
	url=url+"?record_id="+id
	url=url+"&action=load_activity"
	url=url+"&sid="+Math.random()
	xmlHttp.onreadystatechange=loadActivityAction
	xmlHttp.open("GET",url,true)
	xmlHttp.send(null)
}

var removeRole;
var removeArea;
var removeUnitArea;

var firstTime = true;
var role = 0;
var unit = 0;
var area = 0;
var unitNum = "";
var sabhrs =  ""; 
var remarks = "";
var txtdate = "";
var txttime = "";
var cooperator= "";
var bill = "";
var costshare = "";
var isc209 = "";

function loadActivityAction() { 
    if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete"){ 
        if(xmlHttp.responseText!=""){
            if(xmlHttp.responseText!="NULL"){
                firstTime = false;
                var activity_disabled = false
                //Get the JSON back, and parse it to a JavaScript Object (Unmarshall it)
                var foundIt = false
                var myObject =  JSON.parse(xmlHttp.responseText);
                
                if (trim(myObject.primaryYN) == "y"){
                    aspElementById('primary_yn').checked = true;
                    aspElementById('primary_yn').defaultChecked = true
                    aspElementById('initial_primary').value = "Y";
                    aspElementById('initial_primary').defaultValue = "Y";
                }
                else{
                    aspElementById('primary_yn').checked = false;
                    aspElementById('primary_yn').defaultChecked = false;
                    aspElementById('initial_primary').value = "N";
                    aspElementById('initial_primary').defaultValue = "N";
                }
                /*
                var areaSelect = aspElementById('areaList');
                var areaOptions = areaSelect.options;
                if (removeArea!=null){
                     areaSelect.remove(removeArea);  
                     removeArea = null
                }
                for (var i = 0; i<areaOptions.length; i++){
                    if(areaOptions[i].value == myObject.area){
                        areaOptions[i].selected = true;
                        area = i;
                        foundIt = true
                        break;
                    }
                }
                if (foundIt == false){
                    if(trim(myObject.area) != ''){
                        var areaOption = document.createElement('option');
                        areaOption.text = myObject.area
                        areaOption.value = myObject.area;
                        areaOptions.add(areaOption);
                        areaOption.selected = true
                        areaSelect.appendChild(areaOption);
                        areaSelect.disabled = true;
                        activity_disabled = true;
                        
                        areaSelect.className = "disabled";
                        removeArea = areaSelect.length - 1
                        area = areaSelect.length - 1
                        //aspElementById('disabled').value = 'y' 
                    }
                    else{
                        area = 0
                        areaOptions[0].selected = true
                    }
                }
                else{
                    foundIt = false;
                }
                */
                var roleSelect = aspElementById('cboRole');
                var roleOptions = roleSelect.options;
                if (removeRole!=null){
                     roleSelect.remove(removeRole);  
                     removeRole = null
                }
                for (var i = 0; i<roleOptions.length; i++){
                    if(roleOptions[i].value == myObject.activityRole){
                        roleOptions[i].selected = true;
                        roleOptions[i].defaultSelected = true;
                        foundIt = true
                        role = i;
                        break;
                    }
                }
                if (foundIt == false){
                    if(trim(myObject.activityRole) != ''){
                        var roleOption = document.createElement('option');
                        roleOption.text = myObject.roleDescription;
                        roleOption.value = myObject.activityRole;
                        roleOptions.add(roleOption);
                        roleOption.selected = true;
                        roleOptions.defaultSelected = true;
                        roleSelect.appendChild(roleOption);
                        roleSelect.disabled = true
                        activity_disabled = true
                        roleSelect.className = "disabled";
                        //aspElementById('disabled').value = 'y' 
                        removeRole = roleSelect.length - 1
                        role = roleSelect.length - 1
                    }
                    else{
                        role = 0
                        roleOptions[0].selected = true
                        roleOptions[0].defaultSelected = true
                    }
                }
                else{
                    foundIt = false;
                }
                /*
                var unitAreaSelect = aspElementById('cboUnit');
                var unitAreaOptions = unitAreaSelect.options;
                if (removeUnitArea!=null){
                     unitAreaSelect.remove(removeUnitArea);  
                     removeUnitArea = null
                }
                for (var i = 0; i<unitAreaOptions.length; i++){
                    if(unitAreaOptions[i].value == myObject.unitArea){
                        unitAreaOptions[i].selected = true;
                        foundIt = true;
                        unit = i;
                        break;
                    }
                }
                if (foundIt == false){
                    if(trim(myObject.unitArea) != ''){
                        //This needs more rigorus testing
                        var unitAreaOption= document.createElement('option');
                        unitAreaOption.text = myObject.unitArea;
                        unitAreaOption.value = myObject.unitArea
                        unitAreaOptions.add(unitAreaOption);
                        unitAreaOption.selected = true
                        unitAreaSelect.appendChild(unitAreaOption);
                        unitAreaSelect.disabled = true
                        activity_disabled = true
                        unitAreaSelect.className = "disabled";
                        removeUnitArea = unitAreaSelect.length - 1
                        unit = unitAreaSelect.length - 1
                        //aspElementById('disabled').value = 'y' 
                    }
                    else{
                        unit = 0
                        unitAreaOptions[0].selected = true
                    }
                }
                else{
                    foundIt = false;
                }
                */
                //Isn't this cool?
                if(trim(myObject.isc209YN) == "y"){
                    aspElementById('chkISC209').checked = true
                    aspElementById('chkISC209').defaultChecked = true
                    isc209 = "y"
                }
                else{
                    aspElementById('chkISC209').checked = false
                    aspElementById('chkISC209').defaultChecked = false
                    isc209 = ""
                } 
                if(trim(myObject.billYN) == "y" || trim(myObject.billYN) == "Y"){
                    aspElementById('chkBill').checked = true
                    aspElementById('chkBill').defaultChecked = true
                    bill = "y"
                }
                else{
                    aspElementById('chkBill').checked = false
                    aspElementById('chkBill').defaultChecked = false
                    bill = ""
                } 
                if(trim(myObject.costshareYN) == "y"){
                    aspElementById('chkCostShare').checked = true
                    aspElementById('chkCostShare').defaultChecked = true
                    costshare = "y"
                }
                else{
                    aspElementById('chkCostShare').checked = false
                    aspElementById('chkCostShare').defaultChecked = false
                    costshare = ""
                } 
                if(myObject.warnings != null && myObject.warnings != ""){
                    //If we have warnings, show the row!
                    aspElementById('warningsActivity').style.display = ""
                    count = 0;
                    pos = myObject.warnings.indexOf("<li>");
                    while ( pos != -1 ) {
                        count++;
                        pos = myObject.warnings.indexOf("<li>",pos+1);
                    }
                    aspElementById('warningActivityDiv').innerHTML = "<ul>" + myObject.warnings + "</ul>";
                    aspElementById('hlShowHideActivity').innterHTML = "(Show)"
                    aspElementById('lblActivityErrorCount').innerHTML = count
                    aspElementById('warningActivityDiv').style.display = "none"
                }
                else{
                    aspElementById('warningsActivity').style.display = "none"
                }
                
                if(myObject.sabhrs != null){
                    aspElementById('txtSabhrs').value = myObject.sabhrs;
                    aspElementById('generated_sabhrs').value = myObject.sabhrs
                    aspElementById('txtSabhrs').defaultValue = myObject.sabhrs;
                    aspElementById('generated_sabhrs').defaultValue = myObject.sabhrs
                }
                else{
                    aspElementById('txtSabhrs').value = ""
                    aspElementById('generated_sabhrs').value = ""
                    aspElementById('txtSabhrs').defaultValue = ""
                    aspElementById('generated_sabhrs').defaultValue = ""
                }
                sabhrs = myObject.sabhrs;
                if(sabhrs == null){
                    sabhrs = ""
                }
                aspElementById('txtDate').value = myObject.activityDate;
                aspElementById('txtDate').defaultValue = myObject.activityDate;
                txtdate = myObject.activityDate
                if(txtdate == null){
                    txtdate = ""
                }
                aspElementById('txtTime').value = myObject.activityTime;
                aspElementById('txtTime').defaultValue = myObject.activityTime;
                txttime = myObject.activityTime;
                if(txttime == null){
                    txttime = ""
                }
                aspElementById('txtCooperator').value = myObject.cooperator;
                aspElementById('txtCooperator').defaultValue = myObject.cooperator;
                cooperator = myObject.cooperator;
                if(cooperator == null){
                    cooperator = ""
                }
                /*
                aspElementById('txtUnitNum').value = myObject.unitNumber;
                unitNum = myObject.unitNumber
                if(unitNum == null){
                    unitNum = ""
                }
                */
                aspElementById('txtRemarks').value = myObject.remarks;
                aspElementById('txtRemarks').defaultValue = myObject.remarks;
                remarks = myObject.remarks;
                if(remarks == null){
                    remarks = ""
                }
                aspElementById('activity_id').value = myObject.activityId;
                aspElementById('activity_id').defaultValue = myObject.activityId;
                
                var dis = aspElementById('disabled').value 
                var locked = false;
                if (trim(myObject.sabhrs_locked) == "y"){
                    locked = true;
                    aspElementById('txtSabhrs').readOnly = true;
                    aspElementById('txtSabhrs').className = "disabled";
                }      
                else{
                    aspElementById('txtSabhrs').readOnly = false;
                    aspElementById('txtSabhrs').className = "";
                }
                if((activity_disabled==true && aspElementById('cboDispatch').value != "")  ||  dis == 'y' ||  myObject.voided == true || aspElementById('voided').value == "y"){
                    if(myObject.voided == true){
                        aspElementById('voidActivityRow').style.display="";
                    }
                    else{
                        aspElementById('voidActivityRow').style.display="none";
                    }
                    //aspElementById('areaList').disabled = true;
                    //aspElementById('cboUnit').disabled = true;
                    //aspElementById('txtUnitNum').disabled = true;
                    aspElementById('cboRole').disabled = true;
                    aspElementById('txtSabhrs').readOnly = true;
                    aspElementById('txtCooperator').disabled = true;
                    aspElementById('txtDate').disabled = true;
                    aspElementById('txtTime').disabled = true;
                    aspElementById('txtRemarks').disabled = true;
                    aspElementById('chkISC209').disabled = true;
                    aspElementById('chkBill').disabled = true;
                    aspElementById('chkCostShare').disabled = true;
                    aspElementById('btnSave').disabled = true;
                    aspElementById('primary_yn').disabled = true;
                    
                    //aspElementById('areaList').className = "disabled";
                    //aspElementById('cboUnit').className = "disabled";
                    //aspElementById('txtUnitNum').className = "disabled";
                    aspElementById('cboRole').className = "disabled";
                    aspElementById('txtSabhrs').className = "disabled";
                    aspElementById('txtCooperator').className = "disabled";
                    aspElementById('txtDate').className = "disabled";
                    aspElementById('txtTime').className = "disabled";
                    aspElementById('txtRemarks').className = "disabled";
                    aspElementById('chkISC209').className = "disabled";
                    aspElementById('chkBill').className = "disabled";
                    aspElementById('chkCostShare').className = "disabled";
                    aspElementById('btnSave').className = "disabled";
                    aspElementById('primary_yn').className = "disabled";
                }
                else{
                    aspElementById('voidActivityRow').style.display="none";
                    
                    //aspElementById('areaList').disabled = false;
                    //aspElementById('cboUnit').disabled = false;
                    //aspElementById('txtUnitNum').disabled = false;
                    aspElementById('cboRole').disabled = false;
                    
                    //aspElementById('areaList').className = "";
                    //aspElementById('cboUnit').className = "";
                    //aspElementById('txtUnitNum').className = "";
                    aspElementById('cboRole').className = "";
                    if(locked == false){
                        aspElementById('txtSabhrs').readOnly = false;
                        aspElementById('txtSabhrs').className = "";
                    }
                    aspElementById('txtCooperator').disabled = false;
                    aspElementById('txtDate').disabled = false;
                    aspElementById('txtTime').disabled = false;
                    aspElementById('txtRemarks').disabled = false;
                    aspElementById('chkISC209').disabled = false;
                    aspElementById('chkBill').disabled = false;
                    aspElementById('chkCostShare').disabled = false;
                    aspElementById('btnSave').disabled = false;
                    aspElementById('primary_yn').disabled = false;
                    
                    aspElementById('txtCooperator').className = "";
                    aspElementById('txtDate').className = "";
                    aspElementById('txtTime').className = "";
                    aspElementById('txtRemarks').className = "";
                    aspElementById('chkISC209').className = "";
                    aspElementById('chkBill').className = "";
                    aspElementById('chkCostShare').className = "";
                    aspElementById('btnSave').className = "";
                    aspElementById('primary_yn').className = "";
                }
                populateActivityChangeLog(myObject.activityId);
    		}   
    		else{
    			alert('Error: Error Loading Activity');	
    		}
        }	
    }
}

//AJAX call to get the change log when they click on a new activity
function populateActivityChangeLog(id){
     xmlHttp=GetXmlHttpObject()
	    if (xmlHttp==null){
            alert ("Browser does not support HTTP Request")
            return
        }
	    var url="json_activity.aspx"
	    url=url+"?record_id="+id
	    url=url+"&action=get_activity_change_log"
	    url=url+"&sid="+Math.random()
	    xmlHttp.onreadystatechange=populateActivityChangeLogAction
	    xmlHttp.open("GET",url,true)
	    xmlHttp.send(null)

}

function populateActivityChangeLogAction(){
    if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete"){ 
        if(xmlHttp.responseText!=""){
            if(xmlHttp.responseText!="NULL"){
                //Remove the stuff in the changelog and add new changelog stuff to it
                var activityChangeLog = aspElementById('activityChangeLog').getElementsByTagName("TBODY")[0];
                var rows = activityChangeLog.getElementsByTagName("TR")
                while(rows.length > 1){
                    activityChangeLog.deleteRow(rows.length - 1);
                    rows = activityChangeLog.getElementsByTagName("TR")
                }
                var myObject =  JSON.parse(xmlHttp.responseText);
                var lineCtr = 1;
                for(var i = 0; i<myObject.length; i++){
                    if(myObject[i].username != null){
                        var row = document.createElement("TR");
                        var cell = document.createElement("TD");
                        cell.className = "smallfont";
                        cell.noWrap =  true;
                        cell.vAlign = "top";
                        if(lineCtr < 15){
                            cell.innerHTML = '<a href="#" onclick="return openActivityLog(' + myObject[i].activityId + ',' + myObject[i].historyId + ');">' + myObject[i].modDate + ' ' + myObject[i].username + '</a>';
                        }
                        else{
                            cell.innerHTML = '<a href="#" onclick="return openActivityLog(' + myObject[i].activityId + ',0);">More...</a>';
                        } 
                        row.appendChild(cell);
                        activityChangeLog.appendChild(row);
                        if(lineCtr >= 15){
                            break;
                        }
                        lineCtr = lineCtr + 1
                    }
                }
            }
        }
    }
}
/*
//remove a list item from the cooperator select list
function removeSelectedItem(){
    var aspList = aspElementById('lstCooperator');
    for(var i = 0; i<aspList.options.length; i++){
        if(aspList.options[i].selected == true){
            aspList.remove(i);
           }
    }
}
*/
//AJAX call to void a user role
function voidUserRole(id){
    confirm_box = confirm("Press OK to remove this role, Cancel to abort.");
    if(confirm_box == true){
        xmlHttp=GetXmlHttpObject()
	    if (xmlHttp==null){
            alert ("Browser does not support HTTP Request")
            return
        }
	    var url="json_activity.aspx"
	    url=url+"?record_id="+id
	    url=url+"&action=void_user_role"
	    url=url+"&sid="+Math.random()
	    xmlHttp.onreadystatechange=roleDeleteAction
	    xmlHttp.open("GET",url,true)
	    xmlHttp.send(null)
	}
}
function roleDeleteAction() { 
    if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete"){ 
        if(xmlHttp.responseText!=""){
            if(xmlHttp.responseText!="NULL"){
                //alert(xmlHttp.responseText);
                aspElementById('Row'+xmlHttp.responseText).style.display = 'none';
                styleTable(aspElementById('roleTable'));
            }
        }
    }
}
//AJAX to void the current incident,then disable it
function voidActivity(id){
    var theActs = aspElementById('ddlActivity');
    var primaryFlag = false;
    var unvoidedCnt = 0;
    for (var i =0; i<theActs.length; i++){
        var ary = theActs.options[i].text.split(",");
        var optId = theActs.options[i].value;
        var optF1000 = ary[0];
        var optPrimary =  ary[1];
        var optVoid =  ary[2];
        if(optId == id && optPrimary == 'y'){
            primaryFlag = true;
        }
        if(optVoid!='y'){
            unvoidedCnt++;
        } 
    }
    if(unvoidedCnt <=1){
        alert('Cannot void last remaining unvoided activity');
        return false;
    }
    if(primaryFlag == true){
        var f1000Ctr = 0;
        var idToSet = 0;
        for(var i = 0; i<theActs.length; i++){
            var ary = theActs.options[i].text.split(",");
            var optId = theActs.options[i].value;
            var optF1000 = ary[0];
            var optPrimary =  ary[1];
            var optVoid =  ary[2];
            if(optId != id && optVoid!='y' && optF1000=='y'){
                f1000Ctr++;
                idToSet = optId;
            }
        }
        if(f1000Ctr == 1){
            aspElementById('idToSet').value = idToSet;
        }
        else if(f1000Ctr > 1){
            alert('Cannot void the primary activity. Make another activity primary then void');
            return false;
        }
    }
    confirm_box = confirm("Press OK to void this activity, Cancel to abort.");
    if(confirm_box == true){
        vxmlHttp=GetXmlHttpObject();
	    if (vxmlHttp==null){
            alert ("Browser does not support HTTP Request")
            return
        }
	    var url="json_activity.aspx"
	    url=url+"?record_id="+id
	    url=url+"&action=void_activity"
	    url=url+"&id_for_primary=" + aspElementById('idToSet').value
	    url=url+"&sid="+Math.random()
	    vxmlHttp.onreadystatechange=voidActivityAction
	    vxmlHttp.open("GET",url,true)
	    vxmlHttp.send(null)
	}
}
function voidActivityAction() { 
    if (vxmlHttp.readyState==4 || vxmlHttp.readyState=="complete"){ 
        if(vxmlHttp.responseText!=""){
            if(vxmlHttp.responseText!="NULL"){
                if(aspElementById('activity_id').value == vxmlHttp.responseText){
                    aspElementById('voidActivityRow').style.display="";
                    //aspElementById('areaList').disabled = true;
                    //aspElementById('cboUnit').disabled = true;
                    //aspElementById('txtUnitNum').disabled = true;
                    aspElementById('cboRole').disabled = true;
                    aspElementById('txtSabhrs').readOnly = true;
                    aspElementById('txtCooperator').disabled = true;
                    aspElementById('txtDate').disabled = true;
                    aspElementById('txtTime').disabled = true;
                    aspElementById('txtRemarks').disabled = true;
                    aspElementById('chkISC209').disabled = true;
                    aspElementById('chkBill').disabled = true;
                    aspElementById('chkCostShare').disabled = true;
                    aspElementById('btnSave').disabled = true;
                    aspElementById('primary_yn').disabled = true;
                    //aspElementById('areaList').className = "disabled";
                    //aspElementById('cboUnit').className = "disabled";
                    //aspElementById('txtUnitNum').className = "disabled";
                    aspElementById('cboRole').className = "disabled";
                    aspElementById('txtSabhrs').className = "disabled";
                    aspElementById('txtCooperator').className = "disabled";
                    aspElementById('txtDate').className = "disabled";
                    aspElementById('txtTime').className = "disabled";
                    aspElementById('txtRemarks').className = "disabled";
                    aspElementById('chkISC209').className = "disabled";
                    aspElementById('chkBill').className = "disabled";
                    aspElementById('chkCostShare').className = "disabled";
                    aspElementById('btnSave').className = "disabled";
                    aspElementById('primary_yn').className = "disabled";
                }
                var recId = vxmlHttp.responseText;
                var myRow = aspElementById('Row'+recId)
                var myCells = myRow.getElementsByTagName("td");
                for (var i=0; i<myCells.length; i++){
                    myCells[i].style.textDecoration="line-through"
                    if(i == 5){
                        var imgs = myCells[i].getElementsByTagName("img");
                        for (var j=0; j<imgs.length; j++){
                            myCells[i].removeChild(imgs[j]);
                        }
	                    var img = new Image();
	                    img.src = "images/plus_sign.gif";
                        img.id = "plus" + recId;
	                    img.style.height = "16px";
	                    img.style.width = "16px";
	                    var isMSIE = /*@cc_on!@*/false;
	                    if(isMSIE){
                            img.onclick = function(){event.cancelBubble=true; unvoidActivity(recId)}
                        }
                        else{
                            img.onclick = function(e){e.cancelBubble=true; unvoidActivity(recId)}
                        }
                        myCells[i].appendChild(img);
                    }
                }
                if(aspElementById('activity_id').value == recId){
                    populateActivityChangeLog(recId);
                }
                //TODO: NEED TO DETERMINE WHAT IF ANY ACTIVITY TO SET AS THE PRIMARY ONE
                //BE SURE TO CLEAR THE idToSet hidden value after its set.
                
                var theActs = aspElementById('ddlActivity')
                for (var i = 0; i<theActs.length; i++){
                    var ary = theActs.options[i].text.split(",");
                    var optId = theActs.options[i].value;
                    var optF1000 = ary[0];
                    var optPrimary =  'n';
                    var optVoid =  'y';
                    if(optId == recId){
                        theActs.options[i].text = optF1000 + ',' + optPrimary + ',' + optVoid;
                    }
                }
                redrawActivitiesTable();
            }
            else{
                alert("ERROR: Could not void activity");
            }
        }
    }
}
//AJAX to void the current incident,then disable it
function unvoidActivity(id){
    confirm_box = confirm("Press OK to unvoid this activity, Cancel to abort.");
    if(confirm_box == true){
        uvxmlHttp=GetXmlHttpObject();
	    if (uvxmlHttp==null){
            alert ("Browser does not support HTTP Request")
            return
        }
	    var url="json_activity.aspx"
	    url=url+"?record_id="+id
	    url=url+"&action=unvoid_activity"
	    url=url+"&sid="+Math.random()
	    uvxmlHttp.onreadystatechange=unvoidActivityAction
	    uvxmlHttp.open("GET",url,true)
	    uvxmlHttp.send(null)
	}
}
function unvoidActivityAction() { 
    if (uvxmlHttp.readyState==4 || uvxmlHttp.readyState=="complete"){ 
        if(uvxmlHttp.responseText!=""){
            if(uvxmlHttp.responseText!="NULL"){
                if(aspElementById('activity_id').value == uvxmlHttp.responseText){
                    aspElementById('voidActivityRow').style.display="none";
                    //aspElementById('areaList').disabled = false;
                    //aspElementById('cboUnit').disabled = false;
                    //aspElementById('txtUnitNum').disabled = false;
                    aspElementById('cboRole').disabled = false;
                    aspElementById('txtSabhrs').readOnly = false;
                    aspElementById('txtCooperator').disabled = false;
                    aspElementById('txtDate').disabled = false;
                    aspElementById('txtTime').disabled = false;
                    aspElementById('txtRemarks').disabled = false;
                    aspElementById('chkISC209').disabled = false;
                    aspElementById('chkBill').disabled = false;
                    aspElementById('chkCostShare').disabled = false;
                    aspElementById('btnSave').disabled = false;
                    aspElementById('primary_yn').disabled = false;                  
                    //aspElementById('areaList').className = "";
                    //aspElementById('cboUnit').className = "";
                    //aspElementById('txtUnitNum').className = "";
                    aspElementById('cboRole').className = "";
                    aspElementById('txtSabhrs').className = "";
                    aspElementById('txtCooperator').className = "";
                    aspElementById('txtDate').className = "";
                    aspElementById('txtTime').className = "";
                    aspElementById('txtRemarks').className = "";
                    aspElementById('chkISC209').className = "";
                    aspElementById('chkBill').className = "";
                    aspElementById('chkCostShare').className = "";
                    aspElementById('btnSave').className = "";
                    aspElementById('primary_yn').className = "";
                }
                var recId = uvxmlHttp.responseText;
                var myRow = aspElementById('Row' + recId);
                var myCells = myRow.getElementsByTagName("td");
                for (var i=0; i<myCells.length; i++){
                    myCells[i].style.textDecoration=""
                    if(i == 5){
                        var imgs = myCells[i].getElementsByTagName("img");
                        for (var j=0; j<imgs.length; j++){
                            myCells[i].removeChild(imgs[j]);
                        }
	                    var img = new Image();
	                    img.src = "images/remove.gif";
                        img.id = "remove" + recId;
	                    img.style.height = "16px";
	                    img.style.width = "16px";
	                    var isMSIE = /*@cc_on!@*/false;
	                    if(isMSIE){
                            img.onclick = function(){event.cancelBubble=true; voidActivity(recId)}
                        }
                        else{
                            img.onclick = function(e){e.cancelBubble=true; voidActivity(recId)}
                        }
                        
                        myCells[i].appendChild(img);
                    }
                }
                if(aspElementById('activity_id').value == recId){
                    populateActivityChangeLog(recId);
                }
                var theActs = aspElementById('ddlActivity')
                for (var i = 0; i<theActs.length; i++){
                    var ary = theActs.options[i].text.split(",");
                    var optId = theActs.options[i].value;
                    var optF1000 = ary[0];
                    var optPrimary =  ary[1];
                    var optVoid =  'n';
                    if(optId == recId){
                        theActs.options[i].text = optF1000 + ',' + optPrimary + ',' + optVoid;
                    }
                }
                redrawActivitiesTable(); 
            }
            else{
                alert("ERROR: Could not unvoid activity");
            }
        }
    }
}

function redrawActivitiesTable(){
  xmlHttp=GetXmlHttpObject()
	    if (xmlHttp==null){
            alert ("Browser does not support HTTP Request")
            return
        }
	    var url="json_activity.aspx"
	    url=url+"?record_id="+aspElementById('incident_id').value
	    url=url+"&action=get_role_table"
	    url=url+"&sid="+Math.random()
	    xmlHttp.onreadystatechange=redrawActivitiesTableAction
	    xmlHttp.open("GET",url,true)
	    xmlHttp.send(null)

}

function redrawActivitiesTableAction(){
    if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete"){ 
        if(xmlHttp.responseText!=""){
            if(xmlHttp.responseText!="NULL"){
                var myObject=JSON.parse(xmlHttp.responseText)
                for(var i = 0; i<myObject.length; i++){
                    if(aspElementById('activity_id').value == myObject.activityId){
                        if(myObject.primaryYN=='y'){
                            aspElementById('primary_yn').checked = true
                        }
                        else{
                            aspElementById('primary_yn').checked = false
                        }
                    }
                    var theActs = aspElementById('ddlActivity')
                    //Reset the stored values of the the rows
                    for (var j=0; j<theActs.length; j++){
                        var optId = theActs.options[j].value;
                        if(optId == myObject[i].activityId){
                            theActs.options[j].text = myObject[i].f1000YN + "," + myObject[i].primaryYN + "," + myObject[i].voidYN; 
                        }
                    }
                    //add/remove the primary checkbox on the appropriate table row
                    var actTab = aspElementById('activitiesTable');
                    var rows = actTab.getElementsByTagName("tr")
                    for (var j = 1; j<rows.length; j++){
                        var theCells = rows[j].getElementsByTagName("td")
                        var theId = rows[j].id.replace('ctl00_PageContent_Row','');
                        var thePrimaryCell = theCells[4];
                        if(myObject[i].activityId == theId){
                            thePrimaryCell.innerHTML = '';
                            if(myObject[i].primaryYN == 'y'){
	                            var img = new Image();
	                            img.src = "images/check.gif";
	                            img.style.height = "16px";
	                            img.style.width = "16px";
	                            img.style.marginLeft = "auto";
	                            img.style.marginRight = "auto";
	                            img.style.display = "block";
                                thePrimaryCell.appendChild(img);
                            }
                        }
                        
                    }
                    
                 }
                 aspElementById('idToSet').value='';
            }
        }
    }
}

//Self explanatory
function confirmVoid(){
    confirm_box = confirm("Press OK to void this incident, Cancel to abort.");
    return confirm_box;
}

//makes sure they arent trying to convert an incident with more than 1 
//activity to a complex 
function checkIt(){
    var checkBox = aspElementById('chkComplex');
    if(checkBox.checked == true){
        var activityTable = aspElementById('activitiesTable').getElementsByTagName("TBODY")[0];
        var rows = activityTable.getElementsByTagName("TR");
        var rowCount = 0;
        for (var i=1; i<rows.length; i++){
            if(rows[i].cells[0].style.textDecoration != "line-through"){
                rowCount++;
            }
        }
        if(rowCount>1){
            alert("Cannot convert to complex, incident has multiple activities");
            checkBox.checked = false;
            return false;
        }
    }
    return true;
    
}

function singleRoleCheck(){
    var singleRoleList = aspElementById('singleOnly');
    var sIndex  = aspElementById('cboRole').selectedIndex
    var currentRole = aspElementById('cboRole').options[sIndex].value;
    var activity_id = aspElementById('activity_id').value
    var activityTable = aspElementById('activitiesTable').getElementsByTagName("TBODY")[0];
    var rows = activityTable.getElementsByTagName("TR");
    var rowCount = 0;
    for (var i=1; i<rows.length; i++){
        if(rows[i].cells[0].style.textDecoration != "line-through"){
            rowCount++;
        }
    }
    //Add 1 if this is a new activity
    if(trim(activity_id) == ''){
        rowCount++ 
    }
    if(rowCount > 1){
        for (var i=0; i<singleRoleList.length; i++){
            if(singleRoleList.options[i].value == currentRole){
                alert("Cannot add this role, there are multiple activites associted with this incident");
                aspElementById('cboRole').selectedIndex = 0;
                return false;
            }
        }
    }
    return true;
}

//Makes sure we can go ahead and save the form
function validate_form(){
    setIgnoreSaveCheck();
    var txtSabhrs = trim(aspElementById('txtSabhrs').value)
    var role = trim(aspElementById('cboRole').value);
    var cause = trim(aspElementById('cboCause').value);
    if (role == 'DAM' && cause == 4) {
        alert('Cannont have Direct AB-Misc Role with False Alarm');
        unSetIgnoreSaveCheck();
        return false;
    }
    if(txtSabhrs.length>0){
        if (txtSabhrs.substring(0, 1) != '9' && txtSabhrs.substring(0, 1) != '7' && txtSabhrs.substring(0, 1) != '8' && txtSabhrs.substring(0, 1) != '5' && txtSabhrs.substring(0, 1) != '4') {
            alert('ERROR: SABHRS number Starts with ' + txtSabhrs.substring(0,1) + '. Must start with 4, 7, 8 or 9.');
            unSetIgnoreSaveCheck();
            return false;
        }
    }
    var sIndex = aspElementById('cboDispatch').selectedIndex
    if(sIndex == null || trim(aspElementById('cboDispatch').options[sIndex].value) == ''){
        alert('Please set your dispatch center!');
        unSetIgnoreSaveCheck();
        return false;
    }
    sIndex = aspElementById('cboState').selectedIndex
    var cboState = trim(aspElementById('cboState').options[sIndex].value)
    
    var txtFnumber = trim(aspElementById('txtFnumber').value)
    var txtPrimaryIncidentNum =  lpad(trim(aspElementById('txtPrimaryIncidentNum').value),6,'0')
    
    var incidentNum = txtFnumber+txtPrimaryIncidentNum
    if(parseInt(ltrimZeros(txtPrimaryIncidentNum)) == 0 || isNaN(parseInt(ltrimZeros(txtPrimaryIncidentNum)))){
        alert("Incident number " + txtPrimaryIncidentNum + " is invalid");
        unSetIgnoreSaveCheck();
        return false;
    }
    if(trim(cboState) == "" || trim(txtFnumber)== ""  || trim(txtPrimaryIncidentNum) == "" ){
        alert("Incident number is incomplete, cannot save!");
        unSetIgnoreSaveCheck();
        return false;
    }
    var triggerPopup = false
    var reason = "The following fields have changed:"
    var rolechanged = false;
    var incidentchanged = false;
    var areachanged = false;
    var sabhrschanged = false;
    
    if (firstTime == true){
        curElem = aspElementById('areaList')
        if(curElem.options[0].defaultSelected!=true && has_cbo_changed(curElem,true)){
            triggerPopup = true
            areachanged = true;   
        }
        curElem = aspElementById('cboRole')
        if(curElem.options[0].defaultSelected!=true && has_cbo_changed(curElem,true)){
            triggerPopup = true
            rolechanged = true
        }
        curElem = aspElementById('txtSabhrs')
        if(curElem.value!=null && curElem.defaultValue!=null && trim(curElem.defaultValue)!= '' && curElem.value!=curElem.defaultValue){
            triggerPopup = true
            sabhrschanged = true
        }
    }
    else{
        var elem = aspElementById('areaList')
        if(area!=0 && elem.selectedIndex!=area){
            triggerPopup = true
            areachanged = true;   
        } 
        var elem = aspElementById('cboRole')
        if(role !=0 && elem.selectedIndex!=role){
            triggerPopup = true
            rolechanged = true;   
        } 
        elem = aspElementById('txtSabhrs')
        if(sabhrs!=0 && elem.value!=sabhrs){
            triggerPopup = true
            sabhrschanged = true
        } 
        elem = aspElementById('cboState')
        if(elem.selectedIndex!=null && has_cbo_changed(elem,true) && elem.options[0].defaultSelected == false){
            triggerPopup = true
            incidentchanged = true;
        } 
        elem = aspElementById('txtPrimaryIncidentNum')
        if(elem.value!=null && elem.defaultValue!=null && elem.value!=elem.defaultValue && trim(elem.defaultValue)!=''){
            triggerPopup = true
            incidentchanged = true
        } 
        elem = aspElementById('txtFnumber')
        if(elem.value!=null && elem.defaultValue!=null && elem.value!=elem.defaultValue && trim(elem.defaultValue)!=''){
            triggerPopup = true
            incidentchanged = true
        }
    }
    if (firstTime == true){ 
        curElem = aspElementById('txtRemarks')
        if(curElem.value!=null && curElem.value!=curElem.defaultValue){
            triggerPopup = false
        }
    }
    else{
        elem = aspElementById('txtRemarks')
        if(elem.value!=remarks){
            triggerPopup = false
        }
    }
    if(rolechanged == true){
        reason += " Activity Role, " 
    }
    if(incidentchanged == true){
        reason += " Incident Number, " 
    }
    if(sabhrschanged == true){
        reason += " SABHRS, " 
    } 
    if(areachanged == true){
        reason += " Area, " 
    }
    reason += " Please enter a remark about this change before saving."
    if(triggerPopup == true){
        alert(reason);
        unSetIgnoreSaveCheck();
        return false;
    }
    if(validIniNum == false){
        //The server side check will get it if the ajax couldnt verify it.
        if(is_ready == true){
            alert("Incident Number is already in use");
            unSetIgnoreSaveCheck();
            return false
        }
    }
    return true;
}
 
 //AJAX call to validate the incident number, fires after an onchange
 //but doesnt error until they press save, sets globals 
 function validateIncidentNum(){
    var sIndex = aspElementById('cboState').selectedIndex
    var cboState = trim(aspElementById('cboState').options[sIndex].value)
    
    var txtFnumber = rpad(trim(aspElementById('txtFnumber').value), 4, ' ');
    var txtPrimaryIncidentNum =  lpad(trim(aspElementById('txtPrimaryIncidentNum').value),6,'0')
    
    var incidentNum = txtFnumber+txtPrimaryIncidentNum
    validIniNum = false;
    is_ready = false;
    
     xmlHttp=GetXmlHttpObject()
	    if (xmlHttp==null){
            alert ("Browser does not support HTTP Request")
            return
        }
	    var url="json_activity.aspx"
	    url=url+"?record_id="+incidentNum
	    url=url+"&action=validate_incident_num"
	    url=url+"&incident_id="+trim(aspElementById('incident_id').value)
	    url=url+"&state="+cboState
	    url=url+"&sid="+Math.random()
	    xmlHttp.onreadystatechange=validateIncidentNumAction
	    xmlHttp.open("GET",url,true)
	    xmlHttp.send(null)
}
function validateIncidentNumAction(){
    if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete"){ 
        if(xmlHttp.responseText!=""){
            if(xmlHttp.responseText=="OK"){
                validIniNum = true;
            }
        }
        is_ready = true;
    }
}

//Naughty function... This is used to wait for a few milliseconds
//on the AJAX call to verify the incident number to complete if the
//have pressed the save button and the AJAX call hasnt completed
function pausecomp(millis){
    var date = new Date();
    var curDate = null;

    do{
        curDate = new Date();
    }while(curDate-date < millis);
} 

//Sorting 
var currentCol = 0;
var previousCol = -1;
var direction = 0;
var prevTable = -1;

//comparison functions for determining sort order based on the data type
function CompareAlpha(a, b) {
	if (a[currentCol] < b[currentCol]) { return -1; }
	if (a[currentCol] > b[currentCol]) { return 1; }
	return 0;
}

function CompareAlphaIgnore(a, b) {
	strA = a[currentCol].toLowerCase();
	strB = b[currentCol].toLowerCase();
	if (strA < strB) { return -1; }
	else {
		if (strA > strB) { return 1; }
		else { return 0; }
	}
}

function CompareDate(a, b) {
	// this one works with date formats conforming to Javascript specifications, e.g. m/d/yyyy
	datA = new Date(a[currentCol]);
	datB = new Date(b[currentCol]);
	if (datA < datB) { return -1; }
	else {
		if (datA > datB) { return 1; }
		else { return 0; }
	}
}

function CompareNumeric(a, b) {
	//window.alert ("CompareNumeric");
	numA = a[currentCol]
	numB = b[currentCol]
	if (isNaN(numA)) { return 0;}
	else {
		if (isNaN(numB)) { return 0; }
		else { return numA - numB; }
	}
}
//wrapper to the sort_table function for each table in the app
function f300_list_sort(myCol, myType) {
    var listTable= aspElementById('listTable').getElementsByTagName("TBODY")[0];
    sort_table(listTable,myCol,myType,1);
    return false;
}

function sort_activity_table(myCol, myType) {
    var activityTable= aspElementById('activity').getElementsByTagName("TBODY")[0];
    sort_table(activityTable,myCol,myType,2);
    return false;
}

function sort_associated_incidents(myCol, myType) {
    var assocTable= aspElementById('incidents').getElementsByTagName("TBODY")[0];
    sort_table(assocTable,myCol,myType,3);
    return false;
}

function sort_available_incidents(myCol, myType) {
    var avaTable= aspElementById('avaTable').getElementsByTagName("TBODY")[0];
    sort_table(avaTable,myCol,myType,4);
    return false;
}

function sort_user_listing(myCol, myType) {
    var avaTable= aspElementById('tblList').getElementsByTagName("TBODY")[0];
    sort_table(avaTable,myCol,myType,5);
    return false;
}

function sort_user_dispatch(myCol, myType) {
    var avaTable= aspElementById('roleTable').getElementsByTagName("TBODY")[0];
    sort_table(avaTable,myCol,myType,6);
    return false;
}
function f300_sabhrs_sort(myCol, myType) {
    var listTable = aspElementById('tblSabhrs').getElementsByTagName("TBODY")[0];
    sort_table(listTable,myCol,myType,7);
    return false;
}

//Table sorting function
function sort_table(mySource,myCol,myType,currTable){
    //Reset the "ugh" globals if the tables have changes
    if(currTable != prevTable ){
        currentCol = 0;
        previousCol = -1;
        direction = 0;
        prevTable = currTable
    }
    var rows = mySource.getElementsByTagName("TR");
	var myRows = rows.length
	var myCols = rows[0].cells.length;
	currentCol = myCol
	myArray = new Array(myRows)
	for (i=1; i < myRows; i++) {
		myArray[i-1] = new Array(myCols+2)
		for (j=0; j < myCols; j++) {
			myArray[i-1][j] = rows[i].cells[j].innerHTML;
		}
		myArray[i-1][myCols] = rows[i].onclick
		myArray[i-1][myCols+1] = rows[i].cells[0].style.textDecoration
	}

	if (myCol == previousCol ){
	    // Re-write the table contents in reverse
	    var k = 1;
	    for (i=myRows-2; i >= 0; i--) {
	    	for (j=0; j < myCols; j++) {
	    		mySource.rows[k].cells[j].innerHTML = myArray[i][j]
	    	    mySource.rows[k].cells[j].style.textDecoration = myArray[i][myCols+1]
	    	}
	    	mySource.rows[k].onclick = myArray[i][myCols]
	    	k++
	    }
	        var img = mySource.rows[0].cells[myCol].getElementsByTagName("img")[0];
	        mySource.rows[0].cells[myCol].removeChild(img);
	        img = new Image();
	        if(direction == "asc"){
	            img.src = "images/sort_desc.gif";
	            direction = "desc"
	        }
	        else{
	            img.src = "images/sort_asc.gif";
	            direction = "asc"
	        }
	        mySource.rows[0].cells[myCol].appendChild(img);
	        
	}
	else {
		switch (myType) {
			case "a":
				myArray.sort(CompareAlpha);
				break;
			case "ai":
				myArray.sort(CompareAlphaIgnore);
				break;
			case "d":
				myArray.sort(CompareDate);
				break;
			case "n":
				myArray.sort(CompareNumeric);
				break;
			default:
				myArray.sort()
		}
	    for (i=1; i < myRows; i++) {
	    	for (j=0; j < myCols; j++) {
	    		mySource.rows[i].cells[j].innerHTML = myArray[i-1][j]
	    	    mySource.rows[i].cells[j].style.textDecoration = myArray[i-1][myCols+1]
	    	}
	    	mySource.rows[i].onclick = myArray[i-1][myCols]
	    }
	    img = new Image();
	    img.src = "images/sort_asc.gif";
	    mySource.rows[0].cells[myCol].appendChild(img)
	    direction = "asc";
	    if(previousCol != -1){
	        var img2 = mySource.rows[0].cells[previousCol].getElementsByTagName("img")[0];
	        mySource.rows[0].cells[previousCol].removeChild(img2);
	    }
	}
	previousCol = myCol; // remember the current sort column for the next pass
	//Ajax call to set the sort direction and column 
        if(currTable == 1){
            xmlHttp=GetXmlHttpObject()
	        if (xmlHttp==null){
                alert ("Browser does not support HTTP Request")
                return
            }
	        var url="json_activity.aspx"
	        url=url+"?sortColumn="+myCol
	        url=url+"&sortType="+myType
	        url=url+"&sortDirection="+direction
	        url=url+"&action=set_sort"
	        url=url+"&sid="+Math.random()
	        xmlHttp.onreadystatechange=function(){};
	        xmlHttp.open("GET",url,true)
	        xmlHttp.send(null)
        }	
	return false;
}

//Set the Lat/Long values in the form to the converted ones in the converter window
function nris_latlong_submit() {

  var baseform = document.getElementById("aspnetForm")
  var querystr = "";
  var lat_deg, lat_min, long_deg, long_min;

  if(baseform.ctl00_PageContent_lat_deg != null){
    lat_deg = baseform.ctl00_PageContent_lat_deg.value;
    lat_min = baseform.ctl00_PageContent_lat_min.value;
    long_deg = baseform.ctl00_PageContent_long_deg.value;
    long_min = baseform.ctl00_PageContent_long_min.value;
  }

  else{
    lat_deg = rtrim(document.getElementById("ctl00_PageContent_lat_deg").innerHTML);
    lat_min = rtrim(document.getElementById("ctl00_PageContent_lat_min").innerHTML);
    long_deg = rtrim(document.getElementById("ctl00_PageContent_long_deg").innerHTML);
    long_min = rtrim(document.getElementById("ctl00_PageContent_long_min").innerHTML);
  }

  if(lat_deg!="" && lat_min!="" && long_deg!="" && long_min!=""){
    querystr ="LatDD2=" + lat_deg + "&LatMM2=" + lat_min + 
              "&LongDD2=" + long_deg + "&LongMM2=" + long_min + 
              "&Cmd3=Locate+D%2FM.mm";
  }
  nris_submit(querystr)
  unSetIgnoreSaveCheck();
}

 
//Section Township Range window
function nris_trs_submit(){
  var baseform = document.getElementById("aspnetForm")
  var querystr = "";
  var section, twn, rng;

  if(baseform.ctl00_PageContent_legal_sec != null){
    section = baseform.ctl00_PageContent_legal_sec.value;
    twn = baseform.ctl00_PageContent_legal_town.value;
    rng = baseform.ctl00_PageContent_legal_range.value;
  }
  else{
    section = rtrim(document.getElementById("ctl00_PageContent_legal_sec").innerHTML);
    twn = rtrim(document.getElementById("ctl00_PageContent_legal_town").innerHTML);  // A space is added at the end
    rng = rtrim(document.getElementById("ctl00_PageContent_legal_range").innerHTML);     // for display purpose
  }

  if(section.length>0 && twn.length>1 && rng.length>1)
    querystr = "TN=" + twn.substr(0, twn.length-1) + 
               "&N=" + twn.substr(twn.length-1) + 
               "&RG=" + rng.substr(0, rng.length-1) + 
               "&E=" + rng.substr(rng.length-1) +
               "&S=" + section + "&sCmd=Locate+TRS";
  nris_submit(querystr)

}

 

//open up the 
function nris_submit(querystr){

  window.open("http://maps2.nris.mt.gov/scripts/esrimap.dll?name=LocMap&Cmd=Map&" + 
              "L=-44887.4692205943&R=1041064.3842784&B=-226169.339744266&T=759948.290825176&" + 
              "Datum=NAD83&MapSize=Small&" + querystr, "",
              "scrollbars=yes,menubar=no,status=no,toolbar=no,location=no,width=800,height=710");
}

//AJAX call to get the unit number
function unit_changed(){
    if( trim(aspElementById('txtUnitNum').value) !=''){
        if (confirm("Press OK if you want to generate a new unit number.")==false){
            return ;
        }
    }
    var sIndex = aspElementById('cboUnit').selectedIndex
    var unitVal = aspElementById('cboUnit').options[sIndex].text
     xmlHttpDisp=GetXmlHttpObject()
	    if (xmlHttpDisp==null){
            alert ("Browser does not support HTTP Request")
            return
        }
	    var url="json_activity.aspx"
	    url=url+"?record_id="+unitVal
	    url=url+"&action=get_next_unit_number"
	    url=url+"&sid="+Math.random()
	    xmlHttpDisp.onreadystatechange=setUnitNumber
	    xmlHttpDisp.open("GET",url,true)
	    xmlHttpDisp.send(null)
        
}
function setUnitNumber(){
    if (xmlHttpDisp.readyState==4 || xmlHttpDisp.readyState=="complete"){ 
        if(xmlHttpDisp.responseText!=""){
            if(xmlHttpDisp.responseText!="NULL"){
                aspElementById('txtUnitNum').value = xmlHttpDisp.responseText
            }
        }
    }
}

//AJAX call to  get the dispatch number
function dispatch_changed(){
    setUnits();
/*
    var sIndex = aspElementById('cboDispatch').selectedIndex
    var dispatchVal = aspElementById('cboDispatch').options[sIndex].text
    if( trim(aspElementById('txtDispatchNum').value) != ''){
        if(trim(dispatchVal) == ''){
            setUnits()
            return true;
        }
        if (confirm("Do you want to generate a new dispatch number?")==false){
            setUnits()
            return true;
        }
    }
    xmlHttp=GetXmlHttpObject()
	if (xmlHttp==null){
        alert ("Browser does not support HTTP Request")
        return
    }
	var url="json_activity.aspx"
	url=url+"?record_id="+dispatchVal
	url=url+"&action=get_next_dispatch_number"
	url=url+"&sid="+Math.random()
	xmlHttp.onreadystatechange=setDispatchNumber
	xmlHttp.open("GET",url,true)
	xmlHttp.send(null)
	*/
}
function setDispatchNumber(){
    if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete"){ 
        if(xmlHttp.responseText!=""){
            if(xmlHttp.responseText!="NULL"){
                aspElementById('txtDispatchNum').value = xmlHttp.responseText
            }
      //      setUnits();
        }
    }
}

//AJAX call to get the numeric part of the incident number
function incident_changed(){
    aspElementById('txtFnumber').value = aspElementById('txtFnumber').value.toUpperCase(); 
    if( trim(aspElementById('txtPrimaryIncidentNum').value) !=''){
        if (confirm("Press OK if you want to generate a new incident number.")==false){
            validateIncidentNum();
            return true;
        }
    }
    var sIndex = aspElementById('cboState').selectedIndex
    var stateVal = aspElementById('cboState').options[sIndex].value
    var fnumberVal = aspElementById('txtFnumber').value
    aspElementById('txtFnumber').value
    sIndex = aspElementById('cboUnit').selectedIndex
    var unitVal = aspElementById('cboUnit').options[sIndex].value
    if(trim(stateVal) == '' || trim(fnumberVal) == ''){
        return false; 
    }
    
     xmlHttp=GetXmlHttpObject()
	    if (xmlHttp==null){
            alert ("Browser does not support HTTP Request")
            return
        }
	    var url="json_activity.aspx"
	    url=url+"?record_id="+stateVal
	    url=url+"&area_id="+fnumberVal
	    url=url+"&unit_id="+unitVal
	    url=url+"&action=get_next_incident_number"
	    url=url+"&sid="+Math.random()
	    xmlHttp.onreadystatechange=setIncidentNumber
	    xmlHttp.open("GET",url,true)
	    xmlHttp.send(null)
}
function setIncidentNumber(){
    if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete"){ 
        if(xmlHttp.responseText!=""){
            if(xmlHttp.responseText!="NULL"){
                aspElementById('txtPrimaryIncidentNum').value = xmlHttp.responseText
            }
        }
    }
}

//AJAX call to get Sabhrs number
function get_sabhrs(ask){
    if(aspElementById('txtSabhrs').readOnly == true){
        return
    }
    sIndex = aspElementById('cboRole').selectedIndex
    var roleVal = trim(aspElementById('cboRole').options[sIndex].value)
    
    var sIndex = aspElementById('cboUnit').selectedIndex
    var unitVal = trim(aspElementById('cboUnit').options[sIndex].value)
    
    sIndex = aspElementById('areaList').selectedIndex
    var areaVal = trim(aspElementById('areaList').options[sIndex].value)
    
    if(ask != false){
        if( trim(aspElementById('txtSabhrs').value) !=''  && roleVal != null && trim(roleVal)!="" && areaVal!=null && trim(areaVal)!=""){
         if (confirm("Press OK if you want to generate a new SABHRS number.")==false){
             return true;
         }
        }
    }
    
    if(roleVal == '' || areaVal == ''){
        return;
    }
    xmlHttp=GetXmlHttpObject()
	if (xmlHttp==null){
        alert ("Browser does not support HTTP Request")
        return
    }
    var url="json_activity.aspx"
	    url=url+"?record_id="+roleVal
	    url=url+"&area_id="+areaVal
	    url=url+"&unit_id="+unitVal
	    url=url+"&action=get_sabhrs_number"
	    url=url+"&sid="+Math.random()
	    xmlHttp.onreadystatechange=setSabhrsNumber
	    xmlHttp.open("GET",url,true)
	    xmlHttp.send(null)
}

function setSabhrsNumber(){
    if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete"){ 
        if(xmlHttp.responseText!=""){
            if(xmlHttp.responseText!="NULL"){
                aspElementById('txtSabhrs').value = xmlHttp.responseText
                aspElementById('generated_sabhrs').value = xmlHttp.responseText
                hideSabhrsPick();
            }
            else{
                var sIndex = aspElementById('cboRole').selectedIndex
                var roleVal = trim(aspElementById('cboRole').options[sIndex].value)
                sIndex = aspElementById('areaList').selectedIndex
                var areaVal = trim(aspElementById('areaList').options[sIndex].value)
                sIndex = aspElementById('cboUnit').selectedIndex
                var unitVal = trim(aspElementById('cboUnit').options[sIndex].value)
                if(roleVal == 'MIS' || roleVal == 'PFM' || roleVal == 'RHB'){
                    if(areaVal != null && trim(areaVal)!=''){
                        ajaxFillPopupAndShow(areaVal,unitVal);
                    }
                }
                else{
                    hideSabhrsPick();
                }
            }
        }
    }
}

function ajaxFillPopupAndShow(areaVal,unitVal){
     xmlHttp=GetXmlHttpObject()
	if (xmlHttp==null){
        alert ("Browser does not support HTTP Request")
        return
    }
    var url="json_activity.aspx"
	    url=url+"?record_id=dummyval"
	    url=url+"&area_id="+areaVal
	    url=url+"&unit_id="+unitVal
	    url=url+"&action=get_popup_values"
	    url=url+"&sid="+Math.random()
	    xmlHttp.onreadystatechange=fillPopupAndShow
	    xmlHttp.open("GET",url,true)
	    xmlHttp.send(null)
}
function fillPopupAndShow(){
    if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete"){ 
        if(xmlHttp.responseText!=""){
            if(xmlHttp.responseText!="NULL"){
                var myObject=JSON.parse(xmlHttp.responseText)
                aspElementById('nextDirect').innerHTML = myObject.direct;
                aspElementById('nextCA').innerHTML = myObject.assist;
                document.getElementById('pickSabhrs').style.visibility = 'visible';
                showPickSabhrs();
            }
        }
    }
}

//left pad with zeros
function lpad(str,len,ch){
    while(str.length < len){
        str = ch + str
    } 
    return str
}

//right pad with spaces
function rpad(str,len,ch){
    while(str.length < len){
        str = str + ch;
    } 
    return str
}

//next 2 functions get what fields should be disabled via an ajax call when an
//activity role is changed
function roleListChanged(){
    if(singleRoleCheck() == false){
        return false;
    }
    var rIndex = aspElementById('cboRole').selectedIndex
    var roleValue = aspElementById('cboRole').options[rIndex].value
    enableForm();
    if( rIndex != 0 ){
        xmlHttp=GetXmlHttpObject()
	    if (xmlHttp==null){
            alert ("Browser does not support HTTP Request")
            return false;
        }
        var url="json_activity.aspx"
	        url=url+"?record_id="+roleValue
	        url=url+"&action=disable_fields_by_role"
	        url=url+"&sid="+Math.random()
	        xmlHttp.onreadystatechange=disableRoleFields
	        xmlHttp.open("GET",url,true)
	        xmlHttp.send(null)
    }
	if(set_primary_yn()== true){
	    get_sabhrs(true); 
	    return true;
	}
	else{
	    return false;
	}
}


function disableRoleFields(){
    if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete"){ 
        if(xmlHttp.responseText!=""){
            if(xmlHttp.responseText!="NULL"){
                var myObject=JSON.parse(xmlHttp.responseText)
                for (var i=0; i<myObject.length; i++){
                     if(myObject[i] != null){
                        var id = 'ctl00_PageContent_' + myObject[i]
                        document.getElementById(id).disabled = true
                        document.getElementById(id).className = "disabled";
                     }
                }
            }
        }
    }
}

//Enables Everything used  to revert an Activity Role being changed and disabling fields
function enableForm() {
    var count = document.forms[0].elements.length;
    for (i=0; i<count; i++){
        var element = document.forms[0].elements[i]; 
	    element.disabled=false; 
	    element.className = "";
    }
    //Turn off the non complex fields
    if(aspElementById('chkComplex').checked == true){
        toggleComplexes();
    }
    //This is always disabled
    aspElementById('txtSizeClass').disabled = true
    aspElementById('txtSizeClass').className = "disabled";
}

//Workaround for a bug in IE that refuses to respect z-indexes on select lists
//have to block out the textboxes with an iframe
function showBSIFrame(){
    var escd = document.getElementById('extraStartCalDiv')
    var left =  escd.offsetLeft + 'px';
    var top = escd.offsetTop + 'px';
    var width = escd.offsetWidth + 'px'; 
    var height = escd.offsetHeight + 'px';
    
    var iframe = document.getElementById('bsIFrame');
    
    iframe.style.position = "absolute";
    iframe.style.left = left;
    iframe.style.top = top;
    iframe.style.width = width;
    iframe.style.height = height;
    document.getElementById('bsIFrame').style.display='block';
}

//makes the check boxes on the user page behave like radio buttons
function fixChecks(checkBox){
    var id = 'ctl00_PageContent_' + checkBox
    if (document.getElementById(id).checked == false){
        return
    }
    var elements =document.forms[0].elements
    var checks 
    for (var i = 0; i<elements.length; i++){
        if(elements[i].type == "checkbox" ){
            if(elements[i].id != id && elements[i].id != 'ctl00_PageContent_chkPending' && elements[i].id != 'ctl00_PageContent_chkActive'){
                elements[i].checked = false;
            }
        }   
    }
}

//For the Add New Incident to this complex button
function newActivityClick(){
    var val = aspElementById('btnNewActivity').value 
    var iniVal = aspElementById('incident_id').value
    if (val == "Add New Incident (To this complex)"){
        setIgnoreSaveCheck();
        var sc =save_check(false)
        var saveIt = aspElementById('saveIt');
    
        if(sc == true){
            saveIt.value = 'y'    
            return true;
        }
        else if (sc == false){
            if(trim(iniVal) == ""){
                alert("Cannot add incident to unsaved complex, please save this comples before adding new incidents");
                unSetIgnoreSaveCheck();
                return false;
            } 
            return true;
        }
        else{
            if(trim(iniVal) == ""){
                alert("Cannot add incident to unsaved complex, please save this comples before adding new incidents");
                unSetIgnoreSaveCheck();
                return false;
            } 
            if(confirm(sc)==true){
                setIgnoreSaveCheck();
                return true;
            }
            else{
                unSetIgnoreSaveCheck();
                return false;
            }
        }
    }
    else{
        return true;
    }
}
function backClick(){
    var val = aspElementById('btnBack').value 
    if (val ==  "<< Back to Complex"){
        setIgnoreSaveCheck();
        var sc =save_check(false)
        var saveIt = aspElementById('saveIt');
    
        if(sc == true){
            saveIt.value = 'y'    
            return true;
        }
        else if (sc == false){
            return true;
        }
        else{
            if(confirm(sc)==true){
                setIgnoreSaveCheck();
                return true;
            }
            else{
                unSetIgnoreSaveCheck();
                return false;
            }
        }
    }
    else{
        return true;
    }
}

function set_current(){
    var initialAcres = aspElementById('txtInitialAcres')
    var currentAcres = aspElementById('txtTotalAcres')
    
    if(trim(currentAcres.value)==''){
        currentAcres.value = initialAcres.value
    }
}

function set_fire_class(){
    var val = aspElementById('txtTotalAcres').value
    
    xmlHttp=GetXmlHttpObject()
	if (xmlHttp==null){
        alert ("Browser does not support HTTP Request")
        return
    }
    var url="json_activity.aspx"
	    url=url+"?record_id="+val
	    url=url+"&action=get_fire_class"
	    url=url+"&sid="+Math.random()
	    xmlHttp.onreadystatechange=set_fire_class_action
	    xmlHttp.open("GET",url,true)
	    xmlHttp.send(null)
}


function set_fire_class_action(){
    if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete"){ 
        if(xmlHttp.responseText!=""){
            if(xmlHttp.responseText!="NULL"){
                aspElementById('txtSizeClass').value = xmlHttp.responseText
            }
        }
   }
}

function pad_incident_num(){
    var pi = aspElementById('txtPrimaryIncidentNum')
    if (pi.value.length<6 && trim(pi.value)!=""){
        pi.value = lpad(pi.value,6, '0')
    }
}

function pad_dispatch_num(){
    var pi = aspElementById('txtDispatchNum')
    if (pi.value.length<6 && trim(pi.value)!=""){
        pi.value = lpad(pi.value,6,'0')
    }
}

function pad_unit_num(){
    var pi = aspElementById('txtUnitNum')
    if (pi.value.length<3 && trim(pi.value)!=""){
        pi.value = lpad(pi.value,3,'0')
    }
}

function set_area(){
    var areaBox = aspElementById('cboFnumber')
    var textBox = aspElementById('txtFnumber')
    var sIndex = areaBox.selectedIndex
    if(sIndex != 0){
        textBox.value = areaBox.options[sIndex].value
        areaBox.selectedIndex=0
    }   

}

function save_check_activity(aid){
    var formHasChanged = false;
    var curElem;   
    
    if (firstTime == true){
        /*
        curElem = aspElementById('areaList')
        if(curElem.selectedIndex!=null && has_cbo_changed(curElem,false)){
            formHasChanged = true;
        }
        curElem = aspElementById('cboUnit')
        if(curElem.selectedIndex!=null && has_cbo_changed(curElem,false)){
            formHasChanged = true;
        }
        curElem = aspElementById('txtUnitNum')
        if(curElem.value!=null && curElem.defaultValue!=null && curElem.value!=curElem.defaultValue){
            formHasChanged = true;
        }
        */
        curElem = aspElementById('cboRole')
        if(curElem.selectedIndex!=null && has_cbo_changed(curElem,false)){
            formHasChanged = true;
        }
        curElem = aspElementById('txtSabhrs')
        if(curElem.value!=null && curElem.defaultValue!=null && curElem.value!=curElem.defaultValue){
            formHasChanged = true;
        }
        curElem = aspElementById('txtRemarks')
        if(curElem.value!=null && curElem.defaultValue!=null && curElem.value!=curElem.defaultValue){
            formHasChanged = true;
        }
        curElem = aspElementById('txtDate')
        if(curElem.value!=null && curElem.defaultValue!=null && curElem.value!=curElem.defaultValue){
            formHasChanged = true;
        }
        curElem = aspElementById('txtTime')
        if(curElem.value!=null && curElem.defaultValue!=null && curElem.value!=curElem.defaultValue){
            formHasChanged = true;
        }
        curElem = aspElementById('txtCooperator')
        if(curElem.value!=null && curElem.defaultValue!=null && curElem.value!=curElem.defaultValue){
            formHasChanged = true;
        }
        curElem = aspElementById('chkBill')
        if(curElem.defaultChecked!=null && curElem.checked != curElem.defaultChecked){
            formHasChanged = true;
        }
        curElem = aspElementById('chkCostShare')
        if(curElem.defaultChecked!=null && curElem.checked != curElem.defaultChecked){
            formHasChanged = true;
        }
        curElem = aspElementById('chkISC209')
        if(curElem.defaultChecked!=null && curElem.checked != curElem.defaultChecked){
            formHasChanged = true;
        }
    }
    else{
        if (role != aspElementById('cboRole').selectedIndex){
            formHasChanged = true;
        }
        /*
        if (area != aspElementById('areaList').selectedIndex){
            formHasChanged = true;
        }
        if (unit != aspElementById('cboUnit').selectedIndex){
            formHasChanged = true;
        }
        if (aspElementById('txtUnitNum').value != unitNum){
            formHasChanged = true;
        }
        */
        if (aspElementById('txtRemarks').value != remarks){
            formHasChanged = true;
        }
        if (aspElementById('txtSabhrs').value != sabhrs){
            formHasChanged = true;
        }
        if (aspElementById('txtDate').value != txtdate){
            formHasChanged = true;
        }
        if (aspElementById('txtTime').value != txttime){
            formHasChanged = true;
        }
        if (aspElementById('txtCooperator').value != cooperator){
            formHasChanged = true;
        }
        if (aspElementById('chkBill').checked == true && bill == ""){
            formHasChanged = true;
        }
        else if (aspElementById('chkBill').checked == false && bill == "y"){
            formHasChanged = true;
        }
        if (aspElementById('chkCostShare').checked == true && costshare == ""){
            formHasChanged = true;
        }
        else if (aspElementById('chkCostShare').checked == false && costshare == "y"){
            formHasChanged = true;
        }
        if (aspElementById('chkISC209').checked == true && isc209 == ""){
            formHasChanged = true;
        }
        else if (aspElementById('chkISC209').checked == false && isc209 == "y"){
            formHasChanged = true;
        }
        /*
        if(aspElementById('cooperatorChanged') == 'y'){
            formHasChanged = true;
        }
        */
    }
    if(formHasChanged == true){
        if(confirm("Would you like to save your changes?") == true){
                aspElementById('load_after_save').value = aid
                aspElementById('btnSave').click()
                pausecomp(1500);
        }
        else{
            loadActivity(aid);
        }
    }
    else{
        loadActivity(aid);
    }
}

function aspElementById(id){
    return document.getElementById('ctl00_PageContent_'+id)
}

function setUnits(){
    var cboUnit = aspElementById('cboUnit');
    while(cboUnit.length>1){
        var i = cboUnit.length - 1
        cboUnit.remove(i);
    }
    xmlHttp=GetXmlHttpObject()
	if (xmlHttp==null){
        alert ("Browser does not support HTTP Request")
        return
    }
    var sIndex = aspElementById('cboDispatch').selectedIndex
    var val = aspElementById('cboDispatch').options[sIndex].value
    var url="json_activity.aspx"
	    url=url+"?record_id="+val
	    url=url+"&action=get_units_by_dispatch"
	    url=url+"&sid="+Math.random()
	    xmlHttp.onreadystatechange=set_units
	    xmlHttp.open("GET",url,true)
	    xmlHttp.send(null)
}


function set_units(){
    if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete"){ 
        if(xmlHttp.responseText!=""){
            if(xmlHttp.responseText!="NULL"){
                var cboUnit = aspElementById('cboUnit');
                var myObject  = JSON.parse(xmlHttp.responseText);
                for(var i = 0; i<myObject.length; i++){
                    if(myObject[i] != null && myObject[i] != 'null'){
                        var elOptNew = document.createElement('option');
                        elOptNew.text = myObject[i]
                        elOptNew.value = myObject[i]
                        try {
                            cboUnit.add(elOptNew, null); // standards compliant; doesn't work in IE
                            if(myObject.length == 2){
                                cboUnit.selectedIndex = 1;
                                unit_changed();
                            }
                        }
                        catch(ex) {
                            cboUnit.add(elOptNew); // IE only
                            if(myObject.length == 2){
                                cboUnit.selectedIndex = 1;
                                unit_changed();
                            }
                        }
                    }
                }
            }
            setAreas();
        }
   }
}

function setAreas(){
    var cboUnit = aspElementById('areaList');
    while(cboUnit.length>1){
        var i = cboUnit.length - 1
        cboUnit.remove(i);
    }
    xmlHttp=GetXmlHttpObject()
	if (xmlHttp==null){
        alert ("Browser does not support HTTP Request")
        return
    }
    var sIndex = aspElementById('cboDispatch').selectedIndex
    var val = aspElementById('cboDispatch').options[sIndex].value
    var url="json_activity.aspx"
	    url=url+"?record_id="+val
	    url=url+"&action=get_areas_by_dispatch"
	    url=url+"&sid="+Math.random()
	    xmlHttp.onreadystatechange=set_areas
	    xmlHttp.open("GET",url,true)
	    xmlHttp.send(null)
}


function set_areas(){
    if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete"){ 
        if(xmlHttp.responseText!=""){
            if(xmlHttp.responseText!="NULL"){
                var cboUnit = aspElementById('areaList');
                var myObject  = JSON.parse(xmlHttp.responseText);
                for(var i = 0; i<myObject.length; i++){
                    if(myObject[i] != null && myObject[i] != 'null'){
                        var elOptNew = document.createElement('option');
                        elOptNew.text = myObject[i]
                        elOptNew.value = myObject[i]
                        try {
                            cboUnit.add(elOptNew, null); // standards compliant; doesn't work in IE
                            if(myObject.length == 2){
                                cboUnit.selectedIndex = 1;
                            }
                        }
                        catch(ex) {
                            cboUnit.add(elOptNew); // IE only
                            if(myObject.length == 2){
                                cboUnit.selectedIndex = 1;
                            }
                        }
                    }
                }
            }
        }
   }
}

function add_acres(){
    var val1 = parseFloat(aspElementById('txtPrivateAcres').value)
    var val2 = parseFloat(aspElementById('txtStateAcres').value)
    var val3 = parseFloat(aspElementById('txtFederal').value)
    var val4 = parseFloat(aspElementById('txtOther').value)
    var total = parseFloat(aspElementById('txtTotalAcres').value)
    
    if(isNaN(val1) || val1 == null){
        val1 = 0
    }
    if(isNaN(val2) || val2 == null){
        val2 = 0
    }
    if(isNaN(val3) || val3 == null){
        val3 = 0
    }
    if(isNaN(val4) || val4 == null){
        val4= 0
    }
    if(isNaN(total) || total == null){
        total = 0
    }
    
    var sub = val1 + val2 + val3 + val4
    if (sub > 0){
        aspElementById('txtTotalAcres').value = sub
        get_decimal(aspElementById('txtTotalAcres'),2)
        set_fire_class();
    }
}

function check_tr(field){
  var val = field.value;
  
  val = val.toUpperCase();
  if((val.indexOf('.')>=0 && val.length==4) || val.length==2){
    val = "0" + val;
  }
  field.value = val;
}

function setStartDate(){
    if (aspElementById('incident_id') != null){
        if(trim(aspElementById('incident_id').value) != ''){
            return
        }
        var aDate  = aspElementById('txtDate').value
        aspElementById('txtStartDate').value = aDate
    }
}

function setStartTime(){
    var aDate  = aspElementById('txtTime').value
    
    aDate = aDate.toString();
    if(aDate.search(':') == -1){
        if(aDate.length == 3){
            aDate = aDate.substring(0,1) + ':' + aDate.substring(1,3)
            aspElementById('txtTime').value  = aDate
        }
        else if(aDate.length == 4){
            aDate = aDate.substring(0,2) + ':' + aDate.substring(2,4)
            aspElementById('txtTime').value  = aDate
        }
    }
    
    if(trim(aspElementById('incident_id').value) != ''){
        return
    }
    aspElementById('txtStartTime').value = aDate

}

function chooseIt(whichone){
    if(whichone == 'direct'){
        aspElementById('txtSabhrs').value = aspElementById('nextDirect').innerHTML;
    }
    else{
        aspElementById('txtSabhrs').value = aspElementById('nextCA').innerHTML;
    }
    var pop =  aspElementById('popup')
    pop.style.visibility='hidden';

}

function showPickSabhrs(){
    var pop =  aspElementById('popup')
    var contain = document.getElementById('contain')
    
   pop.style.left = (contain.offsetLeft + 50)+"px";
   pop.style.top = 150+"px";
   pop.style.visibility='visible';
}

function hideSabhrsPick(){
   document.getElementById('pickSabhrs').style.visibility = 'hidden';  
   aspElementById('popup').style.visibility='hidden';

}

function set_primary_yn(){
    var incidentId = trim(aspElementById('incident_id').value);
    var activityId = trim(aspElementById('activity_id').value);
    var theActs = aspElementById('ddlActivity');
    var theBox = aspElementById('primary_yn');
    
    if(incidentId == '' && activityId==''){
        if(isF1000Role()){
            theBox.checked = true;
            return true;
        }
        else{
            theBox.checked = false;
            return true;
        }
    }
    
    //Maybe the only f1000 role yet so we need to mark it
    else if(incidentId != ''){
        if(isF1000Role()){
            var foundPrimaryAct = false;
            for(var i =0; i<theActs.length; i++){
                
                var ary = theActs.options[i].text.split(",");
                var optId = theActs.options[i].value;
                var optF1000 = ary[0];
                var optPrimary =  ary[1];
                var optVoid =  ary[2];
                if(optVoid != 'y'){
                    if(trim(activityId)!= trim(optId)){
                        if(optPrimary == 'y'){
                            foundPrimaryAct = true;
                        }
                    }
                } 
            }
            if(foundPrimaryAct == false){
                theBox.checked = true;
            }
            else{
                theBox.checked = false;
            }
        }
        //Not an F1000 Role, not a new incident
        else{
            //if it wasnt checked, we dont care
            if(theBox.checked == true){
                var f1000Ctr = 0;
                var idToSet = '';
                for(var i = 0; i<theActs.length; i++){
                    var ary = theActs.options[i].text.split(",");
                    var optId = theActs.options[i].value;
                    var optF1000 = ary[0];
                    var optPrimary =  ary[1];
                    var optVoid =  ary[2];
                    if(optVoid != 'y' && optId != activityId){
                        if(optF1000 == 'y'){
                            f1000Ctr++;
                            idToSet = optId;
                        }
                    }
                }
                if(f1000Ctr>0){
                    if(f1000Ctr == 1){
                        aspElementById('idToSet').value = idToSet;
                    }
                    else{
                        alert('Cannot change this role to a non F1000 Role, set another role as primary first');
                        var theRoles = aspElementById('cboRole');
                        for(var i =0; i < theRoles.length; i++){
                            if(theRoles.options[i].defaultSelected == true){
                                theRoles.selectedIndex = i;
                                return false;
                            }
                        }
                        theRoles.selectedIndex = 0;
                        return false;
                    }
                }
                theBox.checked = false;
            }
        }
        //were're gonna return true so set the default
        var theRoles = aspElementById('cboRole');
        for(var i = 0; i<theRoles.length; i++){
           theRoles.options[i].defaultSelected = false;
           if(i == theRoles.selectedIndex){
                theRoles.options[i].defaultSelected = true;
          }
       }
    }
    return true;
}

function check_f1000_role(){
    var theBox = aspElementById('primary_yn')
    if(theBox.checked == true){
        if(!isF1000Role()){
            alert('Cannot set this role as primary, this is not a valid f1000 role!');
            theBox.checked = false;
            return false;
        }
    }
    else{
        var activityId = trim(aspElementById('activity_id').value)
        var theActs = aspElementById('ddlActivity')
        var primaryCtr = 0;
        var f1000Ctr = 0;
        var idToSet = "";
        for(var i = 0; i<theActs.length; i++){
            var ary = theActs.options[i].text.split(",");
            var optId = theActs.options[i].value;
            var optF1000 = ary[0];
            var optPrimary =  ary[1];
            var optVoid =  ary[2];
            if(optVoid != 'y' && optId != activityId){
                if(optPrimary == 'y'){
                    primaryCtr++;
                }
                if(optF1000 == 'y'){
                    f1000Ctr++;
                    idToSet = optId;
                }
            }
        }
        if(f1000Ctr == 0){
            if(isF1000Role()){
                alert('Unable to uncheck priamry, this is the only valid F1000 role!. Either change to a non F1000 role or create a new F1000 role and make it primary');
                theBox.checked = true;
                return false;
            }
            else{
                return true;
            }
        }
        else if(f1000Ctr == 1){
            aspElementById('idToSet').value = idToSet;
        }
        else{
            alert('There is more than 1 other F1000 role with this incident! Please chose another activity as primary instead of deselecting this one!');
            theBox.checked = true;
            return false;
        }
    }
}

function isF1000Role(){
    var theList = aspElementById('f1000Roles');
    var theRole = aspElementById('cboRole').options[aspElementById('cboRole').selectedIndex].value;
    for(var i =0; i<theList.length; i++){
        if(theList.options[i].value == theRole){
            return true;
        }
    }
    return false;
}
