//公共方法
var PerformConfig ={Max:6};

var SelectMenu = function(item, obj)
{
	//var items = ['stock', 'fund'];
	jQuery("#js_menu_ul li a").removeClass("current");
	jQuery("#my_stock_list, #my_fund_list").hide();
	if(item == 'fund')
	{
		//获取我的基金的Cookie
		FundPerform.init();
		hq.get();
	}
	jQuery("#my_"+item+"_list").show();
	jQuery(obj).addClass("current");	
}

var deleteCookie = function(Key, code)
{
	var cstr = Cookie.get(Key);
	if(cstr != "")
	{
		data = cstr.split(",");
	}
	else
	{
		data = [];
	}
	var index = -1;
	for(var i = 0,len = data.length; i < len; i++)
	{
		var item = data[i];
		if(data[i] == code){
			index = i;
			break;
		}
	}

	if(index > -1)
	{
		data.splice(index,1);
		Cookie.set(Key,data);
	}
}

var addCookie = function(Key, code)
{
	var cstr = Cookie.get(Key);
	var value = code;
	var name = (Key == "fund")? "基金" : "股票";
	var back = 0;
	
	if(cstr != "")
	{
		data = cstr.split(",");
	}
	else
	{
		data = [];
	}
	for (var i = 0; i < data.length; i++)
	{
		if (data[i] == value)
		{
			alert("您已经添加过此"+name+"。");
			return back;
		}
	}
	if(data.length > PerformConfig.Max)
	{
		document.getElementById("keyword").blur();
		alert("对不起，最多只能添加" + (PerformConfig.Max +1)+ "个"+name+"，请您删除现有的"+name+"再添加！");
		return back;
	}
	
	back = 1;
	data.push(value);
	Cookie.set(Key,data);
	return back;
}

var doAdd = function()
{
	var code = document.finance_search.select_code.value;
	var key = document.finance_search.select_type.value;

	if(code.length <= 0)
	{
		alert("请选择您的股票或基金!");
		return;
	}
	if(key == 'stock')
	{
		StockPerform.getOne(code);
	}
	else if(key == 'fund')
	{
		FundPerform.getOne(code);
	}
}

var Cookie={
	set:function(name,value,expires,path,domain){
		if(typeof expires=="undefined"){
			expires=new Date(new Date().getTime()+1000*3600*24*365);
		}
		document.cookie=name+"="+escape(value)+((expires)?"; expires="+expires.toGMTString():"")+((path)?"; path="+path:"; path=/")+((domain)?";domain="+domain:"");
	},
	get:function(name){
		var arr=document.cookie.match(new RegExp("(^| )"+name+"=([^;]*)(;|$)"));
		if(arr!=null){
			return unescape(arr[2]);
		}
		return "";
	},
	clear:function(name,path,domain){
		if(this.get(name)){
		document.cookie=name+"="+((path)?"; path="+path:"; path=/")+((domain)?"; domain="+domain:"")+";expires=Fri, 02-Jan-1970 00:00:00 GMT";
		}
	}
}

var stock_list = {"default_list" : ["sh601398", "sh600030", "sz000002", "sh600547", "sh601857"], "list" : [], "quote_list" : ""};
var fund_list = {"default_list" : ["of000001", "of000021", "of162204", "sz162703", "of260104"], "list" : [], "quote_list" : ""};
var zs_list = {"default_list" : ["sh000001", "sz399001", "hf_GC", "hf_CL"], "quote_list" : ""};

	
var hq_interval = null;

var hq = {
	init : function()
	{
		//获取我的股票的Cookie
		StockPerform.init();
				
		//获取我的基金的Cookie
		//FundPerform.init();
				
		//指数板块
		zs_list["quote_list"] = zs_list["default_list"].join(",")+",";
	},
	
	get : function()
	{
		hq.init();
		jQuery.getScript("http://quote.finance.china.cn/get.php?l="+stock_list["quote_list"]+fund_list["quote_list"]+zs_list["quote_list"]+"&f=json&e=hq.show();&r="+Math.random());		
	},
	
	show : function()
	{
		//显示我的股票
		StockPerform.show();
		
		//显示我的基金
		if(fund_list["quote_list"] != "")
		{
			FundPerform.show();
			fund_list["quote_list"] = "";
		}
			
		//显示指数板块
		var zs_result = {};
		for(var i in zs_list["default_list"])
		{
			zs_result[zs_list["default_list"][i]] = json_q[zs_list["default_list"][i]];
		}
		BoardShowed.show(zs_result);
	},

	start : function()
	{
		hq_interval = window.setInterval("hq.get()", 6000);	
	},
	
	stop : function()
	{
		window.clearInterval(hq_interval);
	}
}


//股票
var StockPerform = {
	prev_list : {},
	name_list : {},
	
	init : function()
	{
		//获取我的股票的Cookie
 		var data = "";
 		
		if(!Cookie.get("finance_stock"))
		{
			var old_data = Cookie.get("stock");
			Cookie.set("finance_stock", old_data.split(","));
		}
		
		if(Cookie.get("finance_stock"))
		{
			stock_list["list"] = [];
			var cookie_stock_list = Cookie.get("finance_stock").split(",");
			for(var s in cookie_stock_list)
			{
				stock_list["list"][s] = cookie_stock_list[s];
			}
		}
		else
		{
			stock_list["list"] = stock_list["default_list"];
			Cookie.set("finance_stock",stock_list["default_list"]);
		}
		this.format_data();
	},
	
	format_data : function()
	{
		var stock_names_code = [];
		for(var i in stock_list["list"])
		{
			stock_names_code[i] = stock_list["list"][i];
		}
		for(var j in stock_list["list"])
		{
			if(this.name_list[stock_list["list"][j]] == null)
			{
				stock_names_code.push("n_"+stock_list["list"][j]);
			}
		}
		stock_list["quote_list"] = stock_names_code.join(",")+",";		
	},
	
	show : function()
	{		
		if(!isNaN(parseFloat(json_q[stock_list["list"][0]][0]).toFixed(2)))
		{
		//当前价与上一次当前价比较
		var current_list = {};
		for(var i in stock_list["list"])
		{
			current_list[stock_list["list"][i]] = parseFloat(json_q[stock_list["list"][i]][0]).toFixed(2);
		}
		var order_list = {};
		for(var item in current_list)
		{
			if(this.prev_list[item] != "undefined")
			{
				order_list[item] = (current_list[item] - this.prev_list[item] > 0) ? "↑" : ((current_list[item] - this.prev_list[item] < 0) ? "↓" : "");
			}
			else
			{
				order_list[item] = "";
			}
		}
		this.prev_list = current_list;
		
		//显示我的股票
		var stock_box = document.getElementById("my_stock_list");
		var stock_html = '<table id="my_stock" cellspacing="1" cellpadding="0" border="0" width="100%">';
		stock_html +='<tr class="tl"><th scope="col" width="">我的自选股</th><th scope="col" width="80">当前价</th><th scope="col">涨跌幅</th><th scope="col">涨跌额</th><th scope="col">昨收</th><th scope="col">今开</th><th scope="col">成交量</th><th scope="col">删除</th></tr>';

		for(var s in stock_list["list"])
		{
			//获取相应股票名称
			if(this.name_list[stock_list["list"][s]] == null)
			{
				this.name_list[stock_list["list"][s]] = json_q["n_"+stock_list["list"][s]];
			}
			
			var cssText_1 = cssText_2 = cssText_3 = '';
				
			cssText_1 = (json_q[stock_list["list"][s]][2] > 0) ? "red" : "green";
			if(json_q[stock_list["list"][s]][0] - json_q[stock_list["list"][s]][1] == 0)
			{
				cssText_1 = '';
			}
				
			if(json_q[stock_list["list"][s]][4] > json_q[stock_list["list"][s]][1])
			{
				cssText_2 = 'red';
			}
			else if(json_q[stock_list["list"][s]][4] < json_q[stock_list["list"][s]][1])
			{
				cssText_2 = 'green';
			}
			else
			{
				cssText_2 = '';
			}

			stock_html += '<tr id="'+stock_list["list"][s]+'"><Td><a href="http://finance.china.com.cn/stock/quote/'+stock_list["list"][s]+'/" target="_blank">'+this.name_list[stock_list["list"][s]]+'</a></td>';	//名称
			stock_html += '<td class="'+cssText_1+'" style="text-align:right;">'+order_list[stock_list["list"][s]]+parseFloat(json_q[stock_list["list"][s]][0]).toFixed(2)+'</td>';	//当前价
			stock_html += '<td class="'+cssText_1+'" style="text-align:right;">'+parseFloat(json_q[stock_list["list"][s]][3]).toFixed(2)+'%</td>';	//涨跌幅
			stock_html += '<td class="'+cssText_1+'" style="text-align:right;">'+parseFloat(json_q[stock_list["list"][s]][2]).toFixed(2)+'</td>';	//涨跌额
			stock_html += '<td style="text-align:right;">'+parseFloat(json_q[stock_list["list"][s]][1]).toFixed(2)+'</td>';	//昨收 
			stock_html += '<td class="'+cssText_2+'" style="text-align:right;">'+parseFloat(json_q[stock_list["list"][s]][4]).toFixed(2)+'</td>';	//今开
			stock_html += '<td style="text-align:right;">'+parseInt(json_q[stock_list["list"][s]][9]/100)+'手</td>';	//成交量
			stock_html += '<td><a href="javascript:StockPerform.del(&quot;'+stock_list["list"][s]+'&quot;);"><img alt="删除" src="images/delete_s.gif"/></a></td></td></tr>';	 //删除	
		}
		stock_html += '</table>';
		stock_box.innerHTML = stock_html;
		}
	},
	
	del : function(id)
	{
		//停止定时执行
		hq.stop();
		
		//移出对应行并删除cookie
		jQuery("#"+id).remove();
		deleteCookie('finance_stock', id);
		
		//删除name_list中相应code的名称
		delete this.name_list[id];
		
		//开启定时执行
		hq.get();
		hq.start();
	},

	getOne : function(code)
	{
		//将code添加到cookie
		var status = addCookie('finance_stock', code);
		if(status == 1)
		{
			SelectMenu('stock', jQuery("#js_mystock_menu"));
			//停止定时执行
			hq.stop();
			//将code添加到name_list,并设值为null
			this.name_list[code] = null;
			
			//启动定时执行
			hq.get();
			hq.start();
		}
	}
}

//基金
var FundPerform = {
	
	init : function()
	{
		//获取我的基金的Cookie
 		var data = "";
 		
		if(!Cookie.get("finance_fund"))
		{
			var old_data = Cookie.get("fund");
			old_data = old_data.replace(/fu_/g, "of");
			Cookie.set("finance_fund", old_data.split(","));
		}

		if(Cookie.get("finance_fund"))
		{
			fund_list["list"] = [];
			var cookie_fund_list = Cookie.get("finance_fund").split(",");
			for(var f in cookie_fund_list)
			{
				fund_list["list"][f] = cookie_fund_list[f];
			}
		}
		else
		{
			for(var i in fund_list["default_list"])
			{
				fund_list["list"][i] = fund_list["default_list"][i];
			}
			Cookie.set("finance_fund",fund_list["default_list"]);
		}
		this.format_data();
	},
	
	format_data : function()
	{
		var fund_names_code = [];
		for(var i in fund_list["list"])
		{
			fund_names_code[i] = "nv_"+fund_list["list"][i];
		}
		for(var j in fund_list["list"])
		{
			fund_names_code.push("n_"+fund_list["list"][j]);
		}
		fund_list["quote_list"] = fund_names_code.join(",")+",";	
	},
	
	show : function()
	{
		if(!isNaN(parseFloat(json_q["nv_"+fund_list["list"][0]][0]).toFixed(4)))
		{
		//显示我的基金
		var fund_box = document.getElementById("my_fund_list");
		var fund_html = '<table id="my_fund" cellspacing="1" cellpadding="0" border="0" width="100%">';
		fund_html +='<tr class="tl"><th scope="col">基金名称</th><th scope="col">基金代码</th><th scope="col">单位净值</th><th scope="col">净值涨跌</th><th scope="col">净值增长率</th><th scope="col">净值日期</th><th scope="col">删除</th></tr>';

		for(var f in fund_list["list"])
		{
			var cssText = (json_q["nv_"+fund_list["list"][f]][3] < 0)? "green" : "red";	

			fund_html += '<tr id="'+fund_list["list"][f]+'"><Td><a href="http://finance.china.com.cn/money/fund/quote/'+fund_list["list"][f]+'/" target="_blank">'+json_q["n_"+fund_list["list"][f]]+'</a></td>';	//基金名称
			fund_html += '<td><a href="http://finance.china.com.cn/money/fund/quote/'+fund_list["list"][f]+'/" target="_blank">'+fund_list["list"][f].substring(2, fund_list["list"][f].length)+'</a></td>';	//基金代码
			fund_html += '<td class="'+cssText+'" style="text-align:right;">'+parseFloat(json_q["nv_"+fund_list["list"][f]][0]).toFixed(4)+'</td>';	//单位净值
			fund_html += '<td class="'+cssText+'" style="text-align:right;">'+parseFloat(json_q["nv_"+fund_list["list"][f]][2]).toFixed(4)+'</td>';	//净值涨跌
			fund_html += '<td class="'+cssText+'" style="text-align:right;">'+json_q["nv_"+fund_list["list"][f]][3]+'%</td>';	//净值增长率 
				
			var hq_time = new Date(json_q["nv_"+fund_list["list"][f]][6]*1000);
			var month = (hq_time.getMonth()+1 < 10) ? "0"+(hq_time.getMonth()+1) : (hq_time.getMonth()+1);
			var day = (hq_time.getDate() < 10) ? "0"+(hq_time.getDate()) : (hq_time.getDate());
			fund_html += '<td>'+month+"-"+day+'</td>';	//净值日期
				
			fund_html += '<td><a href="javascript:FundPerform.del(&quot;'+fund_list["list"][f]+'&quot;);"><img alt="删除" src="images/delete_s.gif"/></a></td></td></tr>';	//删除	
		}
		fund_html += '</table>';
		fund_box.innerHTML = fund_html;
		}
	},
	
	del : function(id)
	{
		//停止定时执行
		hq.stop();
		
		//将相应的行移除并删除cookie
		jQuery("#"+id).remove();
		deleteCookie('finance_fund', id);
		
		//重新启动定时执行
		FundPerform.init();
		hq.get();
		hq.start();
	},

	getOne : function(code)
	{
		//将code添加到cookie
		var status = addCookie('finance_fund', code);
		if(status == 1)
		{
			SelectMenu('fund', jQuery("#js_myfund_menu"));
			//停止定时执行
			hq.stop();
			
			//重新启动定时执行
			FundPerform.init();
			hq.get();
			hq.start();
		}
	}
}


//左侧板块
var imgInterval = null;

var imgPathObj = {
	"sh000001":["上证指数", "http://chart.finance.china.cn/stock/small/114_sh000001.gif"],
	"sz399001":["深证成指", "http://chart.finance.china.cn/stock/small/114_sz399001.gif"],
	"hf_GC":["黄金", "http://image.finance.china.cn/chart/gold.gif"],
	"hf_CL":["原油", "http://image.finance.china.cn/chart/crude_oil.gif"]
};

var BoardDataSource = [
	{
		contentbox:document.getElementById("js_all_first"),
		params:["sh000001","sz399001","hf_GC","hf_CL"],
		img:"js_img_first",
		defaultimg:"sh000001"
	}
]

var base_date = "";

var BoardShowed = {
	ds : BoardDataSource[0],
	prev_list : {},
	
	change : function(key)
	{	
		var dlList = jQuery("#js_all_first dl");
		
		for(var i = 0, len = dlList.length; i < len; i++)
		{
			dlList[i].className = "";
		}
		
		for(var i = 0, len = BoardDataSource.length; i < len; i++)
		{
			var item = BoardDataSource[i];
			for(var j = 0, jlen = item.params.length; j < jlen; j++)
			{
				if((item.params[j]) == key)
				{
					item.defaultimg = key;
				}
			}
		}
		
		var jump_url = (key == 'hf_GC') ? "http://app.finance.china.com.cn/futures/list.php?exchange=HU&breed=AU" : ((key == "hf_CL") ? "http://app.finance.china.com.cn/futures/list.php?exchange=HU&breed=FU" : "http://finance.china.com.cn/stock/quote/"+this.ds.defaultimg+"/");
		
		jQuery("#"+this.ds.img).parent().attr({"href":jump_url,"target":"_blank"});
		jQuery("#"+this.ds.img).attr("src", imgPathObj[key][1]+"?"+Math.random());
		jQuery("#abc_"+key).addClass("current");
	},
		
	show : function(result)
	{	
		if(!isNaN(parseFloat(result[zs_list["default_list"][0]][0]).toFixed(2)))
		{
		//当前价与上一次当前价比较
		var current_list = {};
		for(var z in zs_list["default_list"])
		{
			current_list[zs_list["default_list"][z]] = parseFloat(result[zs_list["default_list"][z]][0]).toFixed(2);
		}
		var order_list = {};
		for(var item in current_list)
		{
			if(this.prev_list[item] != "undefined")
			{
				order_list[item] = (current_list[item] - this.prev_list[item] > 0) ? "↑" : ((current_list[item] - this.prev_list[item] < 0) ? "↓" : "");
			}
			else
			{
				order_list[item] = "";
			}
		}
		this.prev_list = current_list;
		
		var html = '';
		for(var i in zs_list["default_list"])
		{
			var item_class = '';
			var item = zs_list["default_list"][i];
			var jump_url = (item == 'hf_GC') ? "http://app.finance.china.com.cn/futures/list.php?exchange=HU&breed=AU" : ((item == "hf_CL") ? "http://app.finance.china.com.cn/futures/list.php?exchange=HU&breed=FU" : "http://finance.china.com.cn/stock/quote/"+item+"/");

			if(item == this.ds.defaultimg)
			{
				jQuery("#"+this.ds.img).parent().attr({"href":jump_url,"target":"_blank"});
				jQuery("#"+this.ds.img).attr("src", imgPathObj[this.ds.defaultimg][1]+"?"+Math.random());
				item_class = "current";
			}
			
			var kk = (i == 2 || i == 3) ? 1 : 3;
			var if_percent = (i == 2 || i == 3) ? "" : "%"; 
			
			var cssText = "color:#333";
			cssText = (result[item][kk] > 0) ? "color:red" : "color:green";
			html += '<dl class="'+item_class+'" id="abc_'+item+'">';
			html += '<dt><a href="javascript:BoardShowed.change(\''+item+'\');">'+imgPathObj[item][0]+'</a></dt>';
			html += '<dd style="text-align:right;"><a href="'+jump_url+'" target="_blank" style="'+cssText+'">'+order_list[item]+parseFloat(result[item][0]).toFixed(2)+'</a></dd>';
			html += '<dd style="text-align:right;"><a href="'+jump_url+'" target="_blank" style="'+cssText+'">'+parseFloat(result[item][kk]).toFixed(2)+if_percent+'</a></dd>';
			html += '</dl>';

			if(item == 'sh000001')
			{
				var hq_time = new Date(result[item][34]*1000);
				var year = hq_time.getFullYear();
				var month = (hq_time.getMonth()+1 < 10) ? "0"+(hq_time.getMonth()+1) : (hq_time.getMonth()+1);
				var day = (hq_time.getDate() < 10) ? "0"+(hq_time.getDate()) : (hq_time.getDate());
				
				jQuery("#update_time").text(year+"-"+month+"-"+day);
			}
		}
		jQuery(this.ds.contentbox).html(html);
		}
	}

	
}

