var widget = {
	__proto__ : widgetbase,	//make this object 'extends' widgetbase
	zoom : 1,
	isMovingContent : false,
	isMovingWindow : false,
	isResizing : false,
	moveStartPos : {x : 0,y : 0},
	defaultView : null,
	reloader : null,
	reloadInterval : 20000,
	popupMenuWidth : 230,
	playerMinWidth : 160,
	playerMinHeight : 90,
	
	LOG : function(msg) {
		this.__proto__.LOG.apply(this,["favpart player: "+ msg]);
	},
	
	logger: utils.logger('LM4.WebClipping'),
	
	init : function(){
		this.logger.trace('init');
		var args = window.arguments[0];	
		this.logger.trace(JSON.stringify(args));
		
		this.__proto__.init.apply(this);
		var enabledItems = utils.getPrefFromRoot("extensions.enabledItems","");
		if (enabledItems != "" && enabledItems.indexOf("cehomepage@mozillaonline.com") >= 0){
			var strDomains = utils.getPrefFromRoot("extensions.cehomepage.allowed_domains","");
			var domains = strDomains.split(",");
			var url = args.widgetArgs.location;
			for (var i = 0; i< domains.length; i++){
				var domain = domains[i].replace(' ', '');
				if (url.indexOf(domain) >= 0){
					this.writeCookie(url,"inlivemargin=ture");
				}
			}
		}
		
		widget.showFav( args.id,
						args.widgetArgs.docX,
						args.widgetArgs.docY,
						args.screenX,
						args.screenY,
						args.widgetArgs.width,
						args.widgetArgs.height,
						args.widgetArgs.browserWidth,
						args.widgetArgs.browserHeight,
						args.widgetArgs.location);
		if (args.widgetArgs.zoom == null) {
			args.widgetArgs.zoom = 1;
		};  
		
		if(args.widgetArgs.zoom != 1) {
			widget.setZoom(args.widgetArgs.zoom);
		}
		
		this.args.startWithFirefox = 1;
//		this.showControl(true);
		
		if (args.widgetArgs.autoReload == true){
			this.setAutoReload(true);
		}
		
		this.logger.trace("init done");
	},
	
	showFav : function(id, docX, docY, screenX, screenY, width, height, browserWidth, browserHeight, location) {
		this.logger.trace("width: " + width + ", height: " + height + ", browserWidth: " + browserWidth + ', browserHeight: ' + browserHeight);
		var contentBrowser = document.getElementById("player_browser");
		var contentDoc = contentBrowser.contentDocument;
		var frame = contentDoc.getElementById("contentFrame");
		frame.setAttribute("src", location);
		frame.src = location;
		frame.width = browserWidth;
		
		if (docY + height <= browserHeight){
			frame.height = browserHeight;
		} else {
			frame.height = docY + browserHeight;
		}
		
		var div = contentDoc.getElementById("contentDiv");
		div.width = browserWidth;
		div.height = browserHeight;
		
		contentBrowser.addEventListener('DOMContentLoaded', function() {
			// do not use arguments of the function, because the DOMContentLoaded event maybe not only fired once, and the values may be changed at the time it's refired.
			widget.trace("DOMContentLoaded,scroll," + contentBrowser.currentURI.spec);
			if (widget.args.widgetArgs.posAdjusted == true || contentBrowser.currentURI.spec == "chrome://livemargins/content/apps/webclipping/play.xul"){
				contentDoc.defaultView.scrollTo(widget.args.widgetArgs.docX, widget.args.widgetArgs.docY);
				
				// update app state
				AppCenter.updateAppState(id);
			} else {
				//the webpage use javascript to breakout the iframe, guess the position is the best we can do
				var newBrowserWidth = contentBrowser.contentWindow.scrollMaxX + contentBrowser.boxObject.width;
				var newDocX = widget.args.widgetArgs.docX - (widget.args.widgetArgs.browserWidth - newBrowserWidth) / 2;
				widget.trace("DOMContentLoaded,scroll,condition2," + widget.args.widgetArgs.docX + "," + newBrowserWidth + "," + newDocX);
				contentDoc.defaultView.scrollTo(newDocX, widget.args.widgetArgs.docY);
			}
		}, false);
		
		this.logger.trace("showFav done");
	},
	
	setZoom :function(zoom){
		widget.zoom = zoom;
		var browser = document.getElementById("player_browser");
		var contViewer = browser.docShell.contentViewer;
		var docViewer = contViewer.QueryInterface(Components.interfaces.nsIMarkupDocumentViewer);
		docViewer.fullZoom = widget.zoom;	
	},
	zoomIn : function() {
		var browser = document.getElementById("player_browser");
		var doc = browser.contentDocument;
		var width = browser.boxObject.width;
		var height = browser.boxObject.height;
		var contViewer = browser.docShell.contentViewer;
		var docViewer = contViewer.QueryInterface(Components.interfaces.nsIMarkupDocumentViewer);
		docViewer.fullZoom = widget.zoom+0.2;
		var newWidth = width*docViewer.fullZoom/widget.zoom;
		var newHeight = height*docViewer.fullZoom/widget.zoom;
		widget.zoom = docViewer.fullZoom;
		var doc = browser.contentDocument;
		this.args.widgetArgs.zoom = docViewer.fullZoom;
		var oldWidth = window.innerWidth;
		window.resizeTo(newWidth+10,newHeight+document.getElementById('chrome-title-box').boxObject.height+8);
		window.moveBy(oldWidth - newWidth -10, 0);
		var panel = document.getElementById("control-panel");
		var extButton = document.getElementById("ext-button");
		if (panel.state == "open"){
			panel.hidePopup();
			panel.openPopup(extButton,"after_end",0,0,true,false);
		}
		widget.LOG(doc.width);
		widget.LOG(doc.height);
	},
	zoomOut : function() {
		var browser = document.getElementById("player_browser");
		var doc = browser.contentDocument;
		var width = browser.boxObject.width;
		var height = browser.boxObject.height;
		if (width * (widget.zoom-0.2) / widget.zoom < widget.playerMinWidth){return;}
		
		var contViewer = browser.docShell.contentViewer;
		var docViewer = contViewer.QueryInterface(Components.interfaces.nsIMarkupDocumentViewer);
		docViewer.fullZoom = widget.zoom -0.2;
		var newWidth = width*docViewer.fullZoom/widget.zoom;
		var newHeight = height*docViewer.fullZoom/widget.zoom;
		widget.zoom = docViewer.fullZoom;
		this.args.widgetArgs.zoom = docViewer.fullZoom;
		var oldWidth = window.innerWidth;
		window.resizeTo(newWidth+10,newHeight+document.getElementById('chrome-title-box').boxObject.height+8);
		window.moveBy(oldWidth - newWidth -10, 0);
		var panel = document.getElementById("control-panel");
		var extButton = document.getElementById("ext-button");
		if (panel.state == "open"){
			panel.hidePopup();
			panel.openPopup(extButton,"after_end",0,0,true,false);
		}
		widget.LOG(doc.width);
		widget.LOG(doc.height);
	},
	startMove : function(ev){
		var resizer = document.getElementById("resizer");
		var titlebar = document.getElementById("title-bar");
		if (ev.originalTarget == resizer){
			widget.isResizing = true;
		} else if (ev.originalTarget == titlebar) {
			widget.isMovingWindow = true;
		}else {
			widget.isMovingContent = true;
		}
		widget.moveStartPos.x = ev.screenX;
		widget.moveStartPos.y = ev.screenY;
		ev.stopPropagation();
	},
	moving : function(ev){
		if (widget.isMovingWindow){
			window.moveBy(ev.screenX - widget.moveStartPos.x,ev.screenY - widget.moveStartPos.y);
			widget.moveStartPos.x = ev.screenX;
			widget.moveStartPos.y = ev.screenY;
			ev.stopPropagation();
		} else if (widget.isMovingContent){
			if (widget.defaultView == null){ 
				widget.defaultView = document.getElementById("player_browser").contentWindow;
			}
			widget.defaultView.scrollBy(widget.moveStartPos.x - ev.screenX, widget.moveStartPos.y - ev.screenY);
			widget.moveStartPos.x = ev.screenX;
			widget.moveStartPos.y = ev.screenY;
			widget.args.widgetArgs.docX = document.getElementById("player_browser").contentWindow.scrollX;
			widget.args.widgetArgs.docY = document.getElementById("player_browser").contentWindow.scrollY;
			widget.args.widgetArgs.posAdjusted = true;
			ev.stopPropagation();
		} else if (widget.isResizing){
			var panel = document.getElementById("modify-panel");
			var div = document.getElementById("modify-div");
			var browser = document.getElementById("player_browser");
			var deltaX = 0;
			var deltaY = 0;
			if (window.innerWidth + ev.screenX - widget.moveStartPos.x < widget.playerMinWidth){
				deltaX = 0;
			} else {
				deltaX = ev.screenX - widget.moveStartPos.x;
			}
			if (window.innerHeight + ev.screenY - widget.moveStartPos.y < widget.playerMinHeight){
				deltaY = 0;
			} else {
				deltaY = ev.screenY - widget.moveStartPos.y;
			}
			this.LOG("recording positions:"+widget.moveStartPos.x+","+widget.moveStartPos.y);	
			if (deltaX != 0) widget.moveStartPos.x = ev.screenX;
			if (deltaY != 0) widget.moveStartPos.y = ev.screenY;
			window.resizeBy(deltaX,deltaY);
			div.width = browser.boxObject.width;
			div.height = browser.boxObject.height;
			
			ev.stopPropagation();
		}
	},
	endMove : function(ev){
		widget.isMovingWindow = false;
		widget.isMovingContent = false;
		widget.isResizing = false;
		ev.stopPropagation();
	},
	startModify : function(ev){
		//to enable use the same button to close the panel when the panel is open when clicked( click itself will cause the panel to close first, so use panel.state is not useful)
		if (this.modifyPanelOpened && this.modifyPanelOpened == true) return;
		var browser = document.getElementById("player_browser");
		var titleBox = document.getElementById("chrome-title-box");
		var panel = document.getElementById("modify-panel");
		var div = document.getElementById("modify-div");
		div.width = browser.boxObject.width;
		div.height = browser.boxObject.height;
		panel.openPopup(browser,"overlap",0,0,false,true);
		// panel.addEventListener("mousedown",widget.startMove,true);
		// panel.addEventListener("mousemove",widget.moving,true);
		// panel.addEventListener("mouseup",widget.endMove,true);
	},
	reload : function(){
		var browser = document.getElementById("player_browser");
		var frame = browser.contentDocument.getElementById("contentFrame");
		if (frame){
			frame.contentDocument.defaultView.location = frame.contentDocument.defaultView.location.toString();
			frame.contentDocument.defaultView.location.reload();
			this.LOG(frame.contentDocument.defaultView.location.href);
		} else {
			browser.reload();
		}
	},
	returnURL : function(ev){
		var browser = document.getElementById("player_browser");
		var frame = browser.contentDocument.getElementById("contentFrame");
		const wm = Components.classes["@mozilla.org/appshell/window-mediator;1"]
                         .getService(Components.interfaces.nsIWindowMediator);
		var mainWin = wm.getMostRecentWindow( "navigator:browser" );
		if (mainWin) {
			mainWin.focus();
			var gBrowser = mainWin.getBrowser();
			if (frame){ // there is a possibility that the webpage break out of the frame
				gBrowser.selectedTab = gBrowser.addTab(frame.getAttribute("src"));
			} else {
				gBrowser.selectedTab = gBrowser.addTab(browser.contentDocument.URL);
			}
		} else {
			window.open(frame.getAttribute("src"));
		}
	},
	
	modifyState : function (){
		//this.LOG("tada");
		try {
			var browser = document.getElementById("player_browser");
			var doc = browser.contentDocument;
			var contViewer = browser.docShell.contentViewer;
			var docViewer = contViewer.QueryInterface(Components.interfaces.nsIMarkupDocumentViewer);
			this.args.widgetArgs.zoom = docViewer.fullZoom;
			if (doc.defaultView.scrollX > 0) {
				this.args.widgetArgs.docX = doc.defaultView.scrollX;
			}
			if (doc.defaultView.scrollY > 0) {
				this.args.widgetArgs.docY = doc.defaultView.scrollY;
			}
			widget.args.widgetArgs.posAdjusted = true;
			this.__proto__.modifyState.apply(this);
			
			// update docX and docY
			AppCenter.updateAppArgs(this.args.id, {
				docX: widget.args.widgetArgs.docX,
				docY: widget.args.widgetArgs.docY,
				zoom: widget.args.widgetArgs.zoom
			});
		} catch (e){
			this.LOG(e.toString());
		}
	},

	writeCookie : function(location,cookieStr){
		var ios = Components.classes["@mozilla.org/network/io-service;1"].getService(Components.interfaces.nsIIOService);
		var cookieUri = ios.newURI(location, null, null);
		var cookieSvc = Components.classes["@mozilla.org/cookieService;1"].getService(Components.interfaces.nsICookieService);
		cookieSvc.setCookieString(cookieUri, null, cookieStr, null);
    },
	switchExtendedControl : function(){
		if (window.innerWidth < this.popupMenuWidth){
			var panel = document.getElementById("control-panel");
			var extButton = document.getElementById("ext-button");
			if (extButton.getAttribute("extended") == "true"){
				this.__proto__.switchExtendedControl.apply(this);
			}
			panel.openPopup(extButton,"after_end",0,0,true,false);
		} else {
			this.__proto__.switchExtendedControl.apply(this);
		}
	},
	
	//dock handling
	/*	showMenu : function(ev){
		var buttonBox = document.getElementById("panel-button-box");
		buttonBox.style.display="block";
	},
	hideMenu : function(ev){
		var buttonBox = document.getElementById("panel-button-box");
		buttonBox.style.display="none";
	},
	showControl : function(show){
		var control = document.getElementById("control-panel");
		var windowBox = document.getElementById("widget-box");
		if (show){
			control.openPopup(windowBox,"after_end",-5,-40,false,true);
		} else {
			control.hidePopup();
		}
	},
	switchMenu : function(ev){
		var menuShow = document.getElementById("detail-menu").getAttribute('checkState');
		var browser = document.getElementById("player_browser");
		var buttonBox = document.getElementById("panel-button-box");
		if (menuShow != '1'){
			buttonBox.style.display="block";
		} else {
			buttonBox.style.display="none";
		}
	},*/
};
    
window.addEventListener("load", function() {
	widget.init();
}, false);

window.addEventListener("resize",function() {
	if (!widget) {return;}
	var extButton = document.getElementById("ext-button");
	if (extButton.getAttribute("extended") == "true"){
		if (window.innerWidth < widget.popupMenuWidth){
			var extButtonBox = document.getElementById("extended-button-box");
			extButton.setAttribute("extended","false");
			extButtonBox.style.display = "none";
		}
	}
},true);
