// JavaScript Document
(function($){
  $.fn.quotator = function(options){
    var container = this;
    var defaults = 
    {
      speed : 5000,
      json : "quotator_quotes.js",
      showdots: 1
    }
    
    var options = $.extend(defaults, options);
    
    var quotes_json = options.json;
    var quotes;
    var index = 0;
    var timerid = -1;

    function build_dots_line()
    {
            html = "<div id='dots'>"
            var i;
            for (i = 0; i < quotes.length; i++)
            {
                html += '<span class="dot'
                if (i == index)
                    html += " active"
                html += '"'
                html += 'index="' + i + '"'
                html += '></span>'
            }
            html += "</div>"
            return html
    }

    function activate_quote(which)
    {
	if (which < 0 || which >= quotes.length)
	  return; // safety net
	  //alert(quotes[which].author);
	  
            container.find("#quote_author").html(quotes[which].author);
            container.find("#quote_text").html(quotes[which].quote);
            container.find(".active").removeClass("active");

            var sel = '.dot[index="' + which + '"]';
            container.find(sel).addClass("active");

    }

    function changeQuoteTo(new_index)
    {
            clearTimer(); // so that timer doesn't bump in during some fade op.

			container.children('#quote_content').fadeOut('fast', function() {
				activate_quote(new_index);
				index = new_index;
				container.children('#quote_content').fadeIn('fast', 'linear');
			});

    }


    function clearTimer()
    {
        if (timerid)
        {
            clearTimeout(timerid);
            timerid = 0;
        }
    }


    function startTimer()
    {
        clearTimer();
        timerid = setTimeout(changeQuote, options.speed);
    }


    function changeQuote()
    {
        var nindex = index;
        if(index == quotes.length - 1){
            nindex = 0;
        } else{
            nindex++;
        }
        clearTimer();
        changeQuoteTo(nindex);
        startTimer();
    }


    $.getJSON(quotes_json, function(data) {
        quotes = [];
	quotesl = eval(data.quotes);
	for(i = 0; i < quotesl.length; ++i)
	  if (typeof(quotesl[i]) == "object") // IE -> go to h..l
	    quotes.push(quotesl[i]);

        var html = '<span id="quote_content"><span id="quote_text"></span><div id="quote_author"></div></span>';
        if (options.showdots)
            html += build_dots_line();
        container.html(html);
        if (options.showdots)
            container.find(".dot").click(function() {
                    var i = $(this).attr("index");
                    changeQuoteTo(i);
                    startTimer();
                }
            );
        activate_quote(index);
        startTimer();
  });
  return container;
}
})(jQuery);

