﻿// 基金页面通用js

//格式化字符串(object类型参数不占用序号)
function formatString(txt){
	var str = arguments[0], index=0;
	for(var i=1; i<arguments.length; i++) {
		var obj = arguments[i];
		if(typeof(obj)=="object") {
			for(var key in obj){ str = str.replace(new RegExp("\\{"+key+"\\}","gm"), obj[key]); }
		}else{
			str = str.replace(new RegExp("\\{"+(index++)+"\\}","gm"), obj);
		}
	};
	return str;
}

//查找元素 options = {parent:"mytable", tag:"span", css:"", attr:"_quote_", attrValue:"price"};
function findElements(options){
	function get(obj) {return typeof(obj)=="string" ? document.getElementById(obj) : obj; }
	var css = options.css, attr = options.attr, val = options.attrValue, arr = [];
	var htmlcol = get(options.parent).getElementsByTagName(options.tag || "*");
	var regexp = new RegExp("(^|\\s)" + css + "(\\s|$)");
	for(var i=0; i<htmlcol.length; i++) {
		var obj = htmlcol[i];
		if(css && (obj.className!=css && !obj.className.match(regexp))) continue;
		if(attr && !val && !obj.getAttribute(attr)) continue;
		if(attr && val && obj.getAttribute(attr)!=val) continue;
		arr.push(obj);
	}
	return arr;
}

//提示信息（jQuery Only）
function showTip(jElem, text, timeout){
	var html = formatString("<div style='position:absolute;display:none;background:#FFFFE1; border:solid 1px #CCC';><span style='margin:4px 6px; display:block'>{0}</span></div>", text);
	var elem = jQuery(html).appendTo("body")
		.css("left", jElem.offset().left+24).css("top", jElem.offset().top-24)
		.fadeIn("fast");
	window.setTimeout(function(){
		elem.fadeOut("slow").remove();
	}, timeout);
}

// 有足够扩展性的cookie读写函数
// extcookie("PETER","李志威ABCD",{expires:30,/*30分钟*/ path:"/"}, encodeURIComponent);
// extcookie("PETER", decodeURIComponent);
var extcookie = function(name){
	//获取cookie值
	if(arguments.length==1 || arguments.length==2 && typeof(arguments[1])=="function"){
		var rs = new RegExp("(^|)"+name+"=([^;]*)(;|$)","gi").exec(document.cookie);
		return rs ? (arguments[1] || unescape)(rs[2]) : null;
	}else{ //否则设置Cookie值
		//同时设置多个域
		var options = typeof(arguments[2])=="object" ? arguments[2] : {};
		if(Object.prototype.toString.apply(options.domain) === '[object Array]'){
			var moptions = options;
			var result = [];
			for(var key in options){moptions[key]=options[key];}
			for(var i=0; i<options.domain.length; i++){
				moptions.domain = options.domain[i];
				//按域数组循环设置cookie并返回单个设置结果
				result.push(arguments.callee(name, arguments[1], moptions, arguments[3]));
			}
			return result;
		}
		var encode = typeof(arguments[2])=="object" ? (arguments[3] || escape) : (arguments[2] || escape);
		var str = name+"="+encode(arguments[1]);
		// 该值为分钟数或Date对象
		if(options.expires) {
			var date = null;
			if(typeof(options.expires)=="number"){date = new Date(); date.setMinutes(date.getMinutes()+options.expires);}
			else{date = options.expires;}
			str += ";expires="+date.toGMTString();
		}
		if(options.path) {str += ";path="+options.path;}
		if(options.domain) {str += ";domain="+options.domain;}
		if(options.secure) {str += ";secure";}
		document.cookie = str;
		return str;
	}
}

/*自选基金用户信息*/
var UserUtil = {
	userId:null,
	lastLoginTime:null,
	isLogin:false,
	init:function(){
		//登录信息
		var visitedInfo = extcookie("Fund_163_Inf");
		if(!visitedInfo){
			this.userId = null;
			this.isLogin = false;
			return;
		}
		var arr = visitedInfo.split("|");
		this.userId = arr[0];
		this.lastLoginTime = arr[1];
		this.isLogin = true;
	},
	initPanel : function(){
		if(this.isLogin){
			jQuery("#userPanel .t1").html("欢迎您："+this.userId);
			jQuery("#userPanel .t4").show();
		}
	},
	"logout":function(){
		var nnn = new Date();
		nnn.setYear(1978);
		document.cookie ='Fund_163_Inf=; MyAttetionalFundList=; expires='+ nnn.toGMTString() +'; path=/; domain=quotes.fund.163.com';
		document.location.href = 'http://money.163.com/fund/';
	},
	"initI": function(){
		UserID = '';
		dataSet = new Array(2);
		//0:登陆信息,'Fund_163_Inf'
		//1:自选股列表,'MyAttetionalFundList'
		//初始化
		dataSet[0]=UserCookie.getVisitedInf(2)+'|'+(new Date().toLocaleString());
		dataSet[1]=CookieUtil.getValue('MyAttetionalFundList');
	},
	"processDataSet": function(){
		var cv = '';
		for(var i=0;i<dataSet.length;i++){
			switch(i){
				case 0:
					cv+= 'Fund_163_Inf=';
					cv+= escape(dataSet[0]);
					cv+= '; ';
					break;
				case 1:
					cv+= 'MyAttetionalFundList=';
					cv+= escape(dataSet[1]);
					cv+= '; ';
					break;
				default:
			}
		}
		CookieUtil.creatCookie(cv,null);
	},
	"setVisitedInf": function(userID){
		UserID = userID;
		dataSet[0] = userID+'|'+(new Date().toLocaleString());
		UserCookie.processDataSet();
		CookieUtil.creatCookie('',null);
	},
	"setMyAttetionalFund": function(fundList){
		if(UserID==null || UserID== ''){
			alert('你尚未登陆,请登陆.');
			return;
		}
		dataSet[1] = fundList;
		UserCookie.processDataSet();
	},
	"getMyAttetionalFund": function(){
		return CookieUtil.getValue('MyAttetionalFundList');
	},
	"setMyAttentionalFundCodeList": function(fundCodeList) {
		if(fundCodeList) {
			extcookie("MyAttentionalFundCodeList",fundCodeList);
		}
	},
	"getMyAttentionalFundCodeList": function() {
		//竖线分隔的基金代码列表
		return CookieUtil.getCookie("MyAttentionalFundCodeList");
	}
}

/** 添加一只关注基金 */
function addAttentionalFund(code){
	var had = false;
	var fundArray = []; 
	var attentionalFund = jQuery.cookie("MyAttentionalFundCodeList");
	if(attentionalFund){
		fundArray = attentionalFund.split("|");
		if(fundArray){
			for(var i=0; i<fundArray.length; i++){
				if(code == fundArray[i]){
					had = true;
					break;
				}
			}
		}		
	}
	
	/* 添加到自选基金列表 */
	if(!had){
		fundArray.push(code);
		var arr = [];
		for(var i=0; i<fundArray.length; i++){
			if(fundArray[i].length == 6){
				arr.push(fundArray[i]);
			}
		}
		var codeList = arr.join("|");
		var attentionalFund = jQuery.cookie("MyAttentionalFundCodeList", codeList, {expires: 3650, path: '/'});
		// Ajax
		updateAttentional(arr);
	}
}

/** 删除一只关注基金 */
function removeAttentionalFund(code){
	var codeList = []; 	
	var attentionalFund = jQuery.cookie("MyAttentionalFundCodeList");
	if(attentionalFund){
		fundArray = attentionalFund.split("|");
		if(fundArray){
			for(var i=0; i<fundArray.length; i++){
				if(code != fundArray[i] && fundArray[i].length==6){
					codeList.push(fundArray[i]);
				}
			}
		}		
	}
	
	var value = codeList.join("|");
	jQuery.cookie("MyAttentionalFundCodeList", value, {expires: 3650, path: '/'});
	// Ajax
	updateAttentional(codeList);
}

/** 更新列表 */
function updateAttentional(fundArray){
	if(UserUtil.isLogin) {
		jQuery.getJSON(formatString("http://quotes.fund.163.com/ws/myattentionalfund.do?method=updateAttentionalFunds&param={0}&param={1}", UserUtil.userId, fundArray.join(",")),
				function(json){
					if(!json.success){
						if(typeof(console)!='undefined' && typeof(console.log)=='function'){
							console.log(json.msg);
						}
					}else{
						if(typeof(console)!='undefined'  && typeof(console.log)=='function'){
							console.log("success");
						}
					}
				});
	}
}

/** 在关注基金前的checkbox打钩 */
function checkAttentionalFunds() {
	var attentionalFund = jQuery.cookie("MyAttentionalFundCodeList");
	if(attentionalFund){
		var fundArray = attentionalFund.split("|");
		if(fundArray){
			for(var i=0; i<fundArray.length; i++){
				var selector = "input[@type=checkbox][value=" + fundArray[i] + "]";
				jQuery(selector).attr("checked", "checked");
			}
		}
	}
}


/** 显示我关注的基金 */
function showAttentionalFund(){
	jQuery("tr[code]").hide(); //先隐藏所有
	
	var attentionalFund = jQuery.cookie("MyAttentionalFundCodeList");
	if(attentionalFund){
		var fundArray = attentionalFund.split("|");
		if(fundArray){
			for(var i=0; i<fundArray.length; i++){
				var selector = "tr[code=" + fundArray[i] + "]";
				jQuery(selector).show();
			}
		}		
	}
	jQuery("#showAttentionalFundLabel").hide();
	jQuery("#showAllFundLabel").show();	
}

/** 显示所有基金 */
function showAllFund(){
	jQuery("tr[code]").show();
	
	jQuery("#showAllFundLabel").hide();	
	jQuery("#showAttentionalFundLabel").show();
}



/** 处理用户添加关注基金 */
function handleAttentionalFund(checkboxObj){
	var code = checkboxObj.value;
	if(!code){ return; }
	var chk = jQuery(checkboxObj);
	var row = chk.parents("tr[code="+code+"]");
	var name = row.find("td:eq(4)").text();
	if(checkboxObj.checked){
		/* 添加关注基金 */
		addAttentionalFund(code);
		showTip(chk, formatString("添加关注基金  {0}({1})", name, code), 2000);
	}else{
		/* 删除关注基金 */
		removeAttentionalFund(code);
		showTip(chk, formatString("删除关注基金  {0}({1})", name, code), 2000);
	}
}