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

var widget = {
	__proto__ : widgetbase,	//make this object 'extends' widgetbase
	isMovingContent : false,
	isMovingWindow : false,
	isResizing : false,
	moveStartPos : {x : 0,y : 0},
	defaultView : null,
	reloader : null,
	reloadInterval : 20000,
	titlebarMinWidth : 160,
	width : 300,
	height :300,
	heightWithPlaylist : 700,
	HISTORY_LENGTH : 10,
	
	logger: utils.logger('LM4.search'),

	init : function(){
		this.logger.trace("init");
		//in case this is opened manually
		var args = window.arguments[0];
		if (args.windowStates == null){
			args.windowStates = {
				windowLayer: 1
			};
		}
		if (args.widgetArgs == null){
			args.widgetArgs = {docked:false};
		}
		if (args.widgetArgs.docked == null){
			args.widgetArgs.docked = false;
		}
		this.__proto__.init.apply(this);
		this.args.startWithFirefox = 0;
		var contentBrowser = document.getElementById("player_browser");
		window.setTimeout(function(){
				if( !args.widgetArgs || !args.widgetArgs.data){
				//if no data, that means is not entered from drag, user open the search widget manually, that means we could set focus on the textbox, to wait for user input
					window.focus();
					var textbox = document.getElementById("favpart_textbox_search");
					textbox.focus();
				}
		},0);
		this.logger.trace("init done");
	},
	
	initBrowser : function (){
		if( this.args.widgetArgs && this.args.widgetArgs.data){
			this.doSearch(this.args.widgetArgs.data);
		}
		
		this.openLinkInTab();
		this.registerActivityHandler();
	},
	
	// register web acitivity handler.
	registerActivityHandler: function() {
		var self = this;
		function _handle(data) {
			self.doSearch(data.text);
		}
		AppIntent.registerHandler("app_search", _handle);
		window.addEventListener("unload", function() {
			AppIntent.unregisterHandler("app_search", _handle);
		}, false);
	},
	
	modifyState : function (){
		//this.logger.trace("tada");
		try {
			var browser = document.getElementById("player_browser");
			if (this.args.widgetArgs == null) this.args.widgetArgs = {};
			this.args.widgetArgs.width = browser.boxObject.width;
			this.args.widgetArgs.height = browser.boxObject.height;
			this.args.widgetArgs.data = "";
			this.__proto__.modifyState.apply(this);
		} catch (e){
			this.logger.trace(e.toString());
		}
	},
	getIcon : function(){
		return "chrome://livemargins/skin/search-icon.png";

	},
	doSearch : function(data){
		if (data == null || data == ""){
			window.focus();
			var textbox = document.getElementById("favpart_textbox_search");
			textbox.focus();
			return;
		}
		var browser = document.getElementById("player_browser");
		var request_uri = "resource://livemargins/apps/search/search.html?";
		var link = request_uri + encodeURIComponent(data);
		browser.setAttribute("src",link);
		this.addHistory(data);
		if (windowTools.minimized == true){
			windowTools.minimized = false;
		}
		var textbox = document.getElementById("favpart_textbox_search");
		textbox.value = data;
		window.focus();
	// handle dock
		dockable.hiding = false;
		dockable.showAndHideDockable();
	},
	switchSearchEngine : function(){
		var button = document.getElementById("favpart_search_button");
		var image = button.getAttribute("image");
		var textbox = document.getElementById("favpart_textbox_search");
		var data = textbox.value;
		if (image == "chrome://livemargins/skin/mozilla.png"){
			var browser = document.getElementById("player_browser");
			var request_uri = "http://www.google.cn/m/search?uipref=3&hl=zh-CN&q=";
			var link = request_uri + encodeURIComponent(data);
			browser.setAttribute("src",link);
			button.setAttribute("image","chrome://livemargins/skin/google.png");
		}else if (image == "chrome://livemargins/skin/google.png"){
			this.doSearch(data);
			button.setAttribute("image","chrome://livemargins/skin/mozilla.png");
		}
	},
	onTextEntered : function(){
		widget.LOG("onTextEntered");
		var textbox = document.getElementById("favpart_textbox_search");
		var textvalue = textbox.value;
		widget.doSearch(textvalue);
	},
	reportClick : function(link){
		var req = new XMLHttpRequest();  
		req.open('GET', 'http://www.g-fox.cn/livemargins/reportSearchLink.html?value='+encodeURIComponent(link), true);   
		req.send(null);  
	},
	addHistory : function(data){
		this.logger.trace("addHistory");
		if (this.args.widgetArgs == null){
			this.args.widgetArgs = {history:[]};
		}
		if (this.args.widgetArgs.history == null){
			this.args.widgetArgs.history = new Array();
		}
		var time = (new Date()).valueOf();
		var visited = false;
		for (var i = 0; i < this.args.widgetArgs.history.length; i++){
			if (this.args.widgetArgs.history[i].data.toLowerCase() == data.toLowerCase()){
				this.args.widgetArgs.history[i].time = time;
				visited = true;
				break;
			}
		}
		if (visited){
			this.args.widgetArgs.history.sort(function cmp(e1,e2){return e1.time - e2.time;});
		} else {
			this.args.widgetArgs.history.push({data:data,time:time});
		}
		while(this.args.widgetArgs.history.length > this.HISTORY_LENGTH){
			this.args.widgetArgs.history.shift();
		}
		this.rebuildHistoryMenu();
	},
	rebuildHistoryMenu : function(){
		this.logger.trace("rebuildHistoryMenu");
		if (this.args.widgetArgs == null) return;
		var hisMenu = document.getElementById("history-menupopup");
		while (hisMenu.hasChildNodes()){
			hisMenu.removeChild(hisMenu.childNodes[0]);
		}
		if (this.args.widgetArgs.history.length >0) {
			var strbundle = document.getElementById("livemarginsStrings");
			var clearStr = strbundle.getString("search.clearHistory");
			var menuItem = document.createElement("menuitem");
			menuItem.setAttribute("label",clearStr);
			menuItem.setAttribute("oncommand","widget.clearHistory();");
			hisMenu.appendChild(menuItem);
			var menuSep = document.createElement("menuseparator");
			hisMenu.appendChild(menuSep);
		}
		for (var i = 0; i < this.args.widgetArgs.history.length; i++){
			var menuItem = document.createElement("menuitem");
			menuItem.setAttribute("label",this.args.widgetArgs.history[i].data);
			menuItem.setAttribute("oncommand","widget.doSearch('"+this.args.widgetArgs.history[i].data+"');");
			hisMenu.appendChild(menuItem);
		}
	},
	clearHistory : function(){
		if (this.args.widgetArgs == null){
			this.args.widgetArgs = {history:[]};
		}
		this.args.widgetArgs.history = new Array();
		this.rebuildHistoryMenu();
	},
	closeSearch : function(force){
		var ontop = document.getElementById("ontop-button").getAttribute('ontop');
		if (force ){
			window.close();
		} else if (dockable.docked){
			if (dockable.docked){
				dockable.hiding = true;
				dockable.showAndHideDockable();
			}
			//no close
		}
		else if (ontop && ontop == "false"){
			//do nothing for now:)
		}
	},
};


//basic handling
window.addEventListener("load",function() {
	try {
		widget.init();
	} catch (e) {
		widget.logger.error(e);	
	}
}, false);

//drop handling
function onDrop(event){
	var data = event.dataTransfer.getData("text/plain");
	if (data != null || data !=""){
		widget.doSearch(data);
	}
	event.preventDefault();
}

//window.addEventListener("blur",function() {widget.closeSearch();},true);

window.addEventListener("load",function(){
	window.addEventListener("drop", onDrop, false);
	window.addEventListener("dragover", function(event){event.preventDefault();}, false);
	window.addEventListener("dragenter", function(event){event.preventDefault();}, false);
},false);


//dock handling
window.addEventListener("dockChanged",function(event) {
		if (dockable.docked == true){
			widget.LOG("search docked");
			widget.args.startWithFirefox = 1;
			if (windowTools.winowLayer == 2) {
				//widget.args.widgetArgs.userSetOnTop = true;
			} else {
				windowTools.windowLayer = 2;
			}
		} else {
			widget.args.startWithFirefox = 0;
			if (widget.args.widgetArgs.userSetOnTop){
				// do nothing
			} else {
				windowTools.windowLayer = 1;
			}
		}
	},true);
	
window.addEventListener("windowLayerChanged",function(event) {
		if (dockable.docked == false){
			if (windowTools.windowLayer == 2) {
				widget.args.widgetArgs.userSetOnTop = true;
			} else {
				widget.args.widgetArgs.userSetOnTop = false;
			}
		}
	},true);