var Calendar = new Class({
  initialized: false,
  currentDate: false,
  currentMonth: false,
  keywords: false,
  theme: false,
  typeToneExtension: false,
  typeAspectExtension: false,
  toneSizes: false,
  aspectSizes: false,
  days: false,
  months: [],

  initialize: function() { 
    this.days = new Object();
    this.months = ["januari","februari","maart","april","mei","juni","juli","augustus","september","oktober","november","december"];
    if (typeof(calendarCurrentMonth) != "undefined") {
      this.currentMonth = calendarCurrentMonth;
      this.init();
    }
  },

  init: function () 
  {
    if (!$('calendarComponent')) return;
    if (!base || !base.loaded) return setTimeout(this.init.bind(this),100);
    this.initCells();
    this.initLinks();
    this.initPopups();
    if (this.initialized == false) base.registerURLCallback(this.request.bind(this));
    this.initialized = true;
  },

  initCells: function() {
    days.each( function ( obj ) {
      var dateStr = obj.dateString;
      this.days[dateStr] = obj;
    }.bind(this));
  },

  initLinks: function () {
    var links = $("calendarComponent").getElements("a.link");
    links.each(function (link) {
      link.removeEvents("click")
      link.addEvent("click", function() {
        base.components["ajaxLoader"].show("calendarComponent",true);
        var href = this.href.replace("http://"+window.location.hostname, "");
        document.location.href = "#"+href;
        return false;
      });
    }.bind(this));
  },

  loaded: function() { },

  request: function ( url )
  {
    var urlParts = url.split(".");
    var parts = urlParts[0].split("/");
    var callBack = false;
    var retry = false;
    // Specific date
    if (parts[3] && parts[3].search(/^[0-9]{2}-[0-9]{2}-[0-9]{4}/) >= 0) {
      if (parts[3].replace(/^[0-9]{2}-/,"") != this.currentMonth) {
        retry = url;
        var dateParts = parts[3].split("-");
        this.currentMonth = dateParts[1]+"-"+dateParts[2];
        parts = ["",parts[2],this.months[parseInt(dateParts[1],10)-1],dateParts[2]];
        url = "/calendar/"+parts[2]+"/"+this.months[parseInt(dateParts[1],10)-1]+"/"+parts[4]+"/"+dateParts[0];
      }
    }
    if (parts[3] && parts[3].search(/^[0-9]{2}-[0-9]{2}-[0-9]{4}/) >= 0) {
      if (!$("dayInfo")) {
        this.initPopups();
        setTimeout(this.request.bind(this,url), 100);
        return false;
      }
      if (!base.components['dayInfo']) {
        setTimeout(this.request.bind(this,url), 100);
      }
      if (parts[4]) return false;
      var dateObj = this.days[parts[3]];

      if (dateObj) {
        var title = "Maya tzolkin calendar :: " + dateObj.dateString;
        if (dateObj.longcount) title += " " +dateObj.longcount;
        title += " " + dateObj.tone + "-" + dateObj.aspectName;
        base.components["dayInfo"].setHeader(title);
      }

      callBack = function ( nodes, elements, data ) {
        base.components["ajaxLoader"].hide();
        if (!data) return;
        base.components['dayInfo'].setContent(data);
        base.components['dayInfo'].show();
        var jsComponents = $("dayInfo").getElements("ul[class^=jsComponent]");
        jsComponents.each( function (component) { base.addComponent(component); }.bind(this) );
      };
    } else if (parts.length == 5 && parts[4].search(/^[0-9]*/) >= 0) {
      // Specific month
      callBack = function ( nodes, elements, data ) {
        base.components["ajaxLoader"].hide();
        var monthNr = 0;
        for (var i = 0; i < 12; i++) {
          if (this.months[i] == parts[3]) monthNr = (i+1); 
        };
        if (monthNr < 10) monthNr = "0"+monthNr;
        this.currentMonth = monthNr+"-"+parts[4];
        $("calendarComponent").innerHTML = data;
        this.initCells();
        this.initLinks();
        this.initPopups();
        if (retry) this.request(retry);
      };
    }
    if (callBack) {
      var jsonReq = new Request.HTML({ url: "/data"+url, onComplete: callBack.bind(this) }).get();

      _gaq.push(function() {
        var pageTracker = _gaq._createAsyncTracker('UA-6658542-2');
        pageTracker._trackPageview(url);
      });
    }
  },

  initPopups: function () {
    if (!$("dayInfo")) {
      var popup = base.newComponent({
        "id": "dayInfo",
        "type": "Popup",
        "options": {
          "width": "720",
          "resize": "0",
          "footer": "0",
          "containerClass": "unit23 last",
          "y": "50"
        }
      });
      
      popup.setStyle("display","none");
      $(document.body).appendChild(popup);
      base.loadComponents();
    }

    var cells = $("calendarComponent").getElements("td[class^=calendarDate]");
    var i =0;
    cells.each( function (cell) {
      cell.addEvent("click",function() { 
        var link = cell.getElement("table a.link");
        if (!link) return;

        var href = link.href.replace("http://"+window.location.hostname, "");
        document.location.href = "#"+href;
      });
      cell.addEvent("mouseover",function() { this.addClass("hover"); });
      cell.addEvent("mouseout",function() { this.removeClass("hover"); });
    });
  },

  go: function ( ) {
    var era = $("calendarDate").getElement("select[name=era]").value;
    var currentDate = $("calendarDate").getElement("input[name=date]").value;
    currentDate = currentDate.replace(/\/|\ /g,"-");
    if (era == "BC") currentDate += "BC";
    window.location.href = "#/calendar/tzolkin/"+currentDate+".html";
    return;
  },

  tabSwitch: function ( tab )
  {
  }
});

/* Initialize calendar class */
var calendar;
var callback = function() { if (!calendar) calendar = new Calendar(); else calendar.loaded(); }
window.addEvent('domready', callback);
window.addEvent('load', callback);

