// -----------------------------------------------------------------------------------
//
//	Modal v2.04
//	by Lokesh Dhakar - http://www.lokeshdhakar.com
//	Last Modification: 2/9/08
//
//	For more information, visit:
//	http://lokeshdhakar.com/projects/modal2/
//
//	Licensed under the Creative Commons Attribution 2.5 License - http://creativecommons.org/licenses/by/2.5/
//  	- Free for use in both personal and commercial projects
//		- Attribution requires leaving author name, author link, and the license info intact.
//	
//  Thanks: Scott Upton(uptonic.com), Peter-Paul Koch(quirksmode.com), and Thomas Fuchs(mir.aculo.us) for ideas, libs, and snippets.
//  		Artemy Tregubenko (arty.name) for cleanup and help in updating to latest ver of proto-aculous.
//
// -----------------------------------------------------------------------------------
/*

    Table of Contents
    -----------------
    Configuration

    Modal Class Declaration
    - initialize()
    - updateImageList()
    - start()
    - changeImage()
    - resizeImageContainer()
    - showImage()
    - updateDetails()
    - updateNav()
    - enableKeyboardNav()
    - disableKeyboardNav()
    - keyboardAction()
    - preloadNeighborImages()
    - end()
    
    Function Calls
    - document.observe()
   
*/
// -----------------------------------------------------------------------------------

var Modal = Class.create();

Modal.prototype = {
    fileLoadingImage:        'images/loading.gif',     
    fileBottomNavCloseImage: 'images/closelabel.gif',

    overlayOpacity: 0.8,   // controls transparency of shadow overlay
	overlaySpeed:.5,

    animate: true,         // toggles resizing animations
    resizeSpeed: 7,        // controls the speed of the image resizing animations (1=slowest and 10=fastest)
	resizeDuration:0,
	
	image:null,

    borderSize: 10,         //if you adjust the padding in the CSS, you will need to update this variable
	defaultWidth: 32,
	defaultHeight: 32,
	overlay:"",
	modal:"",
	loading:"",
	preloadImage:"",
	content:"",
	// initialize()
    // Constructor runs on completion of the DOM loading. Calls updateImageList and then
    // the function inserts html at the bottom of the page which is used to display the shadow 
    // overlay and the image container.
    //
    initialize: function() {   
        
        this.keyboardAction = this.keyboardAction.bindAsEventListener(this);

        if (this.resizeSpeed > 10) this.resizeSpeed = 10;
        if (this.resizeSpeed < 1)  this.resizeSpeed = 1;

	    Modal.prototype.resizeDuration = this.animate ? ((11 - this.resizeSpeed) * 0.15) : 0;
	    Modal.prototype.overlayDuration = this.animate ? 0.2 : 0;  // shadow fade in/out duration

        // When Modal starts it will resize itself from 250 by 250 to the current image dimension.
        // If animations are turned off, it will be hidden as to prevent a flicker of a
        // white 250 by 250 box.
        var size = (this.animate ? 250 : 1) + 'px';
    	
		/* Add Overlay and Content divs */
		var _overlay = document.createElement("div");
			_overlay.id = "overlay";
		document.body.appendChild(_overlay);
		var _modal = document.createElement("div");
			_modal.id = "modal";
				var _modalContent = document.createElement("div");
					_modalContent.id = "modal_content";
				_modal.appendChild(_modalContent);
				var _loading = document.createElement("div");
					_loading.id = "loading";
					var _loadingImage = document.createElement("img");
						_loadingImage.src = this.fileLoadingImage;
					_loading.appendChild(_loadingImage);
					var _preloadImage = document.createElement("img");
						_preloadImage.id = "preload_image";
					_loading.appendChild(_preloadImage);
				_modal.appendChild(_loading);
		document.body.appendChild(_modal);
		
		Modal.prototype.overlay = $(_overlay);
		Modal.prototype.modal = $(_modal);
		Modal.prototype.loading = $(_loading);
		Modal.prototype.preloadImage = $(_preloadImage).hide();
		Modal.prototype.content = $(_modalContent);
		
		this.overlay.hide().observe('click', (function() { this.end(); }).bind(this));
		this.modal.hide().observe('click', (function() { this.end(); }).bind(this));
		this.loading.hide().observe('click', (function() { this.end(); }).bind(this));
		this.content.hide().observe('click', (function() { this.end(); }).bind(this));
    },

    start: function() {
        $$('select', 'object', 'embed').each(function(node){ node.style.visibility = 'hidden' });

        // stretch overlay to fill page and fade in
        var arrayPageSize = this.getPageSize();
        this.overlay.setStyle({ width: arrayPageSize[0] + 'px', height: arrayPageSize[1] + 'px' });

        new Effect.Appear(this.overlay, { duration: this.overlaySpeed, from: 0.0, to: this.overlayOpacity });

        // calculate top and left offset for the modal 
        var arrayPageScroll = document.viewport.getScrollOffsets();
        var modalTop = (document.viewport.getHeight() /2) - (this.defaultHeight /2);
        var modalLeft = (document.viewport.getWidth() /2) - (this.defaultWidth /2);
        this.modal.setStyle({ top: modalTop + 'px', left: modalLeft + 'px', width: this.defaultWidth + 'px', height: this.defaultHeight + 'px' }).show();
		this.content.hide();
		this.loading.show();
		var img = this.content.select("img");
		if(img.count > 1) {
			this.end();
		} else {
			if(img == null) {
				this.resize(-1,-1)
				this.image = null;
			} else {
				this.image = img[0];
				this.loadImage();
			}
		}
    },
	
	loadImage: function(){
      var imgPreloader = new Image();
		imgPreloader.onload = (function(){
            this.preloadImage.src = this.image.src;
            this.resize(imgPreloader.width, imgPreloader.height);
        }).bind(this);
        imgPreloader.src = this.image.src;
	},
    
	resize: function(widthNew, heightNew) {
		this.loading.hide();
        // get current width and height
        var widthCurrent  = this.modal.getWidth();
        var heightCurrent = this.modal.getHeight();
		
		var wDiff = 0;
		var hDiff = 0;
		if(widthNew >= 0) {
        // calculate size difference between new and old image, and resize if necessary
	        wDiff = widthCurrent - widthNew;
		}
		if(heightNew >= 0) {
	        hDiff = heightCurrent - heightNew;
		}

        // scalars based on change from old to new
        var xScale = (widthNew  / widthCurrent)  * 100;
        var yScale = (heightNew / heightCurrent) * 100;

        if (hDiff != 0) new Effect.Scale(this.modal, yScale, {scaleX: false, duration: this.resizeDuration, queue: 'front', scaleFromCenter:true}); 
        if (wDiff != 0) new Effect.Scale(this.modal, xScale, {scaleY: false, duration: this.resizeDuration, delay: this.resizeDuration, scaleFromCenter:true}); 

        // 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;   
        }
        (function(){
            this.show();
        }).bind(this).delay(this.resizeDuration *2);
    },

	show: function() {
        new Effect.Appear(this.content, { duration: this.overlaySpeed });
	},

    //
    //  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 modal
            this.end();
        }
    },

    //
    //  end()
    //
    end: function() {
        this.disableKeyboardNav();
        this.modal.hide();
        new Effect.Fade(this.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 () { new Modal(); });