/*
Title: Protoloading
  
About: Author
Rodrigo César Lima Pádua <rodrigoclp@tecnoplace.com.br>
Tecnoplace - Goiânia - Brazil
  
About: Version
0.2
  
About: License
This file is licensed under the MIT license.
  
About: Required Libraries
Prototype JavaScript Framework 1.6.0.2 <http://prototypejs.org/download>
Script.aculo.us Effects.js 1.8.0 <http://script.aculo.us/downloads>
*/

var Protoloading = Class.create();
Protoloading.prototype = {

    initialize: function(options)
    {    
        this.options = {
          opacity: 0.8
        };
        
        Object.extend(this.options, options || { });         
        this.insert();
    },
    
    
    insert: function() 
    {    
        if (!parent.$('protoloading')) {
	        var elLoading = new parent.Element('div', { 'id': 'protoloading', 'class': 'protoloading' });
	
	        elLoading.setStyle({
	            float: 'left',
	            position: 'absolute',
	            top: '0',
	            left: '0',
	            zIndex: '10000'
	        });
	        
	        // define element opacity and hide main element
	        elLoading.setOpacity(this.options.opacity);
	        elLoading.hide();
                      
            var bodyTag = parent.document.getElementsByTagName('body')[0];
            bodyTag.appendChild(elLoading);                    
	    } 
    },
    
    
    show: function()
    {      
        // Get scroll offset
        var topScroll = parent.document.viewport.getScrollOffsets().top;
        parent.$('protoloading').setStyle({ top: topScroll + 'px' });
        
        parent.Effect.BlindDown('protoloading', {duration: 0.4}); // Show loading
    },
    
    
    hide: function()
    {   
        parent.Effect.BlindUp('protoloading', {duration: 0.4}); // Hide loading
    }
};


/*
Observer for automatic ajax loading display
 */
document.observe('dom:loaded', function() 
{
    var ajaxLoading = new Protoloading(); 
    
	Ajax.Responders.register(
	{    
	    onCreate: function() {
	        if (Ajax.activeRequestCount<=1) {
	            ajaxLoading.show();                 
	        }   
	        Ajax.activeRequestCount++;   
	    },
	    
	    onComplete: function() {
	        Ajax.activeRequestCount--;
	        
	        if (Ajax.activeRequestCount==0) {
	            ajaxLoading.hide();      
	        }
	    } 
	});
});
