/*
##DEXTERITY_LICENSE_TEXT##
*/
/**
	PerspectiveUIFrame is a javascript class that represents a set of UI windows forming an 
	application "view" much like an Eclipse perspective.  
	
	The UI windows are defined in a spreadsheet named range from which window layout and source
	urls are determined.
	
	The spreadsheet namedrange is accessed through the RESTful Spreadsheet Server API and returned
	as a JSON javascript array.
	
	JavaScript Windowing is then used to instantiate the window layout.
		
	...
	 loadUI -- loads the windows based on named range values
	 
	 "http://127.0.0.1:8080/workbook/id/1301/csv/namedrange/getcellvalues/windows/0" returns:
	 'crm','/uimodules/crm/intro.jsp','true','?daterange=1+2','10','50','300','400','open CRM','invoice template','/uimodules/crm/intro.jsp','true','?daterange=1+2','20','30','150','250','open last viewed invoice'
	 this is one window definition:
	 'crm','/uimodules/crm/intro.jsp','true','?daterange=1+2','10','50','300','400'
	
**/
PerspectiveUI = Class.create();
PerspectiveUI.prototype = {
	
	// this.last_row = -1; // the last row of tables in the dexterity sheet
	
	/**
		constructor
	**/
	initialize: function(){
		// TODO: look this up somehow...
		this.dexterity_meme = -1;
		this.coords = null;
	},
	
	
	/**
		this will call the Dexterity Plugin which will create the default settings sheet if none
	*/
	saveUIFrame: function(title, module, x, y, w, h){
 		// alert('saving frame state:'  +title +':'+ module+':'+x+':'+y+':'+w+':'+h);
		

		// obtain new coordinates
		try {
			var c= {'title':title,
						'URL': encodeURI(module),
						'X':parseFloat(x),
						'Y':parseFloat(y),
						'W':parseFloat(w),
						'H':parseFloat(h)
						};					
		} catch (e) {
			parent.showError("Unable to get window coordinates " + e);
			return false;
		}
		
		// for each window, we need to insert a row of layout info
		var url = '/workbook/id/'+this.dexterity_meme+'/json/dexterity/savelayout/';
		if(false){ // don't do until we fix the spurious dexterity sheet creation
			try {
				url += Object.toJSON(c);
				// alert( url);
				
				new Ajax.Request(url , {
					method: 'get',
					onSuccess: function(transport){
						debug("Saved window layout: " + transport.responseText);
					},
					onFailure: function(transport){ 
						var response = transport.responseText || "failure";     
					//	parent.showError("Unable to serialize window layout: " + response); 
					}
				});
			} catch (e) { 
				//	parent.showError("Unable to serialize window layout: " + e.toString()); 
			}			
		}
		
		return false;
		
	},
	
	/**
		de-serialize the spreadsheet and restore the perspective
		from the dexterity spreadsheet layout data.
	*/
	restorePerspective: function(midi){
		
		if(typeof(midi)!='undefined')
			this.dexterity_meme = midi;	
		else
			this.dexterity_meme  = uiWindowing.getActiveSheet().memeId; // get from user
	
		//alert('calling ajax for dexterity:' + url);
		var url = '/workbook/id/'+ this.dexterity_meme +'/csv/namedrange/getcellvalues/windows/0';		
		
		var urlskin = '/workbook/id/'+ this.dexterity_meme +'/csv/namedrange/getcellvalues/skin/0';		
		var skin = "extentech";
		
		var _this = this;
		
		// first req.
		new Ajax.Request(urlskin , {
			method: 'get',
			onSuccess: function(transport){
				var jsonResponse = transport.responseText.evalJSON(true);
				// alert(jsonResponse);
				skin = jsonResponse.skin;
			},
			onFailure: function(){ 
				var response = transport.responseText || "failure";     
				parent.showError(" Unable to retrieve theme: " + response); 
			}
		});
		
		// second req.
		new Ajax.Request(url , {
			method: 'get',
			onSuccess: function(transport){
				//alert(transport.responseText);
				_this.loadUIFrames(transport.responseText);			
			},
			onFailure: function(){ 
				var response = transport.responseText || "failure";     
				parent.showError(" Unable to retrieve window definitions: " + response); 
			}
		});
	
	},
	
	/**
		loads the windows defined in the dexterity spreadsheet
		
		template is:
		
		/grid/xls/compositeapplication.xls
	*/
	loadUIFrames: function(resp){
		showStatus('begin restoring perspective');
		
		// alert(resp);
		
		// bust out the vals from csv
		var winarr = new Array();
		// trim the quotes
		if(resp.indexOf("'")==0)
			resp = resp.substring(1);

		if(resp.indexOf("'")==resp.length)
			resp = resp.substring(0,resp.length-1);
						
		// example return	
		// 'mail'	,'acme.com','true','inbox=john@acme.com'	,'10','50','300','400','office email',
		// 'cl'		,'www.craigslist.org','true','?daterange=1+2'			,'20','30','150','250','office voicemail'

	    winarr = resp.split("','");
		for (var i=0; i < winarr.length; i++){ // divide by the number of fields per window def
			var title 	= winarr[i++];
			var module 	= winarr[i++];
			var rule 	= winarr[i++];
			var params  = winarr[i++];
			
			var theme 	= 'extentech';
			
			var x = winarr[i++];
			var y = winarr[i++];
			var w = winarr[i++];
			var h = winarr[i++];
			
			var description = winarr[i];
			
			showStatus('restoring layout: ' + title + ': '+ description);
			if(module.indexOf("http://")<0)
				module = 'http://' + module;
				
			try{
				openWindow(title, module, 'extentech', x, y, w, h);
			}catch(e){
			;
			}
			// alert(title+'::'+module+'::'+'extentech'+'-'+x+'-'+y+'-'+w+'-'+h);
		}

		showStatus('finished restoring perspective');	
	}

}

// instantiate the perspective


var perspective = new PerspectiveUI();
// DO NOT load automatically 
// perspective.restorePerspective();

// Set up a windows observer, check ou debug window to get messages
var myObserver = {
	onStartMove: function(eventName, win) {
		debug(eventName + " on " + win.getId())
	},
	onEndMove: function(eventName, win) {
	
		var title = win.topbar.innerHTML;
		var module = win.options.url;
		var x = win.element.offsetLeft;
		// x = x.substring(0,x.indexOf("px")+2); // strip px
		// x = parseFloat(x);
		
		var y = win.element.offsetTop;
		// y = y.substring(0,y.indexOf("px")+2); // strip px
		// y = parseFloat(y);
		
		
		var w = win.element.offsetWidth;
		var h = win.element.offsetHeight; 
	
		perspective.saveUIFrame(title, module, x, y, w, h);
		debug(eventName + " on " + title+ ":"+ module+ ":"+ x+ ":"+ y+ ":"+ w+ ":"+ h)
		return false;
	},
	
	onStartResize: function(eventName, win) {
		debug(eventName + " on " + win.getId())
	},
	
	onEndResize: function(eventName, win) {
		debug(eventName + " on " + win.getId())
	},

	onClose: function(eventName, win) {
		debug(eventName + " on " + win.getId())
	},

	onDestroy: function(eventName, win) {
		debug(eventName + " on " + win.getId())
	}
}
Windows.addObserver(myObserver);


