﻿//
// CalendarView (for Prototype)
// calendarview.org
//
// Maintained by Justin Mecham <justin@aspect.net>
//
// Portions Copyright 2002-2005 Mihai Bazon
//
// This calendar is based very loosely on the Dynarch Calendar in that it was
// used as a base, but completely gutted and more or less rewritten in place
// to use the Prototype JavaScript library.
//
// As such, CalendarView is licensed under the terms of the GNU Lesser General
// Public License (LGPL). More information on the Dynarch Calendar can be
// found at:
//
//   www.dynarch.com/projects/calendar
//

vCustID = 21;

var Calendar = Class.create()


//------------------------------------------------------------------------------
// Constants
//------------------------------------------------------------------------------

 Calendar.DAY_NAMES = pArrFullDays
 Calendar.SHORT_DAY_NAMES = pArrSortDays
 Calendar.MONTH_NAMES = pArrSortMonths
 Calendar.SHORT_MONTH_NAMES = pArrFullMonths



Calendar.VERSION = '1.2'

Calendar.NAV_PREVIOUS_YEAR  = -2
Calendar.NAV_PREVIOUS_MONTH = -1
Calendar.NAV_TODAY          =  0
Calendar.NAV_NEXT_MONTH     =  1
Calendar.NAV_NEXT_YEAR      =  2

Calendar.EventsJSON  = new Object();
Calendar.MonthJSON   = "";
Calendar.TempMonthJSON   = ".";
Calendar.MyDate = new Date();

//------------------------------------------------------------------------------
// Static Methods
//------------------------------------------------------------------------------

// This gets called when the user presses a mouse button anywhere in the
// document, if the calendar is shown. If the click was outside the open
// calendar this function closes it.
Calendar._checkCalendar = function(event) {
  if (!window._popupCalendar)
    return false
  if (Element.descendantOf(Event.element(event), window._popupCalendar.container))
    return
  window._popupCalendar.callCloseHandler()
  return Event.stop(event)
}

//------------------------------------------------------------------------------
// Event Handlers
//------------------------------------------------------------------------------

Calendar.handleMouseDownEvent = function(event)
{
  Event.observe(document, 'mouseup', Calendar.handleMouseUpEvent)
  Event.stop(event)
}

// XXX I am not happy with how clicks of different actions are handled. Need to
// clean this up!
Calendar.handleMouseUpEvent = function(event)
{
  var el        = Event.element(event)
  var calendar  = el.calendar
  var isNewDate = false

  // If the element that was clicked on does not have an associated Calendar
  // object, return as we have nothing to do.
  if (!calendar) return false

  // Clicked on a day
  if (typeof el.navAction == 'undefined')
  {
    if (calendar.currentDateElement) {
      Element.removeClassName(calendar.currentDateElement, 'selected')
      Element.addClassName(el, 'selected')
 

      SetEventDetails(el.date);
		   
	  
      calendar.shouldClose = (calendar.currentDateElement == el)
      if (!calendar.shouldClose) calendar.currentDateElement = el
    }
    calendar.date.setDateOnly(el.date)
    isNewDate = true
    calendar.shouldClose = !el.hasClassName('otherDay')
    var isOtherMonth     = !calendar.shouldClose
    if (isOtherMonth) calendar.update(calendar.date)
  }

  // Clicked on an action button
  else
  {
    var date = new Date(calendar.date)

    if (el.navAction == Calendar.NAV_TODAY)
      date.setDateOnly(new Date())

    var year = date.getFullYear()
    var mon = date.getMonth()
    function setMonth(m) {
      var day = date.getDate()
      var max = date.getMonthDays(m)
      if (day > max) date.setDate(max)
      date.setMonth(m)
    }
    switch (el.navAction) {

      // Previous Year
      case Calendar.NAV_PREVIOUS_YEAR:
        if (year > calendar.minYear)
          date.setFullYear(year - 1)
        break

      // Previous Month
      case Calendar.NAV_PREVIOUS_MONTH:
        if (mon > 0) {
          setMonth(mon - 1)
        }
        else if (year-- > calendar.minYear) {
          date.setFullYear(year)
          setMonth(11)
        }
        break

      // Today
      case Calendar.NAV_TODAY:
        break

      // Next Month
      case Calendar.NAV_NEXT_MONTH:
        if (mon < 11) {
          setMonth(mon + 1)
        }
        else if (year < calendar.maxYear) {
          date.setFullYear(year + 1)
          setMonth(0)
        }
        break

      // Next Year
      case Calendar.NAV_NEXT_YEAR:
        if (year < calendar.maxYear)
          date.setFullYear(year + 1)
        break

    }

    if (!date.equalsTo(calendar.date)) {
      calendar.setDate(date)
      isNewDate = true
    } else if (el.navAction == 0) {
      isNewDate = (calendar.shouldClose = true)
    }
  }

  if (isNewDate) event && calendar.callSelectHandler()
  if (calendar.shouldClose) event && calendar.callCloseHandler()

  Event.stopObserving(document, 'mouseup', Calendar.handleMouseUpEvent)

  return Event.stop(event)
}

Calendar.defaultSelectHandler = function(calendar)
{
  if (!calendar.dateField) return false

  // Update dateField value
  if (calendar.dateField.tagName == 'DIV')
    Element.update(calendar.dateField, calendar.date.print(calendar.dateFormat))
  else if (calendar.dateField.tagName == 'INPUT') {
    calendar.dateField.value = calendar.date.print(calendar.dateFormat) }

  // Trigger the onchange callback on the dateField, if one has been defined
  if (typeof calendar.dateField.onchange == 'function')
    calendar.dateField.onchange()

  // Call the close handler, if necessary
  if (calendar.shouldClose) calendar.callCloseHandler()
}

Calendar.defaultCloseHandler = function(calendar)
{
  calendar.hide()
}



Calendar.doRefresh = function(calendar)
{
this.MonthJSON = "";
calendar.update(calendar.date);
}


var pPLUArray = new Array();


//------------------------------------------------------------------------------
// Calendar Setup
//------------------------------------------------------------------------------

Calendar.setup = function(params)
{

  function param_default(name, def) {
    if (!params[name]) params[name] = def
  }

  param_default('dateField', null)
  param_default('triggerElement', null)
  param_default('parentElement', null)
  param_default('selectHandler',  null)
  param_default('closeHandler', null)

  // In-Page Calendar
  if (params.parentElement)
  {
    var calendar = new Calendar(params.parentElement)
    calendar.setSelectHandler(params.selectHandler || Calendar.defaultSelectHandler)
    if (params.dateFormat)
      calendar.setDateFormat(params.dateFormat)
    if (params.dateField) {
      calendar.setDateField(params.dateField)
      calendar.parseDate(calendar.dateField.innerHTML || calendar.dateField.value)
    }
    calendar.show()
    return calendar
  }

  // Popup Calendars
  //
  // XXX There is significant optimization to be had here by creating the
  // calendar and storing it on the page, but then you will have issues with
  // multiple calendars on the same page.
  else
  {
    var triggerElement = $(params.triggerElement || params.dateField)
    triggerElement.onclick = function() {
      var calendar = new Calendar()
      calendar.setSelectHandler(params.selectHandler || Calendar.defaultSelectHandler)
      calendar.setCloseHandler(params.closeHandler || Calendar.defaultCloseHandler)
      if (params.dateFormat)
        calendar.setDateFormat(params.dateFormat)
      if (params.dateField) {
        calendar.setDateField(params.dateField)
        calendar.parseDate(calendar.dateField.innerHTML || calendar.dateField.value)
      }
      if (params.dateField)
        Date.parseDate(calendar.dateField.value || calendar.dateField.innerHTML, calendar.dateFormat)
      calendar.showAtElement(triggerElement)
      return calendar
    }
  }

}

function GetFormItems()
 {	
pStep=0; 
if($("ptelephone"))
	{
  
var y= $("ptelephone").getValue();
pVal = "";
for(j=0;j<y.length;j++)
  {if(isNaN(y.substr(j,1)) == false)
    {pVal += y.substr(j,1);}
  }
pVal = pVal.replace(" ","");
if($("ptelephone").getValue() != pVal)$("ptelephone").setValue(pVal) ;
 
    pStep=1;
    if($("pEventId").getValue() >0)pStep=2;

	if(pAcroCaller == "GROUP")
		{vCustID = $("CustID").getValue();}
	
	if(pStep > 1 & document.getElementById("TicketTypes").innerHTML.length > 100)
		{
		if(pAcroCaller == "SINGLE")
			{
			pNumOfTick = 0;
			pTotalPrice = 0;
			pPLUParam = "";
			for(i=1;i<10;i++)
				{if($("numberoftickets" + i).getValue() >0)
					{
					var pPrice = $("price" + i).getValue();
					if(pPrice.indexOf(",") >= 0)pPrice = pPrice.replace(",","."); 

					pNumOfTick = pNumOfTick + (1 * $("numberoftickets" + i).getValue());	
					pTotalPrice = pTotalPrice + (pPrice * $("numberoftickets" + i).getValue());	
					pPLUParam = "" + pPLUParam + $("PLUDescr" + i).getValue() + ":" + $("PLU" + i).getValue() + ":" + pPrice + ":" + $("numberoftickets" + i).getValue() + ":" + $("pEventId").getValue() + "#";
					}
				}	
			pTxt = "";	
			if(pNumOfTick >0 & pNumOfTick < 6)
				{pStep=3;
				pTxt = "<strong>" + p_laDescr1 + ":" + pTotalPrice + "&euro;</strong>";
				}
			if(pNumOfTick >5)
				{pTxt = "<a style='color:#f00'><strong>" + p_laDescr2 + "</strong></a>";
				}
				
			if(pTotalPrice == 0)
				{pStep=2;
				 pTxt = "<a style='color:#f00'><strong>" + p_laDescr1 + ":" + pTotalPrice + "&euro;</strong></a>";
				}				
			document.getElementById("TotalPrice").innerHTML = pTxt;
			}
			
		if(pAcroCaller == "GROUP")
			{
			pNumOfTick = 0;
			pTotalPrice = 0;
			
			for(i=1;i<10;i++)
				{
				var pName2 = $("pDateTime").getValue().substr(0,10) + "-" + $("pEventId").getValue() + ":" + $("PLU" + i).getValue();					
				if($("numberoftickets" + i).getValue() >0)
					{
					pPLUArray[pName2] = 1 * $("numberoftickets" + i).getValue();
					pNumOfTick = pNumOfTick + (1 * $("numberoftickets" + i).getValue());
					
					}
				else
					pPLUArray[pName2] = 0;
				}
				
			pTxt = "";
			pTotalNumOfTick = 0;
			pPLUParam = "";
			pError = 0;
			
			for (aPLU in pPLUArray)
				{if(aPLU.indexOf($("pDateTime").getValue().substr(0,10) + "-")==0 && pPLUArray[aPLU] > 0)
					{
					pTotalNumOfTick += pPLUArray[aPLU];
					ii = 0;
					pEventID = aPLU.substr(aPLU.lastIndexOf("-") + 1);
					pEventID = pEventID.substr(0,pEventID.indexOf(":"));
					
					
					for(i=1;i<6;i++){
					if(aPLU.indexOf(":" + $("PLU" + i).getValue()) >=0 & $("PLU" + i).getValue().length > 0)ii = i;
					}

					var pPrice = $("price" + ii).getValue();
					if(pPrice.indexOf(",") >= 0)pPrice = pPrice.replace(",","."); 

					pTotalPrice += (pPrice * pPLUArray[aPLU]);						
					pPLUParam = "" + pPLUParam + $("PLUDescr" + ii).getValue() + ":" + $("PLU" + ii).getValue() + ":" + pPrice + ":" + pPLUArray[aPLU] + ":" + pEventID + "#";	

					
					}		
				}

			pFullPrice = pTotalPrice;	
			if($("pPricePerc").getValue() == 1)pTotalPrice = pTotalPrice / 10;	

			for(i=0;i<pLoc.length;i++)
				 {
					vNumOfTic = 0;
					for(j=1;j<6;j++)
						{
						var pName2 = pLoc[i].StartDateTime.substr(0,10) + 
								"-" + pLoc[i].EventId + ":" + $("PLU" + j).getValue();					
						if(pPLUArray[pName2])vNumOfTic += pPLUArray[pName2];							
						}
						
					if(vNumOfTic > 0 & vNumOfTic < 15)pError = 1; 
					if(vNumOfTic > pLoc[i].Available - 50)pError = 2;						
						
				 }
			
			if(pTotalNumOfTick >= 15 & pTotalNumOfTick <= 50 & pError == 0 & pFullPrice > 0)
				{pStep=3;
				pTxt = "<strong>" + p_laDescr1 + ":" + pFullPrice + "&euro;</strong>";
				}
			if(pFullPrice == 0)
				{pTxt = "<a style='color:#f00'><strong>Δεν μπορείτε να επιλέξετε μόνο δωρεάν εισιτήρια</strong></a>";
				}

			if(pTotalNumOfTick >50)
				{pTxt = "<a style='color:#f00'><strong>Δεν μπορείτε να αγοράσετε περισσότερα από 50 εισιτήρια</strong></a>";
				}
			if(pTotalNumOfTick >0 & pTotalNumOfTick < 15)
				{pTxt = "<a style='color:#f00'><strong>Δεν μπορείτε να αγοράσετε λιγότερα από 15 εισιτήρια</strong></a>";
				}
			if(pError == 1)
				{pTxt = "<a style='color:#f00'><strong>Δεν μπορείτε να αγοράσετε λιγότερα από 15 εισιτήρια</strong></a>";
				}
			if(pError == 2)
				{pTxt = "<a style='color:#f00'><strong>Δεν υπάρχουν διαθέσιμα εισιτήρια</strong></a>";
				}
				
			
							
			document.getElementById("TotalPrice").innerHTML = pTxt;
			
			if(pNumOfTick > 0)
				document.getElementById("lbook" + $("pEventId").getValue()).innerHTML = pNumOfTick;
			else  
				document.getElementById("lbook" + $("pEventId").getValue()).innerHTML = "";
			}		
		}	  

	if(pStep > 2)
	  {pStep=4;
		if(pAcroCaller == "SINGLE")	  
			{
			if($("pName").getValue().length ==0)pStep=3;
			if($("pSurname").getValue().length ==0)pStep=3;
			if($("pEmail").getValue().length ==0)pStep=3;
			if($("ptelephone").getValue().length < 4)pStep=3;
			if($("pEmail").getValue() != $("pEmailConfirmation").getValue())pStep=3;
			vGroupName = "";
			vCustID = 21;
			vDeliveryMethod = 5;
			}
		if(pAcroCaller == "GROUP")
			{
			if($("pGroupName").getValue().length ==0)pStep=3;
			vGroupName = $("pGroupName").getValue();
			vCustID = $("CustID").getValue();

			if($("pEOT").getValue().length ==0)			
				vDeliveryMethod = 9;
			else
				vDeliveryMethod = 10;			
			}

	  }

	if(pAcroCaller == "GROUP")
		{
		if($("CustID").getValue() > 0)
			{
			$("divStep0").hide();
			}			
		else
			{			
			pStep = 0;			
			$("divStep0").show();			
			}	
		}
	}  
    $("pParams").setValue("");
	if(pStep>0){$("divStep1").show();}else{$("divStep1").hide();}
	if(pStep>1){$("divStep2").show();}else{$("divStep2").hide();}
	if(pStep>2){$("divStep3").show();}else{$("divStep3").hide();}
	if(pStep>3){$("divStep4").show();}else{$("divStep4").hide();}
	if(pStep>3){$("pParams").setValue($("pSessionId").getValue() + ";" +  
						              vCustID + "_" + vDeliveryMethod + ";" +  
						              $("pResourceId").getValue() + ";" +  
						              $("pDateTime").getValue() + ";" +  
									  pTotalPrice + ";" +
									  $("pName").getValue().replace(/;/g,"") + ";" +  
						              $("pSurname").getValue().replace(/;/g,"") + ";" +  
						              $("pAddress").getValue().replace(/;/g,"") + ";" +  
						              $("pTown").getValue().replace(/;/g,"") + ";" +  
						              $("pPostcode").getValue().replace(/;/g,"") + ";" +  
						              $("pEmail").getValue().replace(/;/g,"") + ";" +  
						              $("ptelephone").getValue().replace(/;/g,"") + ";" +  
									  $("country").getValue().replace(/;/g,"") + ";" +  
									  $("pLan").getValue().replace(/;/g,"") + ";" + 
									  vGroupName.replace(/;/g,"") + ";" + 									  
									  pPLUParam);
	           }
	
 }

function GetPLUs(et)
  {
	document.getElementById("TicketTypes").innerHTML = "<img src='loading.gif'>";    

	xmlhttp=null;
	PLUsJson  = new Object();
	if (window.XMLHttpRequest)
		{xmlhttp=new XMLHttpRequest();}
	else if (window.ActiveXObject)
		{xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");}
  
	if (xmlhttp!=null)
		{
	    xmlhttp.onreadystatechange=
			function(){
				if (xmlhttp.readyState==4)
					{// 4 = "loaded"
					if (xmlhttp.status==200)
						{// 200 = "OK"
							if(xmlhttp.responseText.length > 10) 
								{								
								PLUsJson = eval('(' + xmlhttp.responseText + ')');								
								pTxt = "<table width='100%' border='0' cellspacing='0' cellpadding='5'>";							
								for(i=0;i<PLUsJson.PLU.length;i++)
									{
									pTxt += "<tr><td width='280'>" + PLUsJson.PLU[i].Description + "</td>";
									pTxt += "<td>" + PLUsJson.PLU[i].Price + "&euro;</td>";
									pTxt += "<td width='30' align='center'>";
									pTxt += "<input onkeyup='GetFormItems()'  name='numberoftickets" + (i+1) + "' type='text' id='numberoftickets" + (i+1) + "' size='5' maxlength='2' />";
									pTxt += "<input value='" + PLUsJson.PLU[i].PLU + "' name='PLU" + (i+1) + "' type='hidden' id='PLU" + (i+1) + "' size='5' maxlength='1' />";
									pTxt += "<input value='" + PLUsJson.PLU[i].Price + "' name='price" + (i+1) + "' type='hidden' id='price" + (i+1) + "' size='5' maxlength='1' />";
									pTxt += "<input value='" + PLUsJson.PLU[i].Description + "' name='PLUDescr" + (i+1) + "' type='hidden' id='PLUDescr" + (i+1) + "' size='5' maxlength='1' />";
									pTxt += "</td></tr>";
									}
								pTxt += "<tr><td colspan='3'><div align='right' id='TotalPrice'>&nbsp;</div></td></tr></table>";
								}							
							document.getElementById("TicketTypes").innerHTML = pTxt;    							
						}
					else
						{
						alert("Problem retrieving XML data:" + xmlhttp.statusText);
						}
					}
				}
		currentTime = new Date();
		xmlhttp.open("GET","GetPLUs.php?c=" + vCustID + "&a="  + currentTime + "&t=" + et + "&s=" + $("pSessionId").getValue(),true);
		xmlhttp.send(null);
		}
	else
		{alert("Your browser does not support XMLHTTP.");}   
		    	
  }  
 
function GetEvent(i,ev,et,re,dt)
 {	 
    SetEventDetails(Calendar.MyDate);
    if($("pEventTypeId").getValue() != et)GetPLUs(et);
	$("pEventId").setValue(ev);
	$("pResourceId").setValue(re);
    $("pDateTime").setValue(dt);	
    $("pEventTypeId").setValue(et);	
	$("ev" + i).addClassName('bgselected');
	
	if(pAcroCaller == "GROUP")
		{
		for(i=1;i<10;i++)
			{
			var pName2 = $("pDateTime").getValue().substr(0,10) + "-" + $("pEventId").getValue() + ":" + $("PLU" + i).getValue();					
			if(pPLUArray[pName2])
			   $("numberoftickets" + i).setValue(pPLUArray[pName2]);
			else
			   $("numberoftickets" + i).setValue("");
			}	
		}
		
	GetFormItems();
	
 }
				  
function SetEventDetails(pdate)
    {
	$("pEventId").setValue("");
	$("pResourceId").setValue("");
    $("pDateTime").setValue("");		
	GetFormItems();	
	Calendar.MyDate = 	pdate;
		//smecht 
 	var AJAXDate = pdate.getFullYear();
	if(pdate.getMonth() < 9)
	  {AJAXDate = AJAXDate + "-0" + (pdate.getMonth() + 1);}
	else
	  {AJAXDate = AJAXDate + "-" + (pdate.getMonth() + 1);}
	
	if(pdate.getDate() < 10)
	  {AJAXDate = AJAXDate + "-0" + pdate.getDate();}
	else
	  {AJAXDate = AJAXDate + "-" + pdate.getDate();}
			
			pTxt = '' ;
			
			if(Calendar){
			if(Calendar.EventsJSON.Events){
			if(Calendar.EventsJSON.Events[AJAXDate]){
			   pLoc = Calendar.EventsJSON.Events[AJAXDate];		   
			   for(i=0;i<pLoc.length;i++)
			     {
					 pcls = "bgok";
					 pevent = 'onclick="GetEvent(' + i + ',' + pLoc[i].EventId + ',' + pLoc[i].EventTypeId + ',' + pLoc[i].ResourceID + ',\'' + pLoc[i].StartDateTime + '\');"';
					 
					if(pAcroCaller == "SINGLE")
						{
						if(pLoc[i].Available < 70){pcls = "bgsemi";}
						if(pLoc[i].Available < 21){pcls = "bgfull"; pevent = '';}

						if(pTest == 1){pEndTime = pLoc[i].Available;} 
						else{pEndTime = pLoc[i].EndDateTime.substr(11,5);}

						if(pTxt.length > 0){pTxt +='<td width="5" align="center"></td>';}
						if(i==3)pTxt += '</tr><tr><td height="10" align="center"></td><td width="5" height="10" align="center"></td><td height="10" align="center"></td><td width="5" height="10" align="center"></td><td height="10" align="center"></td></tr><tr>';

						pTxt += '<td width="100px" align="center" id="ev' + i + '" ' + pevent +' class="' + pcls + '">' + pLoc[i].StartDateTime.substr(11,5) + " - " +  pEndTime + '</td>';
						}
					if(pAcroCaller == "GROUP")
						{
						if(pLoc[i].Available < 70){pcls = "bgsemi";}
						if(pLoc[i].Available < 65){pLoc[i].Available =50;pcls = "bgfull"; pevent = '';}
						
						pEndTime = pLoc[i].EndDateTime.substr(11,5);
						
						pNumOfTick = 0;

						for(j=1;j<6;j++)
							{
							var pName2 = pLoc[i].StartDateTime.substr(0,10) + "-" + pLoc[i].EventId + ":" + $("PLU" + j).getValue();							if(pPLUArray[pName2])vNumOfTic += pPLUArray[pName2];							
							}

							if(pNumOfTick == 0)pStrOfTick = ""; else pStrOfTick = pNumOfTick;
						
						pTxt += '<tr id="ev' + i + '" ' + pevent +' class="' + pcls + '"><td align="center">' + 
								pLoc[i].StartDateTime.substr(11,5) + " - " +  pEndTime + '</td><td>' + 
								'<div id = "lavail' + pLoc[i].EventId + '">' +
								(pLoc[i].Available - 50) + '</div></td><td>' + '<div id = "lbook' + pLoc[i].EventId + '">' + pStrOfTick + '</div>' + '</td></tr>';

						}
						
				 }
				 
				if(pAcroCaller == "SINGLE")
					{
					pTxt = '<table border="0" align="center" cellpadding="5" cellspacing="0" class="txt"><tr>' +
			        pTxt +   '</tr></table>';
					}
				if(pAcroCaller == "GROUP")
					{
					pTxt = '<table border="0" align="center" cellpadding="5" cellspacing="0" class="txt">' +
						   '<tr><td align="center">' + 
								"Ζώνη" + '</td><td>' + 'Ελεύθ.Θέσεις' + 
								'</td><td>' + 'Κράτηση' + '</td></tr>' +
			        pTxt +   '</table>';
					}
			  		 
		   }}}
		   if(Calendar.MonthJSON != Calendar.TempMonthJSON)pTxt = "<img src='loading.gif'>";
		 document.getElementById("Events").innerHTML = pTxt;  
	} 


//------------------------------------------------------------------------------
// Calendar Instance
//------------------------------------------------------------------------------

Calendar.prototype = {

  // The HTML Container Element
  container: null,

  // Callbacks
  selectHandler: null,
  closeHandler: null,

  // Configuration
  minYear: 2009,
  maxYear: 2020,
  dateFormat: '%Y-%m-%d',

  // Dates
  date: new Date(),
  currentDateElement: null,

  // Status
  shouldClose: false,
  isPopup: true,

  dateField: null,


  //----------------------------------------------------------------------------
  // Initialize
  //----------------------------------------------------------------------------

  initialize: function(parent)
  {
    if (parent)
      this.create($(parent))
    else
      this.create()
  },


  
  
  //----------------------------------------------------------------------------
  // Update / (Re)initialize Calendar
  //----------------------------------------------------------------------------

  update: function(date)
  {
    var calendar   = this
    var today      = new Date()
    var thisYear   = today.getFullYear()
    var thisMonth  = today.getMonth()
    var thisDay    = today.getDate()
    var month      = date.getMonth();
    var dayOfMonth = date.getDate();
	var pyear  = date.getFullYear();
	
   // Ensure date is within the defined range
    if (date.getFullYear() < this.minYear)
      date.setFullYear(this.minYear)
    else if (date.getFullYear() > this.maxYear)
      date.setFullYear(this.maxYear)

    this.date = new Date(date)

    // Calculate the first day to display (including the previous month)
    date.setDate(1)
    date.setDate(-(date.getDay()) + 1)


    Calendar.TempMonthJSON = "m=" + pyear + (month+1);
	if(month < 9) Calendar.TempMonthJSON = "m=" + pyear + "0" + (month+1);
   
    if(Calendar.MonthJSON != Calendar.TempMonthJSON)
				      {
Calendar.MonthJSON = "";					  
xmlhttp=null;
Calendar.EventsJSON  = new Object();
if (window.XMLHttpRequest)
  {// code for all new browsers
  xmlhttp=new XMLHttpRequest();
  }
else if (window.ActiveXObject)
  {// code for IE5 and IE6
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
  
if (xmlhttp!=null)
  {
	  
  xmlhttp.onreadystatechange=
  function(){
if (xmlhttp.readyState==4)
  {// 4 = "loaded"
  if (xmlhttp.status==200)
    {// 200 = "OK"
	if(xmlhttp.responseText.length > 20) Calendar.EventsJSON = eval('(' + xmlhttp.responseText + ')');
    }
  else
    {
    alert("Problem retrieving XML data:" + xmlhttp.statusText);
    }
	    Calendar.MonthJSON = Calendar.TempMonthJSON;
		calendar.update(calendar.date);
  }
  }
  currentTime = new Date();

  if(pAcroCaller == "GROUP")
	{pResourceID = "&r="  + $("pHours").getValue();}
  else
	{pResourceID = "";}
  
  xmlhttp.open("GET","GetDates.php?c=" + vCustID + "&a="  + currentTime + "&" + Calendar.TempMonthJSON + pResourceID + "&s=" + $("pSessionId").getValue(),true);  
  xmlhttp.send(null);
  }
else
  {
  alert("Your browser does not support XMLHTTP.");
  }   
 	//while(Calendar.MonthJSON != Calendar.TempMonthJSON){}
			      }  
   
    // Fill in the days of the month
    Element.getElementsBySelector(this.container, 'tbody tr').each(
      function(row, i) {
        var rowHasDays = false
        row.immediateDescendants().each(
          function(cell, j) {
            var day            = date.getDate()
            var dayOfWeek      = date.getDay()
            var isCurrentMonth = (date.getMonth() == month)
            

			
	var AJAXDate = date.getFullYear();
	if(month < 9)
	  {AJAXDate = AJAXDate + "-0" + (month + 1);}
	else
	  {AJAXDate = AJAXDate + "-" + (month + 1);}
	
	if(day < 10)
	  {AJAXDate = AJAXDate + "-0" + day;}
	else
	  {AJAXDate = AJAXDate + "-" + day;}


			  
	
			  
            // Reset classes on the cell
            cell.className = ''
            cell.date = new Date(date)
            cell.update(day)

            // Account for days of the month other than the current month
            if (!isCurrentMonth)
              cell.addClassName('otherDay')
            else
              rowHasDays = true

            // Ensure the current day is selected
            if (isCurrentMonth && day == dayOfMonth) {
              cell.addClassName('selected')
              calendar.currentDateElement = cell	
			  
			  	SetEventDetails(cell.date);		
		
            }

            // Today
            if (date.getFullYear() == thisYear && date.getMonth() == thisMonth && day == thisDay)
			  {   
              cell.addClassName('today')
			  }
			  
            // Weekend
            if ([0, 6].indexOf(dayOfWeek) != -1)
              cell.addClassName('weekend')

				
			if(date.getMonth() == month){
			if(Calendar.EventsJSON.Events){
			if(Calendar.EventsJSON.Events[AJAXDate]){
			   pLoc = Calendar.EventsJSON.Events[AJAXDate];
			   pcnt = 'AvailFull';
			   	if(pAcroCaller == "SINGLE")
					{
					for(i=0;i<pLoc.length;i++)
					 {
					 if(pLoc[i].Available * 1 > 20){pcnt = 'AvailSemi';}
					 }
					 
				   for(i=0;i<pLoc.length;i++)
					 {
					 if(pLoc[i].Available * 1 > 70){pcnt = 'AvailOk';}
					 }
					if(pcnt == 'AvailOk')
					   {
						paa=0;	 
					   for(i=0;i<pLoc.length;i++){paa += pLoc[i].Available * 1 - 20;}
					   if(paa < 350){pcnt = 'AvailSemi';}
					  }
					}	
			   	if(pAcroCaller == "GROUP")
					{
					 
				   for(i=0;i<pLoc.length;i++)
					 {
					 if(pLoc[i].Available * 1 > 90){pcnt = 'AvailOk';}
					 }
					 
					if(pcnt == 'AvailOk')
					   {
					   paa=0;	 
					   for(i=0;i<pLoc.length;i++){paa += pLoc[i].Available * 1 - 50;}
					   if(paa < 150){pcnt = 'AvailSemi';}
					  }
					}	
					
               cell.addClassName(pcnt);
			   
		   }}}
			
            // Set the date to tommorrow
            date.setDate(day + 1)
          }
        )
        // Hide the extra row if it contains only days from another month
        !rowHasDays ? row.hide() : row.show()
      }
    )

    this.container.getElementsBySelector('td.title')[0].update(
      Calendar.MONTH_NAMES[month] + ' ' + this.date.getFullYear()
    )
  },



  //----------------------------------------------------------------------------
  // Create/Draw the Calendar HTML Elements
  //----------------------------------------------------------------------------

  create: function(parent)
  {

    // If no parent was specified, assume that we are creating a popup calendar.
    if (!parent) {
      parent = document.getElementsByTagName('body')[0]
      this.isPopup = true
    } else {
      this.isPopup = false
    }

    // Calendar Table
    var table = new Element('table')

    // Calendar Header
    var thead = new Element('thead')
    table.appendChild(thead)

    // Title Placeholder
    var row  = new Element('tr')
    var cell = new Element('td', { colSpan: 7 } )
    cell.addClassName('title')
    row.appendChild(cell)
    thead.appendChild(row)

    // Calendar Navigation
    row = new Element('tr')
    this._drawButtonCell(row, '&#x00ab;', 1, Calendar.NAV_PREVIOUS_YEAR)
    this._drawButtonCell(row, '&#x2039;', 1, Calendar.NAV_PREVIOUS_MONTH)
    this._drawButtonCell(row, pTodayDescr,    3, Calendar.NAV_TODAY)
    this._drawButtonCell(row, '&#x203a;', 1, Calendar.NAV_NEXT_MONTH)
    this._drawButtonCell(row, '&#x00bb;', 1, Calendar.NAV_NEXT_YEAR)
    thead.appendChild(row)

    // Day Names
    row = new Element('tr')
    for (var i = 0; i < 7; ++i) {
      cell = new Element('th').update(Calendar.SHORT_DAY_NAMES[i])
      if (i == 0 || i == 6)
        cell.addClassName('weekend')
      row.appendChild(cell)
    }
    thead.appendChild(row)

    // Calendar Days
    var tbody = table.appendChild(new Element('tbody'))
    for (i = 6; i > 0; --i) {
      row = tbody.appendChild(new Element('tr'))
      row.addClassName('days')
      for (var j = 7; j > 0; --j) {
        cell = row.appendChild(new Element('td'))
        cell.calendar = this
      }
    }

    // Calendar Container (div)
    this.container = new Element('div')
    this.container.addClassName('calendar')
    if (this.isPopup) {
      this.container.setStyle({ position: 'absolute', display: 'none' })
      this.container.addClassName('popup')
    }
    this.container.appendChild(table)

    // Initialize Calendar
    this.update(this.date)

    // Observe the container for mousedown events
    Event.observe(this.container, 'mousedown', Calendar.handleMouseDownEvent)

    // Append to parent element
    parent.appendChild(this.container)

  },

  _drawButtonCell: function(parent, text, colSpan, navAction)
  {
    var cell          = new Element('td')
    if (colSpan > 1) cell.colSpan = colSpan
    cell.className    = 'button'
    cell.calendar     = this
    cell.navAction    = navAction
    cell.innerHTML    = text
    cell.unselectable = 'on' // IE
    parent.appendChild(cell)
    return cell
  },



  //------------------------------------------------------------------------------
  // Callbacks
  //------------------------------------------------------------------------------

  // Calls the Select Handler (if defined)
  callSelectHandler: function()
  {
    if (this.selectHandler)
      this.selectHandler(this, this.date.print(this.dateFormat))
  },

  // Calls the Close Handler (if defined)
  callCloseHandler: function()
  {
    if (this.closeHandler)
      this.closeHandler(this)
  },



  //------------------------------------------------------------------------------
  // Calendar Display Functions
  //------------------------------------------------------------------------------

  // Shows the Calendar
  show: function()
  {
    this.container.show()
    if (this.isPopup) {
      window._popupCalendar = this
      Event.observe(document, 'mousedown', Calendar._checkCalendar)
    }
  },

  // Shows the calendar at the given absolute position
  showAt: function (x, y)
  {
    this.container.setStyle({ left: x + 'px', top: y + 'px' })
    this.show()
  },

  // Shows the Calendar at the coordinates of the provided element
  showAtElement: function(element)
  {
    var pos = Position.cumulativeOffset(element)
    this.showAt(pos[0], pos[1])
  },

  // Hides the Calendar
  hide: function()
  {
    if (this.isPopup)
      Event.stopObserving(document, 'mousedown', Calendar._checkCalendar)
    this.container.hide()
  },



  //------------------------------------------------------------------------------
  // Miscellaneous
  //------------------------------------------------------------------------------

  // Tries to identify the date represented in a string.  If successful it also
  // calls this.setDate which moves the calendar to the given date.
  parseDate: function(str, format)
  {
    if (!format)
      format = this.dateFormat
    this.setDate(Date.parseDate(str, format))
  },



  //------------------------------------------------------------------------------
  // Getters/Setters
  //------------------------------------------------------------------------------

  setSelectHandler: function(selectHandler)
  {
    this.selectHandler = selectHandler
  },

  setCloseHandler: function(closeHandler)
  {
    this.closeHandler = closeHandler
  },

  setDate: function(date)
  {
    if (!date.equalsTo(this.date))
      this.update(date)
  },

  setDateFormat: function(format)
  {
    this.dateFormat = format
	 
  },

  setDateField: function(field)
  {
    this.dateField = $(field)
  },

  setRange: function(minYear, maxYear)
  {
    this.minYear = minYear
    this.maxYear = maxYear
  }

}

// global object that remembers the calendar
window._popupCalendar = null





























//==============================================================================
//
// Date Object Patches
//
// This is pretty much untouched from the original. I really would like to get
// rid of these patches if at all possible and find a cleaner way of
// accomplishing the same things. It's a shame Prototype doesn't extend Date at
// all.
//
//==============================================================================

Date.DAYS_IN_MONTH = new Array(31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31)
Date.SECOND        = 1000 /* milliseconds */
Date.MINUTE        = 60 * Date.SECOND
Date.HOUR          = 60 * Date.MINUTE
Date.DAY           = 24 * Date.HOUR
Date.WEEK          =  7 * Date.DAY

// Parses Date
Date.parseDate = function(str, fmt) {
  var today = new Date();
  var y     = 0;
  var m     = -1;
  var d     = 0;
  var a     = str.split(/\W+/);
  var b     = fmt.match(/%./g);
  var i     = 0, j = 0;
  var hr    = 0;
  var min   = 0;

  for (i = 0; i < a.length; ++i) {
    if (!a[i]) continue;
    switch (b[i]) {
      case "%d":
      case "%e":
        d = parseInt(a[i], 10);
        break;
      case "%m":
        m = parseInt(a[i], 10) - 1;
        break;
      case "%Y":
      case "%y":
        y = parseInt(a[i], 10);
        (y < 100) && (y += (y > 29) ? 1900 : 2000);
        break;
      case "%b":
      case "%B":
        for (j = 0; j < 12; ++j) {
          if (Calendar.MONTH_NAMES[j].substr(0, a[i].length).toLowerCase() == a[i].toLowerCase()) {
            m = j;
            break;
          }
        }
        break;
      case "%H":
      case "%I":
      case "%k":
      case "%l":
        hr = parseInt(a[i], 10);
        break;
      case "%P":
      case "%p":
        if (/pm/i.test(a[i]) && hr < 12)
          hr += 12;
        else if (/am/i.test(a[i]) && hr >= 12)
          hr -= 12;
        break;
      case "%M":
        min = parseInt(a[i], 10);
        break;
    }
  }
  if (isNaN(y)) y = today.getFullYear();
  if (isNaN(m)) m = today.getMonth();
  if (isNaN(d)) d = today.getDate();
  if (isNaN(hr)) hr = today.getHours();
  if (isNaN(min)) min = today.getMinutes();
  if (y != 0 && m != -1 && d != 0)
    return new Date(y, m, d, hr, min, 0);
  y = 0; m = -1; d = 0;
  for (i = 0; i < a.length; ++i) {
    if (a[i].search(/[a-zA-Z]+/) != -1) {
      var t = -1;
      for (j = 0; j < 12; ++j) {
        if (Calendar.MONTH_NAMES[j].substr(0, a[i].length).toLowerCase() == a[i].toLowerCase()) { t = j; break; }
      }
      if (t != -1) {
        if (m != -1) {
          d = m+1;
        }
        m = t;
      }
    } else if (parseInt(a[i], 10) <= 12 && m == -1) {
      m = a[i]-1;
    } else if (parseInt(a[i], 10) > 31 && y == 0) {
      y = parseInt(a[i], 10);
      (y < 100) && (y += (y > 29) ? 1900 : 2000);
    } else if (d == 0) {
      d = a[i];
    }
  }
  if (y == 0)
    y = today.getFullYear();
  if (m != -1 && d != 0)
    return new Date(y, m, d, hr, min, 0);
  return today;
};

// Returns the number of days in the current month
Date.prototype.getMonthDays = function(month) {
  var year = this.getFullYear()
  if (typeof month == "undefined")
    month = this.getMonth()
  if (((0 == (year % 4)) && ( (0 != (year % 100)) || (0 == (year % 400)))) && month == 1)
    return 29
  else
    return Date.DAYS_IN_MONTH[month]
};

// Returns the number of day in the year
Date.prototype.getDayOfYear = function() {
  var now = new Date(this.getFullYear(), this.getMonth(), this.getDate(), 0, 0, 0);
  var then = new Date(this.getFullYear(), 0, 0, 0, 0, 0);
  var time = now - then;
  return Math.floor(time / Date.DAY);
};

/** Returns the number of the week in year, as defined in ISO 8601. */
Date.prototype.getWeekNumber = function() {
  var d = new Date(this.getFullYear(), this.getMonth(), this.getDate(), 0, 0, 0);
  var DoW = d.getDay();
  d.setDate(d.getDate() - (DoW + 6) % 7 + 3); // Nearest Thu
  var ms = d.valueOf(); // GMT
  d.setMonth(0);
  d.setDate(4); // Thu in Week 1
  return Math.round((ms - d.valueOf()) / (7 * 864e5)) + 1;
};

/** Checks date and time equality */
Date.prototype.equalsTo = function(date) {
  return ((this.getFullYear() == date.getFullYear()) &&
   (this.getMonth() == date.getMonth()) &&
   (this.getDate() == date.getDate()) &&
   (this.getHours() == date.getHours()) &&
   (this.getMinutes() == date.getMinutes()));
};

/** Set only the year, month, date parts (keep existing time) */
Date.prototype.setDateOnly = function(date) {
  var tmp = new Date(date);
  this.setDate(1);
  this.setFullYear(tmp.getFullYear());
  this.setMonth(tmp.getMonth());
  this.setDate(tmp.getDate());
  
};

/** Prints the date in a string according to the given format. */
Date.prototype.print = function (str) {
  var m = this.getMonth();
  var d = this.getDate();
  var y = this.getFullYear();
  var wn = this.getWeekNumber();
  var w = this.getDay();
  var s = {};
  var hr = this.getHours();
  var pm = (hr >= 12);
  var ir = (pm) ? (hr - 12) : hr;
  var dy = this.getDayOfYear();
  if (ir == 0)
    ir = 12;
  var min = this.getMinutes();
  var sec = this.getSeconds();
  s["%a"] = Calendar.SHORT_DAY_NAMES[w]; // abbreviated weekday name [FIXME: I18N]
  s["%A"] = Calendar.DAY_NAMES[w]; // full weekday name
  s["%b"] = Calendar.SHORT_MONTH_NAMES[m]; // abbreviated month name [FIXME: I18N]
  s["%B"] = Calendar.MONTH_NAMES[m]; // full month name
  // FIXME: %c : preferred date and time representation for the current locale
  s["%C"] = 1 + Math.floor(y / 100); // the century number
  s["%d"] = (d < 10) ? ("0" + d) : d; // the day of the month (range 01 to 31)
  s["%e"] = d; // the day of the month (range 1 to 31)
  // FIXME: %D : american date style: %m/%d/%y
  // FIXME: %E, %F, %G, %g, %h (man strftime)
  s["%H"] = (hr < 10) ? ("0" + hr) : hr; // hour, range 00 to 23 (24h format)
  s["%I"] = (ir < 10) ? ("0" + ir) : ir; // hour, range 01 to 12 (12h format)
  s["%j"] = (dy < 100) ? ((dy < 10) ? ("00" + dy) : ("0" + dy)) : dy; // day of the year (range 001 to 366)
  s["%k"] = hr;   // hour, range 0 to 23 (24h format)
  s["%l"] = ir;   // hour, range 1 to 12 (12h format)
  s["%m"] = (m < 9) ? ("0" + (1+m)) : (1+m); // month, range 01 to 12
  s["%M"] = (min < 10) ? ("0" + min) : min; // minute, range 00 to 59
  s["%n"] = "\n";   // a newline character
  s["%p"] = pm ? "PM" : "AM";
  s["%P"] = pm ? "pm" : "am";
  // FIXME: %r : the time in am/pm notation %I:%M:%S %p
  // FIXME: %R : the time in 24-hour notation %H:%M
  s["%s"] = Math.floor(this.getTime() / 1000);
  s["%S"] = (sec < 10) ? ("0" + sec) : sec; // seconds, range 00 to 59
  s["%t"] = "\t";   // a tab character
  // FIXME: %T : the time in 24-hour notation (%H:%M:%S)
  s["%U"] = s["%W"] = s["%V"] = (wn < 10) ? ("0" + wn) : wn;
  s["%u"] = w + 1;  // the day of the week (range 1 to 7, 1 = MON)
  s["%w"] = w;    // the day of the week (range 0 to 6, 0 = SUN)
  // FIXME: %x : preferred date representation for the current locale without the time
  // FIXME: %X : preferred time representation for the current locale without the date
  s["%y"] = ('' + y).substr(2, 2); // year without the century (range 00 to 99)
  s["%Y"] = y;    // year with the century
  s["%%"] = "%";    // a literal '%' character

  return str.gsub(/%./, function(match) { return s[match] || match });
};







Date.prototype.__msh_oldSetFullYear = Date.prototype.setFullYear;
Date.prototype.setFullYear = function(y) {
  var d = new Date(this);
  d.__msh_oldSetFullYear(y);
  if (d.getMonth() != this.getMonth())
    this.setDate(28);
  this.__msh_oldSetFullYear(y);
}
