// -----------------------------------------------------------------------------------
//
//  Idé Box completely rewritten LightBox 2.0 for Idé Grafisch Ontwerp
//
// -----------------------------------------------------------------------------------
var IdeBoxInstance = null;
var IdeBox = Class.create();

IdeBox.prototype = {
    
    
    // initialize()
    // Constructor runs on completion of the DOM loading. Calls attachOnCklickObserver 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.clickedThumb = null; // Thumb image that has been clicked by the user to launch the IdeBox.
		this.postion = null; // Postion of thumb image that launched the IdeBox.
		this.dimensions = null; // Dimensions of thumb image that launched the IdeBox.
		this.bestelnummer = null; // Ordernumber of kaart. 
		this.kaartDimensions = null; // Dimensions of last loaded kaart, because swithing to a form messes it up.

	    this.fileLoadingImage = 'images/spinner.gif';
		this.actionOpacity = 0.8;
		this.overlayOpacity = 0.4;
		this.resizeDuration = 0.3;
	    this.overlayDuration = 0.2;  // shadow fade in/out duration                
		this.formulierPage = "bestellen.php";
        this.proefprintFormulierPage = "proefprint.php";
        this.mode = "hidden";
        
	    this.attachOnCklickObserver();        
        this.keyboardAction = this.keyboardAction.bindAsEventListener(this);
		                       
		this.borderKaartHorizontal = 2* 30; // 2 * paddings
		this.borderKaartVertical = 135 + (2 * 18); 
		
		this.borderFormulierHorizontal = 2 * 18; // 2 * paddings
		this.borderFormulierVertical = 2 * 18; // 2 * paddings
		
		this.IE6 = Prototype.Browser.IE && parseInt(navigator.userAgent.substring(navigator.userAgent.indexOf("MSIE")+5)) == 6;
		this.IE7 = Prototype.Browser.IE && parseInt(navigator.userAgent.substring(navigator.userAgent.indexOf("MSIE")+5)) == 7;
		this.IE8 = Prototype.Browser.IE && !this.IE6 && !this.IE7;
		
		var objBody = $$('body')[0];
		objBody.appendChild(Builder.node('div',{id:'overlay'}));
	
        objBody.appendChild(Builder.node('div',{id:'ideBox'}, 
            Builder.node('div',{id:'ideBoxMainContainer'},						 
                Builder.node('div',{id:'ideBoxContainer'}, [				
					Builder.node('div',{id:'ideBoxClose'}), 
					Builder.node('div',{id:'ideBoxContent'}, [
						Builder.node('div',{id:'loading'}, 
							Builder.node('img', {id:'loadingImg', src: this.fileLoadingImage})
						),					
						Builder.node('div',{id:'kaart'}, [
							Builder.node('div',{id:'achterVoorTitle'}), 
							Builder.node('div',{id:'achterVoor'}, 
								Builder.node('img',{id:'achterVoorImage'})
							), 
							Builder.node('div',{id:'binnenTitel'}), 
							Builder.node('div',{id:'binnen'}, 
								Builder.node('img',{id:'binnenImage'})
							), 
							Builder.node('div',{id:'bestel'},
							  	Builder.node('div',{id:'bestelContent'},[															  
			              			//Builder.node('div',{id:'proefprint'}), 
									Builder.node('div',{id:'kaartbestellen'}) 
                           		])	
							),							
							
						]),
						Builder.node('div',{id:'formulierMainContainer'},
							Builder.node('div',{id:'formulier'})
						),
					]), 
						
					Builder.node('div',{id:'ideBoxBackground'}, [
						Builder.node('div',{id:'ideBoxBackgroundTopContainer'}, Builder.node('div',{id:'ideBoxBackgroundTop'})), 
						Builder.node('div',{id:'ideBoxBackgroundBottom'}), 
						Builder.node('div',{id:'ideBoxBackgroundRight'}), 
						Builder.node('div',{id:'ideBoxBackgroundLeft'}), 
						Builder.node('div',{id:'ideBoxBackgroundLeftTop'}), 
						Builder.node('div',{id:'ideBoxBackgroundLeftBottom'}), 
						Builder.node('div',{id:'ideBoxBackgroundRightTop'}), 
						Builder.node('div',{id:'ideBoxBackgroundRightBottom'})
					]) 				
				])
			)
		));	

		$("achterVoorTitle").insert("achter- en voorzijde"); 
		$("binnenTitel").insert("binnenzijde"); 
		$("kaartbestellen").insert("<span style=\"cursor:pointer\">bestelling plaatsen</span>");
		//$("proefprint").insert("<span style=\"cursor:pointer\">proefprint aanvragen</span>"); 
		$("kaartbestellen").observe('click', (function() { this.kaartBestellen(); }).bind(this));
		//$("proefprint").observe('click', (function() { this.proefprintBestellen(); }).bind(this)); 
		$('overlay').hide().observe('click', (function() { this.hideIdBox(); }).bind(this));
		$('ideBox').hide().observe('click', (function(event) { if (event.element().id == 'ideBoxClose') this.hideIdBox(); }).bind(this));
		$('loading').hide();
		$('formulierMainContainer').hide();		
		
		var th = this;
        (function(){
            var ids = 
                'overlay ideBox ideBoxMainContainer ideBoxContainer ideBoxClose loading loadingImg ' +
                'ideBoxBackground ideBoxBackgroundTop ideBoxBackgroundBottom ideBoxBackgroundRight ideBoxBackgroundLeft ' + 				
                'ideBoxBackgroundLeftTop ideBoxBackgroundLeftBottom ideBoxBackgroundRightTop ideBoxBackgroundRightBottom ' + 				
                'ideBoxContent kaart achterVoorTitle achterVoor achterVoorImage binnenTitel binnen binnenImage bestel kaartbestellen proefprint ' +
				'formulierMainContainer formulier';   
            $w(ids).each(function(id){ th[id] = $(id); });
        }).defer();

		if (this.IE6)
		{
		    this.FixTransparentBackgroundPNG($('ideBoxClose'));
		    this.HideTransparentBackgroundPNG($('ideBoxBackgroundTop'));
		    this.HideTransparentBackgroundPNG($('ideBoxBackgroundBottom'));
		    this.HideTransparentBackgroundPNG($('ideBoxBackgroundRight'));
		    this.HideTransparentBackgroundPNG($('ideBoxBackgroundLeft'));
		    this.HideTransparentBackgroundPNG($('ideBoxBackgroundLeftTop'));
		    this.HideTransparentBackgroundPNG($('ideBoxBackgroundLeftBottom'));
		    this.HideTransparentBackgroundPNG($('ideBoxBackgroundRightTop'));
		    this.HideTransparentBackgroundPNG($('ideBoxBackgroundRightBottom'));
			
			//$('ideBoxBackgroundTop').setStyle({position: 'absolute', top: '-18px', left: '0px', width: '100%', height: '18px'});
		}
		
    },
	
	HideTransparentBackgroundPNG: function(obj) {
		obj.hide();
	},	
	
	FixTransparentBackgroundPNG: function(obj) {
		var mode = 'scale';
		var bg	= obj.getStyle('backgroundImage');
		var src = bg.substring(5,bg.length-2);
		if (obj.currentStyle.backgroundRepeat == 'no-repeat') 
		{
			mode = 'crop';
		}
		obj.style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + src + "', sizingMethod='" + mode + "')";
		obj.style.backgroundImage = 'url(../images/x.gif)';
	},
    
    //
    // attachOnCklickObserver()
    // Attach an event observer to handle mouse clicks for ideBox targets
    attachOnCklickObserver: function() {   
	
        document.observe('click', (function(event){
            var target = event.findElement('a[rel^=ideBox]') || event.findElement('area[rel^=idBox]');
            if (target) {				

                event.stop();
			    
			    this.clickedThumb = target.down();
			    this.dimensions = $(this.clickedThumb).getDimensions();
			    this.postion = $(this.clickedThumb).cumulativeOffset();
			   
			    var linkVoorAchter = (target.next()).value;
			    var linkBinnenkant = target.next(1).value;
			    this.bestelnummer = target.next(2).value;	
			    this.enableKeyboardNav();		
                this.showKaart(linkVoorAchter, linkBinnenkant);
            }
        }).bind(this));
    },

    /*************
     * Forms, next section handles showing forms in the Idé Box. The form it selfs must be the first element in the html page that is passed to loadForm 
    **************/
    
   	//proefprintBestellen: function() {
	//	this.loadForm(this.proefprintFormulierPage);
	//},
	
    kaartBestellen: function() {
    	this.loadForm(this.formulierPage);
	},

    
	loadForm: function(url) {
	
		// Start hiding image, mode is set after loading to know that we are viewing an card and are switching to the order form in order to attach a cancel handler that shows the card again.
		if (this.mode == 'image')
		{ 
			this.showLoader(this.ideBoxContent.getWidth(), this.ideBoxContent.getHeight());			
		}
		else if (this.mode == 'hidden')
		{
	       // calculate top and left offset for the IdeBox 
		    var width = 100;
			var height = 100;
			var arrayPageScroll = document.viewport.getScrollOffsets(); 
			var IdeBoxLeft = arrayPageScroll[0]  + ((document.viewport.getWidth() - width) / 2);
			var IdeBoxTop = arrayPageScroll[1] + ((document.viewport.getHeight() - height) / 2);
			this.ideBox.setStyle({ top: (IdeBoxTop - 18) + 'px', left: (IdeBoxLeft - 18) + 'px',  width : width + 'px', height: height + 'px'}).show();		 		
	 		this.showLoader(width, height);
			this.kaart.hide();
			this.enableKeyboardNav();
			this.showOverlay();	
		}
		
		this.formulierMainContainer.hide();
		this.formulier.update();	
		
		new Ajax.Request(url, {
		    evalScripts: true,
			onSuccess: (function(transport) {
			    this.formulier.update(transport.responseText);	
				this.formLoaded();
			}).bind(this)
		});	  
	},
		
	formLoaded: function() {
		
  		this.formulier.setStyle({opacity: .0001}).show();
		this.formulierMainContainer.show();
		
      	// The first element in da body must be the target for.
      	var form = this.formulier.down();
		var firstElement = form.down(); 
		
		var width = firstElement.getWidth();
		var height = firstElement.getHeight();

		this.formulier.setStyle({ top: '0px', left: '0px',  width : width + 'px', height: height + 'px'}).hide();		 

		if (this.mode == "image")
		{		
        	var cancelButton = document.getElementById("cancelButton");
			if (cancelButton)
			{				
				Event.observe(cancelButton, 'click', (function(event){ 		
					event.stop();
					this.hideContent();
					this.mode = "image";
					this.kaart.hide();
					//this.resize(this.kaart.getWidth(), this.kaart.getHeight());
					
					this.resize(this.kaartDimensions[0], this.kaartDimensions[1]);
					
					new Effect.Opacity(this.ideBoxContent, {
						duration: 0.2,
						queue: 'end',  
						from: this.actionOpacity, to: 1.0
					});
					
					new Effect.Opacity(this.kaart, {
						duration: 0.2,
						queue: 'end',  
						from: 0.0001, to: 1.0,
						afterSetup : (function(){ this.kaart.setStyle({opacity: 0.0001}).show(); }).bind(this)
					});
	
               }).bind(this));				
			}
			
			var thumb = document.getElementById("thumb");
			if (thumb)
			{
				thumb.src = this.clickedThumb.src;
			}
			
			var bestelnummer = document.getElementById("bestelcode");
			if (bestelnummer)
			{
				bestelnummer.value = this.bestelnummer;
			}

       	}
		else if (this.mode == "hidden")
		{		
        	var cancelButton = document.getElementById("cancelButton");
			if (cancelButton)
			{				
				Event.observe(cancelButton, 'click', (function(event){ 		
				   event.stop();
				   this.hideIdBox();
               }).bind(this));				
			}
       	}
		
        this.mode = "form";
		this.formulierMainContainer.hide();
		
		// Start resizing the the Idé Box
		this.resize(width, height);
		this.showContent();
    },
	
		    
    /******************
    * Images, next section handles showing images in the Idé Box
    *******************/
	
    //
    //  Show  a kaartje.
    //
    showKaart: function(imgVoorAchterLink, imgBinnenkantLink) {    
    	
		this.mode = "image";      

		this.showOverlay();	
		
		var width = this.dimensions.width + 4;
		var height = this.dimensions.height + 4;
		
		this.kaart.hide();
		this.formulierMainContainer.hide();
	    this.ideBox.setStyle({ top: (this.postion.top - 18) + 'px', left: (this.postion.left - 18) + 'px', width: width + 'px', height: height + 'px'}).show();
		this.showLoader(width, height);

		// HACK: Opera9 does not currently support scriptaculous opacity and appear fx
        this.kaart.setStyle({opacity: .0001});
		
        var imgVoorAchter = new Image();
        var imgBinnenkant = new Image();
        
        imgVoorAchter.onload = (function() {
			this.achterVoorImage.src = imgVoorAchterLink;
			if (imgBinnenkantLink)
			{
    			imgBinnenkant.src = imgBinnenkantLink;
			}
			else
			{
    			binnenImage.src = null;
		    	this.resizeKaart(imgVoorAchter.width, imgVoorAchter.height);
      			this.showContent();
			}
    	}).bind(this);
    		
        imgBinnenkant.onload = (function() {
			this.binnenImage.src = imgBinnenkantLink;
    		this.resizeKaart((imgVoorAchter.width + this.borderKaartHorizontal), (imgVoorAchter.height + imgBinnenkant.height + this.borderKaartVertical));
      		this.showContent();
		}).bind(this);    		
    		
        imgVoorAchter.src = imgVoorAchterLink;
	},
	
	resizeKaart: function(newWidth, newHeight) {
	    this.kaart.setStyle({width: (newWidth - 60) + 'px', height: (newHeight - 20) + 'px'}).hide();
		this.kaartDimensions = [newWidth, newHeight];
		this.resize(newWidth, newHeight);
	
	},

   
    /******************
    * next section handles showing and handling the Idé Box
    *******************/
 
   showOverlay: 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.overlayDuration, from: 0.0, to: this.overlayOpacity, 
		queue: 'front' });	 
   },    
       
	showLoader : function(width, height){
		this.ideBoxContent.setStyle({opacity: 0.4}); 
        //var imgTop = (height - this.loadingImg.height) / 2;
		//var imgLeft = (width - this.loadingImg.width) / 2;
        var imgTop = (height - 32) / 2;
		var imgLeft = (width - 32) / 2;
		this.loadingImg.setStyle({ marginTop: imgTop + 'px', marginLeft: imgLeft + 'px' }).show();	
		this.loading.setStyle({ width: width + 'px', height: height + 'px', opacity: 0.6 }).show();
 },
	
	hideLoader : function() {
		this.loading.hide();
	},
 
   resize: function(newWidth, newHeight) {
 
        // ideBox and ideBoxMainContainer must be shown before requesting elementthis.dimensions because requestingthis.dimensions only works if the element is visible.
		this.ideBox.show();
	    this.hideLoader();

		// get current width and height
        var currentWidth  = this.ideBox.getWidth();
        var currentHeight = this.ideBox.getHeight();

        // scalars based on change from old to new
        var xScale = (newWidth  / currentWidth)  * 100;
        var yScale = (newHeight / currentHeight) * 100;

        // calculate size difference between new and old image, and resize if necessary
        var wDiff = currentWidth - newWidth;
        var hDiff = currentHeight - newHeight;

        // calculate top and left offset for the IdeBox 
        var arrayPageScroll = document.viewport.getScrollOffsets();
        var IdeBoxLeft = arrayPageScroll[0]  + ((document.viewport.getWidth() - newWidth) / 2);
        var IdeBoxTop = arrayPageScroll[1] + ((document.viewport.getHeight() - newHeight) / 2);
    	   	
   		new Effect.Parallel(
           [ 
               new Effect.Move(this.ideBox, { sync: true, y: IdeBoxTop,  x: IdeBoxLeft, mode: 'absolute' }),
               new Effect.Scale(this.ideBox, yScale, { sync: true, scaleX: false}),
			   new Effect.Scale(this.ideBox, xScale, { sync: true, scaleY: false})
           ], 
           { 
				duration: this.resizeDuration,
				queue: 'end',
				beforeStart: (function(){ 
					this.ideBoxContent.setStyle({opacity: this.actionOpacity}); 
					this.kaart.hide();
					this.formulierMainContainer.hide();
					}).bind(this)		
		   } 
        );
    },

    hideContent: function() {				
		if ( this.mode == "image"){
			new Effect.Parallel(
				[ 
					new Effect.Opacity(this.kaart, {sync: true, from: 1.0, to: 0.0001}),
					new Effect.Opacity(this.ideBoxContent, {sync: true,  from: 1.0, to: this.actionOpacity})
				],
				{
					duration: 0.2,
					queue: 'end',
					afterSetup: (function(){ this.ideBoxContent.setStyle({opacity: this.actionOpacity}); }).bind(this), 
					afterFinish: (function(){ this.kaart.hide(); }).bind(this) 
				}
			);
		}
		else {
			new Effect.Parallel(
				[ 
					new Effect.Opacity(this.formulier, {sync: true, from: 1.0, to: 0.0001}),
					new Effect.Opacity(this.ideBoxContent, {sync: true,  from: 1.0, to: this.actionOpacity})
				],
				{
					duration: 0.2,
					queue: 'end', 
					afterSetup: (function(){ this.ideBoxContent.setStyle({opacity: this.actionOpacity}); }).bind(this), 
					afterFinish: (function(){ this.formulierMainContainer.hide(); this.formulier.hide(); }).bind(this) 
			}
			);			
		}
	},
	
	 showContent: function() {				
		if ( this.mode == "image"){
			new Effect.Parallel(
				[ 
					new Effect.Opacity(this.ideBoxContent, {sync: true,  from: this.actionOpacity, to: 1.0}),
					new Effect.Opacity(this.kaart, {sync: true, from: 0.0001, to: 1.0})
				],
				{
					duration: 0.4,
					queue: 'end', 
					afterSetup : (function(){ this.kaart.show(); }).bind(this)//,
					//afterFinish: (function(){ this.ideBoxContent.setStyle({background: ''}); }).bind(this) 
				}
			);
		}
		else { 
			new Effect.Parallel(
				[ 
					new Effect.Opacity(this.ideBoxContent, {sync: true,  from: this.actionOpacity, to: 1.0}),
					new Effect.Opacity(this.formulier,{sync: true, from: 0.0001, to: 1.0})
				],
				{
					duration: 0.3,
					queue: 'end', 
					afterSetup  : (function(){ this.formulierMainContainer.show(); this.formulier.show(); }).bind(this),
					afterFinish: (function() { Form.focusFirstElement($("ideboxformulier")) }).bind(this) 
				}
			);			
		}
	},

    //
    //  end()
    //
    hideIdBox: function() {
        this.disableKeyboardNav();
		
		var queue = Effect.Queues.get('global');
        queue.each(function(effect) { effect.cancel(); });
		
		this.hideContent();
	    this.hideLoader();
		
		new Effect.Parallel(
			[ 
				new Effect.Opacity(this.ideBoxContent, {sync: true,  from: this.actionOpacity, to: 0.4}),
				new Effect.Shrink(this.ideBox, {sync: true }),
        		new Effect.Fade(this.overlay, {sync: true })
			],
			{
				duration: 0.8, 
				queue: 'end'
			}
		);
		
        $$('select', 'object', 'embed').each(function(node){ node.style.visibility = 'visible' });
   	    this.mode = "hidden";       
    },



    /*******************
    * General section, event handlers and other stuff.
    ********************/


    //
    //  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 IdeBox
        if (keycode == escapeKey){ // close IdeBox
            this.hideIdBox();
        } 
    },

    //
    //  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 () { IdeBoxInstance = new IdeBox(); });