var _startDateCal; 
var _endDateCal;

var _ignoreCalChangedEvent = false;

function setupStartDateCal(contid)
{
      _startDateCal= new YAHOO.widget.Calendar("startDateCal",contid,
                { title:"Earliest possible date:", 
                  close:true,
                  start_weekday: 1,
                  mindate: minDate() } );
      _startDateCal.selectEvent.subscribe(handleStartDateChosen, _startDateCal, true);
	   _startDateCal.render();
}

function setupEndDateCal(contid)
{
      _endDateCal= new YAHOO.widget.Calendar("endDateCal",contid,
                { title:"Latest possible date:", 
                  close:true,
                  start_weekday: 1,
                  mindate: minDate() } );
      _endDateCal.selectEvent.subscribe(handleEndDateChosen, _endDateCal, true);
	   _endDateCal.render();
}

function getStartDateCal() 
{
   return _startDateCal;
}
function getEndDateCal() 
{
   return _endDateCal;
}

function getCalFromDesc(caldesc) 
{
   var thecal = null;
   
   if(caldesc == "start") {
      thecal = _startDateCal; 
   } else if(caldesc == "end") {
      thecal = _endDateCal; 
   } else {
      alert("Internal error: updateCalendar called with mode: "+caldesc);
   }
   
   return thecal;
}

function getOtherCal(cal)
{
   var othercal;
   
   if(cal == _startDateCal) {
      othercal = _endDateCal; 
   } else {
      othercal = _startDateCal;
   }
   return othercal;
}

function GetAbsX(elem)
{
   var abs_x = 0;

   while( elem != null ) {
      abs_x += elem.offsetLeft;      
      
      if(elem.scrollLeft) {
         abs_x -= elem.scrollLeft;
      }

      elem = elem.offsetParent;
   }
   return parseInt(abs_x);
}

function GetAbsY(elem)
{
   var abs_y = 0;

   while( elem != null ) {
      abs_y += elem.offsetTop;
      
      if(elem.scrollTop) {
         abs_y -= elem.scrollTop;
      }
      elem = elem.offsetParent;
   }
   return parseInt(abs_y);
}


function ShowCalendar(caldesc, calinputid, calcontid)
{
   var calcont  = document.getElementById(calcontid);
   var calinput = document.getElementById(calinputid);
   
   
   //Record that we have shown the calendar at least once
   calcont.calendarEverShown = true;
   
   calcont.style.position = 'absolute';
   calcont.style.top  = (GetAbsY(calinput) + calinput.offsetHeight + 1 )+ "px";
   calcont.style.left = GetAbsX(calinput) + "px";
   
   var cal = getCalFromDesc(caldesc); 
   var othercal = getOtherCal(cal);
   
   othercal.hide();
   cal.show();
   
}

function HideCalendar(caldesc, calcontid)
{
   var cal = getCalFromDesc(caldesc); 
   cal.hide();
}

function ToggleCalendar(caldesc, calinputid, calcontid)
{
   var calcont   = document.getElementById(calcontid);
   
   
   //The first time we toggle style.display may not be set
   if(   calcont.calendarEverShown
      && calcont.style.display != "none") {
      HideCalendar(caldesc)
   } else {
      ShowCalendar(caldesc, calinputid, calcontid)
   }
}

function pad2(number) {
     return (number < 10 ? '0' : '') + number
}

function handleStartDateChosen(type,args,obj)
{ 
   if(_ignoreCalChangedEvent) {
      //We have been told to ignore this event
      _ignoreCalChangedEvent = false;
      return;
   }

   var dates = args[0]; 
   var date = dates[0]; 
   var year = date[0], month = date[1], day = date[2]; 
   
   var chosendate = year+'-'+pad2(month)+'-'+pad2(day);
  
   var instartdate = document.getElementById('instartdate');
   
   if(instartdate) {
      if(instartdate.value != chosendate) {
         instartdate.value = chosendate;      
         instartdate.onchange();  
      }
   } else {
      alert('Internal error: Unable to find instartdate.');
   }
   _startDateCal.hide();   
}

function handleEndDateChosen(type,args,obj)
{
   if(_ignoreCalChangedEvent) {
      //We have been told to ignore this event
      _ignoreCalChangedEvent = false;
      return;
   }

   var dates = args[0]; 
   var date = dates[0]; 
   var year = date[0], month = date[1], day = date[2]; 
   
   var chosendate = year+'-'+pad2(month)+'-'+pad2(day);
  
   var inenddate = document.getElementById('inenddate');
   
   if(inenddate) {
      if(inenddate.value != chosendate) {
         inenddate.value = chosendate;
         inenddate.onchange();
      }
   } else {
      alert('Internal error: Unable to find inendtdate.');
   }
   
   _endDateCal.hide();
}

//Accepts dates in UTC
function setCalendarDate(caldesc, chosendate)
{
   var thecal=getCalFromDesc(caldesc);

   if(thecal == null) {
       //This function may be called before we have set up the calendar
       return;
   }

   //The YUI code can change without warning so we wrap a try around it
   try {
      var selectedDates = thecal.getSelectedDates();
      var firstDate = null;

      if (selectedDates.length > 0) { 
         firstDate = selectedDates[0];
      }
      
      if(firstDate != chosendate) {
      	 //really hacky way to stop a date changed triggered from text input
	     //messing with the text input...we set this var to tell the 
         //handleXXXDate function to ignore the next event
         _ignoreCalChangedEvent = true;


         //create a date object that represents the chosen date but in the local timezone
         var localDate = new Date(chosendate.getUTCFullYear(),chosendate.getUTCMonth(),chosendate.getUTCDate(), 0, 0, 0, 0);
         
         thecal.select(localDate); 

         //Now...if the calendar accepted it as a valid date, update the page 
         var selectedDates = thecal.getSelectedDates();
      
         if (selectedDates.length > 0) { 
            var firstDate = selectedDates[0]; 
            thecal.cfg.setProperty("pagedate", (firstDate.getMonth()+1) + "/" + firstDate.getFullYear()); 
            thecal.render();
         }
      }
   } catch(err) {
   	//alert("Caught: "+err);
   }
}

