/*
 * jQuery preloader
 * 
 * Copyright (c) 2008 Łukasz Świerżewski
 * Licensed under the MIT License:
 * http://www.opensource.org/licenses/mit-license.php
 *
 * @version 1.0.0
 * @author Łukasz Świerżewski
 * @mailto lukasz@zirpe.com
 */

jQuery.fn.extend({
 preloader: function(options) {
  return this.each(function() {
   new jQuery.Preloader(this, options);
  });
 }
});

jQuery.Preloader = function(self, am_options) {
 self = $(self);
 var options = am_options || {};
 var $o_preloader;
 var $o_active;
 var $h_animationInterval;
 var $h_checkInterval;

 $o_preloader = $('<div class="preloader"><div class="squares"><div class="square first"></div><div class="square"></div><div class="square"></div><div class="square"></div><div class="square"></div><div class="square"></div><div class="clear"></div></div></div>')
  .css({width: self.width() + (parseInt(self.css('marginLeft')) || 0) + (parseInt(self.css('marginRight')) || 0) + 'px', height: self.height() + (parseInt(self.css('marginTop')) || 0) + (parseInt(self.css('marginBottom')) || 0) + 'px'})
  .hide()
  .insertBefore(self);
// Error in Opera:
// var $i_squaresWidth = 0;
// $('div.squares div.square', $o_preloader).each(function() { $i_squaresWidth += parseInt($(this).css('width')) + (parseInt($(this).css('marginLeft')) || 0) + (parseInt($(this).css('marginRight')) || 0); })
// $('div.squares:first', $o_preloader).css({width: $i_squaresWidth + 'px', marginTop: Math.floor(self.height()/2) + 'px'});
 $('div.squares:first', $o_preloader).css({paddingTop: Math.floor(self.height()/2) + 'px'});
 self.css({visibility: 'visible'}).hide();
 $o_preloader.show();

 init();

 function init() {
  if (!options.animationSpeed) options.animationSpeed = 300;
  if (!options.checkSpeed) options.checkSpeed = $('div.squares div.square', $o_preloader).length * options.animationSpeed * 2;
  if (options.condition === null) options.condition = true;
  if (options.callback === null) options.callback = function() {};
  $('div.squares div.square', $o_preloader).removeClass('active');
  $o_active = $('div.squares div.square:first', $o_preloader).addClass('active');
  $h_animationInterval = setInterval(loading, options.animationSpeed);
  $h_checkInterval = setInterval(check, options.checkSpeed);
 }

 function loading() {
  var $o_current = $o_active.removeClass('active');
  $o_active = $o_current.next('div.square');
  if ($o_active.length == 0) $o_active = $('div.squares div.square:first', $o_preloader);
  $o_active.addClass('active');
 }

 function check() {
  if ((options.condition).call() === true) finish();
 }

 function finish() {
  clearInterval($h_checkInterval);
  clearInterval($h_animationInterval);
  $o_preloader.hide();
  self.show();
  (options.callback).call();
 }
}
