//the ajax xml object
var xmlhttp=null;
//the xml file that will be loaded into memory
var ldate = new Date()
var toLoad =  "./events-xml/" + ldate.getFullYear()+"_"+(ldate.getMonth()+1)+".xml";
//var toLoad = ldate.getFullYear()+"_"+"0.xml";
//var toLoad = "./events-xml/2010_10.xml";
var xmlDoc;
//the string that gets printed to the dynamic div
var strOutput = "";
var daysToAdd = 0;
var lBound = 0;
var uBound = 9;
var epm = 10;
var pages = 0;
var activePage = 1;
var paginate = "";
var prevDay = 0;
var prevMonth = 0;
var prevYear;
var arbitrary = false;
var noEvents = false;
var previousDate = "";
//var gSiteRegion = "";
var months = new Array("January", "February", "March", "April", "May", "June","July", "August", "September", "October", "November","December");
var shortMonths = new Array("Jan.", "Feb.", "Mar.", "Apr.", "May", "Jun.","Jul.", "Aug.", "Sep.", "Oct.", "Nov.","Dec.");
var days = new Array("Sunday","Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday");
var displayType = new Array("ThisMonth", "ThisWeek", "Today", "spMonth");
daysInMonth=[31,28,31,30,31,30,31,31,30,31,30,31]

//this method sets up the xml object to work with the javascript depending on the browser
function sendRequest(siteRegion)
{   
	//set global site region
	//gSiteRegion = siteRegion;
	//alert(gSiteRegion);
	
   //setting up the firefox 1.5 ,safari 1.3, and opera 8.5 way
   if (window.XMLHttpRequest)
   {
      xmlhttp=new XMLHttpRequest();
   }
   //if that fails try set up for IE
   else if (window.ActiveXObject)
   {
      try
      {
         xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
      }
      catch(e)
      {
         try
         {
            xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
         }
         catch(e)
         {
            xmlhttp = false;
         }
      }
   }
   //if the ajax object was set up properly then download and open the xml file in the 'toLoad' variable
   if (xmlhttp)
   {
      //setting up the eventhandler 
      xmlhttp.onreadystatechange=onReadyState;
      //opening the xml file
      xmlhttp.open("GET", toLoad, true);
      //no need to send anything back to the server      
      
      xmlhttp.send(null);
   }
}

function onReadyState()
{  
    if (xmlhttp.readyState==4)
    {
        if (xmlhttp.status==200)
        {
            xmlDoc = xmlhttp.responseXML;
         
            try
            {
                var query = window.location.search.substring(1);
                var pair = query.split("date=");
                var rawDate = pair[1].split("/");            
                reloadXML("./events-xml/" + rawDate[0]+"_"+rawDate[1]+".xml");
            
                if(rawDate[2] == 0)
                {
                    monthView(rawDate[1],rawDate[0]);
                    drawCal(rawDate[1],rawDate[0]);
                }
                else if(rawDate[1] > 12)
                {                    
                    if(rawDate[1] == 13)
                        testSelect(displayType[0],rawDate[2]);
                    else if(rawDate[1] == 14)
                        testSelect(displayType[1],rawDate[2]);
                    else if(rawDate[1] == 15)
                        testSelect(displayType[2],rawDate[2]);
                    else if(rawDate[1] == 16)
                        testSelect(displayType[3],rawDate[2]);                                                                  
                }
                else
                {
                    dayView(rawDate[0],rawDate[1],rawDate[2]);
                    drawCal(rawDate[1],rawDate[0]);
                }                          
            }
            catch(e)
            {        

                var today = new Date();
                var year = today.getFullYear();
                var month = today.getMonth()+1;
                var day = today.getDate();
                
                //dayView(year,month,day);
                monthView(month,year);
                //displayEvent();
                drawCal(month,year,0);
            }         
        }
		else {
		
			var today = new Date();
			var year = today.getFullYear();
			var month = today.getMonth()+1;
			var day = today.getDate();
			
			//dayView(year,month,day);
			monthView(month,year);
			//displayEvent();
			drawCal(month,year,0);
		}
    }
}
///<summary>
///function dayView(year,month,day)
/// Wraps the dayViewer function,  if dayViewer throws an error,
/// it will call the drawError function
///</summary>
function dayView(year,month,day)
{   
   if(!dayViewer(year,month,day))
      drawError(year,month,day);      
}
///<summary>
///function dayViewer(year,month,day)
///This function displays the events on the given year, month, day
///Will return false if the xml object is null
///</summary>
function dayViewer(year,month,day)
{
   if(xmlDoc == null)
      return false;
   var dateClicked = new Date();
   dateClicked.setFullYear(year,month-1,day);
   
   var eventTitles = xmlDoc.getElementsByTagName("headline");
   var startDates  = xmlDoc.getElementsByTagName("startDate");
   var endDates    = xmlDoc.getElementsByTagName("endDate");
   var descripts   = xmlDoc.getElementsByTagName("description");
   var locations   = xmlDoc.getElementsByTagName("location");
   var websites    = xmlDoc.getElementsByTagName("website");
   var sponsors    = xmlDoc.getElementsByTagName("sponsor");
   var images      = xmlDoc.getElementsByTagName("images");
   var even = true;
   
   var contactX    = xmlDoc.getElementsByTagName("contactInfo");
   var organs      = xmlDoc.getElementsByTagName("organization");
   var strOutput  = "";
 
   var count = 0;
   for (var i=0; i < eventTitles.length; i++)
   {      
      var syear  = startDates[i].attributes.getNamedItem("year").value;
      var smonth = startDates[i].attributes.getNamedItem("month").value;
      var sday   = startDates[i].attributes.getNamedItem("day").value;
    
      var eyear  = endDates[i].attributes.getNamedItem("year").value;
      var emonth = endDates[i].attributes.getNamedItem("month").value;
      var eday   = endDates[i].attributes.getNamedItem("day").value; 
      var endDate = new Date();
      endDate.setFullYear(eyear,emonth-1,eday);
      var startDate = new Date();
      startDate.setFullYear(syear,smonth-1,sday);
      if(startDate < dateClicked && dateClicked < endDate || syear == year && smonth == month && sday == day || eyear == year && emonth == month && eday == day)
      {
         if(lBound <= count && count <= uBound)
         {            
            strOutput += generateCalData(eventTitles,startDates,endDates,descripts,locations,websites,sponsors,images,even,i);
            if(even)
              even = false;
            else
              even = true;
         }
         count++;
      }
   }  
   
   if(count > 0)
   {
      pages = Math.ceil(count/epm);
      var results = "";  
      results = generateResults(dateClicked,count,"day");
      strOutput = results + strOutput;
      if(pages > 1)
         strOutput += '<div class="pager-results clearfix"><p class="pages">'+paginate+'</p></div>';
      document.getElementById('divContent').innerHTML=strOutput;
   }
   else
   {
      noEvents = true;
      arbitraryDayView(year,month,day,7);
      noEvents = false;
      
   }
   return true;
}
///<summary>
///function monthView(month,year)
/// Displays all events that overlap the month and year provided
/// returns false upon an error.
///</summary>
function monthView(month,year)
{    
    if(xmlDoc == null)
       return false;
    var strOutput ="";
    var dateClicked = new Date();
    dateClicked.setFullYear(year,month-1,1);
    
    var eventTitles = xmlDoc.getElementsByTagName("headline");
    var startDates  = xmlDoc.getElementsByTagName("startDate");
    var endDates    = xmlDoc.getElementsByTagName("endDate");
    var descripts   = xmlDoc.getElementsByTagName("description");
    var locations   = xmlDoc.getElementsByTagName("location");
    var websites    = xmlDoc.getElementsByTagName("website");
    var sponsors    = xmlDoc.getElementsByTagName("sponsor");
    var images      = xmlDoc.getElementsByTagName("images");    
 
    //var contactX    = xmlDoc.getElementsByTagName("contactInfo");
    //var organs      = xmlDoc.getElementsByTagName("organization");
    var count = 0;
    var write = 1;
    var even = true;
    for (i =0; i < eventTitles.length; i++)
    {   
       var syear  = startDates[i].attributes.getNamedItem("year").value;
       var smonth = startDates[i].attributes.getNamedItem("month").value;
       var sday   = startDates[i].attributes.getNamedItem("day").value;
        
       var eyear  = endDates[i].attributes.getNamedItem("year").value;
       var emonth = endDates[i].attributes.getNamedItem("month").value;
       var eday   = endDates[i].attributes.getNamedItem("day").value;
        
       var endDate = new Date();
       endDate.setFullYear(eyear,emonth-1,eday);
       var startDate = new Date();
       startDate.setFullYear(syear,smonth-1,sday);       
       
       
       if(syear < eyear && eyear <= year)
       {
          
          if(emonth >= month)
          {
             if(lBound <= count && count <= uBound)
             {
                strOutput += generateCalData(eventTitles,startDates,endDates,descripts,locations,websites,sponsors,images,even,i);
                if(even)
                  even = false;
                else
                  even = true;
             }
             count++;
          }
          
       }
       else if((smonth < month) && (month < emonth)  || (smonth == month && syear == year) || emonth == month && eyear == year )
       {  
          if(lBound <= count && count <= uBound) 
          {
             strOutput += generateCalData(eventTitles,startDates,endDates,descripts,locations,websites,sponsors,images,even,i);
             if(even)
                even = false;
             else
               even = true;
          }
          count++; 
       }
    }
    
    plural = "";
   
    if(count == 1)
       plural = " event";
    else
       plural = " events";    
    
    temp = "";
    temp += '<div class="story-col" id="shaded-col-thin">';
   // temp += '<p class="search-results-number">'+count+ plural+' Found for '+getMonth(month-1)+' '+year+'</p>';
    
    strOutput = temp + strOutput;        
    
    pages = Math.ceil(count/epm);
    var results = "";
    results = generateResults(dateClicked,count,"month");
    strOutput = results + strOutput;
	strOutput += drawMonthBoard(year,month,6)
   
    if(pages > 1)
       strOutput += '<div class="pager-results clearfix"><p class="pages">'+paginate+'</p></div>';
          
       
    document.getElementById('divContent').innerHTML=strOutput;     
    return true;
}
///<summary>
///function generateErrorMessage(month,year)
///displays an error message for the month, and year.  
///This function is best used when error occurs when trying to display
///all events for a month.
///</summary>
function generateErrorMessage(month,year)
{   
   var results = "";
   results += '<div class="story-col" id="shaded-col-thin">';
  // results += '<p class="search-results-number"> 0 events found for '+getMonth(month-1)+' '+year+'</p>';
   results += drawMonthBoard(year,month,6)
   results += '</div>';
   
   document.getElementById('divContent').innerHTML=results;
}
///<summary>
///function arbitraryDayView(year,month,day,add)
///wraps the arbitraryDayViewer function and calls the drawError function upon an error.
///</summary>
function arbitraryDayView(year,month,day,add)
{
   arbitrary = true
   if(!arbitraryDayViewer(year,month,day,add))
      drawError(year,month,day);
}
///<summary>
///function arbitraryDayViewer(year,month,day,add)
/// given a year, month, and day, as a starting point, this function will display events that span this date
/// and the next n days, where n = the given date + add.  Returns false upon an error.
///</summary>
function arbitraryDayViewer(year,month,day,add)
{
   previousDate = "";
   if(xmlDoc == null)
      return false;
   var dateClicked = new Date();
   dateClicked.setFullYear(year,month-1,day);
   
   var dayBound = addDays(year,month,day,add);
   dbyear = dayBound[0];
   dbmonth = dayBound[1];
   dbday = dayBound[2];
         
   var checkDate = new Date();
   var boundDate = new Date();
   checkDate.setFullYear(year,month-1,day);
   boundDate.setFullYear(dbyear,dbmonth-1,dbday);   
        
   var eventTitles = xmlDoc.getElementsByTagName("headline");
   var startDates  = xmlDoc.getElementsByTagName("startDate");
   var endDates    = xmlDoc.getElementsByTagName("endDate");
   var descripts   = xmlDoc.getElementsByTagName("description");
   var locations   = xmlDoc.getElementsByTagName("location");
   var websites    = xmlDoc.getElementsByTagName("website");
   var sponsors    = xmlDoc.getElementsByTagName("sponsor");
   var images      = xmlDoc.getElementsByTagName("images");
   var even = true;
   var strOutput  = "";
   var results = "";
   
 
   var count = 0;
   var total = 0;
   for (var i=0; i < eventTitles.length; i++)
   {      
      var syear  = startDates[i].attributes.getNamedItem("year").value;
      var smonth = startDates[i].attributes.getNamedItem("month").value;
      var sday   = startDates[i].attributes.getNamedItem("day").value;
    
      var eyear  = endDates[i].attributes.getNamedItem("year").value;
      var emonth = endDates[i].attributes.getNamedItem("month").value;
      var eday   = endDates[i].attributes.getNamedItem("day").value; 
      var endDate = new Date();
      endDate.setFullYear(eyear,emonth-1,eday);
      var startDate = new Date();
      startDate.setFullYear(syear,smonth-1,sday);
      if(lBound <= count && count <= uBound)
      { 
         if((year==syear && month == smonth && day == sday) || (dbyear == syear &&  dbmonth == smonth && dbday == sday))
         {  //alert("1");       
            results += generateCalData(eventTitles,startDates,endDates,descripts,locations,websites,sponsors,images,even,i);
            found = true;
            total++;
         }
         else if((year == eyear && month == emonth && day == eday) || (dbyear == eyear &&  dbmonth == emonth && dbday == eday))
         {  //alert("2");
            results += generateCalData(eventTitles,startDates,endDates,descripts,locations,websites,sponsors,images,even,i);
            found = true;
            total++;
         }
         else if((checkDate < startDate && startDate < boundDate)||( checkDate < endDate && endDate < boundDate ))
         {  //alert("3");                
            results += generateCalData(eventTitles,startDates,endDates,descripts,locations,websites,sponsors,images,even,i);
            found = true;
            total++;
         }            
         else if(startDate <= checkDate && checkDate <= endDate) 
         {  //alert("4");
            results += generateCalData(eventTitles,startDates,endDates,descripts,locations,websites,sponsors,images,even,i);
            found = true;
            total++;  
         }
         if(even)
            even = false;
         else
            even = true;         
      }
         //count++;      
   }  
   
   pages = Math.ceil(total/epm);
   //var results = "";  
   page = generateResults(dateClicked,total,"arbitrary");
   strOutput = page + results + strOutput;
   
   if(pages > 1)
      strOutput += '<div class="pager-results clearfix"><p class="pages">'+paginate+'</p></div>';
   document.getElementById('divContent').innerHTML=strOutput;
   return true;
}
///<summary>
///function displayEvent()
///Wraps the displayEvents function, display an error if displayEvents returns false.
///</summary>
function displayEvent()
{
   //arbitrary = true
   if(!displayEvents())
      drawError(year,month,day);
}
///<summary>
///function displayEvents()
///Displays all events in the xml file regardless of all 
///</summary>
function displayEvents()
{  
	previousDate = "";
   if(xmlDoc == null)
      return false;
   
   var eventTitles = xmlDoc.getElementsByTagName("headline");
   var startDates  = xmlDoc.getElementsByTagName("startDate");
   var endDates    = xmlDoc.getElementsByTagName("endDate");
   var descripts   = xmlDoc.getElementsByTagName("description");
   var locations   = xmlDoc.getElementsByTagName("location");
   var websites    = xmlDoc.getElementsByTagName("website");
   var sponsors    = xmlDoc.getElementsByTagName("sponsor");
   var images      = xmlDoc.getElementsByTagName("images");
   var even = true;
   var strOutput  = "";
   var results = "";
     
   var count = 0;
   var total = 0;
   for (var i=0; i < eventTitles.length; i++)
   {      
      if(lBound <= count && count <= uBound)
      {       
		
          results += generateCalData(eventTitles,startDates,endDates,descripts,locations,websites,sponsors,images,even,i);
          found = true;
          total++;
          
          if(even)
             even = false;
          else
             even = true;   
          
      } 
      count++;
   }  
   
   pages = Math.ceil(count/epm);    
   page = generateResults("",count,"Upcoming");
   strOutput = page + results + strOutput;
   
   if(pages > 1)
      strOutput += '<div class="pager-results clearfix"><p class="pages">'+paginate+'</p></div>';
   document.getElementById('divContent').innerHTML=strOutput;
   return true;
}
///<summary>
///function addDays(year,month,day,add)
///This function adds a given number of days to the current date
///This function is often used with the arbitraryDayView function
///in order to compute the upper bound.  The function respects leap years
///and differing months having a different number of days, since it uses
///getDaysInMonth, to check how many days are in the current date provided.
///</summary>
function addDays(year,month,day,add)
{
   var endYear,endMonth,endDay;
   var totalDays = getDaysInMonth(month,year);
   daysToAdd = parseInt(add);
   
   endDay = day + daysToAdd;
   endMonth = month;
   endYear = year;
   if(endDay > totalDays)
   {
       endDay = endDay - totalDays;
       if(month == 12)
       {   
           endMonth = 1;
           endYear++;
       }
       else
       {
          endMonth++;
       }
   }
   var results = new Array(endYear,endMonth,endDay);
   return results;
}
function checkOverlap(month,year)
{
   var nmonth,nyear;
   
   if(month==12)
   {
      nmonth = 1;
      nyear = year;
      nyear++;
   }
   else if(month == 0)
   {
      nmonth = 11;
      //nmonth = 12;
      nyear = year;
      nyear--;
   }
   else
   {
      nmonth = month;
      nmonth++;
      nyear = year;
   }
   var results = new Array(nmonth,nyear);
   return results;  
}
///<summary>
///function generateCalData(eventTitles,startDates,endDates,descripts,locations,websites,sponsors,images,even,i)
///This is the data wrapper function.  This function wraps the data into the client's HTML.
///If you require a different HTML style edit this function
///</summary>
function generateCalData(eventTitles,startDates,endDates,descripts,locations,websites,sponsors,images,even,i)
{
	
   var strOutput = "";
   var title = eventTitles[i].firstChild.nodeValue;  
   
   if(title.toString() == "blank")
      title = "";
   
   var url = eventTitles[i].attributes.getNamedItem("href").value;
   var sDate = startDates[i].firstChild.nodeValue;
   
   if(descripts[i].firstChild != null)
      var descript=descripts[i].firstChild.nodeValue;
   else
      var descript="";
   
   if(false)
   {
   var cUrl  = websites[i].attributes.getNamedItem("href").value;
   
   if(websites[i].attributes.getNamedItem("email") != null)
      var cmail = websites[i].attributes.getNamedItem("email").value;
   else
      var cmail = "";
      
   var venue = locations[i].attributes.getNamedItem("venue").value;   
   var state = locations[i].attributes.getNamedItem("state").value;
   var city  = locations[i].attributes.getNamedItem("city").value;
   
   var location = venue;
   if(location != "" && city != "")
      location += ", " + city;
   if(location != "" && state != "")
      location += ", " + state;
           
   var fone  = locations[i].attributes.getNamedItem("phone").value;
   //var sponsor = images[i].attributes.getNamedItem("sponsor").value;
   var sponsor = sponsors[i].firstChild.nodeValue; 
}   
   
   /*
   var none = "NONE";
   if(org.toString() == none.toString())
      org = "";
   
   var tokens = new Array()
   tokens = cUrl.split(" ");
   var directions = ""
   if(tokens.length > 1)
   {
      cUrl = tokens[0];
   }
   
   tokens = cname.split(" ")
   if(tokens.length > 1)
   {
      cname = tokens[0];
      for(i = 1; i < tokens.length; i++)
      {
         directions += tokens[i] + " ";
      }
   }*/
   
   
   if(even)
      var divTag = '<div class="search-result-row search-result-row-on clearfix">';
   else
      var divTag = '<div class="search-result-row clearfix">';
             
   strOutput += divTag;
   
   if (sDate != previousDate) {
   strOutput += '<h2 class="block-title">' + sDate + '</h2>';
   previousDate = sDate;}
   
   strOutput += '<p class="subtext"><a href="' + url + '" class=showCalendar >' + title + '</a>' ;
   //strOutput += '<p>' + location + '</p>';
   //if(sponsor != "blank")
   //   strOutput +=  sponsor;
	if(descript != "") 
   strOutput += '<br />' + descript + '';
   strOutput += '</p>';
   //strOutput += '<p class="clear"><a' +' target="_blank" ' + 'href="' + cUrl + '">'+cUrl+'</a>'; 
   //if(cmail != "")
   //   strOutput += '- <a href="' + cmail + '">'+cmail+'</a></p>';
   //strOutput += '<p>'+fone+'</p>';
   strOutput += '</div>';
     
   
   return strOutput;  
}
///<summary>
///function generateResults(dateClicked,count,type)
///generates the results header, which is what displays how many events were found for the given
///date, dateClicked.  The type variable sets the context of the results.  The type can be day, month,
///or arbitrary
///</summary>
function generateResults(dateClicked,count,type)
{
   var results = "";
   paginate = "";
   results += '<div class="pager-results clearfix">';
   
   
   if(type == "day")
   {
     // results += '<p class="search-results-number">'+count+' events found for ' + getDay(dateClicked.getDay()) +" "+getMonth(dateClicked.getMonth())+ " " +dateClicked.getDate() +', '+dateClicked.getFullYear() + '</p>';
   }
   else if(type == "month")
   {
   if (count==0)
      results += '<p class="results">'+count+' events found for ' +getMonth(dateClicked.getMonth())+ " " + dateClicked.getFullYear() + '</p>';
   }
   else if(type == "arbitrary")
   {    
      
      var boundDate = addDays(dateClicked.getFullYear(),dateClicked.getMonth(),dateClicked.getDate(),daysToAdd);
      var bDate = new Date();
      bDate.setFullYear(boundDate[0],boundDate[1],boundDate[2]);
      
      
      if(noEvents)
      {
         results += '<p class="search-results-number"> ';
         results += '0 events found for ' +getDay(dateClicked.getDay()) + " " + getMonth(dateClicked.getMonth())+ " " +dateClicked.getDate() +', '+dateClicked.getFullYear() +'<br />'; 
         results += 'Showing events for the next 7 days.';
      }
      else
      {      
       //  results += '<p class="search-results-number">' +count+' events found from ' +getDay(dateClicked.getDay()) + " " + getMonth(dateClicked.getMonth())+ " " +dateClicked.getDate() +', '+dateClicked.getFullYear();
        // results += ' to '+getDay(bDate.getDay())+ " " +getMonth(bDate.getMonth())+" "+bDate.getDate()+", "+bDate.getFullYear()+'</p>';
      }
   }
   else if(type == "Upcoming")
   {
      results += '<p class="results">'+count+' Upcoming Events</p></div>';
      if(activePage > 1)
         paginate += '<a href="javascript:turnPage(0,0,0,'+(activePage-1)+')">&#171; Previous Page</a> | ';
      
      for(var i = 1; i <= pages; i++)
      {
         if(i != activePage)
            paginate += '<a href="javascript:turnPage(0,0,0,'+i+')">'+i+'</a> | ';
         else
            paginate += '' + i + " | ";
      }
      if(activePage != pages)
      {
         var next = activePage + 1;
         paginate += '<a href="javascript:turnPage(0,0,0,'+next+')">Next Page &#187;</a>';
      }      
      return results;
   }
   if(type == "month")
   {
      if(pages > 1)
      {
         results += '<p class="pages">';
         
         if(activePage > 1)
            paginate += '<a href="javascript:turnPage(0,'+(dateClicked.getMonth()+1)+','+dateClicked.getFullYear()+','+(activePage-1)+')">&#171; Previous Page</a> | ';
         
         for(var i = 1; i <= pages; i++)
         {
            if(i != activePage)
               paginate += '<a href="javascript:turnPage(0,'+(dateClicked.getMonth()+1)+','+dateClicked.getFullYear()+','+i+')">'+i+'</a> | ';
            else
               paginate += '' + i + " | ";
         }
         if(activePage != pages)
         {
            var next = activePage + 1;
            paginate += '<a href="javascript:turnPage(0,'+(dateClicked.getMonth()+1)+','+dateClicked.getFullYear()+','+next+')">Next Page &#187;</a>';
         }
         var temp = paginate + '</p></div>';
         results += temp;
      }
      else
         results += '</div>';
   }
   else
      if(pages > 1)
      {
         results += '<p class="pages">';
         
         if(activePage > 1)
            paginate += '<a href="javascript:turnPage('+dateClicked.getDate()+','+(dateClicked.getMonth()+1)+','+dateClicked.getFullYear()+','+(activePage-1)+')">&#171; Previous Page</a> | ';
         
         for(var i = 1; i <= pages; i++)
         {
            if(i != activePage)
               paginate += '<a href="javascript:turnPage('+dateClicked.getDate()+','+(dateClicked.getMonth()+1)+','+dateClicked.getFullYear()+','+i+')">'+i+'</a> | ';
            else
               paginate += "" + i + " | ";
         }
         if(activePage != pages)
         {
            var next = activePage + 1;
            paginate += '<a href="javascript:turnPage('+dateClicked.getDate()+','+(dateClicked.getMonth()+1)+','+dateClicked.getFullYear()+','+next+')">Next Page &#187;</a>';
         }
         var temp = paginate + '</p></div>';
         results += temp;
      }
      else
         results += '</div>';
   return results;
}
///<summary>
///function drawMonthBoard(year,month,months)
///This will draw a list of links to other months. Clicking on the month name
///will open the xml file for that month, and load it into memory.
///</summary>
function drawMonthBoard(year,month,months)
{
   var overLap = checkOverlap(month,year);
   var context = "'month'";
   
   var results = ""; '<div class="story-col" id="shaded-col-thin">';
   results += "<p class=\"calendar_month_tag background_dark\">Next Six Months: </p>";
   results += '<p class="byline center">'; 
     
   
   for(var i = 0; i < months; i++)
   {
      results += '<a href="';
      results += 'javascript:loadMonth('+ overLap[0] +','+ overLap[1] + ')'; //getMonth(overLap[0]-1) + " " + overLap[1] + " ";
      results += '" >';
      results += getMonth(overLap[0]-1).slice(0,3) + " " + overLap[1];
      results += '</a>';
      if(i != months-1)
         results += " | ";          
      overLap = checkOverlap(overLap[0],overLap[1]);
   }
   results += '</p>';
   //results += '</div>';
   return results;
   //document.getElementById('monthListing').innerHTML=results;
   //alert(results);
}
///<summary>
///function turnPage(day,month,year,pageNum)
///displays the given page number, pageNum, for the the given
///day, month, and year
///</summary>
function turnPage(day,month,year,pageNum)
{
   activePage = pageNum;
   uBound = (pageNum*epm)-1;
   lBound = uBound - (epm-1);      
   
   if(arbitrary)
      arbitraryDayView(year,month,day,daysToAdd);
   else if(day != 0)
      dayView(year,month,day);
   else if(day == 0 && month == 0 && year == 0)
      displayEvents();
   else
      monthView(month,year);
            
   document.location.href="#top";
}
///<summary>
///function resetBounds(year,month,day,drawmonth,context,daysToAdd)
///resets the bounds for pagination.  Typically only needs to be called
///When a new date, month, or arbitrary date span has been selected.
///the value of context, determines which view it should display.
///The context can be, month, day, or arbitrary. The daysToAdd will 
///only take into affect when the context is set to arbitrary.
///</summary>
function resetBounds(year,month,day,drawMonth,context,daysToAdd)
{
	previousDate = "";
   activePage = 1;
   lBound = 0;
   uBound = epm - 1;
   arbitrary = false
  // count = 0;
  
   if(context == "month")
   {
      monthView(month,year);
   }
   else if(context=="day")
   {
      dayView(year,month,day);
   }
   else
   {
      arbitraryDayView(year,month,day,daysToAdd);
   }
}
function handleDay(year,month,day)
{

   if(year == prevYear && month == prevMonth && day == prevDay)
   {  
      resetBounds(year,month,day,-1,"day",0);
      //dayView(year,month,day);
   }
   else
   {
      resetBounds(year,month,day,-1,"day",0);
      //dayView(year,month,day);
      prevYear = year;
      prevMonth = month;
      prevDay = day;
   }
}
///<summary>
///function setBounds(lbound,ubound,month,year)
///sets the bounds for pagination lBound and uBound are globals
///</summary>
function setBounds(lbound,ubound,month,year)
{
   lBound = lbound;
   uBound = ubound;
   pages = 0;
   monthView(month,year);
}
///<summary>
///function loadMonth(month,year)
///This function wraps drawMonth
///
///</summary>
function loadMonth(month,year)
{
   /*
   if(reloadXML(year+"_"+month+".xml"))
      resetBounds(year,month,1,-1,"month",0)
   else
     generateErrorMessage(month,year);        
   */
   drawMonth(month,year,0);
   
}
///<summary>
///function drawMonth(month,year,drawFirst)
///This function displays the months for the requested month and year pair.
///drawFirst is a flag that can be either 0 or 1.  Setting drawFirst to 0
///will display all the events for month, setting drawFirst to 1, will 
///display events for only the first of the month.  It's equivalent to the user
///clicking on the April 1st, or June 1st.
///</summary>
function drawMonth(month,year,drawFirst)
{
   //loadMonth(month,year);
   document.getElementById('calendar').innerHTML = "Loading. . .";
   reloadXML("./events-xml/" + year+"_"+month+".xml");
   drawCal(month,year,drawFirst);
   if(!drawFirst)
      resetBounds(year,month,1,-1,"month",0);
}
///<summary>
///function drawCal(month,year,drawFirst)
///This function draws the calender for the given month and year
///This function may be called multiple times to draw several calendars.
///If a client wants a six month view, simply wrap this function in a loop
///that will call this function six times from the requested month/year, and it
///will happily draw it for you.  drawFirst can be either 0 or 1.  Setting drawFirst
///to 1 will display the first 1st of the month's events.  If no events are found
///it will display the no events found for the 1st of the month.
///</summary>
function drawCal(month,year,drawFirst)
{   
   //these 4 values hold the next and previous month and year with respect
   //to the provided month and year.
   var pMonth;
   var nMonth;
   var pYear = year;
   var nYear = year;
   
   //checking for calendar wrap around one year behind
   if(month != 1)
      pMonth = month-1;
   else
   {
      pMonth = 12;
      pYear--;
      
   }
      
   //checking for calendar wrap around one year before
   if(month != 12)
   {
      nMonth = month;
      nMonth++;
   }
   else
   {
      nMonth=1
      nYear++;
   } 
          
   //generating the calendar header
   var calCode = "";
   
   calCode += '<div class="widget_calendar background_dark" style="margin-top: 0px;">';
   calCode += '<p class="month">';   
   //calCode += '<table class="cal-small">';
   //calCode += '<tr class="month">';
   //calCode += '<th><a href="javascript:drawMonth('+pMonth+','+pYear+',0)" title="previous month">&#171;</a></th>';
   calCode += '<a href="javascript:drawMonth('+pMonth+','+pYear+',0)" title="previous month"><strong>&lt;</strong></a>';
   //calCode += '<th colspan="5"><a href="javascript:resetBounds('+year+','+month+',1,-1,'+ "'month'" +',0)">'+getMonth(month-1)+' '+year+'</a></th>';
   calCode += '&nbsp;&nbsp; <a href="javascript:resetBounds('+year+','+month+',1,-1,'+ "'month'" +',0)" class=showCalendar title="Click to display monthly event summary">'+getMonth(month-1)+' '+year+'</a> &nbsp;&nbsp;';
   //calCode += '<th><a href="javascript:drawMonth('+nMonth+','+nYear+',0)">&#187;</a></th></tr>';
   calCode += '<a href="javascript:drawMonth('+nMonth+','+nYear+',0)" title="next month"><strong>&gt;</strong></a>';
   calCode += '</p>';
   calCode += '</div>';
   calCode += '<div class="widget_calendar_body background_neutral">';
   calCode += '<table class="cal-small" style="margin-top: 0px; width: 100%;">';
   calCode += '<tr class="weekdays"><th scope="col">Su</th><th scope="col">M</th><th scope="col">Tu</th><th scope="col">W</th><th scope="col">Th</th><th scope="col">F</th><th scope="col">Sa</th></tr><tr>';
   
   var daysThisMonth = getDaysInMonth(month,year);
   var weekDay = 0;
   var lastDay = getDaysInMonth(pMonth,pYear);
   
   //this loop is used to create the calendar
   for(var i = 1; i<=daysThisMonth; i++)
   {
      var currDate = new Date();
      currDate.setFullYear(year,month-1,i);
      day = currDate.getDay();
      
      //starting a new week
      if(weekDay == 7)
      {
         weekDay=0;
         calCode += '</tr><tr>';
      }
      
      //checking if the current weekDay in the loop matches with the current weekday of the month
      //if so print that day, else we print the previous month's date
      if(day==weekDay)
      {
         if(checkForEvent(year,month,currDate.getDate()))
         {
            calCode += '<td><a href="javascript:handleDay('+currDate.getFullYear()+','+(currDate.getMonth()+1)+','+currDate.getDate()+')" class=showCalendar title="Click to display events">'+i+'</a></td>';
         }
         else
         {
            calCode += '<td>'+i+'</td>';
         }
      }
      else
      {
         var dDay = weekDay;
         dDay++;
         var lastMonthDay = lastDay-(day-dDay);
         //if(checkForEvent(pYear,pMonth,lastMonthDay))
         //{
         //   calCode += '<td class="off"><a href="javascript:dayView('+pYear+','+pMonth+','+lastMonthDay+')">'+lastMonthDay+'</a></td>';
         //}
         //else
         //{
            calCode += '<td class="off">'+lastMonthDay+'</td>';
         //}
         i--;
      }
      
      //checking if it's the last day of the month, and if there is an incomplete
      //week that needs to be filled with the first j days of the next month
      if(i==daysThisMonth && weekDay!=6)
      {  
         var j = 1;
         while(weekDay!=6)
         {
            //if(checkForEvent(nYear,nMonth,j))
            //{
            //   calCode += '<td class="nextMonth"><a href="javascript:dayView('+nYear+','+nMonth+','+j+')">'+j+'</a></td>';
            //}
            //else
            //{
               calCode += '<td class="off">'+j+'</a></td>';
            //}
            weekDay++;
            j++;
         }
      }
      weekDay++;
   }
   calCode += '</table>';
   //calCode += '<br /><div class="moreLink"><NOBR><a href="/socialdatebook/31478.asp">SUBMIT YOUR EVENT &#187;</a></NOBR></div>';
   //calCode += '<br /><br />Sponsored by: <br /><img src="/images/graves_164px.gif">';
   document.getElementById('calendar').innerHTML = calCode;     
   
   if(drawFirst == 1)
   {
      dayView(year,month,1);
   }
}
///<summary>
///function drawError(year,month,day)
///Renders an error message.  Use the function when no events are found for a requested date/month/span
///</summary>
function drawError(year,month,day)
{
   date = new Date();
   date.setFullYear(year,month-1,day);
   var results = "";
   results += '<table class="resultsHeader" cellpadding="0" cellspacing="0">';
   results += '<tr>';
   results += '<td valign="baseline"><h3>0 events found for <BR /> ' + getDay(date.getDay()) +" "+getMonth(month-1)+ " " +day +', '+year + '</h3></td>';
   //results += '<td valign="baseline"><h3>0 events found for ' +getMonth(month-1)+ '</h3></td>';
   //results += '<td valign="baseline" class="pageToolList" align="right">';
   //results += '<ul><li><a href="/code/26171.asp">E-MAIL</a></li>';
   //results += '<li><a href="/entertainment/calendar/default.asp?action=print">PRINT</a></li>';
   //results += '</td></ul>';
   results += '</tr></table>';
   document.getElementById('divContent').innerHTML = results;
}
///<summary>
///function checkForEvent(year,month,day)
///This function checks iterates through the events in the xml file, and determines any
///overlap with the year, month, day.
///</summary>
function checkForEvent(year,month,day)
{
    if(xmlDoc == null)
      return false;
    var startDates  = xmlDoc.getElementsByTagName("startDate");
    var endDates    = xmlDoc.getElementsByTagName("endDate");
    
    for(var i = 0; i < startDates.length; i++)
    {
       var syear  = startDates[i].attributes.getNamedItem("year").value;
       var smonth = startDates[i].attributes.getNamedItem("month").value;
       var sday   = startDates[i].attributes.getNamedItem("day").value;
       var eyear  = endDates[i].attributes.getNamedItem("year").value;
       var emonth = endDates[i].attributes.getNamedItem("month").value;
       var eday   = endDates[i].attributes.getNamedItem("day").value;
       var startDate = new Date();
       var endDate = new Date();
       var checkDate = new Date();
       
       startDate.setFullYear(syear,smonth-1,sday);
       endDate.setFullYear(eyear,emonth-1,eday);
       checkDate.setFullYear(year,month-1,day);
       
       
       if(syear == year && smonth == month && sday == day)
          return true;
       else if(eyear == year && emonth == month && eday == day)
          return true;
       else if(startDate < checkDate && checkDate < endDate)
          return true;
    }
    return false;
}
///<summary>
///function getMonth(month)
///this function returns the name of the month given a number, since
///javascript does not provide this behavior by default.
///</summary>
function getMonth(month)
{   
   return months[month];
}
function getShortMonth(month)
{   
   return shortMonths[month];
}
///<summary>
///function getDay(day)
///this function returns the name of the weekeday given a number, since
///javascript does not provide this behavior by default.
///</summary>
function getDay(day)
{
   return days[day];
}
///<summary>
///function getDaysInMonth(month,year)
///this function retrieves the number of days in a month given a month and a year
///it also takes into account a leap year.
///</summary>
//this function retrieves the number of days in a month given an month and a year
function getDaysInMonth(month,year)
{
   if ((month-1==1)&&(year%4==0)&&((year%100!=0)||(year%400==0)))
{
      return 29;
   }
   else
   {
      return daysInMonth[month-1];
   }
}
///<summary>
///function filterMe(txt)
///Used to convert html characters back to the illegal XML characters.
///If HTML is filtered in the XML, and it is not converted back, the HTML
///break.  For example <br >, will appear as <br > instead of
///rendering a break.
///</summary>
function filterMe(txt)
{
   if(txt != null)
   {
      txt = txt.replace(/>/g,">");
      txt = txt.replace(/</g,"<");
      txt = txt.replace(/&/g,"&");
      return txt;
   }
}
///<summary>
///function reloadXML
///simply loads another XML file
///</summary>
function reloadXML(url)
{  
   //alert(url);
   if (xmlhttp!=null)
   {
      xmlhttp.onreadystatechange=state_Change;
      xmlhttp.open("GET",url,false);
      xmlhttp.send(null);
   }
   else
   {
      alert("Your browser does not support XMLHTTP.");
   }
   
   if (xmlhttp.status==200)
   {  //alert("no problems");
      xmlDoc = null;
      xmlDoc = xmlhttp.responseXML;
      
      return true;
   }
   else
   {
      //alert("Problem retrieving XML data");
      return false;
   }
}
function state_Change()
{
   if (xmlhttp.readyState==4)
   {
   }
}
///<summary>
///function testSelect(form,days)
///This function interacts with the select box on the page.
///form can equal, ThisMonth, ThisWeek, Today, and spMonth
///ThisMonth displays the events for the current month
///ThisWeek Displays the events for the current week
///Today Displays the events for the current date
///spMonth displays the events for a specific month
///</summary>
function testSelect(form,days) 
{
   //item = form.list.selectedIndex;
   //result = form.list.options[item].text;
   //result = form
   
   result = form;
   
   //alert("testSelect(" + form + "," + days +")");
   
   var year = ldate.getFullYear();
   var month = ldate.getMonth()+1;
   var day = ldate.getDate();
   
   //alert(ldate);
      
   if(result == "ThisMonth")
   {
      reloadXML("./events-xml/" + year+"_"+month+".xml");
      resetBounds(year,month,0,-1,"month",0);
      drawCal(month,year,0);
   }
   else if(result == "ThisWeek")
   {
      //alert(year + " " + month + " " + day + " " + "week " + days);
      reloadXML(year+"_"+month+".xml");
      resetBounds(year,month,day,-1,"week",days);      
      drawCal(month,year,0);
   }
   else if(result == "Today")
   {  
      reloadXML("./events-xml/" + year+"_"+month+".xml");
      resetBounds(year,month,day,-1,"day",0); 
      drawCal(month,year,0);
   }
   else if(result == "spMonth")
   {
      var dayString = "" + days;
      var datePieces = dayString.split("42");            
      //resetBounds(datePieces[1],datePieces[0],0,-1,"month",0);
      //drawMonth(datePieces[0],datePieces[1]);
      loadMonth(datePieces[0],datePieces[1]);
      drawCal(datePieces[0],datePieces[1]);
   }
    
   //document.list.submit();      
      
   //alert (result);
}

