// -----------------------------------------------------------------------------------
//
//	Flashbox v0.1
//	by Joseariel Gomez ortigoza
//
// -----------------------------------------------------------------------------------

//
//  Configuration
//
FlashboxOptions = Object.extend({
    fileLoadingImage:        '/images/lightbox/loading.gif',     
    fileBottomNavCloseImage: '/images/lightbox/closelabel.gif',

    overlayOpacity: 0.8,   // controls transparency of shadow overlay

    animate: true,         // toggles resizing animations
    resizeSpeed: 7,        // controls the speed of the image resizing animations (1=slowest and 10=fastest)

    borderSize: 10,         //if you adjust the padding in the CSS, you will need to update this variable
    
    msgWidth: 900,         //Default message width
    msgHeight: 40,         //Default message height
    
    timeout: 4.0             // timeout for hiding the msg
}, window.FlashboxOptions || {});

// -----------------------------------------------------------------------------------

var Flashbox = Class.create();

Flashbox.prototype = {
    // initialize()
    // Constructor runs on completion of the DOM loading. The function inserts html at the bottom of the page 
    // which is used to display the shadow overlay and the flash message container.
    //
    initialize: function() {    
        
      if (FlashboxOptions.resizeSpeed > 10) FlashboxOptions.resizeSpeed = 10;
      if (FlashboxOptions.resizeSpeed < 1)  FlashboxOptions.resizeSpeed = 1;

	    this.resizeDuration = FlashboxOptions.animate ? ((11 - FlashboxOptions.resizeSpeed) * 0.15) : 0;
	    this.overlayDuration = FlashboxOptions.animate ? 0.2 : 0;  // shadow fade in/out duration

      // When Flashbox starts it will resize itself from 250 by 250 to the current message dimension.
      // If animations are turned off, it will be hidden as to prevent a flicker of a
      // white 250 by 250 box.
      var size = (FlashboxOptions.animate ? FlashboxOptions.msgWidth : 1) + 'px';
      

      // Code inserts html at the bottom of the page that looks similar to this:
      //
      //  <div id="flashbox_overlay"></div>
      //  <div id="flashbox">
      //      <div id="innerFlashboxContainer">
      //          # FLASH MESSAGE #
      //      </div>
      //  </div>


      var objBody = $$('body')[0];

			objBody.appendChild(Builder.node('div',{id:'flashbox_overlay'}));
		
	    objBody.appendChild(Builder.node('div',{id:'flashbox'}, [
	        Builder.node('div',{id:'innerFlashboxContainer'})
	        
	        //Builder.node('div',{id:'flashboxBottomNav'},
	        //    Builder.node('a',{id:'flashboxBottomNavClose', href: '#' },
	        //        Builder.node('img', { src: FlashboxOptions.fileBottomNavCloseImage })
	        //    )
	        //)
	    ]));

			//console.info('size: '+size+", "+typeof(size));
			
			$('flashbox_overlay').hide().observe('click', (function() { this.end(); }).bind(this));
			$('flashbox').hide().observe('click', (function(event) { if (event.element().id == 'flashbox') this.end(); }).bind(this));
			//$('innerFlashboxContainer').setStyle({ width: size, height: size });
			$('innerFlashboxContainer').setStyle({ width: size, height: (FlashboxOptions.msgHeight+'px') });
			$('innerFlashboxContainer').observe('click', (function(event) { event.stop(); this.end(); }).bind(this));
			//$('flashboxBottomNavClose').observe('click', (function(event) { event.stop(); this.end(); }).bind(this));
	
			//console.info($('innerFlashboxContainer'));
			
      var th = this;
      (function(){
          var ids = 'flashbox_overlay flashbox innerFlashboxContainer';   
          $w(ids).each(function(id){ th[id] = $(id); });
      }).defer();
      
    },

    
    
    //
    //  start()
    //  Display overlay and flashbox.
    //
    start: function(flash_message, options) {    
				options = (options == undefined ? {} : options)
				options.timeout = (options.timeout == undefined ? FlashboxOptions.timeout : options.timeout)
				
        $$('select', 'object', 'embed').each(function(node){ node.style.visibility = 'hidden' });

        // stretch overlay to fill page and fade in
        var arrayPageSize = this.getPageSize();
        $('flashbox_overlay').setStyle({ width: arrayPageSize[0] + 'px', height: arrayPageSize[1] + 'px' });
				
				//console.info("$('flashbox_overlay'): "); console.info(this.flashbox_overlay);
				
        new Effect.Appear(this.flashbox_overlay, { duration: this.overlayDuration, from: 0.0, to: FlashboxOptions.overlayOpacity });
				
				this.innerFlashboxContainer.update(flash_message);
				
        // calculate top and left offset for the flashbox 
        var arrayPageScroll = document.viewport.getScrollOffsets();
        //var flashboxTop = arrayPageScroll[1] + (document.viewport.getHeight() / 10);
        var flashboxTop = arrayPageScroll[1];
        var flashboxLeft = arrayPageScroll[0];
        
        //console.info("arrayPageScroll: "+arrayPageScroll);
        //console.info("(document.viewport.getHeight() / 10): "+(document.viewport.getHeight() / 10));
        
        this.flashbox.setStyle({ top: flashboxTop + 'px', left: flashboxLeft + 'px' }).show();
        
        
        // ---------------------------------------------------------------------------------
        // ATTENTION: An HTML element with a defined width and height must be the wrapper 
        // around the message passed. Otherwise it will break silently.
        // ---------------------------------------------------------------------------------
        
        var msgDimensions = this.innerFlashboxContainer.down().getDimensions();
        var msgWidth  = msgDimensions.width;
        var msgHeight = msgDimensions.height;
				
				//console.info("msgWidth: "+msgWidth+", msgHeight: "+msgHeight);
        this.resizeMessageContainer(msgWidth, msgHeight);
        
        // Set a timeout to fade the message if the user doesn't click it first.
        this.flashBoxTimeout = (function() { this.end(); }).bind(this).delay(options.timeout, this);
    },

    

    //
    //  resizeMessageContainer()
    //
    resizeMessageContainer: function(msgWidth, msgHeight) {

        // get current width and height
        var widthCurrent  = this.innerFlashboxContainer.getWidth();
        var heightCurrent = this.innerFlashboxContainer.getHeight();
				
				//console.info("widthCurrent: "+widthCurrent+", heightCurrent: "+heightCurrent);
				
        // get new width and height
        //var widthNew  = (msgWidth  + FlashboxOptions.borderSize * 2);
        //var heightNew = (msgHeight + FlashboxOptions.borderSize * 2);
        var widthNew  = msgWidth;
        var heightNew = msgHeight;
				
        // scalars based on change from old to new
        //var xScale = (widthNew  / widthCurrent)  * 100;
        //var yScale = (heightNew / heightCurrent) * 100;

        // calculate size difference between new and old msg, and resize if necessary
        var wDiff = widthCurrent - widthNew;
        var hDiff = heightCurrent - heightNew;
				
        //if (hDiff != 0) new Effect.Scale(this.innerFlashboxContainer, yScale, {scaleX: false, duration: this.resizeDuration, queue: 'front'}); 
        //if (wDiff != 0) new Effect.Scale(this.innerFlashboxContainer, xScale, {scaleY: false, duration: this.resizeDuration, delay: this.resizeDuration}); 
        
				//console.info("msgWidth: "+msgWidth+", msgHeight: "+msgHeight);
				//console.info("widthNew: "+widthNew+", heightNew: "+heightNew);
        
        this.innerFlashboxContainer.hide();
        this.innerFlashboxContainer.setStyle({ width: msgWidth+'px', height: msgHeight+'px' }); 

        // if new and old msg are same size and no scaling transition is necessary, 
        // do a quick pause to prevent image flicker.
        var timeout = 0;
        if ((hDiff == 0) && (wDiff == 0)){
            timeout = 100;
            if (Prototype.Browser.IE) timeout = 250;   
        }

        (function(){
            //this.flashboxBottomNav.setStyle({ width: widthNew + 'px', height: '22px', display: 'none' });
            this.showMessage();
        }).bind(this).delay(timeout / 1000);
    },
    
    //
    //  showMessage()
    //  Display message.
    //
    showMessage: function(){
        /*new Effect.Appear(this.innerFlashboxContainer, { 
            duration: this.resizeDuration, 
            queue: 'end' 
            //afterFinish: (function(){ this.updateDetails(); }).bind(this) 
        });*/
        
        new Effect.Parallel(
          [ 
              new Effect.SlideDown(this.innerFlashboxContainer, { sync: true, duration: this.resizeDuration, from: 0.0, to: 1.0 }), 
              new Effect.Appear(this.innerFlashboxContainer, { sync: true, duration: this.resizeDuration }) 
          ], { 
            queue: 'end' 
          }
        );
    },
    
    //
    //  hideMessage()
    //  slide message up.
    //
    hideMessage: function(){
        //this.flashbox.hide();
        
        new Effect.Parallel(
          [ 
            new Effect.SlideUp(this.flashbox, { sync: true, duration: this.resizeDuration }), 
            new Effect.Fade(this.flashbox, { sync: true, duration: this.resizeDuration }) 
          ], { queue: 'end' });
    },

    //
    //  updateDetails()
    //
    updateDetails: function() {
        new Effect.Parallel(
            [ 
                new Effect.SlideDown(this.flashboxBottomNav, { sync: true, duration: this.resizeDuration, from: 0.0, to: 1.0 }), 
                new Effect.Appear(this.flashboxBottomNav, { sync: true, duration: this.resizeDuration }) 
            ], 
            { 
                duration: this.resizeDuration, 
                afterFinish: (function() {
	                // update overlay size and update nav
	                var arrayPageSize = this.getPageSize();
	                this.flashbox_overlay.setStyle({ height: arrayPageSize[1] + 'px' });
                }).bind(this)
            } 
        );
    },


    //
    //  end()
    //
    end: function() {
    		//console.info('timeout: '); console.info(this.flashBoxTimeout);
    		window.clearTimeout(this.flashBoxTimeout);
        //this.flashbox.hide(); //Moved to hideMessage();
        this.hideMessage();
        new Effect.Fade(this.flashbox_overlay, { duration: this.overlayDuration });
        $$('select', 'object', 'embed').each(function(node){ node.style.visibility = 'visible' });
    },

    //
    //  getPageSize()
    //
    getPageSize: function() {
	        
	    var xScroll, yScroll;
		
			if (window.innerHeight && window.scrollMaxY) {	
				xScroll = window.innerWidth + window.scrollMaxX;
				yScroll = window.innerHeight + window.scrollMaxY;
			} else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
				xScroll = document.body.scrollWidth;
				yScroll = document.body.scrollHeight;
			} else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
				xScroll = document.body.offsetWidth;
				yScroll = document.body.offsetHeight;
			}
			
			var windowWidth, windowHeight;
			
			if (self.innerHeight) {	// all except Explorer
				if(document.documentElement.clientWidth){
					windowWidth = document.documentElement.clientWidth; 
				} else {
					windowWidth = self.innerWidth;
				}
				windowHeight = self.innerHeight;
			} else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
				windowWidth = document.documentElement.clientWidth;
				windowHeight = document.documentElement.clientHeight;
			} else if (document.body) { // other Explorers
				windowWidth = document.body.clientWidth;
				windowHeight = document.body.clientHeight;
			}	
			
			// for small pages with total height less then height of the viewport
			if(yScroll < windowHeight){
				pageHeight = windowHeight;
			} else { 
				pageHeight = yScroll;
			}
		
			// for small pages with total width less then width of the viewport
			if(xScroll < windowWidth){	
				pageWidth = xScroll;		
			} else {
				pageWidth = windowWidth;
			}
	 
			return [pageWidth,pageHeight];
	}
}


document.observe('dom:loaded', function () { flashBox = new Flashbox(); });


