(function($){

  var window = this;
  // getMonth()  	Returns the month (from 0-11)
  var MonthNames = {
    'ro': ['Ianuarie', 'Februarie', 'Martie','Aprilie', 'Mai','Iunie','Iulie','August','Septembrie','Octombrie','Noiembrie','Decembrie'],
    'ru': ['Январь', 'Февраль', 'Март', 'Апрель', 'Май', 'Июнь', 'Июль', 'Август', 'Сентябрь', 'Октябрь', 'Ноябрь', 'Декабрь'],
    'en': ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']
  };

  // getDay()  	Returns the day of the week (from 0-6) 0 - Sunday
  var WeekDayNames = {
    'ro': ['Du', 'Lu', 'Ma', 'Mi', 'Jo', 'Vi', 'Si'],
    'ru': ['Вс', 'Пн', 'Вт', 'Ср', 'Чт', 'Пт', 'Сб'],
    'en': ['Su', 'Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa']
  };
  
	DateCarousel = window.DateCarousel = function(el, options) {
    DateCarousel.fn = DateCarousel.prototype = {
      init: function(el, options) {
        // Handle $(DOMElement)
        if (el.nodeType) {
          _this = el;
          // cache jquery object to avoid multiple constructor call
          $_this = $(_this);
          _setDefaultOptions();
          // copy all public methods and propreties
          $.extend(_this, DateCarousel.fn);
          _setOptions(options);

          _timestamp = _options.timestamp;
          _current = _options.current;

          _drawCarousel();
          _registerEvents();

          return _this;
        }
        // Handle HTML strings
        if (typeof el === "string") {
          return DateCarousel(document.getElementById(el), options);
        }
      },
      CLASSNAME:'DateCarousel'
    }
  // private variables
  var _this; // select element
  var $_this;
  var _current = 0;
//  var $_cellsContainer = null;
  var _options = null;
  var _increasingUnits = ['day', 'month', 'year'];
  var _timestamp;
  var _marginLeft = 0;
  var _hasSelectedCell = false;
  
  return new DateCarousel.fn.init(el, options);

  /* constants
   * %j - Day of the month without leading zeros [1 to 31]
   * %D -	A textual representation of a day [represented by variable WeekDayNames]
   * %n - Numeric representation of a month, without leading zeros [1 to 12]
   * %F - A full textual representation of a month [represented by variable MonthNames]
   * %Y - A full numeric representation of a year, 4 digits
  */
  function formatTemplate(formated_str, timestamp, isHref) {
    var date = new Date(timestamp);
    var str = "";
    formated_str = formated_str.replace(/%Y/g, date.getFullYear());
    formated_str = formated_str.replace(/%n/g, date.getMonth() + 1);
    formated_str = formated_str.replace(/%j/g, date.getDate());

    str = _getWeekDayName(date.getDay(), _options.lang);
    if (str === null) str = "";
    formated_str = formated_str.replace(/%D/g, str);

    str = _getMonthName(date.getMonth(), (_options.lang == 'ru' && isHref == true ? 'en' : _options.lang));
    if (str === null) str = "";
    formated_str = formated_str.replace(/%F/g, str);
    return formated_str;
  }

  function _setDefaultOptions() {
    _options = new Object();
    _options.lang = 'ro';

//    _options.cellHrefPattern = "http://localhost:90/ro/evenimente/cautare?days=(%Y.(%n.(%j.0)))";
    _options.cellHrefPattern = "/ro/arhiva/evenimente/%Y-%F";
//    _options.cellTextPattern = "<span class='date-nr'>%j</span><span class='week-day'>%D</span><span class='month'>%F</span>";
    _options.cellTextPattern = "%j-%n<br />%Y";
    _options.isCellSelectedAnchor = false;
    _options.unitToIncrease= "month";
    _options.selectedCellTimestamp = null;
    var d = new Date();
    _options.timestamp = new Date(d.getFullYear(), d.getMonth(), d.getDate()).getTime();
    _options.current = 0;
    
    _options.cellsCount = 7;  // how many cells in slider to show
    _options.cellWidth = 90;
    _options.limit = 3;       // limit slider counts

    _options.animateDuration = 500;
  }

  function _setOptions(options) {
    if (typeof options != 'object') return;
    if (typeof options.unitToIncrease == 'undefined') 
      options.unitToIncrease = _increasingUnits[0];
    if (options.selectedCellTimestamp && options.selectedCellTimestamp != null) {
      var selectedTimestamp = new Date(options.selectedCellTimestamp);
      options.selectedCellTimestamp = selectedTimestamp.getTime();
      if (options.selectedCellTimestamp && options.selectedCellTimestamp != 'NaN')
        _hasSelectedCell = true;
    }
    if (typeof options.current == 'number' && Math.abs(options.current) > options.limit)
      options.current = options.limit;
    if (typeof options.current == 'number' && options.current < 0)
      options.current = 0;
    
    $.extend(_options, options);

  }

  function _drawCarousel() {
    _this.innerHTML = "<div class='btn-prev'></div>"
          +"<div class='cells-list'><div class='cells-container'>" + _drawCells(_timestamp) + "</div></div>"
          +"<div class='btn-next'></div>"
          +"<div style='clear:both;float:none;'></div>";
//    $_cellsContainer = $($_this.find('.cells-container').get(0));
    $_this.find('.cells').addClass('selected');

    _addCellsToLeft();
    _addCellsToRight();
    if (_current == _options.limit) {
      $_this.find('.btn-next').css("visibility", "hidden");
    }
    if (_current == -_options.limit) {
      $_this.find('.btn-prev').css("visibility", "hidden");
    }
  }

  function _registerEvents() {
    $_this.find('.btn-prev').bind('click', _prevSlide);
    $_this.find('.btn-next').bind('click', _nextSlide);
  }

  function _drawCells(timestamp) {
    var html = "<div class='cells'>";
    var isMatched;

    for (var i = 0; i < _options.cellsCount; i++) {
      isMatched = false;
      if (_hasSelectedCell && timestamp == _options.selectedCellTimestamp)
        isMatched = true;
      html += "<div class='cell" + (isMatched ? " selected" : "") + "'>"
        + (isMatched && !_options.isCellSelectedAnchor
          ? "<span>"
          : "<a href='" + formatTemplate(_options.cellHrefPattern, timestamp, true).toLowerCase() + "'>")
        + formatTemplate(_options.cellTextPattern, timestamp, false)
        + (isMatched && !_options.isCellSelectedAnchor ? "</span>" : "</a>") + "</div>";
      timestamp = _getNextUnit(timestamp, 1);
    }
    
    html += "</div>";
    return html;
  }

  function _addCellsToLeft() {
    $_this.find('.cells-container').prepend(
      _drawCells(
        _getPrevUnit(_timestamp, _options.cellsCount)
      )
    );
    _marginLeft -= _options.cellWidth * _options.cellsCount;
    $_this.find('.cells-container')[0].style.marginLeft = _marginLeft + 'px';
  }

  function _addCellsToRight() {
    $_this.find('.cells-container').append(
      _drawCells(
        _getNextUnit(_timestamp, _options.cellsCount)
      )
    );
      
  }

  function _removeCellsFromLeft() {
    $($_this.find('.cells').get(0)).remove();

    _marginLeft += _options.cellWidth * _options.cellsCount;;
    $_this.find('.cells-container')[0].style.marginLeft = _marginLeft + 'px';
  }

  function _removeCellsFromRight() {
    $($_this.find('.cells').get(2)).remove();
  }

  function _slideLeft() { // btn-next click handler
    _timestamp = _getNextUnit(_timestamp, _options.cellsCount);
    _removeCellsFromLeft();
    _addCellsToRight();
    $_this.find('.cells').removeClass('selected');
    $($_this.find('.cells').get(1)).addClass('selected');
  }

  function _slideRight() { // btn-prev click handler
    _timestamp = _getPrevUnit(_timestamp, _options.cellsCount);
    _removeCellsFromRight();
    _addCellsToLeft();
    $_this.find('.cells').removeClass('selected');
    $($_this.find('.cells').get(1)).addClass('selected');
  }

  function _nextSlide() {
    if (_current < _options.limit) {
      _current++;
      
      $_this.find('.btn-prev').css("visibility", "visible");
      $_this.find('.btn-next').css("visibility", "visible");
      _slideLeft();

      // animate slide
      _marginLeft -= _options.cellWidth * _options.cellsCount;
      $_this.find('.cells-container')
        .animate({marginLeft:_marginLeft+'px'}, _options.animateDuration);

      if (_current == _options.limit) {
        $_this.find('.btn-next').css("visibility", "hidden");
      }
    }
    return false;
  }

  function _prevSlide() {
    if (_current > -_options.limit) {
      _current--;

      $_this.find('.btn-prev').css("visibility", "visible");
      $_this.find('.btn-next').css("visibility", "visible");
      
      _slideRight();

      // animate slider
      _marginLeft += _options.cellWidth * _options.cellsCount;
      $_this.find('.cells-container')
        .animate({marginLeft:_marginLeft+'px'}, _options.animateDuration);

      if (_current == -_options.limit) {
        $_this.find('.btn-prev').css("visibility", "hidden");
      }
    }
    return false;
  }

  function _getMonthName(month, lang) {
    if (MonthNames && MonthNames[lang] && MonthNames[lang][month])
      return MonthNames[lang][month];
    return null;
  }

  function _getWeekDayName(day, lang) {
    if (WeekDayNames && WeekDayNames[lang] && WeekDayNames[lang][day])
      return WeekDayNames[lang][day];
    return null;
  }

  // return timestamp
  function _getNextUnit(timestamp, count) {
    var d = new Date(timestamp);
    if (_options.unitToIncrease == "day")
      d.setDate(d.getDate() + count);
    else if (_options.unitToIncrease == "month")
      d.setMonth(d.getMonth() + count);
    else if (_options.unitToIncrease == "year")
      d.setFullYear(d.getFullYear() + count);
    return d.getTime();
  }

  function _getPrevUnit(timestamp, count) {
    var d = new Date(timestamp);
    // the changes are handled automatically by the Date object itself
    if (_options.unitToIncrease == "day")
      d.setDate(d.getDate() - count);
    else if (_options.unitToIncrease == "month")
      d.setMonth(d.getMonth() - count);
    else if (_options.unitToIncrease == "year")
      d.setFullYear(d.getFullYear() - count);
    return d.getTime();
  }

	};
})(jQuery);




