
/**  ********************************************** **/
/**  Forio Broadcast JavaScript functions           **/
/**  (c) Forio Business Simulations, 2002-7.        **/
/**                                                 **/
/**  Permission is granted to modify and use        **/
/**  these functions within a business simulation   **/
/**  served by Forio Broadcast provided this        **/
/**  notice is included verbatim.                   **/
/**  ********************************************** **/


// Save decisions (if any are present on this screen)
// then advance the simulation.
// Decision form must be named "Decisions" and contain hidden field "FD_action"
// Form with drop down must be named "advance" and contain drop down field "FD_action".
function FD_executeAdvanceDropDown(advanceUrl, resetUrl) {
    
    var formRef = document.Decisions;   // document.<FormName>
    var formRef2 = document.Advance;    // document.<FormName>
    var newURL = advanceUrl;
    
    var action = "";
    if ((formRef2 != null) && (formRef2.FD_action != null))
        var action = formRef2.FD_action.options[formRef2.FD_action.selectedIndex].value;
    
    if (action.toUpperCase().substring(0,5) == "RESET")
        newURL = resetUrl;
    
    // no decisions form-- just advance the sim
    if (formRef == null) {

        // add the query parameter
        if (newURL.indexOf("?") == -1)
            document.location = newURL + "?FD_action=" + action; 
        else
            document.location = newURL + "&FD_action=" + action;  

    // save the decisions and step the simulation
    } else {
        formRef.action = newURL;     // post decisions and go to new page
        formRef.FD_action.value = action;       
        formRef.submit();
    }
}


// Save the decisions when we go to another page.
// Also typically includes extra query tags added by the FML
function FD_gotoLink(newURL) {

    // save the decisions but do not step
    var formRef = document.Decisions;   // document.<FormName>
    if (formRef == null) {
        document.location = newURL; // go to new page
    
    // found a decisions form
    } else {
    
        // search for all FD_action elements and blank them out
        for (var i=0; i < formRef.elements.length; i++) {
            var elem = formRef.elements[i];
            var fldname = elem.name;
            if ( fldname.toLowerCase() == "fd_action" )
                elem.value = "";
        }

    
        formRef.action = newURL;     // post decisions and go to new page

        // may give an error if there an element in the form named submit
        formRef.submit();
    }
}


// Validates a newly entered decision.
// Change the name of the decision form if neccessary.
var AlertInProgress = false;
function FD_validateField(theField, Min, Max, numberFormat) {

    // if we are in middle of validation, then exit
    if (AlertInProgress) {return;}

    var ErrorMessage="";
    var theValue = parseFloat(FD_stripFormat(theField.value));

    if (isNaN(theValue))
    {
        ErrorMessage = "Please enter a number.";
    
    }

    // replace with formatted value
    else
    {
	theField.value = FD_formatDecision(theValue, numberFormat);	
    }

    // Check Min/Max
    if ((typeof Min == "number") && (typeof Max == "number")) 
    {
        if (theValue < Min) 
        {
            ErrorMessage = "Please enter a value between " + Min + " and " + Max + "!";
            theField.value = FD_formatDecision(Min, numberFormat);
            
        }
        else if (theValue > Max) 
        {
            ErrorMessage = "Please enter a value between " + Min + " and " + Max + "!";
            theField.value = FD_formatDecision(Max, numberFormat);
        }

    } 
    else if ((typeof Min == "number") && (typeof Max != "number")) 
    {
        if (theValue < Min)  
        {
            ErrorMessage = "Please enter a value greater than " + Min + "!";
            theField.value = FD_formatDecision(Min, numberFormat);
        }
    } 
    else if ((typeof Min != "number") && (typeof Max == "number")) 
    {
        if (theValue > Max)  
        {
            ErrorMessage = "Please enter a value less than " + Max + "!";
            theField.value = FD_formatDecision(Max, numberFormat);
        }
    }

    // bad input
    if (ErrorMessage != "") {
        AlertInProgress = true;  
        alert (ErrorMessage);

	// use a timeout to work around problem with Firefox	
	var focusFunction = function() {theField.focus(); theField.select();};
	setTimeout(focusFunction,50);
    }
    AlertInProgress=false;
} 

function FD_formatDecision(theValue, numberFormat)
{

    if (numberFormat && numberFormat.length > 0)
    {
        // special logic for percent applies when numberFormat includes a percent.
        //        ENTRY   RESULT
        //        12%     divide by 100 = .12
        //        12      divide by 100 = .12
        //        .12%    divide by 100 = .0012
        //        .12     use exact entry = .12

        if ((numberFormat.indexOf("%") != -1) && (theField.value.indexOf("%") != -1))
        {
            return FD_formatNumber(theValue/100,numberFormat);
        }
        else if ((numberFormat.indexOf("%") != -1) && (theField.value.indexOf("%") == -1) && (theValue >=1))
        {
            return FD_formatNumber(theValue/100,numberFormat);
        }
        else
        {
            return FD_formatNumber(theValue,numberFormat);
        }
    }
    else
    {
        return theValue;
    }
}


// Remove commas, dollar sign, spaces, percent from string
function FD_stripFormat(inputString) {
    var newString = inputString;
    
    // remove comma
    while (newString.indexOf(",") != -1) {
        newString = newString.replace(",","");
    }
    
    // remove $
    while (newString.indexOf("$") != -1) {
        newString = newString.substring(0, newString.indexOf("$"))  + newString.substring(newString.indexOf("$")+1);
    }
    
    // remove spaces
    while (newString.indexOf(" ") != -1) {
        newString = newString.replace(" ","");
    }
    
    // remove percent
    while (newString.indexOf("%") != -1) {
        newString = newString.replace("%","");
    }

    return newString;
}


// Sets the value of a field for a given form.
//
//      frm -- a form reference
//      fldname -- name of the field
//      value -- value to set the field to

function setField(frm, fldname, val)
{
    var fld = getField(frm,fldname);
    if (fld != null)
        fld.value = val;
    else
        alert("No such field " + fldname);
}


// Return a reference to a given field
// This is helpful to use when a field name has a space in it.
//
//      frm -- a form reference
//      fldname -- name of the field

function getField(frm,fldName)
{
    for (var i=0; i < frm.elements.length; i++) {
        var elem = frm.elements[i];
        if (elem.name == fldName)
            return elem;
    }
}



// set a decision field based on whether a boolean value is true or false
function setDecisionField(frm, bool, decisionfldname, truevalue, falsevalue)
{
    if (bool)
        setField(frm,decisionfldname,truevalue);
    else
        setField(frm,decisionfldname,falsevalue);
}


// Original JavaScript code by Duncan Crombie: dcrombie@chirp.com.au
// Please acknowledge use of this code by including this header.

   // CONSTANTS
  var separator = ",";  // use comma as 000's separator
  var decpoint = ".";  // use period as decimal point
  var percent = "%";
  var currency = "$";  // use dollar sign for currency

  function FD_formatNumber(number, format, forceNegativeParens) {  // use: FD_formatNumber(number, "format")
    
    if (number - 0 != number) return null;  // if number is NaN return null
    var useSeparator = format.indexOf(separator) != -1;  // use separators in number
    var usePercent = format.indexOf(percent) != -1;  // convert output to percentage
    var useCurrency = format.indexOf(currency) != -1;  // use currency format
    var isNegative = (number < 0);
    number = Math.abs (number);
    if (usePercent) number *= 100;
    format = strip(format, separator + percent + currency);  // remove key characters
    number = "" + number;  // convert number input to string

     // split input value into LHS and RHS using decpoint as divider
    var dec = number.indexOf(decpoint) != -1;
    var nleftEnd = (dec) ? number.substring(0, number.indexOf(".")) : number;
    var nrightEnd = (dec) ? number.substring(number.indexOf(".") + 1) : "";

     // split format string into LHS and RHS using decpoint as divider
    dec = format.indexOf(decpoint) != -1;
    var sleftEnd = (dec) ? format.substring(0, format.indexOf(".")) : format;
    var srightEnd = (dec) ? format.substring(format.indexOf(".") + 1) : "";

     // adjust decimal places by cropping or adding zeros to LHS of number
    if (srightEnd.length < nrightEnd.length) {
      var nextChar = nrightEnd.charAt(srightEnd.length) - 0;
      nrightEnd = nrightEnd.substring(0, srightEnd.length);
      if (nextChar >= 5) nrightEnd = "" + ((nrightEnd - 0) + 1);  // round up

 // patch provided by Patti Marcoux 1999/08/06
      while (srightEnd.length > nrightEnd.length) {
        nrightEnd = "0" + nrightEnd;
      }

      if (srightEnd.length < nrightEnd.length) {
        nrightEnd = nrightEnd.substring(1);
        nleftEnd = (nleftEnd - 0) + 1;
      }
    } else {
      for (var i=nrightEnd.length; srightEnd.length > nrightEnd.length; i++) {
        if (srightEnd.charAt(i) == "0") nrightEnd += "0";  // append zero to RHS of number
        else break;
      }
    }

     // adjust leading zeros
    sleftEnd = strip(sleftEnd, "#");  // remove hashes from LHS of format
    while (sleftEnd.length > nleftEnd.length) {
      nleftEnd = "0" + nleftEnd;  // prepend zero to LHS of number
    }

    if (useSeparator) nleftEnd = separate(nleftEnd, separator);  // add separator
    var output = nleftEnd + ((nrightEnd != "") ? "." + nrightEnd : "");  // combine parts
    output = ((useCurrency) ? currency : "") + output + ((usePercent) ? percent : "");
    if (isNegative) {
      // patch suggested by Tom Denn 25/4/2001
      output = (useCurrency || forceNegativeParens) ? "(" + output + ")" : "-" + output;
    }
    return output;
  }

  function strip(input, chars) {  // strip all characters in 'chars' from input
    var output = "";  // initialise output string
    for (var i=0; i < input.length; i++)
      if (chars.indexOf(input.charAt(i)) == -1)
        output += input.charAt(i);
    return output;
  }

  function separate(input, separator) {  // format input using 'separator' to mark 000's
    input = "" + input;
    var output = "";  // initialise output string
    for (var i=0; i < input.length; i++) {
      if (i != 0 && (input.length - i) % 3 == 0) output += separator;
      output += input.charAt(i);
    }
    return output;
  }
  
