/**
 * IBox - Derivato da Lightbox
 * 
 * alfredo.cerutti@intercom.it
 * 
 * USAGE
 * 	
 *	document.observe('dom:loaded', function () { 
 *		new IBox({
 *			width: 800,
 *			height: 480,
 *			zindex: 95,
 * 			preload: 'div[rel]' // <div id="xxxx" rel="/path/to/remote">
 * 			currentItem : 'div.current_ibox_item' // with preload detect the current item
 *		}); 
 *	});
 *
 * render :update do |page|  
 *    page.replace_html 'ibox_data', :partial => 'product_detail', :locals =>{:product =>@product }
 *    page.call "$('ibox').fire", 'ibox:load'
 * end
 *  
 * oppure $('ibox').fire('ibox:load');
 *  
 */

IBoxOptions = Object.extend({
	fileLoadingImage:        '/images/ibox/loading.gif',
    fileBottomNavCloseImage: '/images/ibox/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
    showPrevNext: true			// show prev/next buttons and allow to remote call content
}, window.IBoxOptions || {});


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

var IBox = Class.create();

IBox.prototype = {
    initialize: function(conf) {    
		
        this.keyboardAction = this.keyboardAction.bindAsEventListener(this);

        if (IBoxOptions.resizeSpeed > 10) IBoxOptions.resizeSpeed = 10;
        if (IBoxOptions.resizeSpeed < 1)  IBoxOptions.resizeSpeed = 1;

	    this.resizeDuration = IBoxOptions.animate ? ((11 - IBoxOptions.resizeSpeed) * 0.15) : 0;
	    this.overlayDuration = IBoxOptions.animate ? 0.2 : 0;  // shadow fade in/out duration       
		
        var size = (IBoxOptions.animate ? 250 : 1) + 'px';
        var objBody = $$('body')[0];

		objBody.appendChild(Builder.node('div',{id:'overlay_ibox'}));
	
        objBody.appendChild(
			Builder.node('div',{id:'ibox'}, 	
				Builder.node('div',{id:'outer_ibox'},
					[
						Builder.node('div',{id:'ibox_loading'}, 
		              		Builder.node('a',{id:'ibox_loadingLink', href: '#' }, 
		                    	Builder.node('img', {src: IBoxOptions.fileLoadingImage}) 
		                	)
		            	),											
						
						Builder.node('div',{id:'close_ibox'},
							Builder.node('a',{id:'ibox_bottomNavClose', href: '#' },
	                            Builder.node('img', { src: IBoxOptions.fileBottomNavCloseImage, border:'0' })
	                        )						
						),
						
						Builder.node('div',{id:'ibox_hoverNav'}, [
	                        Builder.node('a',{id:'ibox_prevLink', href: '#' }),
	                        Builder.node('a',{id:'ibox_nextLink', href: '#' })
	                    ]),
								
						Builder.node('div',{id:'ibox_data'})
						
					]
				)
			)
		);


		/*
		 * configurations
		 */
		//this.showPrevNext = IBoxOptions.showPrevNext; // show/hide prev/next buttons?		
		
		if (typeof conf == 'undefined')  conf = {};
		this.width = conf.width || 250;
		this.height = conf.height || 250;
		this.zindex = conf.zindex || 100;
		this.preload= conf.preload || null;
		this.currentItem = conf.currentItem || null;
		this.updateTemp = conf.updateTemp || 'temp_ibox';			
		this.top = conf.top || null; // se settato evita l'autocentramento anche dell'asse y
		$('ibox').setStyle({zIndex: this.zindex});


		if (conf.showPrevNext) { // CRAP - fix me
			this.showPrevNext = conf.showPrevNext; 
		} else {
			this.showPrevNext = false;
		}
		
		/*
		 * collect a specific tag
		 */
		if (this.preload) {
			//console.log ($$(this.preload));
			this.ibox_collections = $$(this.preload).
                collect(function(div){ 
					return div.attributes.rel.nodeValue; 
				}).uniq();
            //console.log(this.ibox_collections);
		}
		
		
		$('overlay_ibox').hide().observe('click', (function() { this.end(); }).bind(this));
		$('ibox').hide().observe('click', (function(event) { if (event.element().id == 'lightbox') this.end(); }).bind(this));
		$('outer_ibox').setStyle({ width: size, height: size });		
		$('ibox_bottomNavClose').observe('click', (function(){ this.end(); }).bind(this) );
		
		if (this.showPrevNext) {
			$('ibox_prevLink').observe('click', (function(event){ event.stop(); this.changeItem(this.activeItem - 1); }).bindAsEventListener(this));
			$('ibox_nextLink').observe('click', (function(event){ event.stop(); this.changeItem(this.activeItem + 1); }).bindAsEventListener(this));
		} else {
			$('ibox_prevLink').hide();
			$('ibox_nextLink').hide(); 
		}
		
		document.observe('ibox:load', (function(json){			
			this.start();			 
		}).bind(this) );	

		document.observe('ibox:changeitem', (function(data){
			var item = 0;
			for(var ic= 0; ic < this.ibox_collections.length; ic++) {
				if (this.ibox_collections[ic] == data.memo.openItem) {
					item = ic;
					break;
				}				
			}
			if (this.activeItem != item) this.changeItem(item); 						 
		}).bind(this) );			

		this.overlay_ibox = $('overlay_ibox');
		this.ibox = $('ibox');
		this.outer_ibox = $('outer_ibox');		
    },
 
    changeItem: function(item) {   
		if (item > this.ibox_collections.length-1) item = 0;
		if (item < 0) item = this.ibox_collections.length-1;
		
        this.activeIitem = item; // update global var

        // hide elements during transition
		$('ibox_data').hide({duration:0.5});
		$('ibox_loading').show({duration:0.5});		
		
        new Ajax.Updater(this.updateTemp, 
						this.ibox_collections[item], 
						{	
							asynchronous:true, 
							evalScripts:true
							,onComplete:function() {
								$('ibox_data').show({duration:0.5});
								this._getCurrentItem();
							}							
						});				
									
    },
    
	
	
    //
    //  start()
    //  
    //
    start: function() {
		$$('select', 'object', 'embed').each(function(node){ node.style.visibility = 'hidden' });

        // stretch overlay to fill page and fade in
        var arrayPageSize = this.getPageSize();
        $('overlay_ibox').setStyle({ width: arrayPageSize[0] + 'px', height: arrayPageSize[1] + 'px' });

        new Effect.Appear(this.overlay_ibox, { duration: this.overlayDuration, from: 0.0, to: IBoxOptions.overlayOpacity });

        // calculate top and left offset for the lightbox 
        var arrayPageScroll = document.viewport.getScrollOffsets();
		if (this.top) { // avoid full autocenter
			var IBoxTop = this.top;
		} else {
			var IBoxTop = arrayPageScroll[1] + (document.viewport.getHeight() / 10);
		}  		        
        var IBoxLeft = arrayPageScroll[0];
        this.ibox.setStyle({ top: IBoxTop + 'px', left: IBoxLeft + 'px' }).show();
		
		this.resizeContainer(this.width, this.height);
		$('ibox_loading').hide({duration:0.5});		
				
		this._getCurrentItem();
    },

	_getCurrentItem : function(){
		// select current item
		var currentItem = 0;
		var ci = $(this.currentItem).attributes.rel.nodeValue;
		//console.log('_getCurrentItem', $(this.currentItem));
		
		while ( (this.ibox_collections[currentItem] != ci) 
				&& (currentItem <= this.ibox_collections.length) ) { 
					currentItem++; 
				}
		this.activeItem= currentItem;
		//console.log('activeItem', this.activeItem);		
	},
    
    //
    //  resizeContainer
    //
    resizeContainer: function(imgWidth, imgHeight) {
        // get current width and height
        var widthCurrent  = this.outer_ibox.getWidth();
        var heightCurrent = this.outer_ibox.getHeight();

        // get new width and height
        var widthNew  = (imgWidth  + IBoxOptions.borderSize * 2);
        var heightNew = (imgHeight + IBoxOptions.borderSize * 2);

        // 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 image, and resize if necessary
        var wDiff = widthCurrent - widthNew;
        var hDiff = heightCurrent - heightNew;

        if (hDiff != 0) new Effect.Scale(this.outer_ibox, yScale, {scaleX: false, duration: this.resizeDuration, queue: 'front'}); 
        if (wDiff != 0) new Effect.Scale(this.outer_ibox, xScale, {scaleY: false, duration: this.resizeDuration, delay: this.resizeDuration}); 

        // if new and old image 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;   
        }    		
    },
    
     //
    //  enableKeyboardNav()
    //
    enableKeyboardNav: function() {
        document.observe('keydown', this.keyboardAction); 
    },

    //
    //  disableKeyboardNav()
    //
    disableKeyboardNav: function() {
        document.stopObserving('keydown', this.keyboardAction); 
    },
 
 
    //
    //  keyboardAction()
    //
    keyboardAction: function(event) {
        var keycode = event.keyCode;

        var escapeKey;
        if (event.DOM_VK_ESCAPE) {  // mozilla
            escapeKey = event.DOM_VK_ESCAPE;
        } else { // ie
            escapeKey = 27;
        }

        var key = String.fromCharCode(keycode).toLowerCase();
        
        if (key.match(/x|o|c/) || (keycode == escapeKey)){ // close lightbox
            this.end();
        }
    },

  
    //
    //  end()
    //
    end: function() {
        this.disableKeyboardNav();
        this.ibox.hide();
        new Effect.Fade(this.overlay_ibox, { duration: this.overlayDuration });
        $$('select', 'object', 'embed').each(function(node){ node.style.visibility = 'visible' });
		window.location = '#';
    },

    //
    //  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];
	}
}