Components.utils['import']("resource://livemargins/utils.jsm");
Components.utils["import"]("resource://livemargins/window.jsm");

var windowTools = {
	_logger: new utils.logger("LM4.windowTools"),
	LOG : function(msg) {
		this._logger.trace(msg);
	},
	
    //0 is onDesktop, 1 is normal, 2 is onTop
	_windowLayer : 1,   //right for widget windows, but not for widgetManager
	
	get windowStates(){
		var winStates = {
			windowLayer : this.windowLayer,
//			minimized : this.minimized
		};
		return winStates;
	},
	
	set windowStates(winStates) {
		if (winStates.windowLayer != null) {
			this.windowLayer = winStates.windowLayer;
		}
	},
	
	get windowLayer(){
		return this._windowLayer;
	},
	
	set windowLayer(windowLayer){
		this.LOG("setWindowLayer : " + windowLayer);
//		can not use next line, because can not detect whether the window is ontop by default
//		if (this._windowLayer == windowLayer) return;

		var self = this;
		window.clearTimeout(this._setLayerTimeout);
		this._setLayerTimeout = window.setTimeout(function() {
			if (windowLayer == 1) {
				self.setNoTopMost();
			} else if (windowLayer == 2) {
				self.setTopMost();
			} else {
				self.LOG("windowLayer must be 1 or 2");
			}
			self.sendUIEvent("windowLayerChanged");
		}, 10);
	},
	
	get minimized () {
		var cWin = window.QueryInterface(Components.interfaces.nsIDOMChromeWindow);
		return cWin.windowState == cWin.STATE_MINIMIZED;
	},
	
	set minimized (minimize) {
		if (minimize) {
			window.QueryInterface(Components.interfaces.nsIDOMChromeWindow).minimize();
		}
	},
	
	setTopMost : function(){
		try {
			windowHelper.setTopMost(window, widget.args.name, true);
			this._windowLayer = 2;
		} catch (e) {
			this.LOG(e.toString());
		}
	},
	
	setNoTopMost : function() {
		try {
			windowHelper.setTopMost(window, widget.args.name, false);
			this._windowLayer = 1;
		} catch (e) {
			this.LOG(e.toString());
		}
	},
	
	setRoundRgn : function(width, height) {
		windowHelper.setRoundRgn(window, width, height, widget.args.name);
	},
	
	sendUIEvent : function(type,detail) {
		try{
			if (detail == null) detail = 0;
			e = document.createEvent("UIEvents");
			e.initUIEvent(type, true, true, window, detail);
			window.dispatchEvent(e);
		} catch (e){
			this.LOG(e.toString());
		}
	}
};
