/**
 * @author CHX
 * @namespace nhn.ToolTipTranslation
 * @version 090707
 */
// onmousedown="oTooltip.show(this, {title : this.innerHTML, text : '4'}, { position:'outside-top', align :'right' });"

nhn.ToolTipTranslation = $Class({
	$init: function(oArgs){
		this.option(oArgs);
		var _this = this;
		this.conf = oArgs;
		this.Tip = {         //Tip对象，保存提示层的元素及其状态
			$box: null,       //外层BOX
			parse: function(){
				if(!this.$box) return false;
				var _elBox = this.$box.$value();
				this.$bar_title = _this._getByClassName("tt_tip_title", _elBox)[0];//标题栏
				this.$btn_en = $Element(_this._getByClassName("tt_tip_btn_en", _elBox)[0]);//中译英按钮
				this.$btn_cn = $Element(_this._getByClassName("tt_tip_btn_cn", _elBox)[0]);//英译中按钮
				this.$btn_close = _this._getByClassName("tt_tip_btn_close", _elBox)[0];//关闭按钮
				this.$pane = _this._getByClassName("tt_tip_pane", _elBox)[0];//内容区
				this.ready = true;
			}
		};
		this.Btn = {};//Btn对象，保存工具按钮的元素及其状态
		
		//top note
		this.$topNote = jindo.$(this.conf.topNote);
		this.$topNote = jindo.$Element(this.$topNote);
		if(this.$topNote && !this.topNoteBlocked()){
			this.$topNoteBtnBlock = this._getByClassName(this.conf.ttTopNodeBtnBlock||"tt_note_btn_block", this.$topNote.$value())[0];
			this.$topNoteBtnClose = this._getByClassName(this.conf.ttTopNodeBtnClose||"tt_note_btn_close", this.$topNote.$value())[0];
			if(this.$topNoteBtnBlock) {
				$Fn(this.blockTopNote, this).attach(this.$topNoteBtnBlock, "click");
			}
			if(this.$topNoteBtnClose){
				$Fn(this.hideTopNote, this).attach(this.$topNoteBtnClose, "click");
			}
			setTimeout(function(){
				_this.showTopNote();
			}, 0);
			
			if(this.conf.noteDisplayTime > 0) {
				setTimeout(function(){
					_this.hideTopNote();
				}, this.conf.noteDisplayTime*1000);
			}
		} else{
			this.hideTopNote();
		}
		
		this.googleUrl = this.conf.url || "http://www.google.com/uds/Gtranslate";
		
		var _aBtnTrans = $A(this._getByClassName(oArgs.boxClass, document.body));//获取所有的BOX
		
		//*****获取BTN的模板
		this._getTPL("btn", function(tpl) {
			var _elTpl = null;//从模板获取到的BOX
			if(tpl){
				var _tmpBox = jindo.$Element(jindo.$("<div>"));
				var _elTpl = _tmpBox.html(tpl).first().$value();
				
			}
			_aBtnTrans.forEach(function(v, i, o) {
				var _elBtn = _this._getByClassName(oArgs.btnClass, v)[0];
				if(!_elBtn){//在BOX最后没有找到BTN时，采用模板中的BTN
					if (_elTpl) {
						_elBtn = _elTpl.cloneNode(true);
						v.appendChild(_elBtn);
					}
				}
				var _ttBtn = $Element(_elBtn);
				if(!_ttBtn) return;
//				_ttBtn.css("visibility", "hidden");
				$Fn(function(e){
					this._showTipButton(e, _ttBtn, v);
				}, _this).attach(v, "mouseover").attach(v, "mouseout").attach(_elBtn, "mouseover");
				$Fn(function(e) {
					_this._$targetBox = _ttBtn;//用于定位的目标
					_this._$targetBtn = _ttBtn;//当前的BTN
					var _tmpNode = $Element(this.cloneNode(true));
					_tmpNode.last().leave();
					var s = _tmpNode.text().replace(/\r?\n/ig, "<br />");
//					.replace(/\n+|\t+|\x20{2,}/g, " ").replace(/\x20{2,}/g, " ");//去除多余的空白字符
//					s = s.replace(/<img[^>]+>/ig, "").replace(/<([\w\d]+?)(?:[^>]+>(.*?)<\/\1>/ig, "$2");//去掉图片
					
					_tmpNode = null;
					e.stop();
					_this.translate(s);
				}, v).attach(_elBtn, "click");
			});
		});
		
		//*****获取TIP的模板
		this._getTPL("tip", function(tpl) {
			//优先获取页面内的BOX
			_this.Tip.$box = ("$tip" in oArgs && oArgs.$tip) ? jindo.$Element(oArgs.$tip) : null;
			if(!_this.Tip.$box) {
				if(tpl){
					var _tmpBox = jindo.$Element(jindo.$("<div>"));
					_this.Tip.$box = _tmpBox.html(tpl).first().appendTo(document.body);
				}
				
			}
			_this.Tip.$box.css({
				position: "absolute"
			});
			
			//初始化TIP
			_this.Tip.parse();
			
			//英译中
			$Fn(function(e){
				_this.translate(_this.lastWords, "en|zh");
				e.stop();
			}, _this.Tip.$btn_en).attach(_this.Tip.$btn_en.$value(), "click");
			
			//中译英
			$Fn(function(e){
				_this.translate(_this.lastWords, "zh|en");
				e.stop();
			}, _this.Tip.$btn_cn).attach(_this.Tip.$btn_cn.$value(), "click");
			
			//关闭
			$Fn(function(e){
				this.hideTip(e);
				e.stop();
			}, _this).attach(_this.Tip.$btn_close, "click");
			
			_this.Tip.$box.hide();
			
			//init drag
			new nhn.DragArea(document, {
				className : 'tt_tip_title',
				flowOut : true
			}).attach({
				'dragstart' : function(oEvent) {
					oEvent.element = _this.Tip.$box.$value();
				}
			});
			
			//关闭
			if(typeof _this.conf.hideEvent == "string"){
				var sEvent, oObj;
				if(/^outer_(click|mousedown|dblclick)$/.test(_this.conf.hideEvent)){
					sEvent = RegExp.$1;
					oObj = document;
				} else{
					sEvent = _this.conf.hideEvent;
					oObj = _this.Tip.$box.$value();
				}
				
				$Fn(function(e){
					e.stop();
				}, _this).attach(_this.Tip.$box.$value(), sEvent);
				
				$Fn(_this.hideTip, _this).attach(oObj, sEvent);
			}
		});
		this.scriptBox = document.body;//放置script的父元素
		
	},
	
	///////////////////////////////////
	
	_cache: {
		"zh|en": {},
		"en|zh": {}
	},
	_hasQueue: false,
	_queue: [],
	_tempResult: "",
	
	_closed: true,

	_callbackID: 100,
	
	//使note不再显示
	blockTopNote: function(){
		if(!this.$topNote) return;
		var _cookie = jindo.$Cookie();
		_cookie.set("TTT_note_blocked", "1", 365);
		this.hideTopNote();
	},
	hideTopNote: function(){
		if(!this.$topNote) return;
		this.$topNote.hide();
		this.fireEvent("onTopNoteHide", {});
	},
	topNoteBlocked: function(){
		var _cookie = jindo.$Cookie();
		return !_cookie.get("TTT_note_blocked") != "1";
	},
	showTopNote: function(){
		if(!this.$topNote) return;
		this.$topNote.show();
		
		this.fireEvent("onTopNoteShow", {});
	},
	
	_getByClassName: function(sClassName, oParent){

		return jindo.cssquery("." + sClassName, oParent);
	},
	
	_requestFromGoogle: function(url, oOpt, fnLoad) {

		this._script = jindo.$Element(jindo.$("<script>"));
		var _a = [];
		for (var p in oOpt) {
			_a.push(p + "=" + oOpt[p]);
		}
		this._script.appendTo(this.scriptBox).attr({
			type: "text/javascript",
			src: url + "?" + _a.join("&")
		});
		
	},
	
	/*_tplConf: {
		"tip": "/ttt_template/tip.html",
		"btn": "/ttt_template/btn.html"
	},*/
	requestCount: 0,
	
	//加载模板
	_getTPL: function(sName, callback) {
		if(!sName in this._tplConf) return;
		var aj =jindo.$Ajax(this._options[sName]||this._tplConf[sName], {
			type: "xhr",
			method: "get",
			onload: function(res){
				var _text = res.text();
				_text = _text.replace(/\r?\n+|\t+/g, "").replace(/\s{2,}/g, " ");
				_text = /(<\!\-\-\s?(?:template|tpl)\s?\-\->)(.*?)\1/img.test(_text) ? RegExp.$2 : _text;
				callback(_text);
			}
		}).request({r:Math.random().toString()});
		
	},
	
	//google.language.callbacks.id104('22',{"translatedText":"你好这是内容"}, 200, null, 200)
	_onLoad: function(iContext, oJSON, a, b, c) {
		
		if(this.transTimer) clearTimeout(this.transTimer);
		
		var s = oJSON.translatedText;
		try {
			this.scriptBox.removeChild(this._script.$value());
			delete google.language.callbacks["id" + (this._callbackID - 1)];
		} catch(e){}
		
		if(this._queue.length > 0&&this.requestCount < 9) {//限制请求的次数
			this._hasQueue = true;
			this._tempResult += s;
			var _this = this;
			setTimeout(function() {
				_this._request(_this._queue.shift());
			}, 180);
			
		} else {
			if (this._queue.length > 0) {
				this.loadUnComplete();
				return;
			}
			if(this._hasQueue) this._tempResult += s;
			this.showTip(this._tempResult||s);
			this._hasQueue = false;

			this._cache[this.transLang][this.lastWords] = this._tempResult||s;
			this._sWords = "";
			this._tempResult = "";
			this.requestCount = 0;
			this._queue.length = 0;
			this.fireEvent("onTransEnd", this._$targetBox, this._$targetBtn, this.Tip.$box);
		}
	},
	
	_createNameSpace: function(s, target) {
		var _aNames = s.split(".");
		var _o = window;
		$A(_aNames).forEach(function(v, i, o){
			if (!_o[v]) {
				_o[v] = (i == o.length - 1) ? target : {};
			}
			_o = _o[v];
		});
		return _o;
	},

	_cutRequest: function(s){
		var l = 0;
		var len = 200;
		if (s.length > len) {
			while (l < s.length) {
				this._queue.push(s.substring(l, l+len));
				l += len;
			}
			return this._queue.shift();
		}
		return s;
	},
	
	_request: function(sWords) {
		
		var _sCallback = "google.language.callbacks.id" + (this._callbackID++);
		this._sWords = sWords;
		var _this = this;
		this._createNameSpace(_sCallback, function() {
			_this._onLoad.apply(_this, arguments);
		});
		var _qString = encodeURIComponent(this._cutRequest(sWords));

		this._requestFromGoogle(this.googleUrl, {
			callback: _sCallback,
			context: 22,
			q: _qString,
			langpair: this.transLang,
			key: "notsupplied",
			v: "1.0"
		});
		
		this.transTimer = setTimeout(function() {
			if (_this._tempResult) {//超时但已有部分内容时， 显示已翻译的内容
				_this.loadUnComplete();
			} else {
				_this.timeout();
				_this.requestCount = 0;
			}
			
		}, this._options.transTimeout||5000);
		
		this.requestCount ++;
	},

	loadUnComplete: function() {
		this._queue.length = 0;
		var text = this._options["errLoadMsg_" + this.transLang.split("|")[1]];
		this._onLoad(0, {translatedText: text}, 0,0,0);
	},
		
	_timer_tipBtn: null,
	_MO_$lastBox: null,
	_showTipButton: function(e, theBtn, _theBox) {
		if(!this._closed) return;
		
		//如果没有内容，不显示BTN
		var _text = jindo.$Element(_theBox).text();
		_text = jindo.$S(_text).trim().toString();

		if(!_text) return;

		if(e.type == "mouseover"){
			if(this._timer_tipBtn && this._MO_$lastBox == _theBox) clearTimeout(this._timer_tipBtn);
			theBtn.show();
			this._MO_$lastBox = _theBox;
		} else{
			this._timer_tipBtn = setTimeout(function(){
				theBtn.hide();
			}, this.conf.btnHideDelay||500);
		}
		
//		theBtn.css("visibility", (e.type == "mouseover") ? "visible" : "hidden");
	},
	
	//翻译语言判断
	_getTransLang: function(sWords){
		var ua = navigator.userAgent.toLowerCase();
		
		var ul = (navigator.userLanguage || navigator.language || "").toLowerCase();
		
		return ul.indexOf("zh-cn") == -1 ? "zh|en" : "en|zh";
		
	},
	
	_getScrollPosition: function(){
		var left = document.documentElement.scrollLeft || document.body.scrollLeft;
		var top = document.documentElement.scrollTop || document.body.scrollTop;
		return {
			left: left,
			top: top
		};
	},
	
	_getPosition: function() {

		this.Tip.$box.show();
		var _tWidth = this._$targetBox.width();
		var _tHeight = this._$targetBox.height();
		var _width = this.Tip.$box.width();
		var _height = this.Tip.$box.height();
		var _tPosition = this._$targetBox.offset();

		var _clientSize = jindo.$Document(document).clientSize();
		var _scrollPosition = this._getScrollPosition();
		this.Tip.$box.hide();
		
		var _top = _left = 0;
		
		//top
		if ((_tPosition.top - _height - _scrollPosition.top) < 0) {
			_top = _tPosition.top + _tHeight;
		} else {
			_top = _tPosition.top - _height;
		}

		//left
		if((_tPosition.left + _width) > _clientSize.width){
			_left = _tPosition.left - _width + _tWidth;
		} else{
			_left = _tPosition.left;
		}
		
		return {
			top: _top,
			left: _left
		};
	},
	
	showTip: function(s) {

		this.Tip.$pane.innerHTML = s;
		var _$pane = this.Tip.$pane;

//		if(!this._closed) return;
		var _pos = this._getPosition();
		this.Tip.$box.css({
			top: _pos.top+"px",
			left: _pos.left+"px"
		});
		if (this.conf.tipShowTime > 0) {
			this.Tip.$box.appear(this.conf.tipShowTime || 0.3);
		} else {
			this.Tip.$box.show();
		}

		this._closed = false;
		this.fireEvent("tipShow", this._$targetBox, this._$targetBtn, this.Tip.$box);
	},
	
	hideTip: function(e) {
		if(this._closed) return;
		if (this.conf.tipHideTime > 0) {
			this.Tip.$box.disappear(this.conf.tipHideTime || 0.1);
		} else{
			this.Tip.$box.hide();
		}
		this._$targetBtn.hide();
		this._closed = true;

		this.fireEvent("tipHide", this._$targetBox, this._$targetBtn, this.Tip.$box);
	},
	
	translate: function(sWords, sLang) {
		if(!sWords) return;
		this.btnPosition = null;
		this.btnPosition = this._getPosition();
		
		this.showTip("loading...");
		
		if(this._queue.length>0) return;
		if(typeof sLang != "string" || !/^(en|cn|zh)\|(en|cn|zh)$/i.test(sLang)) {
			sLang = this._getTransLang();
			
		}
		
		if(sLang == "zh|en") {
			this.Tip.$btn_cn.addClass("on");
			this.Tip.$btn_en.removeClass("on");
		} else {
			this.Tip.$btn_en.addClass("on");
			this.Tip.$btn_cn.removeClass("on");
		}
		
		this.transLang = sLang;

		this.lastWords = sWords;
		!!this._cache[sLang][sWords] ? this.showTip(this._cache[sLang][sWords]) : this._request(sWords);
		
		this.fireEvent("onTransStart", this._$targetBox, this._$targetBtn, this.Tip.$box)
	},
	
	timeout: function() {
		this.scriptBox.removeChild(this._script.$value());
		delete google.language.callbacks["id" + (this._callbackID - 1)];
		this._queue.length = 0;
		this._hasQueue = false;
		this.showTip(this._options.transTimeoutMsg||"");
	}
}).extend(nhn.Component);


