var GetDataController = function(obj){
		var _DataSource = {};
		var _refashTime = 0;
		var _config = obj;
		var model = new Model("script","js_top_load_box");
		var url = "http://hq.sinajs.cn/rn="+model.stringMark+"&list=" + _config.params.toString();
		model.stringUrl = url;
		model.intInterval = _config.refash ?  -1 : 5000;
		model.processData = function () {
			_DataSource = {};
			for(var i = 0,len = _config.keys.length; i < len; i++){
				var item = _config.keys[i];
				if(window[item] == undefined){
					continue;
				}
				_DataSource[item] = window[item];
			}
			if(_refashTime < 5){
				_refashTime++;
			}
		}
		model.updateView = function () {
				if(_config.callback){
					_config.callback(_DataSource);
				}
			if(_refashTime >= 5){
				model.intInterval = 10000;
			}
		}
		model.start();
		
		this.ChangeData = function(params,keys){
			_config.params = params;
			_config.keys = keys;
			var url = "http://hq.sinajs.cn/rn="+model.stringMark+"&list=" + _config.params.toString();
			model.stringUrl = url;
			model.start();
		},
		this.Stop = function(){
			model.stop();
		}
	}
	var imgTime = new Date().getTime();
	var imgRefashTime = 1; /*图片更新时间间隔(分钟)*/
	var imgPathObj = {
		activeKey: "hq_str_s_sh000001",
		"hq_str_s_sh000001":"http://image.sinajs.cn/newchart/small/nsh000001.gif",
		"hq_str_s_sz399001":"http://image.sinajs.cn/newchart/small/nsz399001.gif",
		"hq_str_s_sh000300":"http://image.sinajs.cn/newchart/small/nsh000300.gif",
		"hq_str_b_NKY":"http://image.sinajs.cn/newchart/v5/forex/min5_m/NIXI.gif",
		"hq_str_hf_GC":"http://image.sinajs.cn/newchart/v5/futures/global/mins/GC.gif",
		"hq_str_hf_CL":"http://image.sinajs.cn/newchart/v5/futures/global/mins/CL.gif"
	};
	
	var ChangeImg = function(){
		
		function locaImg(_j, _k, _h) {
			var _l = typeof _j == "string" ? document.getElementById(_j) : _j;
			var _m = _l.cloneNode(true);
			_m._A = _l;
			_m._y = typeof _h != "undefined" ? _h: new Function();
			_m[document.all ? "onreadystatechange": "onload"] = function() {
				if (document.all && this.readyState != "loaded" && this.readyState != "complete") {
					return;
				}
				this._A.parentNode.replaceChild(this, this._A);
				_m._y(this);
				_m._y = null;
				this._A = null;
				this[document.all ? "onreadystatechange": "onload"] = null;
			};
			_m.src = _k;
		};
		
		locaImg("js_newchart_img", imgPathObj[imgPathObj.activeKey] + "?" + imgTime);
		//document.getElementById("js_newchart_img").src = imgPathObj[imgPathObj.activeKey] + "?" + imgTime;
	}
	
	var ChangeImgKey = function(key){
		imgPathObj.activeKey = key;
		ChangeImg();
	}
	
	var pageInit = function(){
		GetDataController({
			params:["s_sh000001","s_sz399001","s_sh000300","b_NKY","hf_GC","hf_CL","sh000001"],
			keys:["hq_str_s_sh000001","hq_str_s_sz399001","hq_str_s_sh000300","hq_str_hf_GC","hq_str_hf_CL","hq_str_sh000001"],
			callback: function(result){
				var box = document.getElementById("js_top_datatable");
				var html = "";
				var nowTime = new Date().getTime();
				if((imgTime + 1000 * 60 * imgRefashTime) < nowTime){
					imgTime = nowTime;
					ChangeImg();
				}
				for(var item in result){
					var objItem = result[item].split(",");
					var up1 = Number(objItem[2]).toFixed(2),up2 = objItem[3];
					if(up1>0){
						up1 = (Number(objItem[2]) > 0? "+" : "")+up1;
						up2 = (Number(objItem[3]) > 0? "+" : "")+up2;
					}else if(up1==0){
						up1="-";
						up2="-";
					}
					
					if(item != "hq_str_hf_GC" && item != "hq_str_hf_CL" && item !="hq_str_sh000001"){
						html += "<dl>";
						html += '<dt><a href="javascript://" onclick="ChangeImgKey(\''+item+'\');">'+objItem[0]+'</a></dt>';
						html += '<dd class="'+(Number(objItem[2]) > 0? "red" : "green")+'">'+ Number(objItem[1]).toFixed(2) +'</dd>';
						html += '<dd class="'+(Number(objItem[2]) > 0? "red" : "green")+'">'+ up1 +"</dd>";
						html += '<dd class="'+(Number(objItem[3]) > 0? "red" : "green")+'">'+ up2 +"%</dd>";
						html += "</dl>";
					}
					else if(item == "hq_str_hf_GC"){
						var nu3 = (objItem[1]/objItem[0]*100).toFixed(2);
						var lh = "";
						if(objItem[7] > objItem[0]){
							lh = "-";
						}else if(objItem[7] < objItem[0]){
							lh= "+";
						}

						var cssText = lh=="+"?"red":"green";
						
						html += '<dl id="listdl3">';
						html += '<dt><a href="javascript://" onclick="ChangeImgKey(\''+item+'\');">黄金</a></dt>';
						html += '<dd class="'+cssText+'">'+ Number(objItem[0]).toFixed(2) +"</dd>";
						html += '<dd class="'+cssText+'">'+ lh + Number(objItem[1]).toFixed(2) +"</dd>";
						html += '<dd class="'+cssText+'">'+ lh + nu3 + "%</dd>";
						html += "</dl>";
					}
					else if(item == "hq_str_hf_CL"){
						var nu3 = (objItem[1]/objItem[0]*100).toFixed(2);
						var l = "";
						if(objItem[7] > objItem[0]){
							l = "-";
						}else if(objItem[7] < objItem[0]){
							l= "+";
						}
						var cssText = l=="+"?"red":"green";
						
						html += '<dl id="listdl4">';
						html += '<dt><a href="javascript://" onclick="ChangeImgKey(\''+item+'\');">原油</a></dt>';
						html += '<dd class="'+cssText+'">'+ Number(objItem[0]).toFixed(2) +"</dd>";
						html += '<dd class="'+cssText+'">'+ l + Number(objItem[1]).toFixed(2) +"</dd>";
						html += '<dd class="'+cssText+'">'+ l + nu3 + "%</dd>";
						html += "</dl>";
					}else if(item=="hq_str_sh000001"){
						document.getElementById("update_time").innerHTML = objItem[objItem.length-2]+" 数据";
					}
				}
				box.innerHTML = "";
				box.innerHTML = html;
				
			}
		});
	}
	
	pageInit();
	
	var Cookie={
		set:function(name,value,expires,path,domain){
			if(typeof expires=="undefined"){
				expires=new Date(new Date().getTime()+1000*3600*24*30);
			}
			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 searchController;
	var getCustomData =function(p,newobj){
		
		var k =[];
		for(var i =0,len =p.length;i<len;++i){
			var k_item = "hq_str_"+p[i];
			k.push(k_item);
		}
		if(newobj){
			if(searchController){
				searchController.Stop();
			}
			searchController = undefined;
		}
		
		if(searchController == undefined){
			if(k.length > 0){
			searchController = new GetDataController({
					params:p,
					keys:k,
					callback: function(result){
							
							var box = document.getElementById("my_stock_list");
							box.innerHTML = "";
							var html = "";
							html += '<table id="my_stock" cellspacing="1" cellpadding="0" border="0" width="100%">';
							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><th scope="col">买入/卖出价</th><th scope="col">删除</th></tr>';
							
							for(var item in result){
								if(result[item] != ""){
									var objItem = result[item].split(",");
									var upValue = (objItem[3] - objItem[2]);
                                    var upPsn = (upValue/Number(objItem[2]) * 100).toFixed(2);
									var t = upValue > 0 ? "red":"green";
									if(upValue == 0){
										t = "";
									}
									var t2 = "",t3 = "", t4 = "",t5 = "";;
									if(objItem[1]>objItem[2]){
										t2 ="green",t3 = "red";
									}else if(objItem[1]<objItem[2]){
										t3 ="green",t2 = "red";
									}
									if(objItem[7]>objItem[6]){
										t4 ="green",t5 = "red";
									}else if(objItem[7]<objItem[6]){
										t5 ="green",t4 = "red";
									}
									
									html+='<tr><td class="name"><a title="点击查看详情" href="http://finance.sina.com.cn/realstock/company/'+item.substr(7,8)+'/nc.shtml" target="_blank">'+objItem[0]+'</a></td>'; //名称									
									html+='<td class="'+t+'">'+((objItem[3]==0) ? "-":objItem[3]) +'</td>';	 //当前价
									html+='<td class="'+t+'">'+((objItem[3]==0) ? "-":upPsn+"%")+'</td>';     //涨跌幅
									html+='<td class="'+t+'">'+((objItem[3]==0) ? "-":upValue.toFixed(2))+'</td>';     //涨跌额
									html+='<td class="'+t2+'">'+objItem[2]+'</td>';     //昨收
									
									html+='<td class="'+t3+'">'+((objItem[3]==0) ? "-":objItem[1])+'</td>';     //今开
									
/*									html+='<td><span class="red">'+((objItem[4]==0) ? "-":objItem[4])+'</span>/<span class="green">'+((objItem[5]==0) ? "-":objItem[5])+'</span></td>';     //最高/最低价*/
									html+='<td><span class="'+t4+'">'+((objItem[6]==0) ? "-":objItem[6])+'</span>/<span class="'+t5+'">'+((objItem[7]==0) ? "-":objItem[7])+'</span></td>';     //买入/卖出价
									html+='<td><a href="javascript://" onclick="deleteMystock(this,\''+item.replace("hq_str_","")+'\');"><img alt="删除" src="images/delete_s.gif"/></a></td></tr>';									
								}
								else{
									var no = item.replace("hq_str_","");
									alert(no+"已摘牌！");
									deleteStockCookie(no);
								}
							}
							html+="</table>";
							box.innerHTML = html;
						}
					});
			}
			else{
				var box = document.getElementById("my_stock_list");
				box.innerHTML = "";
				var html = "";
				html += '<table id="my_stock" cellspacing="1" cellpadding="0" border="0" width="100%">';
				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><th scope="col">买入/卖出价</th><th scope="col">删除</th></tr>';
				html+="</table>";
				box.innerHTML = html;
			}
		}
		else{
			searchController.ChangeData(p,k);
		}
	}

	var defaulf_Stock = ["sz000002","sh600036","sh601318","sh601899"], clearStock = Cookie.get("nostock");
	var loadMystock = function(){
		var data = Cookie.get("stockdata");
			
		if(data !== ""){
			getCustomData(data.split(","));
		}else if(clearStock== ""){
			Cookie.set("stockdata",defaulf_Stock);
			getCustomData(defaulf_Stock);
		}
	}
	
	var onPress = function(ev){
		if (ev.keyCode == 13) addMystock();
	}
	
	var addMystock = function(){
		var cstr = Cookie.get("stockdata");
		
		var value = document.getElementById("stock_inp").value;
		var checkValueNo = value.indexOf("sh")||value.indexOf("sz");
		if(checkValueNo==-1&&value.length!==8){
			alert("您添加的股票代码不正确！");
			return;
		}
		
		

		if(cstr != ""){
			data = cstr.split(",");
		}else{
			data = [];
		}
		if(value==""){
			alert("请输入您要添加的股票代码！");　
			return 
		}else{
			for (var i = 0; i < data.length; i++){
				if (data[i] == value) {
					alert("您已经添加过此股票。");
					return;
				}
			}
			if(data.length > 5){
				document.getElementById("stock_inp").blur();
				alert("对不起，最多只能添加6个自选股，请您删除现有的股票再添加！");
				return;
			}
		}
		
		
		
		
		
		for(var i = 0,len = data.length; i < len; i++){
			var item = data[i];
			if(data[i] == value){
				getCustomData(data);
				return;
			}
		}
		data.push(value);
		Cookie.set("stockdata",data);
		getCustomData(data);
	}
	
	var deleteStockCookie = function(stock){
		var cstr = Cookie.get("stockdata");
		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] == stock){
				index = i;
				break;
			}
		}
		if(index > -1){
			data.splice(index,1);
			Cookie.set("stockdata",data);
			getCustomData(data,true);
		}
	}
	
	var deleteMystock = function(ele,stock){
		var cstr = Cookie.get("stockdata");
		if(cstr != ""){
			data = cstr.split(",");
		}
		else{
			data = [];
		}
		if(data.length==1){
			Cookie.clear("stockdata");
			getCustomData([],true);
			return;
		}		
		var index = -1;
		for(var i = 0,len = data.length; i < len; i++){
			var item = data[i];
			if(data[i] == stock){
				index = i;
				break;
			}
		}
		
		if(index > -1){
			data.splice(index,1);
			Cookie.set("stockdata",data);
			Cookie.set("nostock",1)
			getCustomData(data,true);

		}
	}

	var default_Fund = ["f_000001"];
	var loadMyfund = function(){
	}
	
	var addMyfund = function(){
		
	}
	
	loadMystock();