 var request = null;
  
     function createRequest() {
       try {
         request = new XMLHttpRequest();
       } catch (trymicrosoft) {
         try {
           request = new ActiveXObject("Msxml2.XMLHTTP");
         } catch (othermicrosoft) {
           try {
             request = new ActiveXObject("Microsoft.XMLHTTP");
           } catch (failed) {
             request = null;
           }
         }
       }
  
       if (!request){
         alert("Error creating request object!");
       }
     }
     
     function createEvents(params) {
      createRequest();
      var url = "createEvents.php";
      request.open("POST", url, true);
      request.onreadystatechange =  createComplete;
      request.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
      request.send(params);
    }
  
     function getEvents() {
       createRequest();
       var url = "getEvents.php" + "?r="+Math.random();
       request.open("GET", url, true);
       request.onreadystatechange = updatePage;
       request.send(null);
    }
       
    var m_names = new Array("January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December");
    
  
    function updatePage() {
      if (request.readyState == 4) {
        if (request.status == 200) {
            var jsonData = eval('(' + request.responseText + ')');
            var events = jsonData.newevents;
            
            for(var j in events){
                    
              var eventTitle = events[j].title;
              var eventContent = events[j].content; 
              var locationName = events[j].locationName;
              var locationAddr1 = events[j].locationAddr1;
              var locationAddr2 = events[j].locationAddr2;
              var locationCity = events[j].locationCity;
              var locationState = events[j].locationState;
              var locationZip = events[j].locationZip;
              var link = events[j].link;
              var label = events[j].label; 
              var eventDate = events[j].eventDate;
              var dateWork = eventDate.split("-");
              var currMonth = parseInt(dateWork[1], 10) - 1;
                      
              var eventTime = events[j].eventTime;  
              var timeWork = eventTime.split(":");   
              var currHour = parseInt(timeWork[0]);
              var amPm = "pm";
              
              if(currHour >12){
                currHour -= 12;
                amPm = "pm";
              }else if (currHour == 12){
                amPm = "pm";
              }else{
                amPm = "am";
              }
              
              
              var eventDiv = document.getElementById("newEvents");
              var existingHTML = eventDiv.innerHTML;
              var newEvent = 
                  "<h3>" + eventTitle + "</h3>"+
                  "<em>" + m_names[currMonth] + " " + dateWork[2] + ", " + dateWork[0] + "</em> " +
                  "<em>" + currHour + ":" + timeWork[1] + " " + amPm + " PDT</em><br /> ";
                  
              if(locationName) {
                  newEvent += "<em>" + locationName + "</em><br /> ";
              }        
              if(locationAddr1) {
                  newEvent += "<em>" + locationAddr1 + "</em><br /> ";
              }
              if(locationAddr2) {
                  newEvent += "<em>" + locationAddr2 + "</em><br /> ";
              }
              if(locationCity && locationState && locationZip) {
                  newEvent += "<em>" + locationCity + ", " +locationState+ " " +locationZip+ " </em><br /> ";
              }  
              
              newEvent += "<p>" + eventContent + "</p>";
              
              if (link && label) {
                  newEvent += "<a href='" + link + "'>" + label + "</a><br/>";
              }   
              
              eventDiv.innerHTML = existingHTML + newEvent;
              
              request = null;
            }

      } else {
            var message = request.getResponseHeader("Status");
            if ((message.length === null) || (message.length <= 0)) {
              alert("Error! Request status is " + request.status);
            } else {
              alert(message);
            }
          }
      }
    }
    
    
    var errMsg = {
    
    // Checks for when a specified field is required
    required: {
        msg: "This field is required.",
        test: function(obj,load) {
            // Make sure that something was not entered and that this
            // isn't on page load (showing 'field required' messages
            // would be annoying on page load)
           //return obj.value || load || obj.value == obj.defaultValue;
           return obj.value.length > 0 || load;
        }
    },
  
    // Makes sure that the field s a valid email address
    email: {
        msg: "Not a valid email address.",
        test: function(obj) {
            // Make sure that something was entered and that it looks like
            // an email address
            return !obj.value || 
                /^[a-z0-9_+.-]+\@([a-z0-9-]+\.)+[a-z0-9]{2,4}$/i.test( obj.value );
        }
    },
  
    // Makes sure the field is a phone number and
    // auto-formats the number if it is one
    phone: {
        msg: "Not a valid phone number.",
        test: function(obj) {
            // Check to see if we have something that looks like
            // a valid phone number
            var m = /(\d{3}).*(\d{3}).*(\d{4})/.exec( obj.value );
      
            // If it is, seemingly, valid - force it into the specific
            // format that we desire: (123) 456-7890
            if ( m ) obj.value = "(" + m[1] + ") " + m[2] + "-" + m[3];
        
            return !obj.value || m;
        }
    },
    
    // Makes sure the field is a zip code  
   zip:  {
      msg: "Not a valid zip code.",
        test: function(obj) {
            // Make sure that something is entered, and that it
            // looks like a valid zip code (5 digits only)
            return !obj.value || /^\d{5}$/.test(obj.value);
        }
    },
  
    // Makes sure that the field is a valid MM/DD/YYYY date
    date: {
        msg: "Not a valid date.",
        test: function(obj) {
            // Make sure that something is entered, and that it
            // looks like a valid MM/DD/YYYY date
            return !obj.value || /^\d{2}\/\d{2}\/\d{2,4}$/.test(obj.value);
        }
    },
    
    // Makes sure that the field is a valid hh:mm or h:mm am/pm time (19:27 or 7:27pm)
    time:  {
      msg: "Not a valid time.",
        test: function(obj) {
            // Make sure that something is entered, and that it
            // looks like a valid hh:mm or h:mm am/pm time
            return !obj.value || /^\d{1,2}:\d{2}(\s)*([ap]m)?$/.test(obj.value);
        }
    },
  
    // Makes sure that the field is a valid URL
    url: {
        msg: "Not a valid URL.",
        test: function(obj) {
            // Make sure that some text was entered, and that it's
            // not the default http:// text
                return !obj.value || obj.value == 'http://' ||
                    // Make sure that it looks like a valid URL
                    /^https?:\/\/([a-z0-9-]+\.)+[a-z0-9]{2,4}.*$/.test( obj.value );
        }
    }
};

// A function for validating all fields within a form.
// The form argument should be a reference to a form element
// The load argument should be a boolean referring to the fact that
// the validation function is being run on page load, versus dynamically
function validateForm( form, load ) {
    var valid = true;

    // Go through all the field elements in form
    // form.elements is an array of all fields in a form
    for ( var i = 0; i < form.elements.length; i++ ) {

        // Hide any error messages, if they're being shown
        hideErrors( form.elements[i] );

        // Check to see if the field contains valid contents, or not
        if ( ! validateField( form.elements[i], load ) )
            valid = false;

    }

    // Return false if a field does not have valid contents
    // true if all fields are valid
    return valid;
}

// Validate a single field's contents
function validateField( elem, load ) {
    var errors = [];

    // Go through all the possible validation techniques
    for ( var name in errMsg ) {
        // See if the field has the class specified by the error type
        var re = new RegExp("(^|\\s)" + name + "(\\s|$)");

        // Check to see if  the element has the class and that it passes the
        // validatino test
        if ( re.test( elem.className ) && !errMsg[name].test( elem, load ) )
            // If it fails the validation, add the error message to list
            errors.push( errMsg[name].msg );
    }

    // Show the error messages, if they exist
    if ( errors.length )
        showErrors( elem, errors );

    // Return false if the field fails any of the validation routines
    return errors.length == 0;
}

// Hide any validation error messages that are currently shown
function hideErrors( elem ) {
    // Find the next element after the current field
    var next = elem.nextSibling;

    // If the next element is a ul and has a class of errors
    if ( next && next.nodeName == "UL" && next.className == "errors" )
        // Remove it (which is our means of  'hiding')
        elem.parentNode.removeChild( next );
}

// Show a set of errors messages for a specific field within a form
function showErrors( elem, errors ) {
    // Find the next element after the field
    var next = elem.nextSibling;

    // If the field isn't one of our special error-holders.
    if ( next && ( next.nodeName != "UL" || next.className != "errors" ) ) {
        // We need to make one instead
        next = document.createElement( "ul" );
        next.className = "errors";

        // and then insert into the correct place in the DOM
        elem.parentNode.insertBefore( next, elem.nextSibling );
    }

    // Now that we have a reference to the error holder UL
    // We then loop through all the error messages
    for ( var i = 0; i < errors.length; i++ ) {
        // Create a new li wrapper for each
        var li = document.createElement( "li" );
        li.innerHTML = errors[i];

        // and insert it into the DOM
        next.appendChild( li );
    }
}

  function watchFields() {
    var form = document.getElementsByTagName( "form" )[0];
    
    // Go through all the field elements in form
    for ( var i = 0; i < form.elements.length; i++ ) {

        // and attach a 'blur' event handler (which watches for a user
        // to lose focus of an input element)
        addEvent( form.elements[i], 'blur',  function(){
           // Once the focus has been lost, re-validate the field
           return validateField( this );
        });

    }
    
    // addEvent/removeEvent written by Dean Edwards, 2005
// with input from Tino Zijdel
// http://dean.edwards.name/weblog/2005/10/add-event/

function addEvent(element, type, handler) {
  // assign each event handler a unique ID
  if (!handler.$$guid) handler.$$guid = addEvent.guid++;
  // create a hash table of event types for the element
  if (!element.events) element.events = {};
  // create a hash table of event handlers for each element/event pair
  var handlers = element.events[type];
  if (!handlers) {
    handlers = element.events[type] = {};
    // store the existing event handler (if there is one)
    if (element["on" + type]) {
      handlers[0] = element["on" + type];
    }
  }
  // store the event handler in the hash table
  handlers[handler.$$guid] = handler;
  // assign a global event handler to do all the work
  element["on" + type] = handleEvent;
};
// a counter used to create unique IDs
addEvent.guid = 1;

function removeEvent(element, type, handler) {
  // delete the event handler from the hash table
  if (element.events && element.events[type]) {
    delete element.events[type][handler.$$guid];
  }
};

function handleEvent(event) {
  var returnValue = true;
  // grab the event object (IE uses a global event object)
  event = event || fixEvent(window.event);
  // get a reference to the hash table of event handlers
  var handlers = this.events[event.type];
  // execute each event handler
  for (var i in handlers) {
    this.$$handleEvent = handlers[i];
    if (this.$$handleEvent(event) === false) {
      returnValue = false;
    }
  }
  return returnValue;
};

function fixEvent(event) {
  // add W3C standard event methods
  event.preventDefault = fixEvent.preventDefault;
  event.stopPropagation = fixEvent.stopPropagation;
  return event;
};
fixEvent.preventDefault = function() {
  this.returnValue = false;
};
fixEvent.stopPropagation = function() {
  this.cancelBubble = true;
};
    
}

function resetForm() {
  var form = document.getElementsByTagName( "form" )[0];
    
  var input = form.getElementsByTagName( "input" );
  
    for ( var i = 0; i < input.length; i++ ) {
      if(input[i].type != "button") 
        {input[i].value = "";}     
    }
    
  var ta = document.getElementById( "eventContent" );
  ta.value = "";

}
    function saveEvent(form, load) {
       if (validateForm(form, load)){
          
          // Convert mm/dd/yyyy to mysql yyy-mm-dd
          var datework = new Date(form["eventDate"].value);
          var dateYear = datework.getFullYear();
          var dateMo = datework.getMonth() + 1;
          var dateDay = datework.getDate();
          var mysqlDate = dateYear + "-" + dateMo + "-" + dateDay;
          // Convert time to mysql hh:mm:ss
          var timeWork = form["eventTime"].value;
          var timeSplit = timeWork.split(":");
          var hh = parseInt(timeSplit[0]);
          if(timeSplit[1].indexOf("pm") != -1){
            hh += 12;
          }
          
          var mysqlTime = hh + ":" + parseInt(timeSplit[1]) + ":00";
               
          var params = "title=" +  escape(form["eventTitle"].value) +
                       "&date=" +escape(mysqlDate) + 
                       "&time=" +escape(mysqlTime) + 
                       "&content=" + escape(form["eventContent"].value) +
                       "&name=" + escape(form["locationName"].value) +
                       "&addr1=" + escape(form["locationAddr1"].value) +
                       "&addr2=" + escape(form["locationAddr2"].value) +
                       "&city=" + escape(form["locationCity"].value) +
                       "&state=" + escape(form["locationState"].value) +
                       "&zip=" + escape(form["locationZip"].value) +
                       "&type=" + escape(form["eventType"].value) +
                       "&label=" + escape(form["linkLabel"].value) +
                       "&link=" + escape(form["linkContent"].value);
                       
          createEvents(params);
       }else {
          alert("There are errors.  Please refer to messages.");
          return;
       }
       
    }
    
    function createComplete() {
      if (request.readyState == 4) {
          if (request.status == 200) {
             var sqlResult, query, index, msg;
             

             if (request.responseText.indexOf("SQLRESULT:") != -1){
                index = request.responseText.indexOf("SQLRESULT:");
                query = request.responseText.substring(6,index);
                sqlResult = request.responseText.substring(index+10);
                msg = sqlResult;
                if(request.responseText.indexOf("Error", index) != -1){
                  msg += "  " + query
                }else{
                  resetForm(); 
                }
                alert ( msg );
             
             }
                
          }
      }
          
    }
    