
//
// restituisce x con 2 cifre decimali
//
function LZ(x) {return(x<0||x>9?"":"0")+x}

//
// giorno e mese nel formato usato dagli option menu del search form
//
function getDayString(d) {return LZ(d.getDate());}
function getMonthString(d) {return LZ(d.getMonth()+1) + "/" + d.getFullYear();}

//
// codifica monotona della data (es. 21 giugno 1963 => 19630621)
//
function getDateCode(d) {return d.getFullYear() * 10000 + (d.getMonth()+1) * 100 + d.getDate();}

//
// codifica monotona del mese (es. 21 giugno 1963 => 19630600)
//
function getMonthCode(d) {return d.getFullYear() * 10000 + (d.getMonth()+1) * 100;}

//
// restituisce la data corrispondente al primo del mese  
//
function getMonthFirstDay(d)
{
  return new Date(d.getFullYear(), d.getMonth(), 1);
}

//
// restituisce la data del giorno successivo
//
function getNextDate(d)
{
  var nextD = new Date(d.getFullYear(), d.getMonth(), d.getDate());
  nextD.setDate(nextD.getDate()+1);
  return nextD;
}

//
// assegna una data ad una coppia di option menu giorno, mese-anno
// (cfr. search form. fldNamePrefixe' il prefisso comune al nome degli option menu)

function assignDate(fldNamePrefix, d) {
  document.forms[0][fldNamePrefix+"d"].selectedIndex = LZ(d.getDate());
  var fld = document.forms[0][fldNamePrefix+"my"];
  var code = getMonthString(d);
  for (var i=0; i<fld.options.length; i++) { 
    if (fld.options[i].value==code) { 
      fld.selectedIndex=i; 
      return;           
    }
  }
  fld.selectedIndex=0;    
}


//
// id -> oggetto (centralizzare una parte dipendente dal browser)
//
function getObjectById(id)
{
  return document.getElementById(id);
}

//
// costruttore del VenereCalendar
//
function VenereCalendar() {
  this.firstPageDate = getMonthFirstDay(new Date());
  this.scrollDirection = 0;
  this.scrollStartTime = 0;
  this.page1 = 0;
  this.page2 = 0;
  this.page3 = 0;
  this.pageWidth = 140;
  this.win = 0;
  this.isArrival = false; // true => arrival, false => departure
  this.firstDepartureDate = new Date(); // min(tomorrow, arrivalDate+1)
  this.months = ["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dic"];
  this.days = ["S", "M","T","W","T","F","S"];
}



//
// l'utente ha selezionato una data
//
VenereCalendar.prototype.onSelect = function(day,month,year) {
  this.win.hidePopup();
  var d = new Date(year,month,day);
  if(this.isArrival)
  {
    this.firstDepartureDate = getNextDate(d);
    assignDate("cb_s", d);
    assignDate("cb_e", this.firstDepartureDate);
  }
  else
  {
    assignDate("cb_e", d);
  }
}

//
// l'utente ha premuto il link "close window"
//
VenereCalendar.prototype.onCancel = function() {
  this.win.hidePopup();
}

//
// Crea una pagina del calendario: restituisce una stringa
// index = 0,1,2; normalmente sono visibili solo 0 e 1. Durante lo scroll compare anche 2
//
VenereCalendar.prototype.makeCalendarPage = function(index) {

  var d = this.firstPageDate;
  d = new Date(d.getFullYear(), d.getMonth()+index, 1);
  var text = '<table id="calendar_page'+index+'">';
  text += '<tr><td class="monthLabel" colspan="7">' + this.months[d.getMonth()] + ' ' + d.getFullYear() + '</tr>';

  text += '<tr class="header">';
  var j = 0;
  for (j=0;j<6;j++) text = text + '<td>' + this.days[j] + '</td>';
  text = text + '<td class="sunday">' + this.days[j] + '</td>';
  text = text + '</tr><tr>';
  for(j=0;j<d.getDay();j++) text += '<td>&nbsp;</td>';
  var curMonth = d.getMonth();
  var nowDateCode = getDateCode(new Date());
  var firstDateCode = nowDateCode ;
  if(this.isArrival==false) firstDateCode = getDateCode(this.firstDepartureDate);
  var curYear = d.getFullYear();

  while(d.getMonth() == curMonth) {
    if((j%7)==0) text += '</tr><tr>';
    var isSunday = (j%7)==6;
    j++;
    
    var dCode = getDateCode(d);

    if(dCode<firstDateCode) 
      text += '<td class="disabled' + (isSunday ? ' sunday' : '') + '">'+d.getDate()+'</td>';
    else 
    {
      if(dCode==nowDateCode && isSunday) text += '<td class="today sunday">';
      else if(dCode==nowDateCode) text += '<td class="today">';
      else if(isSunday) text += '<td class="sunday">';
      else text += '<td>';
      var day = d.getDate(); 
      text += '<a href="#" onClick="VenereCalendar.instance.onSelect(' 
           + day + ',' + curMonth + ',' + curYear  + ')">' + day + '</a></td>';
    }
    d.setDate(d.getDate()+1);
  }
  for(;j<6;j++) text += '<td>&nbsp;</td>';
  text += '</tr></table>';
  return text;
}

//
// crea tutto il calendario: pagine e bottoni
//
VenereCalendar.prototype.makeCalendar = function () {
  
  var now = new Date();
  var curMonth = now.getFullYear()*1000 + now.getMonth()*100;
  
  var text = "";
  if(getDateCode(this.firstPageDate)>getDateCode(new Date()))
    text += '<a class="leftarrow" href="#" onClick="VenereCalendar.instance.startScroll(-1)"><img src="http://www.venere.com/site/static_pages/img/cal/prev_on.gif"></a>';
  text += '<a class="rightarrow" href="#" onClick="VenereCalendar.instance.startScroll(1)"><img src="http://www.venere.com/site/static_pages/img/cal/next_on.gif"></a>';
  text += '<a class="closebutton" href="#" onClick="VenereCalendar.instance.onCancel()">Close</a>';

  text += '<div id="calendar_page1" class="calendar">' + this.makeCalendarPage(0) + '</div>';
  text += '<div id="calendar_page2" class="calendar">' + this.makeCalendarPage(1) + '</div>';
  text += '<div id="calendar_page3" class="calendar">' + this.makeCalendarPage(2) + '</div>';

  document.getElementById('calendarframe').innerHTML = text;

  this.page1 = document.getElementById('calendar_page1');
  this.page2 = document.getElementById('calendar_page2');
  this.page3 = document.getElementById('calendar_page3');

  this.page1.style.left = '0px';
  this.page2.style.left = this.pageWidth + 'px';
  this.page3.style.left = 2*this.pageWidth + 'px';
}

//
// fa scorrere il calendario a sx (scrollDir==-1) o a dx (scrollDir==1)
//
VenereCalendar.prototype.scroll = function () {
  if(this.scrollDir == 0) return;
  var d = new Date();
  var t = (d.getTime() - this.scrollStartTime) * 0.002;
  var isDone = false;
  if(t>=1) {t=1;isDone = true;}
  if(this.scrollDir<0) t = 1-t;
  var offset = this.pageWidth * t*t*(3-t*2);
  
  if(isDone) {
    offset = 0;
    if(this.scrollDir>0) 
    {
      // scrollando a dx il cambiamento delle pagine va fatto alla fine dello scroll
      this.firstPageDate.setMonth(this.firstPageDate.getMonth()+1);
      this.makeCalendar();
    }
    this.scrollDir = 0;
  }
  else 
    setTimeout('VenereCalendar.instance.scroll()',60);

  this.page1.style.left = (-offset) + "px";
  this.page2.style.left = (this.pageWidth-offset) + "px";
  this.page3.style.left = (2*this.pageWidth-offset) + "px";
}

//
// comincia uno scorrimento a sx (scrollDir==-1) o a dx (scrollDir==1)
//
VenereCalendar.prototype.startScroll = function(dir) {
  var d = new Date();
  this.scrollStartTime = d.getTime(); 
  this.scrollDir = dir; 
  if(this.scrollDir<0)
  {
      // scrollando a sx il cambiamento delle pagine va fatto all'inizio dello scroll
      this.firstPageDate.setMonth(this.firstPageDate.getMonth()-1);
      this.makeCalendar();
  }
  this.scroll();
}

//
// Apri il calendario posizionandolo sotto anchorName.
// isArrival = true => arrival, isArrival = false => departure
//
VenereCalendar.prototype.open = function(anchorName, isArrival) {
  this.isArrival = isArrival;
  if(isArrival)
  { 
    // se viene aperto il primo calendario reinizializziamo la data di partenza
    this.firstDepartureDate = new Date();
    this.firstPageDate = getMonthFirstDay(new Date());
  }
  this.makeCalendar();
  if(!this.win) {
    this.win = new PopupWindow('calendarframe');
    this.win.autoHide(); 
    this.win.offsetX = 0;
    this.win.offsetY = 20;
  }
  this.win.showPopup(anchorName);
}

//
// crea un singleton
//
VenereCalendar.instance = new VenereCalendar();

//
// main function
// 
// 
VenereCalendar.open = function(anchorName, isArrival) 
{
  VenereCalendar.instance.open(anchorName, isArrival);
}
