(function ($) {

/**
* @file
* Javascript support files.
*
*/

Drupal.behaviors.bootstrap_calendar = {
  attach: function (context, settings) {
    // Read URL paramters
    var urlParams = bootstrap_calendar_readURLparams();
    // Create modal
    bootstrap_calendar_create_modal('bootstrap_calendar');

    "use strict";

    var options = {
      events_source: 'ajax/bootstrap_calendar/events',
      view: Drupal.settings.bootstrap_calendar.default_view,
// views needs debbuging
      views: Drupal.settings.bootstrap_calendar.views,
      tmpl_path: Drupal.settings.bootstrap_calendar.path + '/tmpls/',
      tmpl_cache: false,
      time_start: Drupal.settings.bootstrap_calendar.time_start,
      time_end: Drupal.settings.bootstrap_calendar.time_end,
      time_split: Drupal.settings.bootstrap_calendar.time_split,
      day: Drupal.settings.bootstrap_calendar.date,
      language: 'i18n',
      holidays: {},
      onAfterViewLoad: function(view) {
        $('h3.calendar-title').text(this.getTitle());
        $('.btn-group button').removeClass('active');
        $('button[data-calendar-view="' + view + '"]').addClass('active');
      },
      classes: {
        months: {
          general: 'label'
        }
      }
    };

    var calendar = $('#calendar').calendar(options);

    $('.btn-group button[data-calendar-nav]').each(function() {
      var $this = $(this);
      $this.click(function() {
        calendar.navigate($this.data('calendar-nav'));
      });
    });

    $('.btn-group button[data-calendar-view]').each(function() {
      var $this = $(this);
      $this.click(function() {
        calendar.view($this.data('calendar-view'));
      });
    });

    var value = Drupal.settings.bootstrap_calendar.first_day;
    value = value.length ? parseInt(value) : null;
    calendar.setOptions({first_day: value});

    calendar.setLanguage(Drupal.settings.bootstrap_calendar.language);

    calendar.setOptions({modal: parseInt(Drupal.settings.bootstrap_calendar.open_modal)});

    $('#events-modal .modal-header, #events-modal .modal-footer').click(function(e){
      //e.preventDefault();
      //e.stopPropagation();
    });
  }
}

function bootstrap_calendar_readURLparams() {
  (window.onpopstate = function () {
    var match,
      pl     = /\+/g,  // Regex for replacing addition symbol with a space
      search = /([^&=]+)=?([^&]*)/g,
      decode = function (s) { return decodeURIComponent(s.replace(pl, " ")); },
      query  = window.location.search.substring(1);

    urlParams = {};
    while (match = search.exec(query))
      urlParams[decode(match[1])] = decode(match[2]);
  })();
  return urlParams;
}

function bootstrap_calendar_create_modal(id) {
}

}(jQuery));

