//Midnight in-game Javascript functions
  //(c) 2004-2005 Jean-Yves Rouffiac. All Rights Reserved.

  //Tarithel 1.2.0 - [Patton] - 2006-02-28
  //Added checks for if the journal window was actually closed
  //if not, the user is asked to close it
  //The child windows are now automatically closed, consistently
  //if they use the midnight_childwindows_clientside.js script
  //- this relates to bug #48
  // Functions:
  //  - Browserdetect()
  //  - actions(anAction, aParam, aParam2)
  //  - closeAllWindows()
  //  - consumeStores(stores)
  //  - heal(selection)
  //  - hireSwords(aGarrisonID, numberRequired, goldRequired)
  //  - dismissCommand()
  //  - feedarmy(selection)
  //  - transferMen(selection, mode)
  //  - recruitLord(selection)
  //  - groupLord(selection)
  //  - takerownership(selection)
  //  - separateLord()
  //  - switchToVassalHere(selection)
  //  - ... many others

  //Rorthron 1.2.3 - [Patton] - 2006-09-30
  //The journal is no longer cleared when pressing 'Journal' again
  //at a later time
  //- this relates to bug #522

  //Define variables to hold window names
  //If not defined, all the JS below becomes inactive!
  thinkWindow = null;
  hereWindow = null;
  aheadWindow = null;
  journalWindow = null;
  vassalsWindow = null;
  strongholdsWindow = null;
  treasuryWindow = null;
  victoriesWindow = null;
  defeatsWindow = null;
  mapsWindow = null;
  distributeWindow = null;
  battlesWindow = null;

  var arrOldValues;

  //Begin of third party browser detect code, see below for license and credits

  // Browser Detect  v2.1.6
  // documentation: http://www.dithered.com/javascript/browser_detect/index.html
  // license: http://creativecommons.org/licenses/by/1.0/
  // code by Chris Nott (chris[at]dithered[dot]com)

  function BrowserDetect() {
     var ua = navigator.userAgent.toLowerCase();

     // browser engine name
     this.isGecko       = (ua.indexOf('gecko') != -1 && ua.indexOf('safari') == -1);
     this.isAppleWebKit = (ua.indexOf('applewebkit') != -1);

     // browser name
     this.isKonqueror   = (ua.indexOf('konqueror') != -1);
     this.isSafari      = (ua.indexOf('safari') != - 1);
     this.isOmniweb     = (ua.indexOf('omniweb') != - 1);
     this.isOpera       = (ua.indexOf('opera') != -1);
     this.isIcab        = (ua.indexOf('icab') != -1);
     this.isAol         = (ua.indexOf('aol') != -1);
     this.isIE          = (ua.indexOf('msie') != -1 && !this.isOpera && (ua.indexOf('webtv') == -1) );
     this.isMozilla     = (this.isGecko && ua.indexOf('gecko/') + 14 == ua.length);
     this.isFirebird    = (ua.indexOf('firebird/') != -1);
     this.isNS          = ( (this.isGecko) ? (ua.indexOf('netscape') != -1) : ( (ua.indexOf('mozilla') != -1) && !this.isOpera && !this.isSafari && (ua.indexOf('spoofer') == -1) && (ua.indexOf('compatible') == -1) && (ua.indexOf('webtv') == -1) && (ua.indexOf('hotjava') == -1) ) );

     // spoofing and compatible browsers
     this.isIECompatible = ( (ua.indexOf('msie') != -1) && !this.isIE);
     this.isNSCompatible = ( (ua.indexOf('mozilla') != -1) && !this.isNS && !this.isMozilla);

     // rendering engine versions
     this.geckoVersion = ( (this.isGecko) ? ua.substring( (ua.lastIndexOf('gecko/') + 6), (ua.lastIndexOf('gecko/') + 14) ) : -1 );
     this.equivalentMozilla = ( (this.isGecko) ? parseFloat( ua.substring( ua.indexOf('rv:') + 3 ) ) : -1 );
     this.appleWebKitVersion = ( (this.isAppleWebKit) ? parseFloat( ua.substring( ua.indexOf('applewebkit/') + 12) ) : -1 );

     // browser version
     this.versionMinor = parseFloat(navigator.appVersion);

     // correct version number
     if (this.isGecko && !this.isMozilla) {
        this.versionMinor = parseFloat( ua.substring( ua.indexOf('/', ua.indexOf('gecko/') + 6) + 1 ) );
     }
     else if (this.isMozilla) {
        this.versionMinor = parseFloat( ua.substring( ua.indexOf('rv:') + 3 ) );
     }
     else if (this.isIE && this.versionMinor >= 4) {
        this.versionMinor = parseFloat( ua.substring( ua.indexOf('msie ') + 5 ) );
     }
     else if (this.isKonqueror) {
        this.versionMinor = parseFloat( ua.substring( ua.indexOf('konqueror/') + 10 ) );
     }
     else if (this.isSafari) {
        this.versionMinor = parseFloat( ua.substring( ua.lastIndexOf('safari/') + 7 ) );
     }
     else if (this.isOmniweb) {
        this.versionMinor = parseFloat( ua.substring( ua.lastIndexOf('omniweb/') + 8 ) );
     }
     else if (this.isOpera) {
        this.versionMinor = parseFloat( ua.substring( ua.indexOf('opera') + 6 ) );
     }
     else if (this.isIcab) {
        this.versionMinor = parseFloat( ua.substring( ua.indexOf('icab') + 5 ) );
     }

     this.versionMajor = parseInt(this.versionMinor);

     // dom support
     this.isDOM1 = (document.getElementById);
     this.isDOM2Event = (document.addEventListener && document.removeEventListener);

     // css compatibility mode
     this.mode = document.compatMode ? document.compatMode : 'BackCompat';

     // platform
     this.isWin    = (ua.indexOf('win') != -1);
     this.isWin32  = (this.isWin && ( ua.indexOf('95') != -1 || ua.indexOf('98') != -1 || ua.indexOf('nt') != -1 || ua.indexOf('win32') != -1 || ua.indexOf('32bit') != -1 || ua.indexOf('xp') != -1) );
     this.isMac    = (ua.indexOf('mac') != -1);
     this.isUnix   = (ua.indexOf('unix') != -1 || ua.indexOf('sunos') != -1 || ua.indexOf('bsd') != -1 || ua.indexOf('x11') != -1)
     this.isLinux  = (ua.indexOf('linux') != -1);

     // specific browser shortcuts
     this.isNS4x = (this.isNS && this.versionMajor == 4);
     this.isNS40x = (this.isNS4x && this.versionMinor < 4.5);
     this.isNS47x = (this.isNS4x && this.versionMinor >= 4.7);
     this.isNS4up = (this.isNS && this.versionMinor >= 4);
     this.isNS6x = (this.isNS && this.versionMajor == 6);
     this.isNS6up = (this.isNS && this.versionMajor >= 6);
     this.isNS7x = (this.isNS && this.versionMajor == 7);
     this.isNS7up = (this.isNS && this.versionMajor >= 7);

     this.isIE4x = (this.isIE && this.versionMajor == 4);
     this.isIE4up = (this.isIE && this.versionMajor >= 4);
     this.isIE5x = (this.isIE && this.versionMajor == 5);
     this.isIE55 = (this.isIE && this.versionMinor == 5.5);
     this.isIE5up = (this.isIE && this.versionMajor >= 5);
     this.isIE6x = (this.isIE && this.versionMajor == 6);
     this.isIE6up = (this.isIE && this.versionMajor >= 6);

     this.isIE4xMac = (this.isIE4x && this.isMac);
  }

  //End of third party browser detect code, see below for license and credits

  function actions(anAction, aParam, aParam2){
    //passes control to the actions script or opens child windows
    //[TO DO] Move all remaining actions into this function

    var browser = new BrowserDetect();

    if(!aParam){
      aParam = "";
    }

    if(!aParam2){
      aParam2 = "";
    }

    var paramText = "";
    var goToActionScript = false;

    var session = "";
    if ( document.forms["frmMUCM"] )
      session = "sid=" + document.forms["frmMUCM"].hdnSession.value + "&";

    switch(anAction){
      case "move":
        if(aParam == "danger"){
          warning = confirm("There is danger ahead.\nAre you sure you want to do this?");
          if(warning)
            goToActionScript = true;
          else
            break;
        }
        else
          goToActionScript = true;
        break;

      case "sneak":
        if(aParam == "enemy"){
          warning = confirm("There is danger of being discovered by the enemy ahead.\nAre you sure you want to do this?");
          if(warning)
            goToActionScript = true;
          else
            break;
        }
        else
          alert("ERROR: You should not be able to sneak unless there are enemies ahead!");
        break;

      case "view":
        window.location = "./midnight_main.php?view=" + aParam;
        break;

      case "think":
        thinkWindow = window.open("./midnight_think_gui.php?" + session,"thinkWin","width=500px,height=600px,top=150px,left=100px,scrollbars=yes");
        break;

      case "seek":
        if(aParam == "seekinfo"){
          warning = confirm("You can offer money in exchange for local rumours.\nDo you wish to buy information?");
          if(warning){
            anAction = "seekinfo";
            goToActionScript = true;
          }
        }
        goToActionScript = true;
        break;
      
      case "here":
        hereWindow = window.open("./midnight_ahead_gui.php?" + session + "ahead=0","hereWin","width=500px,height=480px,top=150px,left=50px");
        break;

      case "ahead":
        aheadWindow = window.open("./midnight_ahead_gui.php?" + session + "ahead=1","aheadWin","width=500px,height=480px,top=150px,left=50px");
        break;

      case "journal":
        if(journalWindow && !journalWindow.closed){
          journalWindow.focus();
        }
        else{
          if(browser.isIE){
            journalWindow = window.open("./midnight_journal_gui.php?" + session,"journalWind","width=500px,height=600px,top=150px,left=100px"); //WJH - height increased
          }
          else{
            journalWindow = window.open("./midnight_journal_gui.php?" + session,"journalWind","width=500px,height=500px,top=150px,left=100px"); //WJH - height increased
          }
        }
        break;

      case "vassals":
        vassalsWindow = window.open("./midnight_view_vassals_v2.php?" + session,"vassalsWin","width=1067px,height=500px,top=100px,left=30px,scrollbars=yes, resizable=yes");
        break;

      case "strongholds":
        strongholdsWindow = window.open("./midnight_view_strongholds.php?" + session,"strongholdsWin","width=985px,height=500px,top=100px,left=50px,scrollbars=yes, resizable=yes");
        break;

      case "treasury":
        treasuryWindow = window.open("./midnight_view_treasury.php?" + session,"treasuryWin","width=935px,height=500px,top=100px,left=50px,scrollbars=yes, resizable=yes");
        break;

      case "victories":
        victoriesWindow = window.open("./midnight_view_victories.php?" + session,"victoriesWin","width=645px,height=350px,top=100px,left=50px,scrollbars=yes, resizable=yes");
        break;

      case "defeats":
        defeatsWindow = window.open("./midnight_view_defeats.php?" + session,"defeatsWin","width=645px,height=350px,top=100px,left=50px,scrollbars=yes, resizable=yes");
        break;

      case "diplomacy":
        window.location="./midnight_diplomacy.php?" + session;
        break;

      case "show_maps":
        if(mapsWindow && !mapsWindow.closed) mapsWindow.focus();
        mapsWindow = window.open("./midnight_maps.php?" + session + "type=0","mapsWin","width=800px,height=600px,top=50px,left=10px,scrollbars=yes,resizable=yes");
        break;

      case "disband":
        if(aParam2 == "warn"){
          goToActionScript = confirm("Abandoning your men at this time could be seen as cowardice.\nReally disband your " + aParam + "?");
        }
        else{
          goToActionScript = confirm("Really disband your " + aParam + "?");
        }
        anAction = "disband_" + aParam;
        break;

      case "dismount":
        if(aParam == "warn"){
          goToActionScript = confirm("Abandoning your horse in the open will mean losing it.\nReally dismount?");
        }
        else{
          goToActionScript = true;
        }
        anAction = "dismount";
        break;

      case "dismount_riders":
        if(aParam == "warn"){
          goToActionScript = confirm("Abandoning your horses in the open will mean losing them.\nReally dismount your riders?");
        }
        else{
          goToActionScript = confirm("Really dismount your horses?");
        }
        anAction = "dismount_riders";
        break;

      case "save":
        var success = closeAllWindows();
        if(success){
          goToActionScript = true;
        }
        break;

      case "nightscreen":
        var success = closeAllWindows();
        if(success){
          goToActionScript = confirm("End your turn - Please confirm");
        }
        break;

      case "endturn":
        var success = closeAllWindows();
        if(success){
          goToActionScript = confirm("End your turn - Please confirm");
        }
        break;

      case "resign":
        var success = closeAllWindows();
        if(success){
          goToActionScript = confirm("Are you sure that you want to resign/surrender?");
        }
        break;

      case "abandon_game":
        var success = closeAllWindows();
        if(success){
          goToActionScript = confirm("Are you sure that you wish to abandon this game (other players will all need to agree)?");
        }
        break;

      case "distribute_food":
        if(browser.isIE)
          distributeWindow = window.open("./midnight_distribute_food_gui.php?" + session,"distributeWin","width=490px,height=580px,top=150px,left=100px,scrollbars=yes");
        else
          distributeWindow = window.open("./midnight_distribute_food_gui.php?" + session,"distributeWin","width=490px,height=480px,top=150px,left=100px,scrollbars=yes");
        break;

      case "battles":
        battlesWindow = window.open("./midnight_view_battle_details.php?" + session,"battlesWin","width=965px,height=500px,top=100px,left=30px,scrollbars=yes, resizable=yes");
        break;

      default:
        goToActionScript = true;
    }

    if(goToActionScript){
      window.location = "./midnight_actions.php?action=" + anAction + paramText;
    }

    return false;
  }

  function closeAllWindows(){
    //Close any child windows that are open

    //alert("Close Windows");

    if(journalWindow && !journalWindow.closed){
      //  journalWindow.close();
      alert("You have the journal open.\n\nPlease close the journal window before proceeding.");
      journalWindow.focus();
      return false;
    }
    if(thinkWindow && !thinkWindow.closed) thinkWindow.close();
    if(hereWindow && !hereWindow.closed) hereWindow.close();
    if(aheadWindow && !aheadWindow.closed) aheadWindow.close();
    if(vassalsWindow && !vassalsWindow.closed) vassalsWindow.close();
    if(strongholdsWindow && !strongholdsWindow.closed) strongholdsWindow.close();
    if(treasuryWindow && !treasuryWindow.closed) treasuryWindow.close();
    if(victoriesWindow && !victoriesWindow.closed) victoriesWindow.close();
    if(defeatsWindow && !defeatsWindow.closed) defeatsWindow.close();
    if(mapsWindow && !mapsWindow.closed) mapsWindow.close();
    if(distributeWindow && !distributeWindow.closed) distributeWindow.close();
    if(battlesWindow && !battlesWindow.closed) battlesWindow.close();
    
    return true;
  }


  function consumeStores(stores){
    //Consume some stores to regain energy
    var fromLordID = parseInt(document.forms["frmAlsoHere"].selAlsoHere.value)
    stores = stripLeading(stores,"0");

    if(isNaN(stores)) stores = 0;
    if(isNaN(fromLordID)) fromLordID = document.forms["frmMUCM"].hdnLordID.value;

    window.location="./midnight_actions.php?action=consume&fromLordID=" + fromLordID + "&stores=" + stores;
    return false;
  }

  function heal(selection){
    //Wise can heal other lords

    if(selection == ""){
      alert("You must first select a Lord or a Garrison that is to be healed");
      return false;
    }

    var lordID = parseInt(selection);
    
    window.location="./midnight_actions.php?action=heal&lordID=" + lordID;

    return false;
  }

  function hireSwords(aGarrisonID, numberRequired, goldRequired){
    if(goldRequired > 0){
      if(confirm("Recruiting " + numberRequired + " mercenaries will cost " + goldRequired + " gold and take the rest of the day.\nAre you sure you want the hired swords?")){
        //alert("going to hiring script");
        window.location = "./midnight_hire_mercenaries.php?garrisonID=" + aGarrisonID +"&troops="+numberRequired; 
      }
    }
    else{
      if(confirm("Recruiting " + numberRequired + " mercenaries will take the rest of the day.\nAre you sure you want the hired swords?")){
        //alert("going to hiring script");
        window.location = "./midnight_hire_mercenaries.php?garrisonID=" + aGarrisonID +"&troops="+numberRequired; 
      }
    }

    return false;
  }

  function dismissCommand(){
    window.location = "./midnight_dismiss_lords.php";

    return false;
  }

  function feedarmy(selection){
    //Caravans and Garrisons can feed other lords
    if(selection == ""){
      alert("You must first select a Lord or a Garrison that is to be fed");
      return false;
    }

    var lordID = parseInt(selection);
    //alert("You have selected lord " + lordID + " for feeding.");
    window.location="./midnight_actions.php?action=feed_army&feedLordID=" + lordID;
    return false;
  }

  function transferMen(selection, mode){
    //Transfer men between lords

    if(selection == ""){
      alert("You must first select a Lord or a Garrison");
      return false;
    }

    var lordID = parseInt(selection);
    var riders = parseInt(document.forms["frmAlsoHere"].txtRiders.value);
    var warriors = parseInt(document.forms["frmAlsoHere"].txtWarriors.value);

    if(isNaN(riders)) riders = 0;
    if(isNaN(warriors)) warriors = 0;

    var params = "?lordID=" + lordID + "&mode=" + mode + "&riders=" + riders + "&warriors=" + warriors;

    window.location="./midnight_transfer.php" + params;

    return false;
  }


  function recruitLord(selection){
    //Recruit selected lord

    var lordID = (selection.value);
    var field_Race = 'hdnRace' + selection;
    var current_Race = 'hdnCurrentLordRace' + selection;

    if((lordID == "") || (lordID == 0)){
      alert("You did not select a Lord");
      return false;
    }

    window.location = "./midnight_recruit.php?lordID=" + lordID;

    return false;
  }

  // WJH - next two functions added for grouping feature
  function groupLord(selection){
    //Group under selected lord
    //for use with boarding ships, riding dragons and grouping armies

    var lordID = (selection.value);

    if((lordID == "") || (lordID == 0)){
      alert("You did not select a Lord");
      return false;
    }

    window.location = "./midnight_group_units.php?lordID=" + lordID +"&action=join";

    return false;
  }

  function takeownership(selection){
    var lordID = (selection.value);
    var field_Race = 'hdnRace' + selection;
    var current_Race = 'hdnCurrentLordRace' + selection;

    if((lordID == "") || (lordID == 0)){
      alert("You did not select a garrison,");
      return false;
    }
    //alert("LordID: "+lordID+"\nSelection: "+selection);
    window.location = "./midnight_take_ownership.php?lordID=" + selection;

    return false;
  }
  
  function separateLord(){
    //Ungroup lord so that it can be controlled individually again
    //for use in disembarakation, dismounting from dragons and separating
    //from army groups
    window.location = "./midnight_group_units.php?action=split";

    return false;
  }
  // WJH - end of grouping functions

  function switchToVassalHere(selection){
    //Switches control to selected lord/garrison
    if(selection.value == ""){
      alert("You did not select a Lord/Garrison/Caravan to switch to")
      return false;
    }

    var lordID = parseInt(selection.value);
    var lordAllegiance = parseInt(eval('document.forms["frmAlsoHere"].hdnLordAllegianceID' + lordID + '.value'));

    if(document.forms["frmAlsoHere"].hdnCurrentLordAllegianceID.value != lordAllegiance){
      alert("Not your liege lord, nor a vassal");
      return false;
    }

    window.location="./midnight_actions.php?action=selectotherlord&lordID=" + lordID;
    return false;
  }

  function switchToVassalHere2(anID){
    //Switches control to selected lord/garrison
    //alert(selection.value);
    //alert(document.frmAlsoHere.selAlsoHere.value);
    //alert(document.forms["frmAlsoHere"].selAlsoHere.value);
    if(anID == 0){
      alert("You did not select a Lord/Garrison/Caravan to switch to")
      return false;
    }

    var lordID = anID;
    var lordAllegiance = parseInt(eval('document.forms["frmAlsoHere"].hdnLordAllegianceID' + lordID + '.value'));

    if(document.forms["frmAlsoHere"].hdnCurrentLordAllegianceID.value != lordAllegiance){
      alert("Not your liege lord, nor a vassal");
      return false;
    }

    window.location="./midnight_actions.php?action=selectotherlord&lordID=" + lordID;
    return false;
  }


  function nightLord(yesNo){
    //Nights the lord - if use has asked to have night's confirmed, a JS prompt is shown

    if(yesNo == 1){
      if(confirm("Invoke Night? - Please confirm")){
        window.location="./midnight_actions.php?action=night";
      }
    }
    else{
      window.location="./midnight_actions.php?action=night";
    }

    return false;
  }


  function selectLord(selection){
  //Switch to another lord/garrison - from drop down (select) boxes

    if(selection == 0){
      alert("You did not select a vassal/liege lord/garrison/caravan");
      return false;
    }

    lordID = selection.options[selection.selectedIndex].value;

    window.location="./midnight_actions.php?action=selectotherlord&lordID=" + lordID;

    return false;
  }

  function poison(selection){
    //Poison selected lord

    //var lordID = (selection.value);
    var lordID = selection;
    var field_Race = 'hdnRace' + selection;
    var current_Race = 'hdnCurrentLordRace' + selection;

    if((lordID == "") || (lordID == 0)){
      alert("You did not select a Lord");
      return false;
    }
    //alert("Selection number is: "+lordID);

    window.location = "./midnight_poison.php?lordID=" + lordID;

    return false;
  }

  function stealfrom(selection){
    //Steal something from selected lord

    var lordID = selection;
    var field_Race = 'hdnRace' + selection;
    var current_Race = 'hdnCurrentLordRace' + selection;

    if((lordID == "") || (lordID == 0)){
      alert("You did not select a Lord");
      return false;
    }

    window.location = "./midnight_stealfrom.php?lordID=" + lordID;

    return false;
  }

function stripLeading(string,chr) {
   var finished = false;
   for (var i = 0; i < string.length && !finished; i++)
       if (string.substring(i,i+1) != chr) finished = true;
   if (finished) return string.substring(i-1); else return string;
}

function  updateTotal(aForm, existingArmy, maxArmySize){
  //Shows total of warriors and riders selected (makes life easier!)
  //and informs player how many more can be recruited

  // check for oct values
  // strip leading 0
  aForm.txtRiders.value = stripLeading(aForm.txtRiders.value,"0");
  aForm.txtWarriors.value = stripLeading(aForm.txtWarriors.value,"0");

  var total = parseInt(aForm.txtRiders.value);

  if(isNaN(total)){
    aForm.txtRiders.value = 0;
  }
  total = parseInt(aForm.txtWarriors.value);
  if(isNaN(total)){
    aForm.txtWarriors.value = 0;
  }

  total = parseInt(aForm.txtRiders.value) + parseInt(aForm.txtWarriors.value);
  if(isNaN(total)){
    aForm.txtTotal.value = "Error";
    aForm.txtFurther.value = "Error";
  }
  else{
    aForm.txtTotal.value = total;
    aForm.txtFurther.value = maxArmySize - existingArmy - total;
  }
}

function transferGold(anAmount,aMode){
  //alert(anAmount+","+aMode);

  if(document.forms["frmAlsoHere"].selAlsoHere.value)
    selection = parseInt(document.forms["frmAlsoHere"].selAlsoHere.value);

  if(eval('document.forms["frmAlsoHere"].hdnCurrentLordID' + selection))
    currentLord = parseInt(eval('document.forms["frmAlsoHere"].hdnCurrentLordID' + selection).value);

  if(aMode == "give"){
    sourceLord = currentLord;
    targetLord = selection;
  }
  else if(aMode == "take"){
    sourceLord = selection;
    targetLord = currentLord;
  }

  //alert(sourceLord + "," + targetLord + "," + anAmount);

  window.location="./midnight_actions.php?action=exchange_gold&fromLordID=" + sourceLord + "&toLordID=" + targetLord + "&goldAmount=" + anAmount;

  return false;
}


//processSelection function
//- replaces previous functions
//    processSelection_Lord
//    processSelection_Garrison
//    showStores

function processSelection(anID,aMode,anArray){
  //Controls which buttons are displayed in the game interface according to which lord is selected in the "Also Here" box
  //Mode definitions: 0 - old mode, no grouping; 1 - new mode for garrisons; 2 - new mode for lords

  //Initialise variables
  var field_Container = 'hdnContainerOf' + anID;
  var field_Shelter = 'hdnShelter' + anID;                                      // WJH - replaces fieldName, handles stores
  var field_LeastStrength = 'hdnLeastStrength' + anID;
  var field_Hours = 'hdnHours' + anID;
  var field_Race = 'hdnRace' + anID;                                            // WJH - introduced for race specific grouping
  var field_Class = 'hdnClass' + anID;
  var stores = 0;                                                               // WJH - moved from further down in the code
  var form_selection = 'sel' + anID;
  var strength = 100;
  var hours = 0;
  var field_ThisLordShelter = 'hdnCurrentLordShelter' + anID;
  var field_ThisLordRace = 'hdnCurrentLordRace' + anID;
  var strengthFlag = false;
  var hoursFlag = false;
  var strengthNeededFlag = false;
  var returnValue = false;
  var field_Gold = 'hdnGold' + anID;
  var field_ThisLordGold = 'hdnCurrentLordGold' + anID;
  var lordAllegiance = parseInt(eval('document.forms["frmAlsoHere"].hdnLordAllegianceID' + anID + '.value'));
  var currentLordID = parseInt(eval('document.forms["frmAlsoHere"].hdnCurrentLordID' + anID + '.value'));
  var isKing = false;
  var isStockpile = false;
  var isThiefTarget = false;
  var isGarrison = false;
  var isDragonrider = false;
  var isRogue = false;
  var isHighwayman = false;

  if(eval('document.forms["frmAlsoHere"].' + field_ThisLordRace)){
    var thisLordRace = eval('document.forms["frmAlsoHere"].' + field_ThisLordRace + '.value');
  }
  if(eval('document.forms["frmAlsoHere"].' + field_ThisLordShelter)){
    var thisLordShelter = parseInt(eval('document.forms["frmAlsoHere"].' + field_ThisLordShelter + '.value'));
  }

  if(aMode > 0){                                                                 //Only for use with grouping interface
    document.forms["frmAlsoHere"].selAlsoHere.value = anID;
    for( key in anArray ){
      loopID = parseInt(key);
      if(loopID == anID){
        if(!(anID == document.forms["frmMUCM"].hdnLordID.value)){
          var div = document.getElementById("sel"+anID);
          div.style.backgroundColor = "#9898d8";
        }
      }
      else{
        if(!(loopID == document.forms["frmMUCM"].hdnLordID.value)){
          var div = document.getElementById("sel"+loopID);
          div.style.backgroundColor = anArray[key];
        }
      }
    }
  }

  //Set intial states, with no selection made

  //Hide gold transfer buttons by default
  if(document.forms["frmAlsoHere"].btnTakeGold)
    document.forms["frmAlsoHere"].btnTakeGold.style.visibility = 'hidden';
  if(document.forms["frmAlsoHere"].txtTakeGold)
    document.forms["frmAlsoHere"].txtTakeGold.style.visibility = 'hidden';
  if(document.forms["frmAlsoHere"].lblGoldSlash)
    document.forms["frmAlsoHere"].lblGoldSlash.style.visibility = 'hidden';
  if(document.forms["frmAlsoHere"].btnGiveGold)
    document.forms["frmAlsoHere"].btnGiveGold.style.visibility = 'hidden';
  if(document.forms["frmAlsoHere"].txtGiveGold)
    document.forms["frmAlsoHere"].txtGiveGold.style.visibility = 'hidden';
  if(document.forms["frmAlsoHere"].txtMaxGold)
    document.forms["frmAlsoHere"].txtMaxGold.style.visibility = 'hidden';

  //Hide stores transfer/consume buttons by default
  if(document.forms["frmAlsoHere"].txtStores)
    document.forms["frmAlsoHere"].txtStores.value = 0;
  if(document.forms["frmAlsoHere"].txtMaxStores)
    document.forms["frmAlsoHere"].txtMaxStores.value = ' of 0 stores';
  if(document.forms["frmAlsoHere"].btnGetStores)
    document.forms["frmAlsoHere"].btnGetStores.style.visibility = 'hidden';
  if(document.forms["frmAlsoHere"].lblStoresSlash)
    document.forms["frmAlsoHere"].lblStoresSlash.style.visibility = 'hidden';
  if(document.forms["frmAlsoHere"].btnConsume)
    document.forms["frmAlsoHere"].btnConsume.style.visibility = 'hidden';
  if(document.forms["frmAlsoHere"].txtStores)
    document.forms["frmAlsoHere"].txtStores.style.visibility = 'hidden';
  if(document.forms["frmAlsoHere"].txtMaxStores)
    document.forms["frmAlsoHere"].txtMaxStores.style.visibility = 'hidden';
  if(document.forms["frmAlsoHere"].btnGovern)
    document.forms["frmAlsoHere"].btnGovern.style.visibility = 'hidden';

  //Hide grouping buttons by default
  if(document.forms["frmAlsoHere"].btnJoin)                                             // WJH - added for grouping feature
      document.forms["frmAlsoHere"].btnJoin.style.visibility = 'hidden';

  //Hide feeding button by default
  if(document.forms["frmAlsoHere"].btnFeed)                                             // WJH - added for feeding feature
    document.forms["frmAlsoHere"].btnFeed.style.visibility = 'hidden';

  //Hide stealing button by default
  if(document.forms["frmAlsoHere"].btnSteal)
    document.forms["frmAlsoHere"].btnSteal.style.visibility = 'hidden';

  //Hide poisoning button by default
  if(document.forms["frmAlsoHere"].btnPoison)
    document.forms["frmAlsoHere"].btnPoison.style.visibility = 'hidden';

  //Process internal variables
  if(eval('document.forms["frmAlsoHere"].' + field_Shelter)){                             // WJH - field_Shelter replaces fieldName
    stores = parseInt(eval('document.forms["frmAlsoHere"].' + field_Shelter + '.value')); // WJH - field_Shelter replaces fieldName
    if(eval('document.forms["frmAlsoHere"].' + field_Race)){
      if(eval('document.forms["frmAlsoHere"].' + field_Race + '.value') != "Caravan"){
        isGarrison = true;
      }
    }
  }

  if(eval('document.forms["frmAlsoHere"].' + field_LeastStrength)){
    strengthFlag = true;
    strength = parseInt(eval('document.forms["frmAlsoHere"].' + field_LeastStrength + '.value'));
  }

  if(eval('document.forms["frmAlsoHere"].' + field_Hours)){
    hoursFlag = true;
    hours = parseInt(eval('document.forms["frmAlsoHere"].' + field_Hours + '.value'));
  }

  if(eval('document.forms["frmAlsoHere"].' + field_Race)){
    if(thisLordShelter > 0){
      if(strengthFlag && hoursFlag){
        if(strength < 100 && hours > 0 && (currentLordID != anID))
          strengthNeededFlag = true;
      }
    }
  }

  //Determine if this lord is a king
  if(eval('document.forms["frmAlsoHere"].hdnKing' + currentLordID))
    isKing = parseInt(eval('document.forms["frmAlsoHere"].hdnKing' + currentLordID + '.value'));
  if(isKing > 0)
    isKing = true;

  //Determine if this lord is a dragon rider
  if(eval('document.forms["frmAlsoHere"].hdnDragonrider' + currentLordID))
    isDragonrider = parseInt(eval('document.forms["frmAlsoHere"].hdnDragonrider' + currentLordID + '.value'));
  if(isDragonrider > 0)
    isDragonrider = true;

  //Determine if this lord is a rogue
  if(eval('document.forms["frmAlsoHere"].hdnRogue' + currentLordID))
    isRogue = parseInt(eval('document.forms["frmAlsoHere"].hdnRogue' + currentLordID + '.value'));
  if(isRogue > 0)
    isRogue = true;

  //Determine if this lord is a highwayman
  if(eval('document.forms["frmAlsoHere"].hdnHighwayman' + currentLordID))
    isHighwayman = parseInt(eval('document.forms["frmAlsoHere"].hdnHighwayman' + currentLordID + '.value'));
  if(isHighwayman > 0)
    isHighwayman = true;

  //Determine if selection is a stockpile
  if(eval('document.forms["frmAlsoHere"].' + field_Race)){
    if(eval('document.forms["frmAlsoHere"].' + field_Race + '.value') == "Stockpile")
      isStockpile = true;
  }

  //Determine if selection is a thief's target (not a vassal or neutral)
  if(eval('document.forms["frmAlsoHere"].' + field_Class)){
    var lordClass = eval('document.forms["frmAlsoHere"].' + field_Class + '.value');
    if((lordClass == "ally" || lordClass == "enemy") && (isRogue || isHighwayman)){
      isThiefTarget = true;
      if(document.forms["frmAlsoHere"].btnPoison && isRogue)
        document.forms["frmAlsoHere"].btnPoison.style.visibility = 'visible';
      if(document.forms["frmAlsoHere"].btnSteal)
        document.forms["frmAlsoHere"].btnSteal.style.visibility = 'visible';
      returnValue = true;
    }
  }
  
  //If "selected lord" is not current lord or a dragon, make gold transfer buttons visible
  if((document.forms["frmAlsoHere"].hdnCurrentLordAllegianceID.value == lordAllegiance) || isStockpile){
    if(!(anID == document.forms["frmMUCM"].hdnLordID.value)){
      if(eval('document.forms["frmAlsoHere"].' + field_Race)){
        if(eval('document.forms["frmAlsoHere"].' + field_Race + '.value') != "Dragon"){
          if(document.forms["frmAlsoHere"].btnTakeGold)
            document.forms["frmAlsoHere"].btnTakeGold.style.visibility = 'visible';
          if(document.forms["frmAlsoHere"].txtTakeGold){
            if(eval('document.forms["frmAlsoHere"].' + field_Gold).value > 0)
              document.forms["frmAlsoHere"].txtTakeGold.value = parseInt(eval('document.forms["frmAlsoHere"].' + field_Gold).value);
            else
              document.forms["frmAlsoHere"].txtTakeGold.value = 0;
            document.forms["frmAlsoHere"].txtTakeGold.style.visibility = 'visible';
          }
          if(document.forms["frmAlsoHere"].lblGoldSlash)
            document.forms["frmAlsoHere"].lblGoldSlash.style.visibility = 'visible';
          if(document.forms["frmAlsoHere"].btnGiveGold)
            document.forms["frmAlsoHere"].btnGiveGold.style.visibility = 'visible';
          if(document.forms["frmAlsoHere"].txtGiveGold){
            if(eval('document.forms["frmAlsoHere"].' + field_ThisLordGold).value > 0)
              document.forms["frmAlsoHere"].txtGiveGold.value = parseInt(eval('document.forms["frmAlsoHere"].' + field_ThisLordGold).value);
            else
              document.forms["frmAlsoHere"].txtGiveGold.value = 0;
            document.forms["frmAlsoHere"].txtGiveGold.style.visibility = 'visible';
          }
          if(document.forms["frmAlsoHere"].txtMaxGold)
            document.forms["frmAlsoHere"].txtMaxGold.style.visibility = 'visible';
        }
      }
      else if(eval('document.forms["frmAlsoHere"].' + field_Shelter)){                   // WJH - field_Shelter replaces fieldName
        if(document.forms["frmAlsoHere"].btnTakeGold)
          document.forms["frmAlsoHere"].btnTakeGold.style.visibility = 'visible';
        if(document.forms["frmAlsoHere"].txtTakeGold){
          if(eval('document.forms["frmAlsoHere"].' + field_Gold).value > 0)
            document.forms["frmAlsoHere"].txtTakeGold.value = parseInt(eval('document.forms["frmAlsoHere"].' + field_Gold).value);
          else
            document.forms["frmAlsoHere"].txtTakeGold.value = 0;
          document.forms["frmAlsoHere"].txtTakeGold.style.visibility = 'visible';
        }
        if(document.forms["frmAlsoHere"].lblGoldSlash)
          document.forms["frmAlsoHere"].lblGoldSlash.style.visibility = 'visible';
        if(document.forms["frmAlsoHere"].btnGiveGold)
          document.forms["frmAlsoHere"].btnGiveGold.style.visibility = 'visible';
        if(document.forms["frmAlsoHere"].txtGiveGold){
          if(eval('document.forms["frmAlsoHere"].' + field_ThisLordGold).value > 0)
            document.forms["frmAlsoHere"].txtGiveGold.value = parseInt(eval('document.forms["frmAlsoHere"].' + field_ThisLordGold).value);
          else
            document.forms["frmAlsoHere"].txtGiveGold.value = 0;
          document.forms["frmAlsoHere"].txtGiveGold.style.visibility = 'visible';
        }
        if(document.forms["frmAlsoHere"].txtMaxGold)
          document.forms["frmAlsoHere"].txtMaxGold.style.visibility = 'visible';
      }
      else if(isKing){
        if(document.forms["frmAlsoHere"].btnTakeGold)
          document.forms["frmAlsoHere"].btnTakeGold.style.visibility = 'visible';
        if(document.forms["frmAlsoHere"].txtTakeGold){
          if(eval('document.forms["frmAlsoHere"].' + field_Gold).value > 0)
            document.forms["frmAlsoHere"].txtTakeGold.value = parseInt(eval('document.forms["frmAlsoHere"].' + field_Gold).value);
          else
            document.forms["frmAlsoHere"].txtTakeGold.value = 0;
          document.forms["frmAlsoHere"].txtTakeGold.style.visibility = 'visible';
        }
        if(document.forms["frmAlsoHere"].lblGoldSlash)
          document.forms["frmAlsoHere"].lblGoldSlash.style.visibility = 'visible';
        if(document.forms["frmAlsoHere"].btnGiveGold)
          document.forms["frmAlsoHere"].btnGiveGold.style.visibility = 'visible';
        if(document.forms["frmAlsoHere"].txtGiveGold){
          if(eval('document.forms["frmAlsoHere"].' + field_ThisLordGold).value > 0)
            document.forms["frmAlsoHere"].txtGiveGold.value = parseInt(eval('document.forms["frmAlsoHere"].' + field_ThisLordGold).value);
          else
            document.forms["frmAlsoHere"].txtGiveGold.value = 0;
          document.forms["frmAlsoHere"].txtGiveGold.style.visibility = 'visible';
        }
        if(document.forms["frmAlsoHere"].txtMaxGold)
          document.forms["frmAlsoHere"].txtMaxGold.style.visibility = 'visible';
      }
    }
  }

  if(aMode == 2){
    if(!(anID == document.forms["frmMUCM"].hdnLordID.value)){
      if(eval('document.forms["frmAlsoHere"].' + field_Race)){
        if(eval('document.forms["frmAlsoHere"].' + field_Race + '.value') != "Dragon"){
          //If current lord is carrying stores, show Feed button if anyone needs feeding
          if(eval('document.forms["frmAlsoHere"].' + field_ThisLordShelter)){
            if(eval('document.forms["frmAlsoHere"].' + field_ThisLordShelter + '.value') > 0){
              if(strengthFlag && hoursFlag){
                if(strength < 100 && hours > 0){
                  strengthNeededFlag = true;
                  if(document.forms["frmAlsoHere"].btnFeed){
                    document.forms["frmAlsoHere"].btnFeed.style.visibility = 'visible';
                    returnValue = true;
                  }
                }
              }
            }
          }
        }
      }
    }
  }

  //Display stores transfer buttons if appropriate
  if(eval('document.forms["frmAlsoHere"].' + field_Shelter)){                   // WJH - field_Shelter replaces fieldName
    if(document.forms["frmAlsoHere"].btnConsume)
      document.forms["frmAlsoHere"].btnConsume.style.visibility = 'visible';
    if(document.forms["frmAlsoHere"].txtStores)
      document.forms["frmAlsoHere"].txtStores.style.visibility = 'visible';
    if(document.forms["frmAlsoHere"].txtMaxStores)
      document.forms["frmAlsoHere"].txtMaxStores.style.visibility = 'visible';
    if(eval('document.forms["frmAlsoHere"].' + field_Shelter).value > 0){       // WJH - field_Shelter replaces fieldName
      if(document.forms["frmAlsoHere"].txtStores)
        document.forms["frmAlsoHere"].txtStores.value = 1;
    }
    if(document.forms["frmAlsoHere"].txtMaxStores)
      document.forms["frmAlsoHere"].txtMaxStores.value = ' of ' + stores + ' stores';
    if(!(anID == document.forms["frmMUCM"].hdnLordID.value)){
      if(document.forms["frmAlsoHere"].btnGetStores)
        document.forms["frmAlsoHere"].btnGetStores.style.visibility = 'visible';
      if(document.forms["frmAlsoHere"].lblStoresSlash)
        document.forms["frmAlsoHere"].lblStoresSlash.style.visibility = 'visible';
    }
    if(isGarrison == true){
      if(document.forms["frmAlsoHere"].btnGovern)
        document.forms["frmAlsoHere"].btnGovern.style.visibility = 'visible';
    }      
    returnValue = true;
  }

  if(aMode == 1 && isGarrison == false){
    if ( document.forms["frmAlsoHere"].hdnCurrentLordAllegianceID.value == eval('document.forms["frmAlsoHere"].hdnLordAllegianceID' + anID + '.value' ) ) {
      // do not display anything for caravans or skulkrin or trolls is selected (or if selected lord is already inside a container
      if(eval('document.forms["frmAlsoHere"].' + field_Race)){
        if ((eval('document.forms["frmAlsoHere"].' + field_Race + '.value') == "Caravan") ||
            (eval('document.forms["frmAlsoHere"].' + field_Race + '.value') == "Skulkrin") ||
            (eval('document.forms["frmAlsoHere"].' + field_Race + '.value') == "Troll") ||
            (eval('document.forms["frmAlsoHere"].' + field_Container + '.value') > 0)) {
          if(document.forms["frmAlsoHere"].btnJoin){
            document.forms["frmAlsoHere"].btnJoin.value = 'ERROR';
            document.forms["frmAlsoHere"].btnJoin.style.visibility = 'hidden';
          }
          if(strengthNeededFlag && document.forms["frmAlsoHere"].btnFeed)
            document.forms["frmAlsoHere"].btnFeed.style.visibility = 'visible';
          returnValue = true;
          //return true;
        }
        // display "board Ship" text if a ship is selected
        else if (eval('document.forms["frmAlsoHere"].' + field_Race + '.value') == "Ship") {
          if(eval('document.forms["frmAlsoHere"].hdnCurrentLordID' + anID + '.value') != anID){
            if(document.forms["frmAlsoHere"].btnJoin){
              document.forms["frmAlsoHere"].btnJoin.value = 'Board Ship';
              document.forms["frmAlsoHere"].btnJoin.style.visibility = 'visible';
            }
          }
          if(strengthNeededFlag)
            document.forms["frmAlsoHere"].btnFeed.style.visibility = 'visible';
          returnValue = true;
          //return true;
        }
        // else display "Ride Dragon" if the current lord is a dragonrider and selection is a dragon
        else if ((eval('document.forms["frmAlsoHere"].' + field_Race + '.value') == "Dragon") && isDragonrider){
                 //(document.forms["frmMUCM"].hdnLordRace.value == "Wise")) {
          if(eval('document.forms["frmAlsoHere"].hdnCurrentLordID' + anID + '.value') != anID){
            if(document.forms["frmAlsoHere"].btnJoin){
              document.forms["frmAlsoHere"].btnJoin.value = 'Ride Dragon';
              document.forms["frmAlsoHere"].btnJoin.style.visibility = 'visible';
            }
          }
          if(strengthNeededFlag && document.forms["frmAlsoHere"].btnFeed)
            document.forms["frmAlsoHere"].btnFeed.style.visibility = 'visible';
          returnValue = true;
          //return true;
        }
        // else if selected lord is capable of command, show "Give Command" text
        else if ((eval('document.forms["frmAlsoHere"].' + field_Race + '.value') == "Free") ||
                 (eval('document.forms["frmAlsoHere"].' + field_Race + '.value') == "Foul") ||
                 (eval('document.forms["frmAlsoHere"].' + field_Race + '.value') == "Dwarf") ||
                 (eval('document.forms["frmAlsoHere"].' + field_Race + '.value') == "Targ") ||
                 (eval('document.forms["frmAlsoHere"].' + field_Race + '.value') == "Fey") ||
                 (eval('document.forms["frmAlsoHere"].' + field_Race + '.value') == "Marsh Fey") ||
                 (eval('document.forms["frmAlsoHere"].' + field_Race + '.value') == "Giant")) {
          if(eval('document.forms["frmAlsoHere"].hdnCurrentLordID' + anID + '.value') != anID){
            if(document.forms["frmAlsoHere"].btnJoin){
              document.forms["frmAlsoHere"].btnJoin.value = 'Cede Command';
              document.forms["frmAlsoHere"].btnJoin.style.visibility = 'visible';
            }
          }
          if(strengthNeededFlag && document.forms["frmAlsoHere"].btnFeed)
            document.forms["frmAlsoHere"].btnFeed.style.visibility = 'visible';
          returnValue = true;
          //return true;
        }
        else if(strengthNeededFlag && document.forms["frmAlsoHere"].btnFeed){
          document.forms["frmAlsoHere"].btnFeed.style.visibility = 'visible';
          returnValue = true;
          //return true;
        }
      }
    }
  }

  return returnValue;
}

function getStores(stores){
  //Get some stores from another unit

  if(isNaN(stores))
    stores = 0;

  var fromLordID = parseInt(document.forms["frmAlsoHere"].selAlsoHere.value);

  if(isNaN(fromLordID))
    fromLordID = document.forms["frmMUCM"].hdnLordID.value;

  window.location="./midnight_actions.php?action=get_stores&fromLordID=" + fromLordID + "&stores=" + stores;

  return false;
}


function toggleStores(stores,selection){
  if(isNaN(stores))
    stores = 0;

  if(isNaN(selection) || (selection == 0)){
    if(document.forms["frmAlsoHere"].selAlsohere)
      selection = parseInt(document.forms["frmAlsohere"].selAlsoHere.value);
    if(selection == 0)
      selection = document.forms["frmMUCM"].hdnLordID.value;
  }

  if(eval('document.forms["frmAlsoHere"].hdnShelter' + selection))
    maxStores = parseInt(eval('document.forms["frmAlsoHere"].hdnShelter' + selection + '.value'));

  if((maxStores > 0) && document.forms["frmAlsoHere"].txtStores){
    if(stores == 1)
      document.forms["frmAlsoHere"].txtStores.value = maxStores;
    else
      document.forms["frmAlsoHere"].txtStores.value = 1;
    return true;
  }
  return false;
}


function createCaravan(aSource,anID){
  //Create a caravan - only garrisons can do this and it costs gold
  if(confirm("Really create a caravan?")){
    if(aSource == "main")
      window.location = "./midnight_actions.php?action=create_caravan";
    else if(aSource == "treasury"){
      alert(anID);
      parent.window.location = "./midnight_create_unit.php?action=create_caravan&source="+anID;
    }
    else
      alert("Incorrect source for caravan creation command!");
  }
  return false;
}

// WJH - function added to create ships
function createShip(){
  //Create a ship - only garrisons at ports can do this and it costs gold
  if(confirm("Really hire a new ship?")){
    window.location = "./midnight_actions.php?action=create_ship";
  }
  return false;
}

function captureUnit(lordID){
  //Capture units, such as caravans
  if(lordID == ""){
    alert("You must first select a unit that is to be captured");
    return false;
  }
  window.location="./midnight_actions.php?action=capture&lordID=" + lordID;
  return false;
}

function keyPress(event){
  var evt ;
  var eventElement ;
  var keyChar ;

  var browser = new BrowserDetect();
  if ( browser.isOpera ){
    return;
  }

  if ( window.event ) {
    evt = window.event ;
    eventElement = window.event.srcElement;
    keyChar = String.fromCharCode(evt.keyCode);
  }else{
    evt = event ;
    eventElement = event.target;
    keyChar = String.fromCharCode(evt.charCode);
  }

  if ( eventElement.tagName == "INPUT" ) {
    if ( (eventElement.type == "text" || eventElement.type == "password") ) {
      return;
    }
  }
  if ( keyChar=="=" )
    actions("view","next");
  else if ( keyChar=="-" )
    actions("view","prev");
  else if ( keyChar=="1" )
    actions("view","N");
  else if ( keyChar=="2" )
    actions("view","NE");
  else if ( keyChar=="3" )
    actions("view","E");
  else if ( keyChar=="4" )
    actions("view","SE");
  else if ( keyChar=="5" )
    actions("view","S");
  else if ( keyChar=="6" )
    actions("view","SW");
  else if ( keyChar=="7" )
    actions("view","W");
  else if ( keyChar=="8" )
    actions("view","NW");

  return;
}

function SelectAllList(CONTROL){
  for(var i = 0;i < CONTROL.length;i++){
    CONTROL.options[i].selected = true;
  }
}

function DeselectAllList(CONTROL){
  for(var i = 0;i < CONTROL.length;i++){
    CONTROL.options[i].selected = false;
  }
}

function FillListValues(CONTROL){
  var arrNewValues;
  var intNewPos;
  var strTemp = GetSelectValues(CONTROL);
  arrNewValues = strTemp.split(",");
  for(var i=0;i<arrNewValues.length-1;i++){
    if(arrNewValues[i]==1){
      intNewPos = i;
    }
  }

  for(var i=0;i<arrOldValues.length-1;i++){
    if(arrOldValues[i]==1 && i != intNewPos){
      CONTROL.options[i].selected= true;
    }
    else if(arrOldValues[i]==0 && i != intNewPos){
      CONTROL.options[i].selected= false;
    }

    if(arrOldValues[intNewPos]== 1){
      CONTROL.options[intNewPos].selected = false;
    }
    else{
      CONTROL.options[intNewPos].selected = true;
    }
  }
}

function GetSelectValues(CONTROL){
  var strTemp = "";
  for(var i = 0;i < CONTROL.length;i++){
    if(CONTROL.options[i].selected == true){
      strTemp += "1,";
    }
    else{
      strTemp += "0,";
    }
  }
  return strTemp;
}

function GetCurrentListValues(CONTROL){
  var strValues = "";
  strValues = GetSelectValues(CONTROL);
  arrOldValues = strValues.split(",")
}

//Pass selected lords from the selDistFood form to php for processing
//CONTROL is an array of lords listed in the select box - it contains both selected and unselected lords.
function distributeFood(CONTROL, maxStores){
  var serializedData = "";
  var selectedLords = [];
  var maxDist = 0;

  //Filter out unselected lords
  for(var i = 0;i < CONTROL.length;i++){
    if(CONTROL.options[i].selected == true)
      selectedLords[i] = eval(CONTROL.options[i].value);
  }

  if(selectedLords.length == 0){
    alert("You have not selected any lords to receive the food!");
    return false;
  }
  
  if(!(isNaN(maxStores.value))) maxDist = maxStores.value;
  //alert (maxStores.value)
  //Convert array of lords into a string which can then be passed to PHP to be reverted into an array by the unserialize() function
  serializedData = php_serialize(selectedLords);
  opener.parent.location = "./midnight_distribute_food_process.php?maxStores=" + maxDist + "&lords= " + escape(serializedData);
  window.close();

  return false;
}


/** PHP Serialize - by Morten Amundsen (mor10am@gmail.com) */
function php_serialize(obj){
  var string = '';

  if(typeof(obj) == 'object'){
    if(obj instanceof Array){
      string = 'a:';
      tmpstring = '';
      count = 0;
      for(var key in obj){
        tmpstring += php_serialize(key);
        tmpstring += php_serialize(obj[key]);
        count++;
      }
      string += count + ':{';
      string += tmpstring;
      string += '}';
    }
    else if(obj instanceof Object){
      classname = obj.toString();

      if(classname == '[object Object]'){
        classname = 'StdClass';
      }

      string = 'O:' + classname.length + ':"' + classname + '":';
      tmpstring = '';
      count = 0;
      for(var key in obj){
        tmpstring += php_serialize(key);
        if(obj[key]){
          tmpstring += php_serialize(obj[key]);
        }
        else{
          tmpstring += php_serialize('');
        }
        count++;
      }
      string += count + ':{' + tmpstring + '}';
    }
  }
  else{
    switch(typeof(obj)){
      case 'number':
        if(obj - Math.floor(obj) != 0){
          string += 'd:' + obj + ';';
        }
        else{
          string += 'i:' + obj + ';';
        }
        break;

      case 'string':
        string += 's:' + obj.length + ':"' + obj + '";';
        break;

      case 'boolean':
        if(obj){
          string += 'b:1;';
        }
        else{
          string += 'b:0;';
        }
        break;
    }
  }
  return string;
}

sfHover = function(){
  var sfEls = document.getElementById("nav").getElementsByTagName("LI");
  for (var i=0; i<sfEls.length; i++){
    sfEls[i].onmouseover=function(){
      this.className+=" sfhover";
    }
    sfEls[i].onmouseout=function(){
      this.className=this.className.replace(new RegExp(" sfhover\\b"), "");
    }
  }
}

//if (window.attachEvent) window.attachEvent("onload", sfHover);

function init(){
  var browser = new BrowserDetect();

  if(browser.isIE);
  else
    if (window.attachEvent) window.attachEvent("onload", sfHover);
  return false;
}

function hideDivs(exempt){
  if (!document.getElementsByTagName) {
    return null;
  }
  if (!exempt) exempt = "";
  var divs =
    document.getElementsByTagName("div");
  for(var i=0; i < divs.length; i++)
  {
    var div = divs[i];
    var id = div.id;
    if ((id.indexOf("admOp") != -1) &&
        (id != exempt))
    {
      //div.className = "hidden";
      div.style.display = "none";
    }
  }
}

function fixLinks(){
  if (!document.getElementsByTagName) {
    return null;
  }
  var anchors =
    document.getElementsByTagName("a");
  for(var i=0; i < anchors.length; i++)
  {
    var a = anchors[i];
    var href = a.href;
    if ((href.indexOf("#") != -1) &&
        (href.indexOf("header") == -1))
    {
      var index = href.indexOf("#") + 1;
      href = "javascript:show('" +
        href.substring(index) + "');";
      a.setAttribute("href",href);
    }
  }
}

function show(what){
  if (!document.getElementById) {
    return null;
  }
  showWhat =
    document.getElementById(what);
  //showWhat.className = "box_container";
  showWhat.style.display = "block";
  hideDivs(what);
}

function initOverLabels () {
  if (!document.getElementById) return;  	

  var labels, id, field;

  // Set focus and blur handlers to hide and show 
  // LABELs with 'overlabel' class names.
  labels = document.getElementsByTagName('label');
  for (var i = 0; i < labels.length; i++) {
	
    if (labels[i].className == 'overlabel') {

      // Skip labels that do not have a named association
      // with another field.
      id = labels[i].htmlFor || labels[i].getAttribute('for');
      if (!id || !(field = document.getElementById(id))) {
        continue;
      }

      // Change the applied class to hover the label 
      // over the form field.
      labels[i].className = 'overlabel-apply';

      // Hide any fields having an initial value.
      if (field.value !== '') {
        hideLabel(field.getAttribute('id'), true);
      }

      // Set handlers to show and hide labels.
      field.onfocus = function () {
        hideLabel(this.getAttribute('id'), true);
      };
      field.onblur = function () {
        if (this.value === '') {
          hideLabel(this.getAttribute('id'), false);
        }
      };

      // Handle clicks to LABEL elements (for Safari).
      labels[i].onclick = function () {
        var id, field;
        id = this.getAttribute('for');
        if (id && (field = document.getElementById(id))) {
          field.focus();
        }
      };

    }
  }
};

function hideLabel (field_id, hide) {
  var field_for;
  var labels = document.getElementsByTagName('label');
  for (var i = 0; i < labels.length; i++) {
    field_for = labels[i].htmlFor || labels[i].getAttribute('for');
    if (field_for == field_id) {
      labels[i].style.textIndent = (hide) ? '-1000px' : '0px';
      return true;
    }
  }
}


  //window.onload = function(){
  //  hideDivs("intro");
  //  fixLinks();
  //}
//window.onload=init;