/*
Script:	AJAX stuff for e-lunches
Author:	Andrew Snowball
Date:	2009.10.26
*/

// --- Basic HTTP object used by all AJAX calls
function getHTTPObject(){
  if ( window.ActiveXObject )
    return new ActiveXObject("Microsoft.XMLHTTP");
  else if ( window.XMLHttpRequest )
    return new XMLHttpRequest();
  else {
    alert("Your browser does not support AJAX.");
    return null;
  }
}

// --- Obtain school data from DB and return it to populate 2 DIVs on the form
function ObtainSchoolInfo() {
  httpObject = getHTTPObject();

  if ( httpObject != null ) {
    httpObject.open( "GET", "getschoolinfo.php?SchoolID=" + document.getElementById( 'SchoolID' ).value, true );
    httpObject.send( null );
    httpObject.onreadystatechange = PopulateSchoolData;
  }
}
// --- Return the data
function PopulateSchoolData() {
  if ( httpObject.readyState == 4 ) {
    var ResultText = httpObject.responseText.split( "|" );
    document.getElementById( 'SchoolDIV' ).innerHTML = ResultText[0];
    document.getElementById( 'ItemsDIV' ).innerHTML  = ResultText[1];
  }
}

// --- Update and return the contents of a lunch order (bag)
function ChangeLunchBag( pVerb ) {
  httpObject = getHTTPObject();

  if ( httpObject != null ) {

  // --- Parse the form
    var TheForm = document.OrderForm;

  // --- store which movement
    var sItemType;
    if ( pVerb == "add" ) {
      sItemType = "available";
    } else if ( pVerb == "remove" ) {
      sItemType = "selected";
    } else {
      return;
    }

  // --- Get all selected items

    var sItems = "";

    for( var k in TheForm ) {
      var BaseName = k.split( "_" );
      if ( BaseName[0] == sItemType ) {
        box = eval( "TheForm." + sItemType + "_" + BaseName[1] );
        if ( box.checked ) {
          sItems += BaseName[1] + ",";
          box.checked = false;
        } // - was checked
      } // - correct item type
    } // - for every form field

    var Params = sItems.substring( 0, sItems.length - 1 );	// - Chop off the last ","

    httpObject.open( "GET", "updatelunchorder.php?" + pVerb + "=" + Params, true );
    httpObject.send( null );
    httpObject.onreadystatechange = PopulateLunchOrder;
  }
} // - ChangeLunchBag

// --- Return the data
function PopulateLunchOrder() {
  if ( httpObject.readyState == 4 ) {
    var ResultText = httpObject.responseText.split( "|" );
    document.getElementById( 'LunchBagDIV' ).innerHTML   = ResultText[0];
    document.getElementById( 'LunchTotalDIV' ).innerHTML = ResultText[1];
  }
}

// --- End of Script: lunchajax.js --- //
