var path = BASE_CONTEXT + "/events.xml";
var xmlDoc = null;
var currMonth = 0;
var currYear = 0;
var strRegion = "";
var strCategory = "";

var year2008 = new Array("january_2008.gif", "february_2008.gif", "march_2008.gif", "april_2008.gif", "may_2008.gif", "june_2008.gif", "july_2008.gif", "august_2008.gif", "september_2008.gif", "october_2008.gif", "november_2008.gif", "december_2008.gif");
var year2009 = new Array("january.2009.gif", "february.2009.gif", "march.2009.gif", "april.2009.gif", "may.2009.gif", "june.2009.gif", "july.2009.gif", "august.2009.gif", "september.2009.gif", "october.2009.gif", "november.2009.gif", "december.2009.gif");
var months = new Array("JAN", "FEB", "MAR", "APR", "MAY", "JUN", "JUL", "AUG", "SEP", "OCT", "NOV", "DEC");
var lClasses = new Array("eventDate", "lblEvent", "eventDescription");
var aYears = new Array("2008", "2009");
var eventList= new Array();


/* Looks for a value within an array */
function hash(arr, val)
{
  var result = -1;
  for (i = 0; i < arr.length; i++)
    if (arr[i] == val)
      result = i;
  return result;
}


/* Opens the given XML file */
function openXML(fName)
{
  if (window.ActiveXObject) /* Microsoft IE */
  {
    xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
    xmlDoc.async = false;
    xmlDoc.load(fName);
    setCalendar();
  }
  else	  
  // Firefox, Opera 8.0+, Safari
	if(document.implementation && document.implementation.createDocument)
	{
	   //load xml file
	   XMLDocument.prototype.load = function(fName)
	   {
		  var xmlhttp = new XMLHttpRequest();
		  xmlhttp.open("GET", fName, false);
		  xmlhttp.setRequestHeader("Content-Type","text/xml");
		  xmlhttp.setRequestHeader("charset", "utf-8");
		  xmlhttp.send(null);
		  var newDOM = xmlhttp.responseXML;
		  if( newDOM )
		 {
		   var newElt = this.importNode(newDOM.documentElement, true);
		   this.appendChild(newElt);
		   return true;
		}
	 }
	 xmlDoc = document.implementation.createDocument("", "", null);
	 xmlDoc.async = false;
	 xmlDoc.load(fName);
	 setCalendar(); 
    }	
}


/* Returns a node value, given a root node, a child and node name */
function getXMLNodeValue(root, nChild, nodeName)
{
  return root[nChild].getElementsByTagName(nodeName)[0].firstChild.nodeValue;
}


/* Deletes the list of events every time the user changes the month. */
function deleteItemList()
{
  var list = document.getElementById("textDetail");
  while (list.getElementsByTagName("li").length > 0)
  {
    list.removeChild(list.firstChild);
  }
}


/* Creates the necessary <li> elements and their content. */
function createContent(nDate, nName, nLocation)
{
  var list = document.getElementById("textDetail"); /* This is the <ul> element */
  var li = document.createElement("li");
  for (i = 0; i < 3; i++)
  {
    if (i == 2)
    {
      var br = document.createElement("br");
      li.appendChild(br);
    }
    var p = document.createElement("p");
    p.className = lClasses[i];
    var txt = "";
    if (lClasses[i] == "eventDate")
    {
      txt = document.createTextNode(nDate);
    }
    if (lClasses[i] == "lblEvent")
    {
      txt = document.createTextNode(nName);
    }
    if (lClasses[i] == "eventDescription")
    {
      txt = document.createTextNode(nLocation);
    }
    p.appendChild(txt);
    li.appendChild(p);
  }
  list.appendChild(li);
  document.getElementById("eventDetail").appendChild(list);
}


function createEmptyItemList()
{
  deleteItemList();
  createContent("", "", "We're sorry. There are no events that match your search. Please refine your search criteria and try again.");
}

/* Loads the events data for the selected month */
function createItemList()
{
  deleteItemList();
  var cIndex = 0;
  var pyear, pdate, pname, plocation;
  var strMonth= "";

  cIndex = document.getElementById("comboRegion").selectedIndex;
  strRegion = document.getElementById("comboRegion").options[cIndex].text;
  if (strRegion == "North Central")
     strRegion = "NorthCentral";
  if (strRegion == "South Central")
     strRegion = "SouthCentral";

  cIndex = document.getElementById("comboCategory").selectedIndex;
  strCategory = document.getElementById("comboCategory").options[cIndex].text;

  displayRegion(strRegion);
  if (eventList.length > 0)
  {
    /* Sort the array of events by month */
    var aEvent= new Array();
    for (var i=0; i < months.length; i++)
    {
      for (var j=0; j < eventList.length; j++)
      {
        pdate= getNodeByName(eventList[j], "date");
        strMonth= ((pdate.firstChild.nodeValue).substr(0, 3)).toUpperCase();
        if (strMonth == months[i])
           aEvent.push(eventList[j]);
      }
    }
	/* Sort the array of events by day */
	var ordered = false;
	while(!ordered){
		ordered = true;
		for (var j=0; j < aEvent.length - 1; j++){
			var first = getNodeByName(aEvent[j], "date");
			var second = getNodeByName(aEvent[j + 1], "date");		
			if( first.firstChild.nodeValue.substr(5, 3) > second.firstChild.nodeValue.substr(5, 3)){
				var copyNode = aEvent[j];
				aEvent[j] = aEvent[j + 1];
				aEvent[j + 1] = copyNode;
				ordered = false;
			}
		 }
	}
    
    for (var i=0; i < aEvent.length; i++)
    {
      pname= getNodeByName(aEvent[i], "name");
      pdate= getNodeByName(aEvent[i], "date");
      plocation= getNodeByName(aEvent[i], "location");
      createContent(pdate.firstChild.nodeValue, pname.firstChild.nodeValue, plocation.firstChild.nodeValue);
    }
  }
}





/* Establishes the month images to load.
 * It is fired by the "Update" button and the navigation arrows */
function setCalendar()
{
 eventList.length= 0;
  var m1 = document.getElementById("firstMonth");
  var m2 = document.getElementById("secondMonth");
  m1.style.background = (currYear == "2008") ? "url(../content/en/images/experience/eventsCalendar/" + year2008[currMonth] + ") no-repeat" : "url(../content/en/images/experience/eventsCalendar/" + year2009[currMonth] + ") no-repeat"
  m2.style.background = (currYear == "2008") ? "url(../content/en/images/experience/eventsCalendar/" + year2008[currMonth + 1] + ") no-repeat" : "url(../content/en/images/experience/eventsCalendar/" + year2009[currMonth + 1] + ") no-repeat";

  var m = document.getElementById("comboMonth");
  m.selectedIndex = currMonth;
  document.getElementById("comboMonth").options[currMonth].selected = true;
  createItemList();
  if (eventList.length == 0)
     createEmptyItemList();
}


/* Gets the current month number from the system's date. */
function getCurrentDate()
{
  var d = new Date();
  currMonth = d.getMonth();
  currYear = d.getFullYear();
  document.getElementById("comboMonth").selectedIndex = currMonth;
  document.getElementById("comboYear").selectedIndex = hash(aYears, currYear);
  openXML(path);

}


/* Loads the previous month images. */
function priorMonth()
{
  var minMonth = 0;
  //var minMonth = (currYear == "2008") ? 2 : 0;
  if (currMonth > minMonth)
  {
	currMonth -= 1;
    setCalendar();
  }
}


/* Loads the next month images. */
function nextMonth()
{
	if (currMonth <= 10)
  {
    currMonth += 1;
  }
  setCalendar();
}


/*
 * Sets the proper month images when the user chooses
 * an option from the months <select> element.
 */
function setMonth()
{
  currMonth = document.getElementById("comboMonth").selectedIndex;
/*  if (currMonth == 11)
  {
    currMonth = 10;
  }
  if ((currYear == "2008") && (currMonth < 2))
  {
    currMonth = 2;
  }*/
}


/* Sets the calendar according to the selected year */
function setYear()
{
  var aIndex = document.getElementById("comboYear").selectedIndex;
  currYear = document.getElementById("comboYear").options[aIndex].text;
}

/* --------------------------------------------------------------------- */

function getNodeByName(rootNode, strName)
{
  var result= null;
  var list= (rootNode.length > 0) ? rootNode : rootNode.childNodes;
  for (var i=0; i < list.length; i++)
    if ((list[i].nodeType == 1) && (list[i].nodeName == strName))
       result= list[i];
  return result;
}


function displayRegion(regionName)
{
	if (xmlDoc == null)
		return;


  var root= xmlDoc.documentElement.childNodes;
  var reg= (regionName == "All Regions") ? root : getNodeByName(root, regionName);
  if (regionName == "All Regions")
  {
    for (var i=0; i < reg.length; i++)   // Go through all regions.
      if (reg[i].nodeType == 1)
      {
        displayCategory(reg[i]);
      }
  }
  else
  {
    displayCategory(reg);
  }
}


function displayCategory(pRegion)
{
  var cat= null;
  if (strCategory == "All Events")
  {
    cat= pRegion.childNodes;
    for (var j=0; j < cat.length; j++)   // Go through all categories.
      if (cat[j].nodeType == 1)
      {
        displayEvents(cat[j]);
      }
  }
  else                                   // Visits the selected category for all regions.
  {
    strCategory = strCategory.replace(" ", "");
	cat= getNodeByName(pRegion, strCategory);
    if (cat != null)
       displayEvents(cat);
  }
}


function displayEvents(pCategory)
{

  var eventMonth= "";
  var eventYear="";
  var pdate;
  var pyear;
  var event= null;
  var info= null;

  for (var i=0; i < pCategory.childNodes.length; i++)
  {
    event= pCategory.childNodes[i];
    if (event.nodeType == 1)
    {
	  pyear= getNodeByName(event, "year");
      pdate= getNodeByName(event, "date");
      eventMonth = ((pdate.firstChild.nodeValue).substr(0, 3)).toUpperCase();
	  eventYear = pyear.firstChild.nodeValue;
      if (eventMonth == months[currMonth] && eventYear == currYear)
      {
        eventList.push(event);
//        createContent(pdate.firstChild.nodeValue, pname.firstChild.nodeValue, plocation.firstChild.nodeValue);
      }
    }
  }
}

