function BookingCalendar(element, options)
{
  this.element = element;
  this.options = options;

  this.reload = function()
  {
    var url = '/providers/';
    url += this.options['provider'].toString();
    url += '/booking_schedule?';
    url += 'date=' + this.options['date'];
    url += '&';
    url += 'details=' + this.options['details'];
    url += '&';
    if (this.options['reason']) {
      url += 'reason=' + this.options['reason'];
      url += '&';
    }
    url += 'window=' + this.options['window'];

    
    if (typeof(this.options['book_function']) != 'undefined')
    {
      url += '&';
      url += 'fn=' + this.options['book_function'];
    }

    this.element.load(url);
  }

  this.date = function(arg)
  {
    this.options['date'] = arg;
    this.reload();
  }

  this.provider = function(arg)
  {
    this.options['provider'] = arg;
    this.reload();
  }

  this.defaultBook = function(args)
  {
    var url = '/appointments/new';

    url += '?p=' + encodeURIComponent(args.provider);
    url += '&d=' + encodeURIComponent(args.date);
    url += '&t=' + encodeURIComponent(args.time);
    url += '&l=' + encodeURIComponent(args.len);
    url += '&r=' + encodeURIComponent(args.reason);

    if (('wait' in args) && (args.wait == true))
    {
      url += '&wait=1';
    }

    window.location = url;
  }

  this.book = ('book' in options) ? options.book : this.defaultBook;
  
  this.element.data('_bookingCalendar', this);
  this.element.addClass('_booking_calendar');
  this.reload();
}

$.fn.extend({'bookingCalendar':function(method, arg){
  if (method == 'find')
  {
    return $(this).closest('._booking_calendar');
  }
  else if (typeof(method) == 'string')
  {
    var obj = $(this).data('_bookingCalendar');
    if (obj == null)
    {
      obj = $(this).closest('._booking_calendar').data('_bookingCalendar');
    }
    return obj[method].call(obj, arg);
  }
  else
  {
    var obj = new BookingCalendar($(this), method);
    return $(this);
  }
  return null;
}});

