﻿(function($) {

  $.fn.ajaxPreloader = function(options) {
  
    var options = $.extend({}, $.fn.ajaxPreloader.defaults, options);
  
    ajaxPreloader = function(preloader, options) {
      this.preloader = preloader;
      this.options = options;
      this.init();
    };
    
    ajaxPreloader.prototype = {
    
      init : function() {
        if (this.preloader) {
          $(this.preloader).hide();
        }      
        if (Sys && Sys.WebForms) {
          Sys.WebForms.PageRequestManager.getInstance().add_beginRequest(Function.createDelegate(this, this.show));
          Sys.WebForms.PageRequestManager.getInstance().add_endRequest(Function.createDelegate(this, this.hide));
        }
        $(this.preloader).ajaxStart(Function.createDelegate(this, this.show));
        $(this.preloader).ajaxStop(Function.createDelegate(this, this.hide));
        $(this.preloader).ajaxError(Function.createDelegate(this, this.hide));
      },
    
      show : function() {
        if (this.preloader) {
          $(this.preloader).show();
          $(this.preloader).removeClass(this.options.inactiveCssClass);
          $(this.preloader).addClass(this.options.activeCssClass);
          
          if (this.options.blockUI && $.blockUI) {
		    $.blockUI(this.options.blockUIOptions);
          }
        }
      },    
      
      hide : function() {
        if (this.preloader) {
          $(this.preloader).hide();
          $(this.preloader).removeClass(this.options.activeCssClass);
          $(this.preloader).addClass(this.options.inactiveCssClass);
          
          if (this.options.blockUI && $.blockUI) {
            $.unblockUI();
          }          
        }
      }      
    };
    
    $(this).each(function() {
      new ajaxPreloader(this, options);
    });
	};			
	
	$.fn.ajaxPreloader.defaults = {
    activeCssClass : '',
    inactiveCssClass : '',
    blockUI: false,
    blockUIOptions: { 
      message: '',
      overlayCSS:  { 
        backgroundColor: '#000',
        opacity: '0.0',
	      cursor: 'wait'
      }
    }
	};

})(jQuery);