// 系统对象
var System = {
	Cache: {},
	Data: {}
};
System.Cache.history_info = toJSON(decodeURIComponent(getCookie("history_info") || '') || '{}');

$.extend(String.prototype, {
	// 格式化字符串
	format: function() {
		var temp = $A(arguments);
		return this.replace(/.?\{\d+\}/img, function(value) {
			if (value.indexOf('\\') == 0) return value.replace('\\', '');
			var index = value.match(/{(\d+)\}/)[1];
			return value.replace(/{(\d+)\}/, temp[index]);
		});
	},
	
	size: function() {
		var arr = this.split('');
		var re = /[^\x00-\xff]/;
		for (var i = 0, k = 0; k < arr.length; i++,k++) {
			if (re.test(arr[k])) i++;
		}
		return i;
	},
	
	truncate: function(length, truncation) {
		if (this.size() <= length) return this;
		length = length || 30;
		truncation = truncation === undefined ? '...' : truncation;
		var arr = this.split('');
		var result = '';
		var re = /[^\x00-\xff]/;
		for (var i = 0, k = 0; i < length - truncation.length && k < arr.length; i++,k++) {
			result += arr[k];
			if (re.test(arr[k])) i++;
		}
		return i >= length - truncation.length ?
		result + truncation : String(this);
	}
});

// 转数组
function $A(iterable) {
	if (!iterable) return [];
	else {
		var results = [];
		for (var i = 0, length = iterable.length; i < length; i++)
			results.push(iterable[i]);
		return results;
	}
}

// 搜索配置
var engineData = {
	"web":{
		"engine":{
			"baidu":{"url":"www.baidu.com/s","post":{"ie":"utf-8"},"var":"wd"},
			"google":{"url":"www.google.com.hk/search","post":{"hl":"zh-CN","oe":"utf8","channel":"searchbutton"},"var":"q"},
			"sogou":{"url":"www.google.com.hk/search","post":{"hl":"zh-CN","oe":"utf8","channel":"searchbutton"},"var":"q"}
		}
	},
	"movie":{
		"engine":{
			"gougou":{"url":"movie.gougou.com/search","post":{"id":"1"},"var":"search"}
		}
	},
	"music":{
		"engine":{
			"gougou":{"url":"mp3.gougou.com/search","post":{"id":"0"},"var":"search"}
		}
	},
	"news":{
		"engine":{
			"baidu":{"url":"news.baidu.com/ns","post":{"tn":"news","ie":"utf-8","cl":"2","rn":"20","ct":"1"},"var":"word"},
			"google":{"url":"news.google.com.hk/news/search","post":{"pz":"1","cf":"all","ned":"cn","hl":"zh-CN"},"var":"q"}
		}
	},
	"pics":{
		"engine":{
			"gougou":{"url":"pic.gougou.com/search","post":{"id":"10000001"},"var":"search"}
		}
	},
	"shop":{
		"engine":{
			"taobao":{"url":"search.taobao.com/search","post":{"commend":"all","isnew":"2","source":"search1","ie":"utf-8"},"var":"q"}
		}
	},
	"zhidao":{
		"engine":{
			"baidu":{"url":"zhidao.baidu.com/q","post":{"ct":"17","tn":"ikaslist"},"var":"word"}
		}
	}
};
System.Cache.engine = engineData.web.engine.baidu;

// 初始化
$(document).ready(function() {
	// 显示我的导航
	showcuky();
	// 选择邮箱
	$('#selectMail').click(function() {
		if ($('#mailBox').html() == '') {
			$('#mailBox').html('<iframe src="Themes/Default/_mail.html" width="961" height="174" marginwidth="0" marginheight="0" hspace="0" vspace="0" frameborder="0" scrolling="no"></iframe>');
		}
		$('#mailBox').toggle();
		return false;
	});
	$(document).click(function() {
		$('#mailBox').hide();
		return true;
	});
	// 点击统计
	$('#normal_tools a, #block0 a, .seven a, .fourline a').click(function() {
		clickCount($(this));
		return true;
	});
	// 搜索切换
	$('#search_radios_list input').click(function() {
		var searchEngine = $(this).attr('id').replace('search', '').toLowerCase();
		var img = $('#engine_img').attr('src').replace(/\w+\.png/i, searchEngine+'.png');
		$('#engine_img').attr('src', img);
		var tab = $('#stabs li.selected').attr('name');
		System.Cache.engine = engineData[tab].engine[searchEngine];
	});
	$('#stabs li').click(function() {
		$('#stabs li').removeClass('selected');
		$(this).addClass('selected');
		var tab = $(this).attr('name');
		searchTab(tab);
	});
	// 导航切换
	$('#tab_nav li').click(function() {
		$('#tab_nav li').removeClass('selected');
		$(this).addClass('selected');
		var show = $(this).attr('show');
		if ($('#'+show).html() == 'load') {
			$('#'+show).load('Themes/Default/_'+show+'.html?'+new Date().getTime())
		}
		$('#nav_blocks > div').hide();
		$('#'+show).show();
	});
	// 显示日期
	$('#date').html(getDateStr() + ' ' + getLunarDateStr(new Date()));
	// 显示标准时间
	$.get('/?action=getBaseTime&r'+new Date().getTime(), function(result) {
		var time = parseInt(result);
		setInterval(function() {
			time += 1000;
			showTimer(time);
		}, 1000);
	});
});

function clickCount(e) {
	var url = e.attr('href');
	if (url.indexOf('http') == 0) {
		var title = e.html();
		if (!System.Cache.history_info[title]) {
			System.Cache.history_info[title] = [url, 1];
		} else {
			System.Cache.history_info[title][1]++;
		}
		setCookie("history_info", encodeURIComponent(toStr(System.Cache.history_info)));
		showcuky();
		$.get("/?action=clickCount", {'url': url, 'title': title});
	}
}

function searchTab(tab) {
	$('#search_radios_list span').hide();
	var i = 0;
	for (var key in engineData[tab].engine) {
		i++;
		$('#'+key+'Radio').show();
		if (i == 1) {
			$('#'+key+'Radio input').click();
		}
	}
}

function getCookieVal(offset) {
	var endstr = document.cookie.indexOf(";",offset);
	if(endstr == -1){
		endstr = document.cookie.length;
	}
	return document.cookie.substring(offset, endstr);
}

function getCookie(name){
	var arg = name + "=";
	var alen = arg.length;
	var clen = document.cookie.length;
	var i = 0;
	while (i < clen) {
	var j = i + alen;
	if (document.cookie.substring(i,j) == arg) return getCookieVal (j);
	i = document.cookie.indexOf(" ", i) + 1;
	if (i == 0) break;
	}
	return null;
}

function setCookie(name,value) {
	var exp = new Date();
	exp.setTime (exp.getTime()+3600000000);
	document.cookie = name + "=" + value + "; expires=" + exp.toGMTString();
}

function toJSON(str){
	eval('var data = '+str+';');
	return data;
}

function toStr(object){
	var cooky = "";
	for (var key in object) {
		if (!object[key]) continue;
		cooky += '"'+key+'":["'+object[key][0]+'",'+object[key][1]+'],';
	}
	var aa = "{"+cooky.substring(0,cooky.length-1)+"}";
	return aa;
}

function toQueryStr(object) {
	var arr = [];
	for (var key in object) {
		arr.push(key+'='+encodeURI(object[key]));
	}
	return arr.join('&');
}

function delAll() {
	System.Cache.history_info = {};
	setCookie("history_info", "");
	showcuky();
}

function delSingle(title) {
	System.Cache.history_info[title] = null;
	setCookie("history_info", encodeURIComponent(toStr(System.Cache.history_info)));
	showcuky();
}

function showcuky() {
	var content = '';
	var data = System.Cache.history_info;
	var temp = [];
	for (var key in data) {
		if (!data[key]) continue;
		temp.push([key, data[key][0], data[key][1]]);
	}
	temp.sort(function(a,b) {
		return b[2] - a[2];
	});
	for (var i = 0; i < temp.length && i < 36; i++) {
		content += '<div class="style1conitem"><a title="'+temp[i][0]+'" href="'+temp[i][1]+'">'+temp[i][0].truncate(12, '')+'</a><a class="del" href="javascript:;" onclick="delSingle(\''+temp[i][0]+'\');return false;"></a></div>';
	}
	$('#history').html(content);
	$('#history a').click(function() {
		clickCount($(this));
		return true;
	});
}

function sub_search() {
	var obj = System.Cache.engine;
	var url = 'http://'+obj.url+'?'+toQueryStr(obj.post)+'&'+obj['var']+'=';
	var wd = $('#keyword').val();
	if (obj.url.indexOf('zhidao') == -1) {
		wd = encodeURIComponent(wd);
	}
	url = url + wd;
	window.open(url, "_blank")
	return false;
}

var bSearchData = {
	"baidu":"www.baidu.com/s?ie=utf-8&wd=",
	"google":"www.google.cn/search?sa=%CB%D1+%CB%F7&client=aff-9991&ie=utf8&oe=utf8&channel=searchbutton&q=",
	"qihoo":"www.qihoo.com/wenda.php?do=search&src=result_suggest&area=0&kw=",
	"book":"books.google.cn/books?q=",
	"music":"mp3.gougou.com/search?id=0&search=",
	"video":"video.gougou.com/search?id=0&s=",
	"movie":"movie.gougou.com/search?id=1&search=",
	"image":"image.baidu.com/i?ct=201326592&cl=2&lm=-1&tn=baiduimage&pv=&z=0&s=0&oq=zhuo&f=3&rsp=1&word=",
	"life":"shenghuo.google.cn/shenghuo/search?client=aff-avalanche&channel=searchbox&ie=gb2312&q=",
	"taobao":"search.taobao.com/search?commend=all&isnew=2&source=search1&q=",
	"dict":"www.nciku.com/search/all/",
	"map":"ditu.google.cn/maps?ie=gb2312&oe=UTF-8&hl=zh-CN&q=",
	"zhidao":"zhidao.baidu.com/q?&ct=17&pn=0&rn=10&tn=ikaslist&word=",
	"soft":"soft.gougou.com/search?restype=2&id=1&search="
};
function n_sch(){
	var wd = $('#bts_text').val();
	if (!wd) {
		alert("搜索值不能为空");
		return false;
	}
	var url;
	$('#rg input').each(function() {
		var e = $(this);
		if (e.attr('checked')) {
			var n = e.val();
			url = 'http://' + bSearchData[n];
			if (n != 'zhidao') {
				url += encodeURIComponent(wd);
			} else {
				url += wd;	
			}
		}
	});
	window.open(url, "_blank");
}

function setHome(obj, url) {
	obj.style.behavior = 'url(#default#homepage)';
	if(!obj.isHomePage(url)) {
		obj.sethomepage(url);
	}
}

function addBookmark(title, url){
	if (window.sidebar) {
		window.sidebar.addPanel(title, url, "");
	} else {
		if (document.all) {
			window.external.AddFavorite(url, title);
		} else {
			alert("浏览器不支持");
		}
	}
}
