/**
 * IIC Live - functions.js
 *
 * Javascript functions to support the site.
 *
 * @author     Shane Archer <futureal@rctech.net>
 * @copyright  2005-2007 RC Tech, LLC
 * @version    svn: $Revision:$ $Date:$
 * @package    IICLive
 */

/** JSON structure for the various class costs. */
var classCosts = {
  1 : { 1 : 150, 2 : 90, 3 : 90 },
  2 : { 1 : 150, 2 : 90, 3 : 90 },
  3 : { 1 : 150, 2 : 90, 3 : 90 },
  4 : { 1 : 170, 2 : 110, 3 : 110 },
  5 : { 1 : 135, 2 : 70, 3 : 70 },
  6 : { 1 : 135, 2 : 70, 3 : 70 },
  7 : { 1 : 135, 2 : 70, 3 : 70 },
  8 : { 1 : 150, 2 : 90, 3 : 90 },
  9 : { 1 : 150, 2 : 90, 3 : 90 }
};

/** JSON structure for the various edit fields. */
var editFields = {
  1 : "name",
  2 : "country",
  3 : "tshirt",
  4 : "class1",
  5 : "class2",
  6 : "class3",
  7 : "address1",
  8 : "address2",
  9 : "citystatezip",
  10 : "email",
  11 : "phone",
  12 : "paypalemail",
  13 : "hometrack",
  14 : "yearsracing",
  15 : "firstcar",
  16 : "chassis",
  17 : "sponsors",
  18 : "payingfor",
  19 : "paidby",
  20 : "poker"
};

/** JSON structure for the various edit class fields. */
var editClassFields = {
  1 : "transponder",
  2 : "freq1",
  3 : "freq2",
  4 : "freq3"
};

var maxCostClass = 0;

/**
 * Simulate the behavior of the PHP in_array function.
 */
Array.prototype.in_array = function(needle) {

  var i = this.length;

  if (i > 0) {

    do {

      if (this[i] === needle) {
        return true;
      }

    } while (i--);

  }

  return false;

}

/**
 * Called whenever a class selection is changed.
 */
function checkClassAddition(classNum) {

  var js_reg_class1 = document.getElementById("reg_class1");
  var js_reg_class2 = document.getElementById("reg_class2");
  var js_reg_class3 = document.getElementById("reg_class3");

  // do not allow a second or third class to be chosen before a first
  if (classNum > 1 && chosenClasses.class1 == 0) {

    alert("You must select a first class before selecting a second or third.");

    // reset whatever they just changed
    eval("js_reg_class" + classNum).selectedIndex = eval("chosenClasses.class" + classNum);

  // if they set class 1 to None, reset the others
  } else if (classNum == 1 && js_reg_class1.selectedIndex == 0) {

    js_reg_class2.selectedIndex = 0;
    js_reg_class3.selectedIndex = 0;

    // reset all saved class values
    chosenClasses.class1 = 0;
    chosenClasses.class2 = 0;
    chosenClasses.class3 = 0;

    // hide all details views
    document.getElementById("details_class1").style.display = "none";
    document.getElementById("details_class2").style.display = "none";
    document.getElementById("details_class3").style.display = "none";

    // set the styles for the headings to middle
    document.getElementById("header_class1").style.verticalAlign = "middle";
    document.getElementById("header_class2").style.verticalAlign = "middle";
    document.getElementById("header_class3").style.verticalAlign = "middle";

  // do not allow duplicates
  } else if (classIsChosen(eval("js_reg_class" + classNum).selectedIndex)) {

    alert("You may not select the same class twice.");

    // reset whatever they just changed
    eval("js_reg_class" + classNum).selectedIndex = eval("chosenClasses.class" + classNum);

  } else {

    // assemble a new array of the chosen classes
    var newChosen = new Array();
    var newChosenSize = 0;

    for (var i = 0; i < 3; i++) {

      if ((i+1) == classNum) {

        var newValue = eval("js_reg_class" + classNum).selectedIndex;

        if (newValue > 0) {
          newChosenSize = newChosen.push(newValue);
        }

      } else {

        if (chosenClasses["class" + (i+1)] > 0) {
          newChosenSize = newChosen.push(chosenClasses["class" + (i+1)]);
        }

      }

    }

    // if the size is three, we need to make sure one of the classes is 1/12

    // 2009: took this restriction out
/*
    if (newChosenSize == 3 && !(newChosen.in_array(7) || newChosen.in_array(8))) {

      alert("If you choose three classes, one of them must be a 1/12 Scale class.");

      // reset whatever they just changed
      eval("js_reg_class" + classNum).selectedIndex = eval("chosenClasses.class" + classNum);

    } else {
*/
      // keep track of what we just changed
      chosenClasses["class" + classNum] = eval("js_reg_class" + classNum).selectedIndex;

      // un-hide the details view for this class
      document.getElementById("details_class" + classNum).style.display = "block";

      // set the style for the heading to top
      document.getElementById("header_class" + classNum).style.verticalAlign = "top";

/*
    }
*/

  }

  // do class costs any time anything changes
  calculateClassCosts();

  // reset the total cost any time anything changes
  document.getElementById("cost_total").replaceChild(document.createTextNode("$" + getTotalCost() + ".00"),document.getElementById("cost_total").firstChild);

}

/**
 * Determines if a class is currently selected.
 */
function classIsChosen(classId) {

  // zero is never chosen
  if (classId == 0) {
    return false;
  }

  var i = 3;

  do {

    if (eval("chosenClasses.class" + i) == classId) {
      return true;
    }

  } while (--i);

  return false;

}

/**
 * Determine the price of a class depending on where it is looked up.
 */
function getClassPrice(classNum,classId) {

  if (classId) {
    return classCosts[classId][classNum];
  } else {
    return 0;
  }

}

/**
 * Calculate the price of each selected class.
 */
function calculateClassCosts() {

  var i = 3;
  var j = 3;

  // always start fresh
  maxCostClass = 0;

  do {

    var chosenClass = chosenClasses['class' + j];

    if (chosenClass > 0) {

      if (maxCostClass == 0) {
        maxCostClass = chosenClass;
      } else if (classCosts[chosenClass][1] > classCosts[maxCostClass][1]) {
        maxCostClass = chosenClass;
      }

    }

  } while (--j);

  do {

    var js_cost_class = document.getElementById("cost_class" + i);
    var chosenClass = chosenClasses["class" + i];

    // override this so it's either using max cost, or second cost
    if (chosenClass == maxCostClass) {
      var classCost = getClassPrice(1,chosenClass);
    } else {
      var classCost = getClassPrice(2,chosenClass);
    }

    var newPriceText = document.createTextNode("$" + classCost + ".00");

    if (classCost == 0) {

      if (js_cost_class.firstChild) {
        js_cost_class.removeChild(js_cost_class.firstChild);
      }

    } else if (classCost > 0) {

      if (js_cost_class.firstChild) {
        js_cost_class.replaceChild(newPriceText,js_cost_class.firstChild);
      } else {
        js_cost_class.appendChild(newPriceText);
      }

    }

  } while (--i);

}

/**
 * Calculate the total cost of currently selected classes.
 */
function getTotalCost() {

  var i = 3;
  var totalCost = 0;

  do {

    var chosen = eval("chosenClasses.class" + i);

    if (chosen > 0) {

      if (maxCostClass == chosen) {

        totalCost += classCosts[chosen][1];

      } else {

        totalCost += classCosts[chosen][2];

      }

    }

  } while (--i);

  return totalCost;

}

/**
 * Display or hide the proper payment info fields.
 */
function checkPaymentFields() {

  var pMethod = document.getElementById("reg_payment").selectedIndex;
  var pFor = document.getElementById("reg_payment_for").selectedIndex;

  if (pMethod == 0) {

    // hide all

    togglePFields("paypalemail","off");
    togglePFields("payingfor","off");
    togglePFields("paidby","off");

    return;

  }

  if (pMethod == 1) {

    togglePFields("paypalemail","on");

  } else if (pMethod == 2) {

    togglePFields("paypalemail","off");

  }

  if (pFor == 0) {

    togglePFields("payingfor","off");
    togglePFields("paidby","off");

  } else if (pFor == 1) {

    togglePFields("payingfor","on");
    togglePFields("paidby","off");

  } else if (pFor == 2) {

    togglePFields("payingfor","off");
    togglePFields("paidby","on");

  }

}

/**
 * Toggle the payment info fields.
 */
function togglePFields(type,state) {

  var display = (state == "on" ? "" : "none");

  document.getElementById(type + "_spacer_1").style.display = display;
  document.getElementById(type + "_text").style.display = display;
  document.getElementById(type + "_spacer_2").style.display = display;
  document.getElementById(type + "_field").style.display = display;

}

/**
 * Check for appropriate input in the various form fields.
 */
function checkFormFields() {

  // array of fields to check for non-empty
  var checkFields = {
    "reg_firstname" : "First Name",
    "reg_lastname" : "Last Name",
    "reg_email" : "Email Address",
    "reg_phone_ac" : "Area Code",
    "reg_phone_number" : "Phone Number",
    "reg_address1" : "Address 1",
    "reg_city" : "City",
    "reg_state" : "State/Province",
    "reg_postal" : "Postal Code",
    "reg_country" : "Country"
  };

  // contain any error message
  var errMsg = "";

  // check the fields
  for (var x in checkFields) {

    if (document.getElementById(x).value == "") {
      errMsg += "You must enter a value for " + checkFields[x] + ".\n";
    }

  }

  // check for t-shirt size
  if (document.getElementById("reg_tshirt").selectedIndex == 0) {
    errMsg += "You must select a T-shirt size.\n";
  }

  // check for poker tournament
  if (document.getElementById("reg_poker").selectedIndex == 0) {
    errMsg += "You must select Yes or No for the IIC Poker Tournament.\n";
  }

  // check for at least one class
  if (document.getElementById("reg_class1").selectedIndex == 0) {
    errMsg += "You must select at least one class to enter.\n";
  }

  // check payment type
  if (document.getElementById("reg_payment").selectedIndex == 0) {
    errMsg += "You must select a payment type.\n";
  }

  // check paypal field
  if ((document.getElementById("reg_payment").selectedIndex == 1) && document.getElementById('reg_paypalemail').value == '') {
    errMsg += "You must enter a PayPal email address.\n";
  }

  // check other payment fields
  if ((document.getElementById("reg_payment_for").selectedIndex == 1) && document.getElementById('reg_payingfor').value == '') {
    errMsg += "You must enter the name(s) of the drivers you are paying for, yourself included.\n";
  }

  if ((document.getElementById("reg_payment_for").selectedIndex == 2) && document.getElementById('reg_paidby').value == '') {
    errMsg += "You must enter the name of the driver who is paying for your registration.\n";
  }

  if (errMsg != "") {

    alert(errMsg);
    return false;

  } else {

    return true;

  }

}

/**
 * Check for appropriate input in the various form fields.
 */
function checkFormFieldsBypass() {

  // array of fields to check for non-empty
  var checkFields = {
    "reg_firstname" : "First Name",
    "reg_lastname" : "Last Name"
  };

  // contain any error message
  var errMsg = "";

  // check the fields
  for (var x in checkFields) {

    if (document.getElementById(x).value == "") {
      errMsg += "You must enter a value for " + checkFields[x] + ".\n";
    }

  }

  // check for t-shirt size
  if (document.getElementById("reg_tshirt").selectedIndex == 0) {
    errMsg += "You must select a T-shirt size.\n";
  }

  // check for at least one class
  if (document.getElementById("reg_class1").selectedIndex == 0) {
    errMsg += "You must select at least one class to enter.\n";
  }

  // check payment type
  if (document.getElementById("reg_payment").selectedIndex == 0) {
    errMsg += "You must select a payment type.\n";
  }

  if (errMsg != "") {

    alert(errMsg);
    return false;

  } else {

    return true;

  }

}

/**
 * Make sure all select fields are reset on page load.
 */
function iicRegInit() {

  // reset all saved class values
  chosenClasses.class1 = 0;
  chosenClasses.class2 = 0;
  chosenClasses.class3 = 0;

  // hide all details views
  document.getElementById("details_class1").style.display = "none";
  document.getElementById("details_class2").style.display = "none";
  document.getElementById("details_class3").style.display = "none";

  // reset selects
  document.getElementById("reg_class1").selectedIndex = 0;
  document.getElementById("reg_class2").selectedIndex = 0;
  document.getElementById("reg_class3").selectedIndex = 0;
  document.getElementById("reg_payment").selectedIndex = 0;

}

/**
 * When an update is made to an entry's confirm checkbox,
 * flag the appropriate hidden field in the form.
 *
 * @param mixed One or more entry IDs to toggle.
 * @param integer The source ID of the checkbox control.
 */
function changeConfirmation(entryId,source) {

  // if we got an array, run the change on each value
  if (typeof(entryId) == "object") {

    for (var i = 0; i < entryId.length; i++) {
      changeConfirmation(entryId[i],source);
    }

  } else {

    // the box that has been clicked
    var checkbox = document.getElementById("cb_confirmed_" + source);

    // this is the form
    var js_iicEntries = document.getElementById("iicEntries");

    // new value of the entry
    var entryValue = (checkbox.checked ? 1 : 0);

    if (document.getElementById("confirm_" + entryId)) {

      document.getElementById("confirm_" + entryId).value = entryValue;

    } else {

      var js_newInput = document.createElement("input");
      js_newInput.setAttribute("type","hidden");
      js_newInput.setAttribute("name","confirm_" + entryId);
      js_newInput.setAttribute("id","confirm_" + entryId);
      js_newInput.setAttribute("value",entryValue);

      js_iicEntries.appendChild(js_newInput);

    }

  }

}

/**
 * When an update is made to a driver's paid checkbox,
 * flag the appropriate hidden field in the form.
 *
 * @param integer The ID of the registered driver.
 */
function changePaid(driverId) {

  // the box that has been clicked
  var checkbox = document.getElementById("cb_paid_" + driverId);

  // this is the form
  var js_iicEntries = document.getElementById("iicEntries");

  // new value of the entry
  var paidValue = (checkbox.checked ? 1 : 0);

  if (document.getElementById("paid_" + driverId)) {

    document.getElementById("paid_" + driverId).value = paidValue;

  } else {

    var js_newInput = document.createElement("input");
    js_newInput.setAttribute("type","hidden");
    js_newInput.setAttribute("name","paid_" + driverId);
    js_newInput.setAttribute("id","paid_" + driverId);
    js_newInput.setAttribute("value",paidValue);

    js_iicEntries.appendChild(js_newInput);

  }

}

/**
 * Expand or collapse the details section of an entry.
 */
function expandEntry(entryId) {

  var js_entryDetails = document.getElementById("details_" + entryId);

  js_entryDetails.style.display = (js_entryDetails.style.display == "none" ? "" : "none");

  return false;

}

/**
 * Expand or collapse the details section of an entry, and then enable editing it.
 */
function expandAndEdit(entryId) {

  // expand it, but only if it isn't already expanded
  if (document.getElementById("details_" + entryId).style.display == "none") {
    expandEntry(entryId);
  }

  // hit each field
  for (var i in editFields) {

    var js_aFieldOff = document.getElementById(editFields[i] + "_off_" + entryId);
    var js_aFieldOn = document.getElementById(editFields[i] + "_on_" + entryId);

    if (js_aFieldOff && js_aFieldOn) {
      js_aFieldOff.style.display = "none";
      js_aFieldOn.style.display = "";
    }

  }

  // flag it as having been edited (to be checked remotely)
  var js_hiddenInput = document.createElement("input");
  js_hiddenInput.setAttribute("type","hidden");
  js_hiddenInput.setAttribute("name","edited_" + entryId);
  js_hiddenInput.setAttribute("value","true");

  document.getElementById("iicEntries").appendChild(js_hiddenInput);

  return false;

}

/**
 * Expand or collapse the details section of a class, and then enable editing it.
 */
function expandAndEditClass(classId) {

  // hit each field
  for (var i in editClassFields) {

    var js_aFieldOff = document.getElementById(editClassFields[i] + "_off_" + classId);
    var js_aFieldOn = document.getElementById(editClassFields[i] + "_on_" + classId);

    if (js_aFieldOff && js_aFieldOn) {
      js_aFieldOff.style.display = "none";
      js_aFieldOn.style.display = "";
    }

  }

  // flag it as having been edited (to be checked remotely)
  var js_hiddenInput = document.createElement("input");
  js_hiddenInput.setAttribute("type","hidden");
  js_hiddenInput.setAttribute("name","edited_" + classId);
  js_hiddenInput.setAttribute("value","true");

  document.getElementById("iicEntries").appendChild(js_hiddenInput);

}

/**
 * Ask a user to confirm deletion of a registrant, and if
 * successfully, create and submit a form for it.
 */
function deleteDriver(driverId,driverName) {

  if (confirm("Are you sure you want to delete " + driverName + "? This action cannot be undone!")) {

    var js_newForm = document.createElement("form");

    js_newForm.action = "management.php";
    js_newForm.method = "post";

    var js_formAction = document.createElement("input");
    js_formAction.setAttribute("type","hidden");
    js_formAction.setAttribute("name","iicEntryAction");
    js_formAction.setAttribute("value","update");
    js_newForm.appendChild(js_formAction);

    var js_deleteDriver = document.createElement("input");
    js_deleteDriver.setAttribute("type","hidden");
    js_deleteDriver.setAttribute("name","deleteDriver");
    js_deleteDriver.setAttribute("value",driverId);
    js_newForm.appendChild(js_deleteDriver);

    var js_returnAction = document.createElement("input");
    js_returnAction.setAttribute("type","hidden");
    js_returnAction.setAttribute("name","returnAction");
    js_returnAction.setAttribute("value","viewbyname");
    js_newForm.appendChild(js_returnAction);

    document.body.appendChild(js_newForm);
    js_newForm.submit();

  }

  return false;

}