
//
//  Configurationl
//
FormOverlayOptions = Object.extend({
    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
}, window.FormOverlayOptions || {});

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

var FormOverlay = Class.create();

FormOverlay.prototype = {
    imageArray: [],
    activeImage: undefined,
    
    // 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 (FormOverlayOptions.resizeSpeed > 10) FormOverlayOptions.resizeSpeed = 10;
        if (FormOverlayOptions.resizeSpeed < 1)  FormOverlayOptions.resizeSpeed = 1;

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

        // When FormOverlay 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 = (FormOverlayOptions.animate ? 250 : 1) + 'px';
        

        // Code inserts html at the bottom of the page that looks similar to this:
        //
        //  <div id="overlay"></div>
        //  <div id="formoverlay">
        //      <div id="outerImageContainer">
        //          <div id="imageContainer">
        //              <img id="formoverlayImage">
        //              <div style="" id="hoverNav">
        //                  <a href="#" id="prevLink"></a>
        //                  <a href="#" id="nextLink"></a>
        //              </div>
        //              <div id="loading">
        //                  <a href="#" id="loadingLink">
        //                      <img src="images/loading.gif">
        //                  </a>
        //              </div>
        //          </div>
        //      </div>
        //      <div id="imageDataContainer">
        //          <div id="imageData">
        //              <div id="imageDetails">
        //                  <span id="caption"></span>
        //                  <span id="numberDisplay"></span>
        //              </div>
        //              <div id="bottomNav">
        //                  <a href="#" id="bottomNavClose">
        //                      <img src="images/close.gif">
        //                  </a>
        //              </div>
        //          </div>
        //      </div>
        //  </div>


		var content = $('formoverlay-content');
		if (!content)
		{
			return;
		}

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

		objBody.appendChild(Builder.node('div',{id:'overlay'}));
	
        objBody.appendChild(Builder.node('div',{id:'formoverlay'}, [
            Builder.node('div',{id:'outerContainer'}, [
				Builder.node('div',{className: 'top'}, Builder.node('a',{id:'formOverlayClose', href: '#' }, 'Close X')),
				Builder.node('div',{className: 'middle'}, Builder.node('div',{id:'contentContainer'}, [content]) ),
				Builder.node('div',{className: 'bottom'})
				]
            )
        ]));


		$('overlay').hide().observe('click', (function() { this.end(); }).bind(this));
		$('formoverlay').hide().observe('click', (function(event) { if (event.element().id == 'formoverlay') this.end(); }).bind(this));
		$('outerContainer').setStyle({ width: '524px', height: '530px' });
		$('formOverlayClose').observe('click', (function(event) { event.stop(); this.end(); }).bind(this));
		content.style.display = 'block';

        var th = this;
        (function(){
            var ids = 
                'overlay formoverlay outerContainer contentContainer ' + 
                'formOverlayClose';   
            $w(ids).each(function(id){ th[id] = $(id); });
			if (window.location.href.indexOf('sendmail') > -1) 
			{
				$('freepitch-introtext').style.display = 'none';
		   		th.start(); 
			}
        }).defer();

    },

    //
    //  start()
    //  Display overlay and formoverlay. If image is part of a set, add siblings to imageArray.
    //
    start: function(imageLink) {    

        $$('select', 'object', 'embed').each(function(node){ node.style.visibility = 'hidden' });

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

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

        this.imageArray = [];
        var imageNum = 0;       

        // calculate top and left offset for the formoverlay 
        var arrayPageScroll = document.viewport.getScrollOffsets();
        var formoverlayTop = arrayPageScroll[1] + (document.viewport.getHeight() / 10);
        var formoverlayLeft = arrayPageScroll[0];
        this.formoverlay.setStyle({ top: formoverlayTop + 'px', left: formoverlayLeft + 'px' }).show();
		this.formoverlay.setOpacity(0.0);
		this.formoverlay.style.visibility = 'visible';
        new Effect.Appear(this.formoverlay, { duration: 1, from: 0.0, to: 1.0 });
    },

    //
    //  resizeImageContainer()
    //
    resizeImageContainer: function(imgWidth, imgHeight) {

        // get current width and height
        var widthCurrent  = this.outerImageContainer.getWidth();
        var heightCurrent = this.outerImageContainer.getHeight();

        // get new width and height
        var widthNew  = (imgWidth  + FormOverlayOptions.borderSize * 2);
        var heightNew = (imgHeight + FormOverlayOptions.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.outerImageContainer, yScale, {scaleX: false, duration: this.resizeDuration, queue: 'front'}); 
        //if (wDiff != 0) new Effect.Scale(this.outerImageContainer, 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;   
        }

        (function(){
            this.imageDataContainer.setStyle({ width: widthNew + 'px' });

        }).bind(this).delay(timeout / 1000);
    },
    
    //
    //  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 formoverlay
            this.end();
        } 
    },

    //
    //  end()
    //
    end: function() {
        this.disableKeyboardNav();
        this.formoverlay.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 () { window.formOverlay = new FormOverlay(); });

