/* -----------------------------------------------------------------

	Script: 
		mocha.js v.0.7
	
	Copyright:
		Copyright (c) 2007 Greg Houston, <http://greghoustondesign.com/>
	
	License:
		MIT-style license

	Contributors:
		Scott F. Frederick
		Joel Lindau
	
   ----------------------------------------------------------------- */
var c = 0;
var testObject = null;
var MochaDesktop = new Class({
		options: {
		draggable: false,
		resizable: true,
		minimizable: false, // this is automatically reset to false if there is no dock
		maximizable: false, // this is automatically reset to false if #mochaDesktop is not present
		closable: true,
		headerHeight: 25,
		footerHeight: 30,
		cornerRadius: 10,
		desktopTopOffset: 10, // use a negative number if neccessary to place first window where you want it
		/*desktopLeftOffset: 0,*/
		mochaTopOffset: 0, // initial vertical spacing of each window
		mochaLeftOffset: 0, // initial horizontal spacing of each window
		newWindowPosTop: 0, // In the current setup this just initializes the variable and does not effect the position
		newWindowPosLeft: 0, // In the current setup this just initializes the variable and does not effect the position
		minWidth: 250, // minimum width of windows when resized
		maxWidth: 2500, // maximum width of windows when resized
		minHeight: 100,	// minimum height of windows when resized	
		maxHeight: 2000, // maximum height of windows when resized	
		optional_RGBA_TopHeaderGradient: 'rgba(10,10,10,1.0)', //default added SFF
		optional_RGBA_BottomHeaderGradient: 'rgba(10,10,10,10.0)', //default added SFF
		optional_RGBA_FooterColor: 'rgba(10,10,10,1.0)', //default added SFF
		optional_RGBA_ResizeTriangleColor: 'rgba(209, 209, 209, 1.0)', //default added SFF
		optional_RGBA_ControlCloseLineColor: 'rgba(0, 0, 0, 1.0)', //default added SFF
		optional_RGBA_ControlCloseBaseColor: 'rgba(229, 217, 217, 1.0)', //default added SFF
		optional_RGBA_ControlMaximizeLineColor: 'rgba(0, 0, 0, 1.0)', //default added SFF
		optional_RGBA_ControlMaximizeBaseColor: 'rgba(217, 229, 217, 1.0)', //default added SFF
		optional_RGBA_ControlMinimizeLineColor: 'rgba(0, 0, 0, 1.0)', //default added SFF
		optional_RGBA_ControlMinimizeBaseColor: 'rgba(231, 231, 209, 1.0)' //default added SFF
		
	},
	initialize: function(name ,options){
		this.setOptions(options);
		
		this.name = name;		
		// Private properties		
		this.indexLevel = 1;
		this.mochaControlsWidth = 0;
		this.minimizebuttonX = 0;
		this.maximizebuttonX = 0;
		this.closebuttonX = 0;
		this.scrollWidthOffset = 6;
		this.windowIDCount = 0;
		new Element('canvas');
		// Add properties to elements in the DOM
		// Consider moving this to windowProperties
		// so it is not added to all the elements in the DOM
		// but just to the windows
		Element.implement({oldTop: ''});
		Element.implement({oldLeft: ''});
		Element.implement({oldWidth: ''});
		Element.implement({oldHeight: ''});
		Element.implement({maximizeToggle: 'maximize'});
		Element.implement({modal: ''});
		Element.implement({iframe: ''});
		Element.implement({contentURL: ''});

		$$(name).setStyle('display', 'block');
		this.insertWindowElements($$(name));

		this.drawAll();

		// Modal initialization
		var mochaModal = new Element('div', {
			'id': 'mochaModalBackground'
		});		

		if ($('mochaDesktop')){
			mochaModal.injectInside($('mochaDesktop'));
		}
		else {
			mochaModal.injectInside(document.body);
		}
		this.setModalSize();

		mochaModal.setStyle('opacity', .4);
		this.modalOpenMorph = new Fx.Morph($('mochaModalBackground'), {
				'duration': 200
				});
		this.modalCloseMorph = new Fx.Morph($('mochaModalBackground'), {
			'duration': 200,
			onComplete: function(){
				$('mochaModalBackground').setStyle('display', 'none');
			}.bind(this)
		});		
		
},


	focusWindow: function(el){
		this.indexLevel ++;
		el.setStyle('zIndex', this.indexLevel);
	},
	
	getWindowWidth: function(){
		var windowDimensions = $('test').getCoordinates(); 
		return windowDimensions.width;
	},
	
	getWindowHeight: function(){
		var windowDimensions = $('test').getCoordinates(); 
		return windowDimensions.height;
	},	
	setModalSize: function(){
		$('mochaModalBackground').setStyle('height', this.getWindowHeight());
	},	
	insertWindowElements: function(elementArray){
		elementArray.each(function(el){
			var mochaTempContents = el.innerHTML;
			el.empty();

			if (window.ie6){
				el.innerHTML = '<iframe class="zIndexFix" scrolling="no" marginwidth="0" src="" marginheight="0"></iframe>';
			}
			
			var mochaOverlay = new Element('div', {
				'class': 'mochaOverlay'
			}).injectInside(el);
			
			if (window.ie){
				mochaOverlay.setStyle('zIndex', 2)
			}

			//Insert mochaTitlebar
			var mochaTitlebar = new Element('div', {
				'class': 'mochaTitlebar'
			}).injectTop(mochaOverlay);
			
			if (this.options.draggable && !el.modal){
				mochaTitlebar.setStyle('cursor', 'move');
			}

			var mochaContent = new Element('div', {
				'class': 'mochaContent'
			}).injectInside(mochaOverlay);

			mochaContent.setStyles({
				width: el.getStyle('width'),
				height: el.getStyle('height')
			});

			var mochaScroller = new Element('div', {
				'class': 'mochaScroller'
			}).injectTop(mochaContent);

			var mochaScrollerpad = new Element('div', {
				'class': 'mochaScrollerpad'
			}).setHTML(mochaTempContents).injectInside(mochaScroller);
			
			if (el.iframe){
				var mochaIframe = new Element('iframe', {
					'id': el.id + 'Iframe',						  
					'class': 'mochaIframe',
					'src': el.contentURL,
					'marginwidth': 0,
					'marginheight': 0,
					'frameBorder': 0,
					'scrolling': 'auto'
				}).injectInside(mochaScrollerpad);
			}			
			
			var mochaTitlebarH3 = mochaScrollerpad.getElement('h3.mochaTitle').clone().injectInside(mochaTitlebar);
			mochaScrollerpad.getElement('.mochaTitle').dispose();

			if(el.contentURL && !el.iframe){
				new Request({
					url: el.contentURL,
					onRequest: function(){
					},
					onFailure: function(){
						mochaScrollerpad.setHTML('<p><strong>Error Loading XMLHttpRequest</strong></p><p>Make sure all of your content is uploaded to your server, and that you are attempting to load a document from the same domain as this page. XMLHttpRequests will not work on your local machine.</p>');
					},
					onSuccess: function(response) {
						mochaScrollerpad.setHTML(response);
						if ( el.onContentLoaded ) el.onContentLoaded();
					}
				}).get();
			}
			
			//Insert canvas
			var canvas = new Element('canvas', {
				'class': 'mochaCanvas',
				'width': 1,
				'height': 1
			}).injectInside(el);

			// Dynamically initialize canvas using excanvas. This is only required by IE
			if (window.ie) {
				G_vmlCanvasManager.initElement(canvas);
			}

		}.bind(this));
	},
	drawAll: function(){
		$$('div.mocha').each(function(el){
			if (el.getStyle('display') != 'none'){
				this.drawWindow(el);
			}
		}.bind(this));
	},
	/*
	
	Method: drawWindow
	
	Arguments: 
		el: the $(window)
		shadows: (boolean) false will draw a window without shadows
		
	Notes: This is where we create the canvas GUI	

	*/	
	drawWindow: function(el, shadows) {
		var mochaIframe = el.getElement('.zIndexFix');
		var mochaOverlay = el.getElement('.mochaOverlay');
		var mochaContent = el.getElement('.mochaContent'); 
		var mochaScroller = el.getElement('.mochaScroller');
		var mochaTitlebar = el.getElement('.mochaTitlebar');
		var mochaCanvas = el.getElement('.mochaCanvas');


		var ctx = mochaCanvas.getContext('2d');

		//Assign a unique id to each window, 
		//that doesn't yet have an id.
		//This is happening at least three times for windows not created onstart.
		//Should rethink the flow on this.
		if(el.id == ""){el.id = 'win' + (++this.windowIDCount);}
		
		mochaScroller.setStyle('height', mochaContent.getStyle('height'));
		mochaScroller.setStyle('width', mochaContent.getStyle('width'));
		
		//Resize iframe when window is resized
		if (el.iframe) {
			el.getElement('.mochaIframe').setStyles({
				'height': mochaContent.getStyle('height')
			});
		}
	
		mochaHeight = this.getWindowHeight();
		mochaWidth = this.getWindowWidth() + 30;
		mochaHeight += this.options.headerHeight + this.options.footerHeight;
		
		//Firefox returns null and IE returns empty string difference
		// Definitely in the wrong place
		var sTitleBarTitle = mochaTitlebar.getProperty('title');
		
		//Firefox
		//Also in the wrong place
		if(sTitleBarTitle == null) {
			sTitleBarTitle = "";
		}

		mochaOverlay.setStyle('height', mochaHeight);
		el.setStyle('height', mochaHeight);

		if (window.webkit) {
			mochaCanvas.setProperties({
				'width': 4000,
				'height': 2000
			});
		} else {
			mochaCanvas.width = mochaWidth;
			mochaCanvas.height = mochaHeight;
		}
		
		// Part of the fix for IE6 select z-index bug and FF on Mac scrollbar z-index bug
		if (window.ie6){
			mochaIframe.setStyle('width', mochaWidth);
			mochaIframe.setStyle('height', mochaHeight);
		}

		// Set width		
		mochaOverlay.setStyle('width', mochaWidth); 
		el.setStyle('width', mochaWidth);
		mochaTitlebar.setStyle('width', mochaWidth - 6);
	
		// Draw shapes
		ctx.clearRect(0, 0, this.getWindowWidth(), this.getWindowHeight());
		if (shadows == null || shadows == false && !window.ie){
			this.roundedRect(ctx, 1, 0, mochaWidth-2, mochaHeight-2, this.options.cornerRadius, 'rgba(75, 75, 75, 1.0)'); //shadow
			this.roundedRect(ctx, 1, 1, mochaWidth - 3, mochaHeight - 3, this.options.cornerRadius, 'rgba(75, 75, 75, 1.0)'); //shadow
			this.roundedRect(ctx, 3, 2, mochaWidth - 4, mochaHeight - 4, this.options.cornerRadius, 'rgba(75, 75, 75, 1.0)'); //shadow
		}		
		this.roundedRect(ctx,3,2,mochaWidth-6,mochaHeight-6,this.options.cornerRadius,this.options.optional_RGBA_FooterColor);	//mocha body
		this.topRoundedRect(ctx,3,2,mochaWidth-this.scrollWidthOffset,this.options.headerHeight,this.options.cornerRadius); //mocha header


		/*this.closebuttonX = mochaWidth - 15;*/

			/*if (this.options.closable || el.modal){
				this.closebutton(ctx, this.closebuttonX, 15, this.options.optional_RGBA_ControlCloseBaseColor,this.options.optional_RGBA_ControlCloseLineColor);
			}
			if (this.options.maximizable && !el.modal){
				this.maximizebutton(ctx, this.maximizebuttonX, 15, this.options.optional_RGBA_ControlMaximizeBaseColor,this.options.optional_RGBA_ControlMaximizeLineColor);
			}
			if (this.options.minimizable && !el.modal){
				this.minimizebutton(ctx, this.minimizebuttonX, 15, this.options.optional_RGBA_ControlMinimizeBaseColor,this.options.optional_RGBA_ControlMinimizeLineColor); //Minimize
			}
			if (this.options.resizable && !el.modal){
			this.triangle(ctx, mochaWidth - 20, mochaHeight - 20, 12, 12,this.options.optional_RGBA_ResizeTriangleColor); //resize handle
			}
			this.triangle(ctx, mochaWidth - 20, mochaHeight - 20, 10, 10, 'rgba(0, 0, 0, 0)'); *///invisible dummy object. The last element drawn is not rendered consistently while resizing in IE6 and IE7.

	},
	//mocha body
	roundedRect: function(ctx,x,y,width,height,radius,rgba){
		ctx.fillStyle = rgba; //changed SFF
		ctx.beginPath();
		ctx.moveTo(x,y+radius);
		ctx.lineTo(x,y+height-radius);
		ctx.quadraticCurveTo(x,y+height,x+radius,y+height);
		ctx.lineTo(x+width-radius,y+height);
		ctx.quadraticCurveTo(x+width,y+height,x+width,y+height-radius);
		ctx.lineTo(x+width,y+radius);
		ctx.quadraticCurveTo(x+width,y,x+width-radius,y);
		ctx.lineTo(x+radius,y);
		ctx.quadraticCurveTo(x,y,x,y+radius);
		ctx.fill(); 
	},
	//mocha header with gradient background
	topRoundedRect: function(ctx,x,y,width,height,radius){

		ctx.fillStyle = this.getHeaderGradientFillStyle(ctx); //SFF 12/14/2007

		// draw header
		ctx.beginPath();
		ctx.moveTo(x,y);
		ctx.lineTo(x,y+height);
		ctx.lineTo(x+width,y+height);
		ctx.lineTo(x+width,y+radius);
		ctx.quadraticCurveTo(x+width,y,x+width-radius,y);
		ctx.lineTo(x+radius,y);
		ctx.quadraticCurveTo(x,y,x,y+radius);
		ctx.fill(); 
	},
	// resize handle
	/*triangle: function(ctx,x,y,width,height,rgba){
		ctx.beginPath();
		ctx.moveTo(x+width,y);
		ctx.lineTo(x,y+height);
		ctx.lineTo(x+width,y+height);
		ctx.closePath();
		ctx.fillStyle = rgba; //changed SFF
		ctx.fill();
	},*/
	drawCircle: function(ctx,x,y,diameter,rgba){
		//circle
		ctx.beginPath();
		ctx.moveTo(x,y);
		ctx.arc(x,y,diameter,0,Math.PI*2,true);
		ctx.fillStyle = rgba;
		ctx.fill();
	},
	getHeaderGradientFillStyle: function(ctx) //SFF 12/14/2007
	{	
		// Create gradient
		if (window.opera != null ){
			var lineGradient = ctx.createLinearGradient(0,0,0,this.options.headerHeight+2);
		}
		else {
			var lineGradient = ctx.createLinearGradient(0,0,0,this.options.headerHeight);
		}
		
		lineGradient.addColorStop(0, this.options.optional_RGBA_TopHeaderGradient); 
		lineGradient.addColorStop(1, this.options.optional_RGBA_BottomHeaderGradient); 
		
		return lineGradient;
	},initDock: function (el){
		document.addEvent('mousemove', function (objDoc){
			if(objDoc.event.clientY > (document.body.clientHeight -10) && $('mochaDock').getProperty('autoHide')) { 
				$('mochaDock').setStyle('display','block');
			}
		});		

		//Insert canvas
		var canvas = new Element('canvas', {
			'class': 'mochaCanvas',
			'id': 'canv1'
		}).injectInside(el);
		
		canvas.setStyles({
			position: 'absolute',
			top: '4px',
			left: '2px',
			zIndex: 2
		});

		canvas.width=15;
		canvas.height=18;

		// Dynamically initialize canvas using excanvas. This is only required by IE
		if (window.ie) {
			G_vmlCanvasManager.initElement(canvas);
		}
		
		//Position top or bottom selector
		$('mochaDockPlacement').setProperty('title','Position Dock Top');
			
		//Auto Hide on/off 
		$('mochaDockAutoHide').setProperty('title','Turn Auto Hide On');
		
		//attach event
		$('mochaDockPlacement').addEvent('click', function(event){
			var objDock=event.target.parentNode;
			var ctx = el.getElement('.mochaCanvas').getContext('2d');
			
			//switch to top position
			if (objDock.getStyle('position') != 'absolute'){
				objDock.setStyles({
					'position': 'absolute',
					'bottom': 0,
					'border-top': '1px solid #bbb',
					'border-bottom': '1px solid #fff'
				})
				$('mochaDesktopHeader').setStyle('height', 54);
				objDock.setProperty('dockPosition','Bottom');
				this.drawCircle(ctx, 5, 4, 3, 241, 102, 116, 1.0); 

				if ($('mochaDock').getProperty('autoHide') != 'true' || $('mochaDock').getProperty('autoHideDisabled') != 'true') {
					this.drawCircle(ctx, 5 , 14, 3, 241, 102, 116, 1.0); 
				}
				} else {
					objDock.setStyles({
						'position': 'relative',
						'bottom': null,
						'border-top': '1px solid #fff',
						'border-bottom': '1px solid #bbb'
					})
					$('mochaDesktopHeader').setStyle('height', 74);
					objDock.setProperty('dockPosition','Top');	
					this.drawCircle(ctx, 5, 4, 3, 0, 255, 0, 1.0);
					this.drawCircle(ctx, 5, 14, 3, 212, 208, 200, 1.0);
				}

			//diasble/enable autohide and grey/orange/green out button
			if($('mochaDock').getProperty('autoHide') == 'true' || $('mochaDock').getProperty('autoHideDisabled') == 'true')
			{
				if (objDock.getProperty('dockPosition') == 'Bottom') {
					$('mochaDock').setProperty('autoHideDisabled', 'false');
					$('mochaDock').setProperty('autoHide', 'true')
					this.drawCircle(ctx, 5, 14, 3, 0, 255, 0, 1.0);
				}
				else{
					$('mochaDock').setProperty('autoHideDisabled', 'true');
					$('mochaDock').setProperty('autoHide', 'false')
				}

			}

			//update title tag
			$('mochaDockPlacement').setProperty('title',(objDock.getStyle('position') == 'relative')?'Position Dock Bottom':'Position Dock Top');
		}.bind(this));

		//attach event Auto Hide 
		$('mochaDockAutoHide').addEvent('click', function(event){
			var objDock=event.target.parentNode;
			var ctx = el.getElement('.mochaCanvas').getContext('2d');

			//disable auto hide when Dock bar on top
			if(objDock.getProperty('dockPosition')=='Top'){return false;}
		
			//update title tag
			if(objDock.getProperty('autoHide') == 'true'){
				$('mochaDockAutoHide').setProperty('title', 'Turn Auto Hide On');
				this.drawCircle(ctx, 5 , 14, 3, 241, 102, 116, 1.0);
				objDock.setProperty('autoHide','false');
				objDock.setStyle('display','block');
			}
			else{
				$('mochaDockAutoHide').setProperty('title','Turn Auto Hide Off');
				this.drawCircle(ctx, 5 , 14, 3, 0, 255, 0, 1.0); 
				objDock.setProperty('autoHide','true');
				objDock.setStyle('display','none');
			}
		}.bind(this));		

		$('mochaDock').addEvent('mouseleave', function(objDock)
		{	if(this.getProperty('autoHide') == 'true'){ //mozilla doesn't understand true evaluations, so made the property a string???
				if((objDock.event.clientY < (document.body.clientHeight - this.getStyle('height').toInt()))){
					this.setStyle('display', 'none');
				}
			}
		});
		
	},

	attachFocus: function(elementArray){
		elementArray.each(function(element) {
			element.addEvent('click', function(event){
				// Only focus when needed, otherwize onFocus() will run on every click
				if ( element.getStyle('zIndex').toInt() < this.indexLevel ) {
				this.focusWindow(element);
					if (element.onFocus){
						element.onFocus();
					}
				}
			}.bind(this));
		}.bind(this));
	}
	});
MochaDesktop.implement(new Options);



/* -----------------------------------------------------------------

	Initialize Everything onLoad

   ----------------------------------------------------------------- */

window.addEvent('load', function(){
		
		document.mochaDesktop = new MochaDesktop('div.mocha');

		/*addSlider();*/ // remove this if you remove the example corner radius slider
		
		//remove if not using mocha color picker theme SFF
		/*if ($('windowColorAdmin')) {
			document.windowColorAdmin = new MochaColorPickerTheme();
			document.windowColorAdmin.mocha_ColorPickerThemeLoad();
		}	*/
});
