﻿var App = {
	start: function() {
		App.FavoriteResults.initialize();
		App.VietTyping.initialize();
	}
};

App.FavoriteResults = {
	_favMngr: null,
	_containerEl: null,
	_statusEl: null,
	
	initialize: function() {
		this._containerEl = $("results-pane");
		if ($defined(this._containerEl)) {
			this._favMngr = new GM.Utils.FavoriteManager({maxEntries: GM.Consts.numFavoriteResults});
			this._favMngr.removeAll();
			
			this._statusEl = $E(".caption strong", "caption-bar");
			
			$E("a.deleteAll", this._containerEl).addEvent("click", this._deleteAll.bind(this));
			
			$ES("li", this._containerEl).each(function(el) {
				var fav = $E("a.title", el).href;
				
				this._favMngr.add(fav);
				
				$E("a.delete", el).addEvent("click", this._delete.bindWithEvent(this, fav));
			}, this);
			
			this._updateStatus();
		}
	},
	
	_deleteAll: function() {
		this._favMngr.removeAll();
		
		this._containerEl.replaceWith(new Element("div", {
			"id": "message-pane",
			"class": "pane"
		}).adopt(new Element("p").setText("Bạn đã xóa hết các kết quả ưa thích!")));
		
		this._updateStatus(0);
	},
	
	_delete: function(evt, fav) {
		if ($ES("li", this._containerEl).length > 1) {
			this._favMngr.remove(fav);
			
			evt.target.getParent().getParent().remove();
			
			this._updateStatus();
		}
		else
			this._deleteAll();
	},
	
	_updateStatus: function(count) {
		this._statusEl.setText(count || this._favMngr.count());
		
		return this;
	}
};

App.VietTyping = {
	_el: null,
	
	initialize: function() {
		this._el = $E("img.vietTyping", "top-search-box");
		if ($defined(this._el)) {
			this._el.addEvent("click", this._toggleOnOff.bind(this));
			
			var on = Cookie.get("AVIM_on_off");
			if (on && on.toInt())
				this._toggleOnOff();
		}
	},
	
	_toggleOnOff: function() {
		if (this._el.hasClass("on")) {
			AVIMObj.setMethod(-1);
			
			this._el.title = "Bật bộ gõ tiếng Việt";
		}
		else {
			AVIMObj.setMethod(0);
			
			this._el.title = "Tắt bộ gõ tiếng Việt";
		}
		
		this._el.toggleClass("on");
	}
};