/**
* DIALOG CLASS
* TODO : Animating not yet working in IE6
*/
var Dialog = {};
Dialog.Box = Class.create();
Object.extend(Dialog.Box.prototype, {
	 moOptions : {
	 	 dimmingOpacity 		: 0.75
		,dimmingBackground 		: '#000000'
		,closeOnClickBackground	: true
		,miDialogZIndex			: 501
		,iResizeDuration		: 1 // seconds
	}
	,moDialogBox				: {}
	,moOverlay					: {}
	
  	,initialize: function(mmId,oOptions) 
  	{
  		// Fix to make dialog box appear in centre of the screen
  		// while the page is scrolled to the bottom
  		window.scroll(0,0);
  		
  		// Extend the given options with the default options
  		if(!Object.isUndefined(oOptions))
	  		Object.extend(this.moOptions,oOptions)
	  	
  		if(typeof(Effect) == 'undefined')
  			alert("Scriptaculous Effect class is required.");
  		
  		// Create the overlayer
	    this.createOverlay();
  		
  		// Check if the element is already in the viewport
		if(Object.isElement($($(mmId).parentNode)))
	    	this.moDialogBox = $(mmId);
	    else
	    	this.createDialogBox(mmId);
	    
	    this.moDialogBox.show = this.show.bind(this);
	    this.moDialogBox.hide = this.hide.bind(this);
	    
	  	//alert(this.oDialogBox.setStyle());
	   // this.oDialogBox.setSyle({display : 'none'});
	    this.miDialogBoxId = this.moDialogBox.identify();
	    
		// Position the overlayer to the absolute middle
      	this.positionOverlay();
      	
		// Position the dialog box in the middle
		this.positionDialogBox();
		
		// Set the window resize observer
		Event.observe(window,'resize', function() {
			this.positionOverlay();
			this.positionDialogBox();
		}.bind(this));
	
		// Set the default css properties of the dialog
		this.moDialogBox.style.position = 'absolute';

		if(this.moOptions.miDialogZIndex <= this.moOverlay.style.zIndex)
			return alert('zIndex of Dialog must be higher than overlay');
			
		this.moDialogBox.style.zIndex = this.moOptions.miDialogZIndex;
	}
	
	/*
	*
	*/
	,setContent : function(sContent)
	{
    //alert(sContent.style.width);
		if(!Object.isUndefined($(this.moDialogBoxContent).style.position))
		{
			this.moDialogBoxContent.style.position="absolute";
			this.moDialogBoxContent.style.visibility="hidden";
			this.moDialogBoxContent.style.display="block";
		}
		this.moDialogBoxContent.update(sContent);
		if($(this.moDialogBoxContent))
		{
			//alert("WIDTH :: " + $(this.moDialogBoxContent).getWidth())
			//alert("HEIGHT :: " + $(this.moDialogBoxContent).getHeight())
		}
	}
	
	/*
	*
	*/
	,updateContent : function(mContent,oOptions)
	{
		this.setContent(mContent);
		var o_dims = this.getContentDimensions(mContent);	
		Object.extend(oOptions,{o_dims : o_dims});
		this.resizeDialogBox(mContent,oOptions);
		this.positionDialogBox();
	}
	
	,getContentDimensions : function(mContent)
	{
		var o_dims = {
			 width  : $(this.moDialogBoxContent).getWidth()
			,height : $(this.moDialogBoxContent).getHeight()
		}
		
		return o_dims;
	
	}
	
	/*
	*
	*/
	,createDialogBox : function(mContent)
	{
		//var o_dimensions = this.getContentDimensions(mContent);
		this.moDialogBox = new Element('div',{'class' : 'dialog_box'});
		this.moDialogBoxContent = new Element('div',{'class' : 'dialog_box_content', 'id' : 'dialog_box_content'});
		this.moDialogBox.insert(this.moDialogBoxContent);
		this.moveDialogBox('in');
		this.setContent(mContent);
		this.resizeDialogBox(mContent);
		
		
		//alert(this.moDialogBox.id);
	}

	
	
	,resizeDialogBox : function(mContent,oOptions)
	{
		if(!Object.isUndefined(oOptions) && !Object.isUndefined(oOptions.o_dims))
			var o_dims = oOptions.o_dims;
		else
			var o_dims = this.getContentDimensions(mContent);
			
		if(!Object.isUndefined(oOptions) &&  oOptions.b_animate == true)
		{
			// get current width and height
	        var i_width_current  = this.moDialogBox.getWidth();
	        var i_height_current = this.moDialogBox.getHeight();
	
	        // get new width and height
	        var i_width_new  = o_dims.width;
	        var i_height_new = o_dims.height;
	
	        // scalars based on change from old to new
	        var x_scale = (i_width_new  / i_width_current)  * 100;
	        var y_scale = (i_height_new / i_height_current) * 100;

	        // calculate size difference between new and old image, and resize if necessary
	        var i_wdiff = i_width_current - i_width_new;
	        var i_hdiff = i_height_current - i_height_new;
	        
	       // alert(i_height_current);
	       	//alert(i_height_new);
	        
	        if (i_hdiff != 0) new Effect.Scale(this.moDialogBox, y_scale, {
				 scaleFromCenter : true
				,scaleX: false
				,duration: this.moOptions.iResizeDuration
				,scaleContent : false
				,afterFinish: function() {
					//alert(i_wdiff);
					if(i_wdiff == 0) this.moDialogBoxContent.style.visibility = 'visible';
				}.bind(this) 
				,queue: 'front'}); 
	        if (i_wdiff != 0) new Effect.Scale(this.moDialogBox, x_scale, {
	        	 scaleFromCenter : true
	        	,scaleY: false
	        	,duration: this.moOptions.iResizeDuration
	        	,scaleContent : false
	        	,afterFinish: function() {
					this.moDialogBoxContent.style.visibility = 'visible';
				}.bind(this)
	        	,delay: this.moOptions.iResizeDuration}); 
	
	        // if new and old image are same size and no scaling transition is necessary, 
	        // do a quick pause to prevent image flicker.
	        var i_timeout = 0;
	        if ((i_hdiff == 0) && (i_wdiff == 0)){
	            i_timeout = 100;
	            if (Prototype.Browser.IE) i_timeout = 250;   
	        }
	    }
		else
		{
			// set width and height
			this.moDialogBox.style.width = o_dims.width + 'px';
			this.moDialogBox.style.height = o_dims.height + 'px';
			this.moDialogBoxContent.style.visibility = 'visible';
		}
		
		
		
		this.moDialogBoxContent.show();
		
	}
	
	,createOverlay: function() 
	{
		if($('dialog_overlay')) 
	    	this.moOverlay = $('dialog_overlay');
	    else 
	    {
	    	this.moOverlay = new Element('div',{id : 'dialog_overlay'});
	   		Object.extend(this.moOverlay.style, {
	      		 position	: 'absolute'
	      		,zIndex		: 500
	      		,display	: 'none'
	      		,background : this.moOptions.dimmingBackground
	      		,top 		: '0px'
	      		,left 		: '0px'
	      	});
	      	// Insert the overlayer at the end of the body
	      	document.body.appendChild(this.moOverlay);
	    }
	}

	,positionOverlay : function()
	{
		this.moPage = this.getPageSize();
		this.moDialogBox.moDimensions = this.moDialogBox.getDimensions();
		//alert('width' + this.moDialogBox.getStyle('width'));
		
		var i_alternative_height = (Prototype.Browser.IE && this.moDialogBox && this.moOverlay) 
				? parseInt(this.moOverlay.style.top) + this.moPage.height
				: 0; 
		
		var i_new_height = Math.max(this.moPage.pageHeight,this.moDialogBox.moDimensions.height);
		
		i_new_height = Math.max(i_new_height,i_alternative_height);
		
		// TODO : USE SETSTYLE HERE
		this.moOverlay.style.width  = '100%';

		this.moOverlay.style.height = Math.max(this.moPage.pageHeight,i_new_height) + 'px';
	}

	,positionDialogBox : function()
	{
		
		//alert(this.moDialogBox.moDimensions.height);
		// TODO : CHeck if this is necessary
	    var e_dims = Element.getDimensions(this.moDialogBox);
	   	var b_dims = Element.getDimensions(this.moOverlay);
	   
		this.moDialogBox.style.left = ((b_dims.width/2) - (e_dims.width/2)) + 'px';
		this.moDialogBox.style.top = Math.max((this.moPage.height - e_dims.height) / 2,0) + 'px';
		
	}

  	,moveDialogBox: function(where) 
  	{
		
    	//Element.remove(this.moDialogBox);
    	//alert(this.moDialogBox.id);
  		if(where == 'back')
      		this.moDialogBox = this.moParentElement.appendChild(this.moDialogBox);
    	else
      		this.moDialogBox = this.moOverlay.parentNode.insertBefore(this.moDialogBox, this.moOverlay);
      	
      	this.moParentElement = this.moDialogBox.parentNode;
  	}

	,show: function() 
	{
		this.moveDialogBox('out');
	  	if(this.moOptions.closeOnClickBackground)
      		this.moOverlay.onclick = this.hide.bind(this);
      	
      	this.toggleSelectBoxes('hide');
      	if(this.moOverlay.style.display == 'none')
	      	new Effect.Appear(this.moOverlay, {duration: 0.1, from: 0.0, to: this.moOptions.dimmingOpacity});
    	
    	Object.extend(this.moDialogBox.style, {
      		 position: 'absolute'
      		,display: ''
      		,visibility : 'visible'
      	});
	}
/*
	,setSize : function (to) {
		try {
				//this.wrapper.style.width = (to.w + 2*this.offsetBorderW) +'px';
				this.moDialogBox.style.width = to.w +'px';
				//if (hs.safari) this.content.style.maxWidth = this.content.style.width;
				this.moDialogBox.height = to.h +'px';
			//if (to.op) hs.setStyles(this.wrapper, { opacity: to.op }); 
					
			
			//if (this.objOutline && this.outlineWhileAnimating) {
			//	var o = this.objOutline.offset - to.o;
			//	this.objOutline.setPosition(this, to.x + o, to.y + o, to.w - 2 * o, to.h - 2 * o, 1);
			//}
				
			
			this.moDialogBox.setStyle ( {
				'visibility': 'visible',
				'left': to.x +'px',
				'top': to.y +'px'
				,'z-index' : 1000
			});
			
		} catch (e) { window.location.href = this.src;	}
	}
	*/
  	,hide: function() 
	{
	    this.toggleSelectBoxes('show');
	    new Effect.Fade(this.moOverlay, {duration: 0.1});
	    this.moDialogBox.style.display = 'none';
	    this.moveDialogBox('back');
	    $A(this.moDialogBox.getElementsByTagName('input')).each(function(e){if(e.type!='submit')e.value=''});
	}
  	/*
  	,hidebox : function()
  	{
	  	this.moDialogBox.style.display = 'none';
  	}
  	*/
  	,toggleSelectBoxes: function(what) 
  	{
  		$$('select').each(function(select){
  			if(select.hasClassName('ie6hidden') && Prototype.Browser.IE6)
	  		{
	  			if(what=='hide')
  					select.hide();
  				else
  					select.show();
  			}
  		});

    	if(what == 'hide')
     		 $A(this.moDialogBox.getElementsByTagName('select')).each(function(select){Element.show(select)})
  	}
  	
  	
	//	External function RIPPED from Highslide
	,getPageSize : function () 
	{
		var d = document, w = window, iebody = d.compatMode && d.compatMode != 'BackCompat' 
			? d.documentElement : d.body;	
		
		var b = d.body;
		var xScroll = (w.innerWidth && w.scrollMaxX) 
				? w.innerWidth + w.scrollMaxX : Math.max(b.scrollWidth, b.offsetWidth),
			yScroll = (w.innerHeight && window.scrollMaxY) 
				? w.innerHeight + w.scrollMaxY : Math.max(b.scrollHeight, b.offsetHeight),
			pageWidth = Prototype.Browser.IE ? iebody.scrollWidth :
				(d.documentElement.clientWidth || self.innerWidth),
	      	pageHeight = Prototype.Browser.IE ? Math.max(iebody.scrollHeight, iebody.clientHeight) : 
				(d.documentElement.clientHeight || self.innerHeight);
		
		var width = Prototype.Browser.IE ? iebody.clientWidth : 
				(d.documentElement.clientWidth || self.innerWidth),
			height = Prototype.Browser.IE ? iebody.clientHeight : self.innerHeight;
		
		return {
			pageWidth: Math.max(pageWidth, xScroll),
			pageHeight: Math.max(pageHeight, yScroll),
			width: width,
			height: height,		
			scrollLeft: Prototype.Browser.IE ? iebody.scrollLeft : pageXOffset,
			scrollTop: Prototype.Browser.IE ? iebody.scrollTop : pageYOffset
		}
	}
});


	
	/*
	* Only usuable for images

	,growFrom : function(oSource,oDestination)
	{
		var o_source = $(oSource)
		 ,a_dialog_dims = Element.getDimensions(this.dialog_box)
		 ,a_source_dims = Element.getDimensions(o_source)
		 ,a_source_pos	= o_source.cumulativeOffset()
		
		this.dialog_box.style.display = 'block';
		this.dialog_box.style.position = 'absolute';
		
		//alert(e_dims.width);
		/*o_source.setStyle({
			 width : a_source_dims.width
			,height : a_source_dims.height
		});
		*/
	//	Element.clonePosition(this.dialog_box,o_source);
		//this.show();
		/*
		new Effect.Scale(this.dialog_box,100,{
			 scalemode 		: 'box'
			,originalHeight	: a_source_dims.height
			,originalWidth	: a_source_dims.width
		})
		
		
		// Apply size change		
		alert(o_source.left);
		alert(o_source.top);
		
		this.changeSize(
			1,
			{ 
				x: a_source_pos.left, //this.thumbLeft + this.thumbOffsetBorderW - this.offsetBorderW,
				y: a_source_pos.top, // + this.thumbOffsetBorderH - this.offsetBorderH,
				w: a_source_dims.width,
				h: a_source_dims.height,
			
				o: 3
			},
			{
				x: this.dialog_box.style.left,
				y: this.dialog_box.style.top,
				w: a_dialog_dims.width,
				h: a_dialog_dims.height,
			
				o: 0
			},
			250,
			10

		);
		
	 	//new Effect.Appear(this.overlay, {duration: 0.1, from: 0.0, to: this.dimmingOpacity});
	 	//
	}
  	
  	,changeSize : function(up, from, to, dur, steps) {
	
		if (up && this.objOutline && !this.outlineWhileAnimating) 
			this.objOutline.setPosition(this, this.x.min, this.y.min, this.x.span, this.y.span);
		/*
		else if (!up && this.objOutline) {	
			if (this.outlineWhileAnimating) this.objOutline.setPosition(this, from.x, from.y, from.w, from.h);
			else this.objOutline.destroy();
			}	
				
		if (!up) { // remove children
			var n = this.wrapper.childNodes.length;
			for (var i = n - 1; i >= 0 ; i--) {
				var child = this.wrapper.childNodes[i];
				if (child != this.content) hs.discardElement(child);
			}
		}
			
		if (this.fadeInOut) {
			from.op = up ? 0 : 1;
			to.op = up;
		}
		
		var t,
		exp = this,
		easing = Math[this.easing] || Math.easeInQuad;
		
		/* if (!up) easing = Math[this.easingClose] || easing; 
				
		for (var i = 1; i <= steps; i++) {
			t = Math.round(i * (dur / steps));
			(function(){
				var pI = i, size = {};
				
				for (var x in from) {
					size[x] = easing(t, from[x], to[x] - from[x], dur);
					if (/[xywh]/.test(x)) size[x] = Math.round(size[x]);
				}
				
				setTimeout ( function() {
					if (up && pI == 1) {
						exp.dialog_box.style.visibility = 'visible';
						/* exp.a.className += ' highslide-active-anchor';
					}
					exp.setSize(size);
				}, t);				
			})();		
		}
	
		/*
		if (up) { 
			
			setTimeout(function() {
				if (exp.objOutline) exp.objOutline.table.style.visibility = "visible";
			}, t);
			setTimeout(function() {
				if (exp.caption) exp.writeCaption();
				
			}, t + 50);
			
		}
		else setTimeout(function() { exp.afterClose(); }, t);
		
	}
	*/
	/*
	,resize : function()
	{
		// get current width and height
        var i_width_current  = this.moDialogBox.getWidth();
        var i_height_current = this.moDialogBox.getHeight();

        // get new width and height
        var widthNew  = (imgWidth  + LightboxOptions.borderSize * 2);
        var heightNew = (imgHeight + LightboxOptions.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;   
        }
	}
	*/
