/*******************************************************************************
* Event Registration - register.js                                             *
*              JavaScript file for register.php                                *
*                                                                              *
* Version 001--Originial Version                                               *
*              1140565--Marc Rodriguez                                         *
*              02/19/08--Jose Rosado                                           *
*******************************************************************************/
/***************************************
* Global Variables                     *
***************************************/
var xmlHttp = false; // AJAX HTTP request object
var xmlDoc = false; // XML document containing data from response string

/***************************************
* Global Functions                     *
***************************************/
// Loads the passed string into global XML document object
function loadXML( strXML )
{
  xmlDoc = false;
  
  // Create XML document from passed string
  try //Internet Explorer
  {
    xmlDoc = new ActiveXObject( "Microsoft.XMLDOM" );
    xmlDoc.async= "false";
    xmlDoc.loadXML( strXML );
  }
  catch( e )
  {
    try //Firefox, Mozilla, Opera, etc.
    {
      parser = new DOMParser();
      xmlDoc = parser.parseFromString( strXML, "text/xml" );
    }
    catch( e )
    { 
      // Could not load XML string
      xmlDoc = false;
    }
  }
} // loadXML()

// Formats passed number to US currency format
function formatCurrency( num ) 
{
  num = num.toString().replace( /\$|\,/g,'' );
  
  if( isNaN( num ) )
  {
    num = "0";
  }
  
  sign = ( num == ( num = Math.abs( num ) ) );
  num = Math.floor( num * 100 + 0.50000000001 );
  cents = num % 100;
  num = Math.floor( num / 100 ).toString();
  
  if( cents < 10 )
  {
    cents = "0" + cents;
  }
  
  for( var i = 0; i < Math.floor( ( num.length - ( 1 + i ) ) / 3 ); i++)
  {
    num = num.substring( 0, num.length - ( 4 * i + 3 ) ) + ',' + num.substring( num.length - ( 4 * i + 3 ) );
  }
  
  return ( ( ( sign ) ? '' : '-' ) + '$' + num + '.' + cents );
} // formatCurrency()

// Empties the location selection list
function emptyLocations()
{
  var selLoc = window.document.getElementById( "selLoc" ); // Location selection list
  var lstLoc = selLoc.getElementsByTagName( "OPTION" ); // List of <option>s in selection list
  
  // Iterate backwards through child nodes and remove valid options
  for( var i = ( lstLoc.length - 1 ); i >= 0; i-- )
  {
    // Check if node is an element node
    if( lstLoc[ i ].nodeType == 1 )
    {
      // Check if element is indeed an <option> element
      if( lstLoc[ i ].nodeName == "OPTION" )
      {
        // Check if <option> has a valid value
        if( lstLoc[ i ].value !== "" )
        {
          // Remove the node
          selLoc.removeChild( lstLoc[ i ] );
        }
      }
    }
  }
} // emptyLocations()

// Empties the date selection list
function emptyDates()
{
  var selDate = window.document.getElementById( "selDate" ); // Date selection list
  var lstDate = selDate.getElementsByTagName( "OPTION" ); // List of <option>s in selection list

  // Iterate backwards through child nodes and remove valid options
  for( var i = ( lstDate.length - 1 ); i >= 0; i-- )
  {
    // Check if node is an element node
    if( lstDate[ i ].nodeType == 1 )
    {
      // Check if element is indeed an <option> element
      if( lstDate[ i ].nodeName == "OPTION" )
      {
        // Check if <option> has a valid value
        if( lstDate[ i ].value !== "" )
        {
          // Remove the node
          selDate.removeChild( lstDate[ i ] );
        }
      }
    }
  }
} // emptyDates()

// Empties the price selection list
function emptyPrices()
{
  var selPrice = window.document.getElementById( "selPrice" ); // Price selection list
  var lstPrice = selPrice.getElementsByTagName( "OPTION" ); // List of <option>s in selection list
  
  // Iterate backwards through child nodes and remove valid options
  for( var i = ( lstPrice.length - 1); i >= 0; i-- )
  {
    // Check if node is an element node
    if( lstPrice[ i ].nodeType == 1 )
    {
      // Check if element is indeed an <option> element
      if( lstPrice[ i ].nodeName == "OPTION" )
      {
        // Check if <option> has a valid value
        if( lstPrice[ i ].value !== "" )
        {
          // Remove the node
          selPrice.removeChild( lstPrice[ i ] );
        }
      }
    }
  }
} // emptyPrices()

// Empties the hidden event input fields
function emptyEvent()
{
  window.document.getElementById( "hidId" ).value = ""; // Empty Event ID
  window.document.getElementById( "hidTrainer" ).value = ""; // Empty event trainer
  window.document.getElementById( "divDesc" ).innerHTML = ""; // Empty event description
  window.document.getElementById( "divAddress" ).innerHTML = ""; // Empty event address
} // emptyEvent()

// Loads the locations selection list with data from global XML document
function loadLocations()
{
  // Empty out the old lists before starting to populate
  emptyLocations();
  emptyDates();
  emptyPrices();
  emptyEvent();
  
  var selLoc = window.document.getElementById( "selLoc" ); // Location selection list
  var lstLoc = xmlDoc.getElementsByTagName( "LOC" ); // List of <LOC> nodes in XML doc
  var lstDesc = xmlDoc.getElementsByTagName( "DESC" ); // List of <DESC> nodes in XML doc

  for( var i = 0; i < lstLoc.length; i++ )
  {
    var strLoc = lstLoc[ i ].childNodes[ 0 ].nodeValue; // The value of the <LOC> element
    var strDesc = lstDesc[ i ].childNodes[ 0 ].nodeValue; // The value of the <DESC> element
    var elmLoc = window.document.createElement( "option" ); // New <option> element
    var elmText = window.document.createTextNode( strDesc ); // A text node of the location

    // Assign value to new <option>
    elmLoc.value = strLoc;
    // Append text node to new <option>
    elmLoc.appendChild( elmText );
    // Append new <option> to selection list
    selLoc.appendChild( elmLoc );
  }
} // loadLocations()

// Loads the date selection list with data from global XML document
function loadDates()
{
  // Empty out the old lists before starting to populate
  emptyDates();
  emptyPrices();
  emptyEvent();

  var selDate = window.document.getElementById( "selDate" ); // Date selection list
  var lstDate = xmlDoc.getElementsByTagName( "DATE" ); // List of <DATE> nodes in XML doc
  var lstDesc = xmlDoc.getElementsByTagName( "DESC" ); // List of <DESC> nodes in XML doc

  // Iterate through <DATE>s and create <option>s in date selection list
  for( var i = 0; i < lstDate.length; i++ )
  {
    var strDate = lstDate[ i ].childNodes[ 0 ].nodeValue; // The value of the <DATE> element
    var strDesc = lstDesc[ i ].childNodes[ 0 ].nodeValue; // The value of the <DESC> element
    var elmDate = window.document.createElement( "option" ); // New <option> element
    var elmText = window.document.createTextNode( strDesc ); // The description of date
    
    // Assign value to new <option>
    elmDate.value = strDate;
    // Append text to new <option>
    elmDate.appendChild( elmText );
    // Append new <option> to selection list
    selDate.appendChild( elmDate );
  }
} // loadDates()

// Loads price selection list with data from global XML doc
function loadPrices()
{
  // Empty out the old lists before starting to populate
  emptyPrices();
  emptyEvent();
  
  var selPrice = window.document.getElementById( "selPrice" ); // Price selection list
  var lstPrice = xmlDoc.getElementsByTagName( "PRICE" ); // List of <PRICE> nodes in XML doc
  var lstDesc = xmlDoc.getElementsByTagName( "DESC" ); // List of <DESC> nodes in XML doc
  
  // Iterate through <PRICE>s and create <option>s in price selection list
  for( var i = 0; i < lstPrice.length; i++ )
  {
    var strPrice = lstPrice[ i ].childNodes[ 0 ].nodeValue; // The value of the <PRICE> element
    var strDesc = lstDesc[ i ].childNodes[ 0 ].nodeValue // The value of the <DESC> element
    var elmPrice = window.document.createElement( "option" ); // New <option> element
    var elmText; // The value of the <PRICE> element
    
    if( parseFloat( strPrice ) >= 1000 )
    {
      
    }
    
    // Write description of registration price option with value of matching <DESC> node
    switch( i )
    {
      case 0:
        elmText = window.document.createTextNode( strDesc + " @ " + formatCurrency( strPrice ) );
        break;
      case 1:
        elmText = window.document.createTextNode( strDesc + " @ " + formatCurrency( strPrice ) );
        break;
      case 2:
        elmText = window.document.createTextNode( strDesc + " @ " + formatCurrency( strPrice ) );
        break;
      default:
        break;
    }
    
    // Assign value to new <option>
    elmPrice.value = strPrice;
    // Append text to new <option>
    elmPrice.appendChild( elmText );
    // Append new <option to selection list
    selPrice.appendChild( elmPrice );
  }
} // loadPrices()

// Loads hidden event inputs with data from global XML doc
function loadEvent()
{
  // Empty out the old lists before starting to populate
  emptyEvent();

  var hidId = window.document.getElementById( "hidId" ); // The ID of the event being registered for
  var hidTrainer = window.document.getElementById( "hidTrainer" ); // The trainer for the event
  var divDesc = window.document.getElementById( "divDesc" ); // The description of the event
  var divAddress = window.document.getElementById( "divAddress" ); // The address of the event
  var lstEvent = xmlDoc.getElementsByTagName( "EVENT" ); // List of <EVENT> nodes in XML doc

  // Iterate through <EVENT>s and populate hidden fields
  for( var i = 0; i < lstEvent.length; i++ )
  {
    var strEvent = lstEvent[ i ].childNodes[ 0 ].nodeValue; // The value of the <EVENT> element
    
    // Assign value based on which event tag is being read
    switch( i )
    {
      // Record ID of the event
      case 0:
        hidId.value = strEvent;
        break;
      // The Master trainer for the event
      case 1:
        hidTrainer.value = strEvent;
        break;
      // The description of the event
      case 2:
        divDesc.innerHTML = strEvent;
        break;
      // The address of the event
      case 3:
        // Replace semi-colons with line breaks as line breaks are not easily passed via AJAX
        strEvent = strEvent.replace( /;/g, "<br />");
        divAddress.innerHTML = strEvent;
        break;
      default:
        break;
    }
  }
}

// Handles the response text from HTTP request
function handleResponse()
{ 
  // Switch handling based on stated of HTTP request object
  switch( xmlHttp.readyState )
  {
    case 0:
      // Request not initializes
      break;
    case 1:
      // Request has been set up
      break;
    case 2:
      // Request has been sent
      break;
    case 3:
      // Request in progress
      break;
    case 4:
      // Request is complete
      // Load the response text into XML document
      loadXML( xmlHttp.responseText );
      
      // Check if XML doc was successfully loaded
      if( xmlDoc !== false )
      {
        // Switch handling based on XML doc's root element
        switch( xmlDoc.documentElement.nodeName )
        {
          // Location data recieved
          case "LOC_list":
            loadLocations();
            break;
          // Date data recieved
          case "DATE_list":
            loadDates();
            break;
          // Price data recieved
          case "PRICE_list":
            loadPrices();
            break;
          // Event data recieved
          case "EVENT_list":
            loadEvent();
            break;
          default:
            break;
        }
      }
      break;
    default:
      break;
  }
} // handleResponse()

// Sends the AJAX HTTP request
function sendRequest( strParms )
{
  xmlHttp = false;
  
  // Create HTTP request object
  try
  {
    // Firefox, Opera 8.0+, Safari
    xmlHttp=new XMLHttpRequest();
  }
  catch( e )
  {
    // Internet Explorer
    try
    {
      xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
    }
    catch( e )
    {
      try
      {
        xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
      }
      catch( e )
      {
        // Could not create HTTP request object
        xmlHttp = false;
        return;
      }
    }
  }
  
  // Assign response handler
  xmlHttp.onreadystatechange = handleResponse;
  
  // Send request
  xmlHttp.open( "GET", "register.ajax.php?" + strParms, true );
  xmlHttp.send( null );
} // sendRequest()

// Called by onChange event from selection list. Formats data for HTTP request to get further event info.
function getEventInfo( strId, strSelect )
{ 
  // Check if valid option was selected
  if( strSelect === "" )
  {
    // No valid option was selected, so return
    return;
  }
  
  var strEvent = window.document.getElementById( "selEvent" ).value; // The value of the currently selected event
  var strLoc = window.document.getElementById( "selLoc" ).value; // The value of the currently selected location
  var strDate = window.document.getElementById( "selDate" ).value; // The value of the currently selected date
  var strInfo = ""; // The info to be requested
  
  // Switch on what info to get based on the ID of the element that called this function
  switch( strId )
  {
    // Event has been selected, so request locations
    case "selEvent":
      strInfo = "LOC";
      break;
    // Location has been selected, so request dates
    case "selLoc":
      strInfo = "DATE";
      break;
    case "selDate":
      strInfo = "PRICE";
      break;
    case "selPrice":
      strInfo = "EVENT";
      break;
    default:
      strInfo = "";
      break;
  }
  
  var strRequest = "INFO=" + strInfo + "&EVENT=" + strEvent + "&LOC=" + strLoc + "&DATE=" + strDate;
  
  // Send HTTP request
  // Check to see if we have a valid INFO string to pass
  if( strInfo !== "" )
  {
    sendRequest( strRequest );
  }
} // getEventInfo()

// Gets the class of the passed element based on the browser
function getClass( elm )
{
}
// Validates the form before submitting, displays error and returns false if error
function validate()
{
  var blnError = false; // Boolean containing whether error has been encountered

  // Array of elements to validate
  var aryVal = new Array();
  aryVal[ 0 ] = window.document.getElementById( "selEvent" );    // Event selection list
  aryVal[ 1 ] = window.document.getElementById( "selLoc" );      // Location selection list
  aryVal[ 2 ] = window.document.getElementById( "selDate" );     // Date selection list
  aryVal[ 3 ] = window.document.getElementById( "selPrice" );    // Price selection list
  aryVal[ 4 ] = window.document.getElementById( "txtName" );     // Name input field
  aryVal[ 5 ] = window.document.getElementById( "txtAddress" );  // Address input field
  aryVal[ 6 ] = window.document.getElementById( "txtCity" );     // City input field
  aryVal[ 7 ] = window.document.getElementById( "txtState" );    // State input field
  aryVal[ 8 ] = window.document.getElementById( "txtZip" );      // Zip input field
  
  for( var i in aryVal )
  {
    if( aryVal[ i ].value === "" )
    {
      var elmParent = aryVal[ i ].parentNode; // The parent node of the element being validated
      var lstSpan = elmParent.getElementsByTagName( "SPAN" ); // List of span nodes in the parent element
      var txtError = window.document.createTextNode( "*" ); // Error string to be added to parent node
      var spnError = window.document.createElement( "span" ); // Span to contain error message
      
      // Iterate through span list and remove old error spans
      for( var j = ( lstSpan.length - 1 ); j >= 0; j-- )
      {
        // If span is of class "error", remove it
        if( lstSpan[ j ].getAttribute( "class" ) == "error" || lstSpan[ j ].getAttribute( "className" ) == "error" )
        {
          elmParent.removeChild( lstSpan[ j ] );
        }
      }
      
      // Assign attributes to error span
      spnError.id = "err" + aryVal[ i ].id;
      spnError.setAttribute( "class", "error" );
      spnError.setAttribute( "className", "error" );
      
      // Append error text to error span
      spnError.appendChild( txtError );
      // Append span to parent node before node being validated
      elmParent.insertBefore( spnError, aryVal[ i ] );
      
      blnError = true;
    }
    else
    {
      var elmParent = aryVal[ i ].parentNode; // The parent node of the element being validated
      var lstSpan = elmParent.getElementsByTagName( "SPAN" ); // List of span nodes in the parent element
      
      // Iterate through spans
      for( var j = ( lstSpan.length - 1 ); j >= 0; j-- )
      {
        // If span is of class "error", remove
        if( lstSpan[ j ].getAttribute( "class" ) == "error" || lstSpan[ j ].getAttribute( "className" ) == "error" )
        {
          elmParent.removeChild( lstSpan[ j ] );
        }
      }
    }
  }
  
  // If there was a validation error, display error message on top of form
  if( blnError )
  {
    // Add text to error div
    window.document.getElementById( "divError" ).innerHTML = "* Required Fields"
  }
  else
  {
    // Remove text from error div
    window.document.getElementById( "divError" ).innerHTML = "";
  }
  
  return !blnError;
} // validate()