(function ($) {
   var defaults = {
     prev_link: '#news-prev',
     next_link: '#news-next',
     boxes:     '#news-boxes',
     box_str:   '&nbsp;',
     box_class: 'active',
     timer:     10
   };

   var NewsTick = function (element, options) {
     var self = this;

     this.init = function (element, options) {
       this.options = $.extend({}, defaults, options);
       this.element = $(element);
       this.child = null;
       this.index = null;

       var children = this.element.children("li");
       children.hide();

       this.size = children.size();
       this.boxes();
       this.display(0);

       $(this.options.next_link).click(function () {
         self.cancelTimer();
         self.next();
       });

       $(this.options.prev_link).click(function () {
         self.cancelTimer();
         self.prev();
       });
     };

     this.boxes = function () {
       var boxes = $(this.options.boxes);
       if (!boxes) return;

       for (var i=0; i!=this.size; ++i) {
         boxes.append("<a href=\"javascript:void();\">" + this.options.box_str + "</a>");
         boxes.children("a:eq(" + i + ")").click(function () {
           self.cancelTimer();
           self.display($(self.options.boxes).children("a").index(this));
         });
       }
     };

     this.display = function (index) {
       this.deactivate();
       this.activate(index);
     };

     this.deactivate = function () {
       if (!this.child) return;
       this.child.hide();
       var path = "a:eq(" + this.index + ")";
       var boxes = $(this.options.boxes);
       if (!boxes) return;
       boxes.children(path).removeClass(this.options.box_class);
     };

     this.activate = function (index) {
       this.index = index;
       var news_path = "li:eq(" + this.index + ")";
       this.child = this.element.children(news_path).show();
       var box_path = "a:eq(" + this.index + ")";
       var boxes = $(this.options.boxes);
       if (!boxes) return;
       boxes.children(box_path).addClass(this.options.box_class);
     };

     this.prev = function () {
       this.display(this.index == 0 ? this.size - 1 : this.index - 1);
     };

     this.next = function () {
       this.display((this.index + 1) % this.size);
     };

     this.timer = function () {
       self.next();
     };

     this.cancelTimer = function () {
       if (!self.timer_id) return;
       clearInterval(self.timer_id);
       self.timer_id = null;
     };

     this.init(element, options);
     this.timer_id = setInterval(this.timer, this.options.timer * 1000);
   };

   $.fn.newstick = function (options) {
     this.each(function () {
       new NewsTick(this, options);
     });
   };

})(jQuery);
