function setInputStyle(el, defaultText) {
  if (el) {
    if (el.getValue() == '' || el.getValue() == defaultText) {
      el.addClassName('empty');
      if (el.getValue() == '') {
	el.value = defaultText;
      }
    } else {
      el.removeClassName('empty');
    }
  }
}

function init_carousel()
{
  $$('.carousel').each(function(el) {
    var list = el.select('.carousel_item');
    if (list && list.length > 0) {
      var current = 0;
      new PeriodicalExecuter(function(pe) {
        var items = list[current].up('.carousel_items');
        var left = items.getStyle('left');
        if (left) left = Math.abs(parseInt(left.substring(0, left.length - 2)));
        current++;
        if (current >= list.length) {
	  current = left = 0;
        } else {
          left = left + parseInt(list[current].getWidth());
        }
        new Effect.Opacity(items, { duration: 0.1, from: 1, to: 0.4 });
        new Effect.Morph(items, {
	  afterFinish: function(effect) { new Effect.Opacity(effect.element, { from: 0.4, to: 1, duration: 0.2 }); },
	  style: 'left: -' + left + 'px',
	  duration: 0.5
        });
      }, 5);
    }
  });
}

Event.observe(window, 'load', function() {
  if ($('ajax_doc_search')) {
   new Ajax.Autocompleter("ajax_doc_search", "ajax_doc_search_results", "/ajax/doc/search", {
    paramName: "keyword", 
    minChars: 3,
    updateElement: function(li) {
      if (li.id) {
        document.location.href = '/doc/' + li.id;
      } else {
        $('ajax_doc_search_form').submit();
      }
    }
   });
  }
  if ($('ajax_doc_search')) {
    Event.observe($('ajax_doc_search'), 'focus', function(event) {
      var el = Event.element(event);
      el.removeClassName('empty');
      if (el.getValue() == quicksearchDefaultText) {
	el.value = '';
      }
    });
    Event.observe($('ajax_doc_search'), 'blur', function(event) {
      var el = Event.element(event);
      if (el.getValue() == '') {
        el.addClassName('empty');
        el.value = quicksearchDefaultText;
      }
    });
    setInputStyle($('ajax_doc_search'), quicksearchDefaultText);
  }

  init_carousel();
});
