// $Id: listMaint.js,v 1.50 2008/11/06 21:20:47 dharris Exp $

function addCommittees() {
  var thenewvalue = "";

  for (i = 0; i < document.listForm.committee.options.length; i++) {
    if (document.listForm.committee.options[i].selected == true) {
      thenewvalue = document.listForm.committee.options[i].value;

      if (document.listForm.displayvalue.options.length == 1) {
        if (document.listForm.name.value == "") {
          document.listForm.displayvalue.options[0].value = thenewvalue;
        } else {
          document.listForm.displayvalue.options[document.listForm.displayvalue.options.length] = new Option(thenewvalue, "anonymous");
        }
      } else {
        document.listForm.displayvalue.options[document.listForm.displayvalue.options.length] = new Option(thenewvalue, "anonymous");
      }

      document.listForm.value.value = document.listForm.value.value + " " + thenewvalue;
    }
  }

  for (i = 0; i < document.listForm.subcommittee.options.length; i++) {
    if (document.listForm.subcommittee.options[i].selected == true) {
      thenewvalue = document.listForm.subcommittee.options[i].value;

      if (document.listForm.displayvalue.options.length == 1) {
        if (document.listForm.name.value == "") {
          document.listForm.displayvalue.options[0].value = thenewvalue;
        } else {
          document.listForm.displayvalue.options[document.listForm.displayvalue.options.length] = new Option(thenewvalue, "anonymous");
        }
      } else {
        document.listForm.displayvalue.options[document.listForm.displayvalue.options.length] = new Option(thenewvalue, "anonymous");
      }

      document.listForm.value.value = document.listForm.value.value + " " + thenewvalue;
    }
  }

  document.listForm.dispatch.value = "new";

  document.listForm.displayvalue.focus();
  document.listForm.submit();
}


// on the bill list stand-alone wizard, if a bill list is chosen...add it to the value field
function chooseBillList() {
  var theindex = document.listForm.mylists.selectedIndex;
  if (theindex == 0)
    return; // do nothing
  // if the index is greater than the size of the list set, then assume
  // that the request is a global list set request...
  var thenewvalue = "";
  if (theindex > thelist.length) {
    var i = theindex - (thelist.length + 4);
    if (theglobalblist[i])
      thenewvalue = URLDecode(theglobalblist[i]);
  } else {
    thenewvalue = URLDecode(thelist[theindex - 1]);
    // fill in the name if it is blank
    if (document.listForm.name.value == "") {
      document.listForm.name.value = document.listForm.mylists.options[theindex].text;
    }
  }
  document.listForm.value.value = (document.listForm.value.value.length == 0 ?
      thenewvalue :
      document.listForm.value.value + " " + thenewvalue);
  document.listForm.value.focus();
}

// this is a specialized version of chooseListLoad targeted at the new word list fields.
// listSelector is the select control of the lists that can be selected.
// listValueArea is the text area for the word list value.
// listExcludeField is the text field for the exclude words
// idPrefix is the string prefix for the ids of the radio buttons specifying how the word list is to be used.
// if appendValues is present and true, then the selected values are appended instead of overwriting the current values
// list name field is the optional field name where the list name gets populated
// set the values of all the controls based on the selected list
function chooseWordList(listSelector, listValueArea, listExcludeField, idPrefix, appendValues, listNameField) {
  var theindex = listSelector.selectedIndex;
  var selectedValue = URLDecode(thewlist[theindex - 1]);
  if (appendValues) {
    listValueArea.value = listValueArea.value + " " + selectedValue;
  } else {
    listValueArea.value = selectedValue;
  }
  if (wordListRelatedValues[theindex - 1]) {
    listExcludeField.value = wordListRelatedValues[theindex - 1];
  } else {
    listExcludeField.value = "";
  }
  var valueMode = "0";
  if (wordListValueModes[theindex - 1]) {
    valueMode = wordListValueModes[theindex - 1];
  }
  var rbToSelect = document.getElementById(idPrefix + valueMode + "id");
  rbToSelect.checked = true;
  // if a listNameField was specified AND that field is blank, fill it in with the name of the selected list
  if (listNameField) {
    if (listNameField.value == "") {
      listNameField.value = listSelector.options[theindex].text;
    }
  }
}

// a list is chosen...set the value of the specified field to the list's value
// where the list's value is retrieved from the array thelistset
function chooseListLoad(theindex, thefield, thelistset, thegloballistset, append) {
  if (theindex == 0)
    return; // do nothing
  // if the index is greater than the size of the list set, then assume that
  // the request is a global list set request...
  var thenewvalue = "";
  if (theindex > thelistset.length) {
    var i = theindex - (thelistset.length + 4);
    if (thegloballistset[i])
      thenewvalue = URLDecode(thegloballistset[i]);
  } else {
    thenewvalue = URLDecode(thelistset[theindex - 1]);
  }
  if (append)
    thefield.value = thefield.value + " " + thenewvalue;
  else
    thefield.value = thenewvalue;
  
  thefield.focus();
}

// specialization of chooseListLoad that includes ability to validate and dedupe bills
function chooseListLoadBills(theindex, thefield, thelistset, thegloballistset, append, validate, dedupe) {
  chooseListLoad(theindex, thefield, thelistset, thegloballistset, append);
  
  if (validate) {
    var validatedBills = validateBillNumbers(thefield.value);
    if (validatedBills != null)
      thefield.value = validatedBills;
  }
  
  if (dedupe) {
    var billsArray = thefield.value.split(" ");
    var dedupedBillsArray = new Array();
    for (var n = 0; n < billsArray.length; n++) {
      var bFound = false;
      for (var l = 0; !bFound && l < dedupedBillsArray.length; l++) {
        if (billsArray[n] == dedupedBillsArray[l]) {
          bFound = true;
        }
      }
      if (!bFound) {
        dedupedBillsArray[dedupedBillsArray.length] = billsArray[n];
      }
    }
    var dedupedString = "";
    for (var n = 0; n < dedupedBillsArray.length; n++) {
      dedupedString = dedupedString + (n > 0 ? " " : "") + dedupedBillsArray[n];
    }
    thefield.value = dedupedString;
  }
}

// a list is chosen...select the corresponding values in the list.
function chooseListSelectValues(listSelect, valueSelect) {
  var selectedListName = listSelect.options[listSelect.selectedIndex].value;

  if (listSelect.selectedIndex == 0)
    return; // do nothing
  if (selectedListName == "")
    return; // do nothing

  // Unselect all values
  var options = valueSelect.options;
  for (var i=0; i<options.length; i++) {
    options[i].selected = false;
  }

  // Now select the values based on the list.
  var listValues = "";

  for (var i=0; i<theclistnames.length; i++) {
    if (theclistnames[i] == selectedListName)
      listValues = URLDecode(theclist[i]).split(" ");
  }
  if (listValues == "") {
    for (var i=0; i<theglobalclistnames.length; i++) {
      if (theglobalclistnames[i] == selectedListName)
        listValues = URLDecode(theglobalclist[i]).split(" ");
    }
  }

  var options = valueSelect.options;
  for (var i=0; i<listValues.length; i++) {
    var value = listValues[i];
    for (var j=0; j<options.length; j++) {
      if (options[j].value == value)
        options[j].selected = true;
    }
  }
}


// a list is chosen...set the value of the specified field to the list's value
// where the list's value is retrieved from the array thegloballistset
function chooseGlobalListLoad(theindex, thefield, thegloballistset) {
  if (theindex == 0)
    return; // do nothing

  var i = theindex - 4;
  if (thegloballistset[i])
    thefield.value = URLDecode(thegloballistset[i]);

  thefield.focus();
}

function doCancel(type) {
  if (confirm("Are you sure you want to cancel? (Changes will not be saved)"))
    window.location.href="editlist.do?dispatch=new&type=" + type;
}

function doEditWindow() {
  // open the popup window
  popup = open("lists/popupWordList.html", "PopupWordList", 
       "dependent=yes,scrollbars=yes,width=600,height=400,resizable=yes");
}

// returns false if the form doesn't validate
function validate() {
  // validate based on type of list
  if (document.listForm.type.value == 'BILL') {
    // make sure there is a value
    if (document.listForm.value.value == "") {
      alert("You must enter a value for your bill list.");
      return false;
    }

    var normbills = validateBillNumbers(document.listForm.value.value);
    if (normbills == null)
      return false;
    document.listForm.value.value = normbills;
  } else if (document.listForm.type.value == 'WORD') {
    // make sure the value is not empty and is less than 3000
    if (document.listForm.value.value == "") {
      alert("You must enter a value for your word list.");
      return false;
    }
    if (document.listForm.value.value.length > 3000) {
      alert("Your word list is " + document.listForm.value.value.length +
          " characters long.  It cannot be more than 3000 characters long.");
      return false;
    }
  } else if (document.listForm.type.value == 'MEMBER') {
    if (document.listForm.value.value == "") {
      alert("You must select at least one member for your member list.");
      return false;
    }
  } else if (document.listForm.type.value == 'COMMITTEE') {
    if (document.listForm.value.value == "") {
      alert("You must select at least one committee for your committee list.");
      return false;
    }    
  } else if (document.listForm.type.value == 'VOTE') {
    if (!document.listForm.value || document.listForm.value.value == "") {
      alert("You must select at least one vote for your vote list.");
      return false;
    }
  } else if (document.listForm.type.value == 'LAW') {
    // must have at least one entry
    var el;
    var n = 0;
    var countVal = 0;
    while (countVal < (lcLim + 1)) {
      el = document.getElementById("cite" + n + "editf");
      if (el == null)
        break;
      if (el.value != "")
        ++countVal;
      ++n;
    }
    if (countVal == 0) {
      alert("You must specify at least one entry for your law list.");
      document.listForm.cite.focus();
      return false;
    }
    if (countVal > lcLim) {
      alert("We're sorry, you cannot have more than " + lcLim + " sections in your list.");
      return false;
    }
  }

  // make sure we have a valid save name
  validateNoSpecialCharacters(document.listForm.name, "List Name");
  // make sure there is a name
  if (document.listForm.name.value == "") {
    alert("You must name your list.");
    document.listForm.name.focus();
    return false;
  }

  if (!checkForOverwrite()) {
    if (!confirm("You already have a list named " + document.listForm.name.value +
        ".  Are you sure you want to replace it with this list?")) {
      return false;
    }
  }

  // make sure the comment isn't too long
  if (document.listForm.description.value.length > 1999) {
    alert("Your description cannot be more than 2000 characters.");
    return false;
  }

  return true;
}

function save() {
  if (!validate())
    return;
  document.listForm.dispatch.value = 'save';
  document.listForm.submit();
}

function checkForOverwrite() {
  // check to see if list already exists
  var checkforName = document.listForm.name.value;
  if (document.listForm.name.value == document.listForm.oldname.value)
    checkforName = ""; // don't check if we're saving over...
  if (checkforName != "") {
    var listnamecheck;
    if (document.listForm.mylists)
      listnamecheck = document.listForm.mylists; // use list loader (e.g. word)
    else
      listnamecheck = document.listForm.loadlist; // use list filter (e.g. member)
    for (n = 1; n < listnamecheck.options.length; n++) {
      if (listnamecheck.options[n].text == checkforName) {
        return false;
      }
    }
  }
  return true;
}

function rename() {
  // do regular validation
  if (!validate())
    return;

  // verify name change
  if (document.listForm.name.value == document.listForm.oldname.value) {
    alert("Renaming the list requires that you change the list name.");
    return;
  }
  if (!checkForOverwrite()) {
    alert("A list named " + document.listForm.name.value +
        " already exists, please choose a different name.");
    return;
  }

  document.listForm.action = "editlist.do?dispatch=rename";
  document.listForm.submit();
}

// this function compares bill1 to bill2 and returns true if bill2 is
// greater than bill1
function compareBills(bill1, bill2) {
  var n1 = bill1.search(thesuffixre);
  if (n1 == -1)
    return false;
  var pref1 = bill1.substring(0, n1);
  var thenum1 = Number(bill1.substring(n1));

  var n2 = bill2.search(thesuffixre);
  if (n2 == -1)
    return false;
  var pref2 = bill2.substring(0, n2);
  var thenum2 = Number(bill2.substring(n2));

  if (bprefixes[pref2] < bprefixes[pref1]) {
    return true;
  } else if (bprefixes[pref2] == bprefixes[pref1] &&
    thenum2 < thenum1) {
    return true;
  }
  return false;
}

// this function sorts the document.listForm.value.value as bills
function doBillSort() {
  var splitre = new RegExp("[ ,\n\r\t.;]+");
  var theswap;
  var normbills = validateBillNumbers(document.listForm.value.value);
  if (normbills == null)
    return;
  document.listForm.value.value = normbills;
  var thebills = document.listForm.value.value.split(splitre);
  var count = 0;
  do {
    // in case of unexpected problem, bail out
    if (count++ > 2000) {
      alert("Couldn't complete bill sort.");
      break;
    }
    changed = false;
    for (n = 1; n < thebills.length; n++) {
      if (compareBills(thebills[n-1], thebills[n])) {
        // need to swap
        theswap = thebills[n - 1];
        thebills[n - 1] = thebills[n];
        thebills[n] = theswap;
        changed = true;
      }
    }
  } while (changed);
  
  // thebills is sorted, convert back to string and store
  var thesortedvalue = "";
  for (n = 0; n < thebills.length; n++)
    thesortedvalue = (thesortedvalue.length == 0 ? thebills[n] :
        thesortedvalue + " " + thebills[n]);
  document.listForm.value.value = thesortedvalue;
}

function deleteList(listname, listtype, timestamp) {
  if (confirm("Are you sure you want to delete your list named: " + listname
    + "?")) {
    window.location.href = "editlist.do?dispatch=delete&name=" + listname +
        "&type=" + listtype + "&ts=" + timestamp;
  }
}

// this function called when the user selects one or more "filters" for
// loading list data....
function doFilter() {
  // put all the displayvalue items into the hidden value
  var displayvalue = "";
  // only do this IF we have a displayvalue input
  if (document.listForm.displayvalue) {
    for (n = 0; n < document.listForm.displayvalue.options.length; n++) {
      if (document.listForm.displayvalue.options[n].value != "anonymous") {
        displayvalue = displayvalue + (n == 0 ? "" : " ") +
            document.listForm.displayvalue.options[n].value;
      }
    }
    document.listForm.value.value = displayvalue;
  }
  
  if (document.listForm.loadlist.value != 'anonymous')
    document.listForm.name.value = document.listForm.loadlist.value;
  
  document.listForm.dispatch.value = 'filter';
  document.listForm.submit();
}

// this function called when the congress on a wizard is changed
function changeCongress() {
  document.listForm.dispatch.value = "chgcong";
  document.listForm.submit();
}

// remove the selected displayvalue items from value
function removeItems() {
  document.listForm.loadlist.value = "anonymous";
  document.listForm.dispatch.value = "removeitems";
  // gather the items to remove
  var itemstoremove = "";
  for (n = 0; n < document.listForm.displayvalue.options.length; n++) {
    if (document.listForm.displayvalue.options[n].selected) {
      itemstoremove = itemstoremove + "," +
        document.listForm.displayvalue.options[n].value;
    }
  }
  document.listForm.itemstoremove.value = itemstoremove;
  document.listForm.submit();
}

// remove all the displayvalue items from value
function removeAllItems() {
  // select all items and call removeItems
  for (n = 0; n < document.listForm.displayvalue.options.length; n++) {
    document.listForm.displayvalue.options[n].selected = true;
  }
  removeItems();
}

function removeAllMembers() {
  // select all items and call removeItems
  for (n = 0; n < document.listForm.displayvalue.options.length; n++) {
    document.listForm.displayvalue.options[n].selected = true;
  }
  removeItems();
  document.listForm.displayvalue.options[0] = new Option("No Members Selected", "anonymous");
}

function removeAllCommittees() {
  // select all items and call removeItems
  for (n = 0; n < document.listForm.displayvalue.options.length; n++) {
    document.listForm.displayvalue.options[n].selected = true;
  }
  removeItems();
  document.listForm.displayvalue.options[0] = new Option("No Committees Selected", "anonymous");
}

/////////////////////////////////////////////////////////////////////////////
// this function is invoked by the continue button on the member list
// wizard to generate an anon list
function doContMember()
{
  document.listForm.makeAnonymous.value = 'true';
  document.listForm.name.value = '';
  document.listForm.description.value = '';
  document.listForm.dispatch.value = 'save';
  document.listForm.submit();
}

/////////////////////////////////////////////////////////////////////////////
// this function is used by the vote list wizard and vote report wizard in
// response to the positions/captions button.  It is also used by the show
// bills title link on the edit bill list wizard.
function loadHitList(theform, pageIntegSource) {
  if (pageIntegSource) {
    theform.pageIntegSource.value = pageIntegSource;
  }
  theform.dispatch.value = 'loadlist';
  theform.submit();
}

/////////////////////////////////////////////////////////////////////////////
// This function is used by the vote and bill list wizards to jump to the
// alternate advanced search forms.
function jumpToSearch() {
  document.listForm.dispatch.value = 'jumpto';
  document.listForm.submit();
}

// globals
var bprefixes = new Array("S","SJRES","SCONRES","SRES","HR","HJRES",
    "HCONRES", "HRES","DSAPPS","DS","DSJRES","DSCONRES","DSRES","DHAPPS",
    "DHR","DHJRES","DHCONRES","DHRES");
bprefixes["S"] = 0;
bprefixes["SJRES"] = 1;
bprefixes["SCONRES"] = 2;
bprefixes["SRES"] = 3;
bprefixes["DSAPPS"] = 4;
bprefixes["DS"] = 5;
bprefixes["DSJRES"] = 6;
bprefixes["DSCONRES"] = 7;
bprefixes["DSRES"] = 8;
bprefixes["HR"] = 9;
bprefixes["HJRES"] = 10;
bprefixes["HCONRES"] = 11;
bprefixes["HRES"] = 12;
bprefixes["DHAPPS"] = 13;
bprefixes["DHR"] = 14;
bprefixes["DHJRES"] = 15;
bprefixes["DHCONRES"] = 16;
bprefixes["DHRES"] = 17;
var thesuffixre = new RegExp("[0-9]{1,4}$");


