// dynamic kiosk script file
// v 2.2

// constructor
function dynKiosk (id, handler) {
 var inst = this; 
 this.id = id;           // kiosk ID
 this.handler = handler; // handler URL
 this.date = new Date(); // current date
 this.date.setDate(1);
 this.scrollDate = new Date(this.date.getTime() ); // date shown in scroller
 this.incMonth(this.scrollDate, -1);

 // make 3 month buttons
 var em = $(".evtMonth", id);
 em.after(em.clone());
 em.after(em.clone());
 
 $('.next a', id).click( function() {inst.next(); return false;} );
 $('.prev a', id).click( function() {inst.prev(); return false;} );

 $(".dynCtrl li a", id).slice(1, -1).click( function() {
  inst.monthClick(this);
  return false;
 } );

 // init
 this.scroll(0);
 this.setDate(this.date.getTime());
};

// loading text
dynKiosk.prototype.LOADING = '<div class="dynLoading">Loading...</div>';
// month names
dynKiosk.prototype.MONTHS = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];

// next date
dynKiosk.prototype.next = function () {
 this.scroll(1)
};

// prev date
dynKiosk.prototype.prev = function () {
 this.scroll(-1)
};

// change month by delta
dynKiosk.prototype.incMonth = function (date, delta) {
 date.setMonth(date.getMonth()+delta, 1);
};

// scroll kiosk controller
dynKiosk.prototype.scroll = function (delta) {
 var lis = $(".dynCtrl li", this.id).slice(1, -1);

 this.incMonth(this.scrollDate, delta);
 var d = new Date(this.scrollDate.getTime());  

 $(".evtMonth a", this.id).removeClass("active");
 
 for (var i=0;  i<lis.length; i++) {
  var monthName = this.MONTHS[d.getMonth()]; 
  var dateName = monthName + " " + d.getFullYear();
  
  $("a", lis.eq(i)).attr( {
   dyndate: d.getTime(),
   title: dateName });
  if (d.getTime() == this.date.getTime())
   $("a", lis.eq(i)).addClass("active");
     
  $(".month", lis.eq(i)).html( monthName );
  $(".year", lis.eq(i)).html( d.getFullYear() );
  
  this.incMonth(d, 1);
 }
};


// return request URL string
dynKiosk.prototype.getRequestString = function (m, y) {
 var month = m || this.date.getMonth();
 var year = y || this.date.getFullYear();
 return this.handler + '?m=' + ++month + '&y=' + year;
};

// set current month and load content
dynKiosk.prototype.setDate = function (date) {
 this.date.setTime(date);

 // debug output
 $(".debug", this.id).html(this.getRequestString() );
 
 // update content
 with ( $(".dynContent", this.id)) {
  html(this.LOADING);
  load(this.getRequestString() ); 
 }
};

// month button click 
dynKiosk.prototype.monthClick = function(link) {
 if ($("a.active", this.id).get(0) != $(link).get(0))
  this.setDate($(link).attr("dyndate") );
  
 $(".evtMonth a", this.id).removeClass("active");
 $(link, this.id).addClass("active"); 
}
