var searchHelper_url = {
	querys: [],
	get: function(key){
		if (this.querys.length == 0){
			var pairs = document.location.search.substring(1).split("&"), _this = this;
			pairs.forEach(function(item){
				var pair = item.split("=");
				_this.querys[pair[0]] = pair[1];
			});
		}
		return this.querys[key] ? this.querys[key] : '';
	}
};
var searchHelper_config = {
	options: [],
	small: {
		width: 54,
		height: 54,
		buttons: ['so'],
		html: null,
		scroll : 19,
		getHtml: function(){
			this.html = '<img id="searchHelper_so" src='+chrome.extension.getURL("img/so.png")+' />';
		}
	},
	big: {
		width: 183,
		height: 91,
		buttons: ['google', 'baidu', 'soso', 'sogou', 'taobao', 'a360buy', 'dang', 'amazon'],
		html: null,
		scroll : 19,
		getHtml: function(){
			this.html = '<table cellspacing=0 cellpadding=0 border=0><tr>';
			for (var i=0, btnLen = this.buttons.length; btn = this.buttons[i];){
				var style='line-height:90%;';
				if (i%4 !== 0)
					style += "border-left:#e4eefb 1px solid;";
				if (i < 4)
					style += "border-bottom:#e4eefb 1px solid;";
					
				this.html += '<td style="'+style+'"><img id="searchHelper_'+btn+'" src='+chrome.extension.getURL( "img/"+btn+".png" )+' /></td>';

				i++;
				if (i%4 == 0 && i < btnLen)
					this.html += '</tr><tr>';
			}
			this.html += '</tr></table>';
		}
	},
	urlRe: [
		{re:/http:\/\/www.google.com(.hk){0,1}\/#hl=zh-CN/i, name:'google', type:'search'},
		{re:/http:\/\/(www|images).google.com(.hk){0,1}\/search\?hl=zh-CN/i, name:'google', type:'image'},
		{re:/http:\/\/www.google.cn\/music\/search\?hl=zh-CN/i, name:'google', type:'mp3'},
		{re:/http:\/\/www.baidu.com\/s/i, name:'baidu', type:'search'},
		{re:/http:\/\/image.baidu.com\/i/i, name:'baidu', type:'image'},
		{re:/http:\/\/video.baidu.com\/v/i, name:'baidu', type:'video'},
		{re:/http:\/\/mp3.baidu.com\/m/i, name:'baidu', type:'mp3'},
		{re:/http:\/\/www.youdao.com\/search/i, name:'youdao', type:'search'},
		{re:/http:\/\/image.youdao.com\/search/i, name:'youdao', type:'image'},
		{re:/http:\/\/video.youdao.com\/search/i, name:'youdao', type:'video'},
		{re:/http:\/\/mp3.youdao.com\/search/i, name:'youdao', type:'mp3'},
		{re:/http:\/\/(cn|www).bing.com\/search/i, name:'bing', type:'search'},
		{re:/http:\/\/(cn|www).bing.com\/images\/search/i, name:'bing', type:'image'},
		{re:/http:\/\/(cn|www).bing.com\/videos\/search/i, name:'bing', type:'video'},
		{re:/http:\/\/www.gougou.com\/search/i, name:'gougou', type:'search'},
		{re:/http:\/\/pic.gougou.com\/search/i, name:'gougou', type:'image'},
		{re:/http:\/\/video.gougou.com\/search/i, name:'gougou', type:'video'},
		{re:/http:\/\/mp3.gougou.com\/search/i, name:'gougou', type:'mp3'},
		{re:/http:\/\/.*.taobao.com\/search/i, name:'taobao', type:'search'},
		{re:/http:\/\/www.sogou.com\//i, name:'sogou', type:'search'},
		{re:/http:\/\/mp3.sogou.com\/music/i, name:'sogou', type:'mp3'},
		{re:/http:\/\/pic.sogou.com\/pics/i, name:'sogou', type:'image'},
		{re:/http:\/\/v.sogou.com\/v/i, name:'sogou', type:'video'},
		{re:/http:\/\/search.360buy.com\/Search/i, name:'a360buy', type:'search'},
		{re:/http:\/\/search.dangdang.com\/search/i, name:'dang', type:'search'},
		{re:/http:\/\/www.amazon*.cn\/s/i, name:'amazon', type:'search'},
		{re:/http:\/\/www.amazon*.cn\/gp\/search/i, name:'amazon', type:'search'},		
		{re:/http:\/\/www.soso.com\/q/i, name:'soso', type:'search'},
		{re:/http:\/\/image.soso.com\/image.cgi/i, name:'soso', type:'image'},
		{re:/http:\/\/video.soso.com\/search/i, name:'soso', type:'video'},
		{re:/http:\/\/cgi.music.soso.com\/fcgi-bin\/m.q/i, name:'soso', type:'mp3'},		
	],
	targetUrl: {
		google_search:'http://www.google.com.hk/#hl=zh-CN&q=',
		google_image:'http://www.google.com.hk/search?hl=zh-CN&q=',
		google_mp3:'http://www.google.cn/music/search?hl=zh-CN&q=',
		google_video:'http://www.google.com.hk/search?hl=zh-CN&tbm=vid&q=',
		
		baidu_search:'http://www.baidu.com/s?tn=baidcom_dg&word=',
		baidu_image:'http://image.baidu.com/i?tn=baidcom_dg&word=',
		baidu_mp3:'http://mp3.baidu.com/m?tn=baidcom_dg&word=',
		baidu_video:'http://video.baidu.com/v?tn=baidcom_dg&word=',
		
		bing_search:'http://cn.bing.com/search?q=',
		bing_image:'http://cn.bing.com/images/search?q=',
		bing_video:'http://cn.bing.com/videos/search?q=',
		
		youdao_search:'http://www.youdao.com/search?q=',
		youdao_image:'http://image.youdao.com/search?q=',
		youdao_mp3:'http://mp3.youdao.com/search?q=',
		youdao_video:'http://video.youdao.com/search?q=',
		
		gougou_search:'http://www.gougou.com/search?search=',
		gougou_image:'http://pic.gougou.com/search?search=',
		gougou_mp3:'http://mp3.gougou.com/search?search=',
		gougou_video:'http://video.gougou.com/search?s=',

		sogou_search:'http://www.sogou.com/sogou?pid=sogou-site-155fa09596c7e18e&query=',
		sogou_image:'http://www.sogou.com/pics?pid=sogou-site-155fa09596c7e18e&query=',
		sogou_mp3:'http://www.sogou.com/music.so?pid=sogou-site-155fa09596c7e18e&query=',
		sogou_video:'http://www.sogou.com/v?pid=sogou-site-155fa09596c7e18e&query=',

		taobao_search:'http://s8.taobao.com/search?commend=all&pid=mm_14420296_2052106_9221063&q=',
		
		a360buy_search:'http://click.union.360buy.com/JdClick/?unionId=436&t=5&to=http://search.360buy.com/Search&keyword=',
		dang_search:'http://union.dangdang.com/transfer.php?from=P-280524&ad_type=10&sys_id=1&backurl=http://search.dangdang.com/search.php?key=',
		amazon_search:'http://www.amazon.cn/gp/search?ie=UTF8&tag=bd001-23&index=aps&linkCode=ur2&camp=536&creative=3200&keywords=',
		
        soso_search:'http://www.soso.com/q?unc=e400077&cid=union.s.wh&w=',
        soso_image:'http://image.soso.com/image.cgi?sc=img&ie=utf-8&unc=e400077&cid=union.s.wh&w=',
        soso_mp3:'http://music.soso.com/music.cgi?sc=mus&ie=utf-8&unc=e400077_sw4c &cid=union.s.wh&w=',
        soso_video:'http://video.soso.com/search/?unc=e400077_sw4c&cid=union.s.wh&w=',
	}
};
var searchHelper_main = {
	status: 'small',  //small or big
	wrapID: 'searchHelper_wrap',
	win: null,
	scroll: null,
	isScroll: false,
	isGetSearchType: false,
	siteName: null,
	searchType: null,
	searchKeyword: null,
	$:function(id){
		return document.getElementById(id);
	},
	rm: function(obj){
		obj && obj.parentNode && obj.parentNode.removeChild(obj);
	},
	getIsScroll: function(){
		this.isScroll = {
			Y: document.documentElement.clientHeight < document.documentElement.offsetHeight, 
			X: document.documentElement.scrollWidth > window.innerWidth
		};
	},
	getWin: function(){
		this.win = {height: window.innerHeight - 12, width: window.innerWidth - 10};
	},
	getScroll: function(){
		this.scroll = {top: document.body.scrollTop, left: document.body.scrollLeft};
	},
	computeRect: function(conf, arg){
		var w = h = null;
		if (arg != 'height'){
			w = conf.width + this.isScroll.Y * conf.scroll + (document.compatMode == 'BackCompat' || this.siteName == 'bing' || (this.siteName == 'taobao' && !this.isScroll.Y) ? conf.scroll : 0);
		}
		if (arg != 'width'){
			h = conf.height + this.isScroll.X * conf.scroll;
		}
		return {
			width: w,
			height: h
		};
	},
	init: function(){
		this.getSearchType();
		if (!this.isSearchEngine())
			return ;
		
		this.getIsScroll();
		this.getWin();
		this.getScroll();
		
		var conf = searchHelper_config[this.status],
			width = this.computeRect(conf, 'width').width,
			height = this.computeRect(conf, 'height').height,
			newWrap = document.createElement('div'), wrap, tableNodes;
		
		if (conf.html === null)
			conf.getHtml();

		newWrap.id = this.wrapID;
		newWrap.style.cssText = '-webkit-user-select:none;-webkit-box-shadow:3px 3px 3px #ccc;-webkit-border-radius:8px;background:-webkit-gradient(linear, 0 0, 0 100%, from(#deeeff), to(#c5d4f0));border:1px solid #a6b4cf;position:absolute;z-index:999999;width:'+ conf.width +'px;height:'+ conf.height +'px;left:'+ (this.win.width - width + this.scroll.left) +'px;top:'+ (this.win.height - height + this.scroll.top) +'px;';
		newWrap.innerHTML = conf.html;
		if (wrap = this.$(this.wrapID)){
			document.body.replaceChild(newWrap, wrap);
		}else{
			document.body.appendChild(newWrap);
		}
		
		if (this.status == 'big') {
			this.$('searchHelper_' + this.siteName).style[this.getBorderRadius(this.siteName)] = '8px';
			this.$('searchHelper_' + this.siteName).style.background = '-webkit-gradient(linear, 0 0, 0 100%, from(#7691C0), to(#deeeff))';
		}

		this.bindEvent();
        this.filterAD();
	},
	changeStatus: function(status){
		this.status = status;
		this.init();
	},
	htmlSpecialChars: function(str){
//		return str.replace(/%/g,'%25').replace(/#/g,'%23').replace(/&/g,'%26').replace(/'/g,'%27').replace(/@/g,'%40').replace(/\?/g,'%3F').replace(/=/g,'%3D').replace(/\+/g,'%2B').replace(/;/g,'%3B').replace(/\//g,'\/');
		return str;
	},
	getBorderRadius: function(siteName){
		var borderRadius = {
			'google':'webkitBorderTopLeftRadius',
			'sogou':'webkitBorderTopRightRadius',
			'taobao':'webkitBorderBottomLeftRadius',
			'amazon':'webkitBorderBottomRightRadius'
		};
		return (siteName in borderRadius) ? borderRadius[siteName] : '';
	},
	bindEvent: function(){
		function mouseover(){
			var borderRadius = (searchHelper_main.status == 'big') ? searchHelper_main.getBorderRadius(this.id.split('_').pop()) : 'webkitBorderRadius';
			this.style[borderRadius] = '8px';
			this.style.background = '-webkit-gradient(linear, 0 0, 0 100%, from(#d6e6fc), to(#aec2e6))';
			this.style.cursor = 'pointer';
		}
		
		function mouseout(){
			this.style.background = 'none';
			this.style.cursor = 'none';
		}
		
//		var so = searchHelper_main.$('searchHelper_so');
//		so.addEventListener('mouseover', mouseover, false);
//		so.addEventListener('mouseout', mouseout, false);
			
		if (searchHelper_main.status == 'small'){
			so.addEventListener('click', function(){
				searchHelper_main.changeStatus('big');
			}, false);
		}else{
//			so.addEventListener('click', function(){
//				searchHelper_main.changeStatus('small');
//			}, false);
			
			var _this = this;
			['google', 'baidu', 'soso', 'sogou', 'taobao', 'a360buy', 'dang','amazon'].forEach(function(item){
				if (item != _this.siteName) {
					var itemObj = searchHelper_main.$('searchHelper_' + item);
					itemObj.addEventListener('mouseup', function(e){
						var command = (e.button == 0) ? 'updateTab' : 'createTab';
						var searchType = item + '_' + _this.searchType, defaultSearchType = item + '_search', tUrl = searchHelper_config.targetUrl;
						
						
				switch(_this.siteName){
					case 'google':
						_this.searchKeyword = (document.getElementsByClassName('lst')[0] || _this.$('music_search_box')).value;
						break;
					case 'gougou':
						_this.searchKeyword = _this.$('s1').value;
						break;
					case 'youdao':
						_this.searchKeyword = _this.$('query').value;
						break;
					case 'bing':
						_this.searchKeyword = _this.$('sb_form_q').value;
						break;
					case 'baidu':
						_this.searchKeyword = (item.type == 'mp3') ? _this.$('ww').value : _this.$('kw').value;
						break;
					case 'taobao':
						_this.searchKeyword = _this.$('title').value;
						break;

					case 'sogou':
						_this.searchKeyword = _this.$('upquery').value;
						break;
					case 'dang':
						_this.searchKeyword = _this.$('key_S').value;
						break;
					case 'a360buy':
						_this.searchKeyword = _this.$('key').value;
						break;
					case 'amazon':
						_this.searchKeyword = _this.$('twotabsearchtextbox').value;
						break;
					case 'soso':
						if(item.type == 'search'){
							_this.searchKeyword = _this.$('smart_input').value;
						}else if(item.type == 'image'){
							_this.searchKeyword = _this.$('sb').value;
						}else if(item.type == 'video'){
							_this.searchKeyword = _this.$('s_input').value;
						}else if(item.type == 'mp3'){
							_this.searchKeyword = _this.$('search_input').value;
						}						break;
				}
						
						
						
						var t=_this.searchKeyword;
						switch(item){
							case 'google':
							case 'gougou':
							case 'youdao':
							case 'bing':
							case 'baidu':
							case 'sogou':
								break;
							case 'taobao':
							case 'dang':
							case 'a360buy':
							case 'amazon':
							case 'soso':
								t=UrlEncode(t);
								break;
						}
						url = (tUrl[searchType] ? tUrl[searchType] : tUrl[defaultSearchType]) + _this.htmlSpecialChars(t);

						connection = chrome.extension.connect();
						if (item == 'setting'){
							command = 'createTab';
							url = chrome.extension.getURL('options.html');
						}
						connection.postMessage({
							"action": 'createTab',
							"url": url,
						});
					}, false);
					itemObj.addEventListener('mousedown', function(e){
						// Disable Chrome auto-scroll feature
						if (e.button == 1) e.preventDefault();
					});
					
					itemObj.addEventListener('mouseover', mouseover, false);
					itemObj.addEventListener('mouseout', mouseout, false);
				}
			});
		}
	},
	getSearchType: function(){
		if (this.isGetSearchType)
			return;
		
		this.isGetSearchType = true;
		this.status = this.getStorage('status', 'small');
		this.status = (searchHelper_url.get('searchHelper_status') == 'big' || this.status == 'big') ? 'big' : 'small'; 
		this.status = 'big'; 
		var url = document.location.href, _this = this;
		searchHelper_config.urlRe.forEach(function(item){
			if (item.re.test(url)){
				_this.siteName = item.name;
				_this.searchType = item.type;
				
				if (item.name == 'google' && item.type == 'search' && searchHelper_url.get('tbs').split(',').indexOf('vid:1') != '-1'){
					_this.searchType = 'video';
				}
				
				switch(item.name){
					case 'google':
						_this.searchKeyword = (document.getElementsByClassName('lst')[0] || _this.$('music_search_box')).value;
						break;
					case 'gougou':
						_this.searchKeyword = _this.$('s1').value;
						break;
					case 'youdao':
						_this.searchKeyword = _this.$('query').value;
						break;
					case 'bing':
						_this.searchKeyword = _this.$('sb_form_q').value;
						break;
					case 'baidu':
						_this.searchKeyword = (item.type == 'mp3') ? _this.$('ww').value : _this.$('kw').value;
						break;
					case 'taobao':
						_this.searchKeyword = _this.$('title').value;
						break;

					case 'sogou':
						_this.searchKeyword = _this.$('upquery').value;
						break;
					case 'dang':
						_this.searchKeyword = _this.$('key_S').value;
						break;
					case 'a360buy':
						_this.searchKeyword = _this.$('key').value;
						break;
					case 'amazon':
						_this.searchKeyword = _this.$('twotabsearchtextbox').value;
						break;
					case 'soso':
						if(item.type == 'search'){
							_this.searchKeyword = _this.$('smart_input').value;
						}else if(item.type == 'image'){
							_this.searchKeyword = _this.$('sb').value;
						}else if(item.type == 'video'){
							_this.searchKeyword = _this.$('s_input').value;
						}else if(item.type == 'mp3'){
							_this.searchKeyword = _this.$('search_input').value;
						}
						break;
				}
				return ;
			}
		});
	},
	isSearchEngine: function(){
		return !!this.siteName && !!this.searchType;
	},
	filterAD: function(){
		//iframe广告会遮盖扩展，导致不能使用，所以移除该iframe
		if (this.siteName == 'baidu' && this.searchType == 'mp3'){
            this.rm(this.$('bd_asp_t5s'));
		}
	},
	getStorage: function(key, defaultValue){
		defaultValue = defaultValue ? defaultValue : '';
		return searchHelper_config.options[key] ? searchHelper_config.options[key] : defaultValue;
	},
	getOptions: function(){
		var connection = chrome.extension.connect();
		connection.postMessage({action:"getOptions"});
		connection.onMessage.addListener(function(msg, conn){
			searchHelper_config.options = msg.result;
		});
	}
};
searchHelper_main.getOptions();
setTimeout(function(){
	searchHelper_main.init();
	if (searchHelper_main.isSearchEngine()){
	
		window.addEventListener('resize', function(){
			searchHelper_main.getWin();
			searchHelper_main.getScroll();
			searchHelper_main.getIsScroll();
			
			var win = searchHelper_main.win, 
				scroll = searchHelper_main.scroll,
				conf = searchHelper_config[searchHelper_main.status], 
				width = searchHelper_main.computeRect(conf, 'width').width,
				height = searchHelper_main.computeRect(conf, 'height').height,
				wrap = document.getElementById(searchHelper_main.wrapID);
				
			wrap.style.top = win.height - height + scroll.top + 'px';
			wrap.style.left = win.width - width + scroll.left + 'px';
			
		}, false);
		
		document.addEventListener('scroll', function(){
			searchHelper_main.getScroll();
			searchHelper_main.getIsScroll();
			
			var win = searchHelper_main.win, 
				scroll = searchHelper_main.scroll,
				conf = searchHelper_config[searchHelper_main.status],
				width = searchHelper_main.computeRect(conf, 'width').width,
				height = searchHelper_main.computeRect(conf, 'height').height,
				wrap = document.getElementById(searchHelper_main.wrapID);
				
			wrap.style.top = win.height - height + scroll.top + 'px';
			wrap.style.left = win.width - width + scroll.left + 'px';
			
		}, false);
	}
},100);


