// JavaScript Document
(function($){
  $.fn.quotator = function(options){
    var container = this;
    var defaults = 
    {
      speed : 2000,
      json : "quotator_quotes.js"
    }
    
    var options = $.extend(defaults, options);
    
    var quotes_json = options.json;
    var quotes;
    
    $.getJSON(quotes_json, function(data){
    var quotesobject = eval(data.quotes);
	var testding = "";
    var index = Math.floor(Math.random()*quotesobject.length);
    
    
    setInterval(changeQuote, options.speed);
    
	testding = quotesobject[index].quote.substr(0, 165);
	last_char = testding.charAt(testding.length-1);
	for (i=0;i<quotesobject.length;i++)
	{
		quotesobject[i].active=1;
	}
	  while (last_char != " " && (testding.length-1) > 100)
	  {
	  testding = testding.substr(0,testding.length-2);
	  last_char = testding.charAt(testding.length-1);
	  }
	  if (last_char == " ")
	  {
		testding = testding.substr(0,testding.length-1);
	  }
    container.html("<strong>&ldquo;</strong>" + testding + "...<strong>&rdquo;</strong><br /><a href='testimonials.php?id=" + quotesobject[index].id + "'>Lees verder...</a><br /><div id='author'><a href='" + quotesobject[index].website + "' target='_blank' >" + quotesobject[index].author + "</a><br /><a href='" + quotesobject[index].website + "' target='_blank'>" + quotesobject[index].bedrijf + "</a></div>");
	quotesobject[index].active = 0;
    
    function changeQuote(){
	  testding = quotesobject[index].quote.substr(0, 165);
	  last_char = testding.charAt(testding.length-1);
      container.fadeOut(function(){
		  testding = quotesobject[index].quote.substr(0, 165);
		  last_char = testding.charAt(testding.length-1);
		  	  while (last_char != " " && (testding.length-1) > 100)
			  {
				testding = testding.substr(0,testding.length-2);
				last_char = testding.charAt(testding.length-1);
			  }
			  if (last_char == " ")
			  {
				testding = testding.substr(0,testding.length-1);
			  }
    container.html("<strong>&ldquo;</strong>" + testding + "...<strong>&rdquo;</strong><br /><a href='testimonials.php?id=" + quotesobject[index].id + "'>Lees verder...</a><br /><div id='author'><a href='" + quotesobject[index].website + "' target='_blank' >" + quotesobject[index].author + "</a><br /><a href='" + quotesobject[index].website + "' target='_blank'>" + quotesobject[index].bedrijf + "</a></div>").fadeIn();
	quotesobject[index].active = 0;
      });
      
        pre_index = Math.floor(Math.random()*quotesobject.length);
		while (quotesobject[pre_index].active != 1)
		{
			pre_index = Math.floor(Math.random()*quotesobject.length);
		}
		index = pre_index;
		
		a=0;
		for (i=0;i<quotesobject.length;i++)
		{
			if (quotesobject[i].active == 0)
			{
				a+=1;
			}
			if (a >= quotesobject.length-1)
			{
				for (o=0;o<quotesobject.length;o++)
				{
					quotesobject[o].active=1;
				}				
			}
		}
		
    }
      
  });
  return container;
}
})(jQuery);