var PLACEHOLDER = "--";//定义过存续期／封闭期的行情数据占位符

//截取字符串函数
function xSubString(__stringTarget, __intLength) {
	var __stringTargetTransformed = __stringTarget.replace(/[xy]/g, "z").replace(/[^\x00-\xff]/g,"xy");
	if (__stringTargetTransformed.length > __intLength) {
		__stringTargetTransformed = __stringTargetTransformed.substr(0, __intLength);
		if (__stringTargetTransformed.substr(__intLength - 1, 1) == "x") {
			return __stringTarget.substr(0, __intLength - 1 - __stringTargetTransformed.match(/xy/g).length);
		}
		else {
			return __stringTarget.substr(0, __intLength - __stringTargetTransformed.match(/xy/g).length);
		}
	}
	else {
		return __stringTarget;
	}
}


function $(objName){
	if(document.getElementById){
		return document.getElementById(objName);
	}else{
		return document.all.objName;
	}
}
if( typeof $C == 'undefined' )$C = function(t){return document.createElement(t)};

function oEvent(evt){ 
	var evt = evt ? evt : (window.event ? window.event : null);
	var objSrc = (evt.target) ? evt.target : evt.srcElement;
	return(objSrc);
}

function getEvent(){
	var evt = window.event ? window.event : getEvent.caller.arguments[0];
	return(evt);
}

function addEvent(oTarget, sEventType, fnHandler){
	if (oTarget.addEventListener) {
		oTarget.addEventListener(sEventType, fnHandler, false);
	}
	else if(oTarget.attachEvent) {
		oTarget.attachEvent("on" + sEventType, fnHandler);
	}
	else {
		oTarget["on" + sEventType] = fnHandler;
	}
}

//Object.prototype.addEvent = function(sEventType, fnHandler){
//	var oTarget = this;
//	if (oTarget.addEventListener) {
//		oTarget.addEventListener(sEventType, fnHandler, false);
//	}
//	else if(oTarget.attachEvent) {
//		oTarget.attachEvent("on" + sEventType, fnHandler);
//	}
//	else {
//		oTarget["on" + sEventType] = fnHandler;
//	}
//}

String.prototype.trim = function() {
	return this.replace(/(^\s+)|(\s+$)/g,"");
}

Function.prototype.Bind = function() { 
	var __m = this, object = arguments[0], args = new Array(); 
	for(var i = 1; i < arguments.length; i++){
		args.push(arguments[i]);
	}
	
	return function() {
		return __m.apply(object, args);
	}
};

Function.prototype.BindForEvent = function() { 
	var __m = this, object = arguments[0], args = new Array();
	for(var i = 1; i < arguments.length; i++){
		args.push(arguments[i]);
	}
	
	return function(event) {
		return __m.apply(object, [( event || window.event)].concat(args));
	}
}

var isIE = false;
var userAgent = navigator.userAgent.toLowerCase();
if ((userAgent.indexOf('msie') != -1) && (userAgent.indexOf('opera') == -1)) {
	isIE = true;
}
//------------------------------------------------------------------------------
// Cookie Related
//------------------------------------------------------------------------------

var Cookie = function()
{
	this.Init.apply(this, arguments);
};

Cookie.prototype = {
	_items: {},
	_nItems: 0,
	
	Init: function() {
		
	},
	
	/**
	 * Initialize from cookie
	 */
	_init: function() {
		if (document.cookie.length == 0) {
			return;
		}
		
		var cookiesArr = document.cookie.split(';');
		var temp;
		this._nItems = cookiesArr.length;

		if (this._nItems == 0) {
			return;
		}
		
		for (var i = 0; i < this._nItems; i++) {
			temp = cookiesArr[i].split('=');
			if (temp.length != 2) {
				continue;
			}
			this._items[temp[0].trim()] = temp[1].trim();
		}
	},
	
	/**
	 * Get cookie contents by name
	 * 
	 * @param {String} name
	 * @return {String} Contents of the cookie
	 */
	get: function(name) {
		this._init();
		
		if (typeof this._items[name] != 'undefined') {
			return unescape(this._items[name]);
		}
		
		return '';
	},
	
	/**
	 * Set a cookie
	 * 
	 * @param {String} name Cookie name
	 * @param {String} value Cookie value
	 * @param {String} expire Cookie expire time, formatted as 'Fri, 21 Dec 1976 04:31:24 GMT'
	 * @param {String} path Cookie Path
	 * @param {String} domain Cookie domain
	 * @param {Boolean} secure Whether the cookie can only access in HTTPS
	 * @return {Boolean}
	 */
	set: function(name, value, expire, path, domain, secure) {
		if (typeof name == 'undefined') {
			return false;
		}
		
		if (typeof value == 'undefined') {
			return false;
		}
		
		var cookieStr = name + '=' + escape(value) + '; ';
		
		if (typeof expire != 'undefined') {
			cookieStr += 'expires=' + expire + '; '
		}
		
		if (typeof path != 'undefined') {
			cookieStr += 'path=' + path + '; '
		}
		
		if (typeof domain != 'undefined') {
			cookieStr += 'domain=' + domain + '; ';
		}
		
		if (secure == true) {
			cookieStr += 'secure;';
		}
		
		document.cookie = cookieStr;
	},
	
	/**
	 * Remove a cookie
	 * 
	 * @param {String} name
	 */
	remove: function(name) {
		document.cookie = name + "=; expires=Fri, 21 Dec 1976 04:31:24 GMT;";
	},
	
	/**
	 * Get cookie count
	 * 
	 * @return {Number}
	 */
	getCount: function() {
		this._init();
		return this._nItems;
	}
};

//------------------------------------------------------------------------------
//navigation top
//------------------------------------------------------------------------------
var Nav = function (arrayData) {
	this.element = $("nav");
	var table = $C("table");
	table.className = "table";
	table.cellPadding = 0;
	table.cellSpacing = 0;
	table.border = 0;
	var line = table.insertRow(0);
	for (var i = 0; i < arrayData.length; i++) {
		var cell = line.insertCell(i);
		cell.className = i == 0 ? "index" : "off";
		cell.onmouseover = function () {
			this.className = this.className == "index" ? "index" : "on";
		};
		cell.onmouseout = function () {
			this.className = this.className == "index" ? "index" : "off";
		};
		var link = $C("a");
		link.target = "_blank";
		link.href = arrayData[i][0];
		link.innerHTML = arrayData[i][1];
		cell.appendChild(link);
	}
	this.element.appendChild(table);
};

//------------------------------------------------------------------------------
//navigation left
//------------------------------------------------------------------------------
var NavLeft = function () {
	this.tempHtml = $("navLeft").innerHTML;
	this.tempHtml = this.tempHtml.replace(/@CODE@/g,FUNDCODE);
	$("navLeft").innerHTML = this.tempHtml;
}


//------------------------------------------------------------------------------
//tab switch
//------------------------------------------------------------------------------
var TabSwitch = function(){
	this.Init.apply(this, arguments);
};
TabSwitch.prototype = {
	Init: function(tabs,targets,subTargets,callbackObjArr){
		this.tabs = [];
		this.targets = [];
		var tempTabs = tabs.childNodes;
		var tempTargets = targets.childNodes;
		for (var i = 0; i < tempTabs.length; i++){
			if (tempTabs[i].nodeType == 1){
				this.tabs.push(tempTabs[i]);
			}
		};
		for (var j = 0; j < tempTargets.length; j++){
			if (tempTargets[j].nodeType == 1){
				this.targets.push(tempTargets[j]);
			}
		};

		if (subTargets) {
			this.subTargets = [];
			var tempSubTargets = subTargets.childNodes;
			for (var h = 0; h < tempSubTargets.length; h++){
				if (tempSubTargets[h].nodeType == 1){
					this.subTargets.push(tempSubTargets[h]);
				}
			};
			this.activeSubTarget = this.subTargets[0];
		}

		if (callbackObjArr) {
			for (var k = 0; k <  this.tabs.length; k++ ){
				this.tabs[k].onclick = this.showTab.BindForEvent(this,k,callbackObjArr[k])
			}
		}
		else {
			for (var k = 0; k <  this.tabs.length; k++ ){
				this.tabs[k].onclick = this.showTab.BindForEvent(this,k)
			}
		}

		this.activeTab = this.tabs[0];
		this.activeTarget = this.targets[0];
	},
	showTab: function(obj,_index,callback){
		if (this.tabs[_index] == this.activeTab){
			return;
		}
		if (this.activeTab){
			this.activeTab.className = "";
		}
		this.activeTab = this.tabs[_index];
		this.activeTab.className = "active";

		if (this.activeTarget){
			this.activeTarget.style.display = "none";
		}
		this.activeTarget = this.targets[_index];
		this.activeTarget.style.display = "";

		if (this.subTargets) {
			this.activeSubTarget.style.display = "none";
			this.activeSubTarget = this.subTargets[_index];
			this.activeSubTarget.style.display = "";
		}

		if (callback) {
			this.activeCallback = callback;
			callback();
		}
	}
}



// Color configuration
var __UP_COLOR = '#F00';
var __DOWN_COLOR = '#008000';
var __STABLE_COLOR = '#000';

/**
 * Global color code function
 * 
 * @param {Number} value
 * @return {String}
 */
function getColorCode(value)
{
	value = parseFloat(value);
	if (value > 0) {
		return __UP_COLOR;
	} else if (value < 0) {
		return __DOWN_COLOR;
	} else {
		return __STABLE_COLOR;
	}
};

//------------------------------------------------------------------------------
//fund url parse / to diff of & cf
//------------------------------------------------------------------------------
function fundUrlCheck (code) {
	var typeRex = /(sh|sz)/;
	var sCode = code.toString();
	if (typeRex.test(sCode)) {
		var tempCode = sCode.replace(typeRex,"");
		return __FUND_URL_CF.replace("__CODE__",tempCode);
	}
	else {
		return __FUND_URL.replace("__CODE__",sCode);
	}
}

//------------------------------------------------------------------------------
//code trim
//------------------------------------------------------------------------------
function codeTrim(code) {
	var typeRex = /(sh|sz)/;
	return code.toString().replace(typeRex,"");;
}


//fu 预测
//基金名称,更新时间,最新净值,昨日净值,累计净值,五分钟涨速,涨跌幅
//f 实际净值
//基金名称,最新净值,累计净值,昨日净值,净值日期,基金规模(亿份)
//若为货币式基金返回: 基金名称,最新净值,7日年化收益率%, ,净值日期,基金规模(亿份)
var __SINAJS_URL = "http://hq.sinajs.cn/list=";
var __REALTIME_INDEXS = "http://hq.sinajs.cn/?list=sh000001,sz399001,sh000011,sz399305";
var __FUND_URL = "http://finance.sina.com.cn/fund/quotes/of__CODE__/bc.shtml";
var __FUND_URL_CF = "http://finance.sina.com.cn/fund/quotes/cf__CODE__/bc.shtml";
var __VISITED_FUNDS_NUM = 19;
var __VISITED_FUNDS_COOKIE_NAME = 'visited_cfunds';
//------------------------------------------------------------------------------
//fund compare
//------------------------------------------------------------------------------
var FundQuote = {
	dataQuote: [],
	dataReal: [],
	Init: function () {
		this.futureTblTpl = this.futureTblTpl.replace("@TOTALSHARE@", TOTALSHARE).replace("@LTSHARE@", LTSHARE);
		this.titleTpl = this.titleTpl.replace("@LIPPER_CODE@", LipperControl.generateCode());
		this.tplReplace($("fundTitle"),this.titleTpl,[
				["@FUNDNAME@",FUNDNAME],
				["@FUNDTYPE@",FUNDTYPE],
				["@FUNDCODE@",FUNDCODE],
				["@FUNDSYMBOL@",FUNDCODE.substr(2)],
				["@FUNDURL@",window.location.href]
			]);
		this.scriptLoader();
		var quoteInterval = window.setInterval(this.scriptLoader.Bind(this),5000);
	},
	scriptLoader: function () {
		this.sCode = codeTrim(FUNDCODE);
		var sLoader = new IO.Script();
		var url = __SINAJS_URL + FUNDCODE + ",f_" + this.sCode;
		sLoader.load(url, this.update.Bind(this));
	},
	tplReplace: function (targetContainer,targetTpl,dataArr) {
		for (var i = 0; i < dataArr.length; i++) {
			targetTpl = targetTpl.replace(dataArr[i][0],dataArr[i][1]);
		};
		targetContainer.innerHTML = targetTpl;
	},
	colorRender: function (targetText,color) {
		return '<span style="color:' + color + ';">' + targetText + '</span>';
	},
	update: function () {
		this.dataQuote = [];
		this.dataReal = [];
		var tempDF = window["hq_str_" + FUNDCODE].split(",");
		for (var i = 0; i < tempDF.length; i++) {
			this.dataQuote.push(tempDF[i] ? tempDF[i] : PLACEHOLDER)
		};
		for(var i=0;i<32;i++)
		{
			this.dataQuote[i] = typeof this.dataQuote[i]=='undefined' ? PLACEHOLDER : this.dataQuote[i];
		}

		var tempDR = window["hq_str_f_" + this.sCode].split(",");
		for (var i = 0; i < tempDR.length; i++) {
			this.dataReal.push(tempDR[i] ? tempDR[i] : PLACEHOLDER)
		};

		var quote_color = getColorCode(this.dataQuote[3] - this.dataQuote[2]);
		var f_color = getColorCode(this.dataReal[1] - this.dataReal[3]);

		var priceOff = (this.dataQuote[3]==PLACEHOLDER)||(this.dataQuote[1]==PLACEHOLDER)||(this.dataQuote[3]==0)
			? "--"
		   	: ((this.dataQuote[3] - this.dataReal[1]) / this.dataReal[1] * 100).toFixed(2);
		var changePrice = (this.dataQuote[3]==PLACEHOLDER)||(this.dataQuote[2]==PLACEHOLDER)||(this.dataQuote[3]==0) 
						? PLACEHOLDER 
						:(this.dataQuote[3] - this.dataQuote[2]).toFixed(3) ;
		var changeRate = (this.dataQuote[3]==PLACEHOLDER)||(this.dataQuote[2]==PLACEHOLDER)||(this.dataQuote[3]==0) 
						? PLACEHOLDER +"%"
						:((this.dataQuote[3]-this.dataQuote[2])/this.dataQuote[2]*100).toFixed(3)+"%";
		var volumn = this.dataQuote[8]=='--' ? PLACEHOLDER :(this.dataQuote[8] / 100).toFixed(0);
		//基金对比 写出当前基金名称
		this.tplReplace($('compareHead'),this.compareHeadTpl,[
				["@FUNDNAME@",this.dataQuote[0]]
			]);

		this.tplReplace($("futureTbl"),this.futureTblTpl,[
				["@FUTURE_PRICE@",this.colorRender(this.dataQuote[3],quote_color)],
				["@CHANGE@",this.colorRender(changePrice, quote_color)],
				["@CHANGE_RATE@",this.colorRender(changeRate,quote_color)],
				["@LAST_UPDATE_TIME@",this.dataQuote[31]],
				["@LAST_CLOSE@",this.dataQuote[2]],
				["@OPEN_PRICE@",this.dataQuote[1]],
				["@HIGH_PRICE@",this.dataQuote[4]],
				["@LOW_PRICE@",this.dataQuote[5]],
				["@VOLUME@", volumn],
				["@PRICEOFF_RATE@",priceOff < 0 ? "折价率: " + priceOff + "%" : "溢价率: " + priceOff + "%"]
			]);

		this.tplReplace($("realTh"),this.realThTpl,[
				["@REAL_PRICE@",this.colorRender(this.dataReal[1],f_color)],
				["@REAL_TOTAL_PRICE@",this.dataReal[2]],
				["@REAL_CHANGE_RATE@",this.colorRender((((this.dataReal[1] - this.dataReal[3]) / this.dataReal[3] * 100).toFixed(4) + "%"),f_color)],
				["@REAL_UPDATE_TIME@",this.dataReal[4]]
			]);

		this.fillTenPrices(quote_color);
		QuoteData.show(this.dataQuote);

		if (this.lastPrice != this.dataQuote[3] || !this.lastPrice) {
			this.lastPrice = this.dataQuote[3];
		}
		else {
			return ;
		}
		this._twinkle(0);
	},

	_twinkle: function(count) {
		if (typeof count == 'undefined') {
			count = 0;
		}
		
		if (count % 2 == 0) {
			$('current_quote_big').innerHTML = FundFormatter.formatCommon(this.dataQuote[3], (this.dataQuote[3] - this.dataQuote[2]));
		} else {
			$('current_quote_big').innerHTML = this.dataQuote[3];
		}
		
		if (count == 4) {
			return;
		}
		
		count++;
		
		window.setTimeout(this._twinkle.Bind(this, count), 300);
	},

	fillTenPrices: function (quote_color) {
		var price , volumn;
		if (!this.tenPricesRows) {
			this.tenPricesRows = $("tenPrices").tBodies[0].rows;
		}
		for (var i = 0; i < this.tenPricesRows.length; i++) {
			if (i != 5) {
				price = this.dataQuote[this.tenPricesArr[i][1]] ;
				volumn = this.dataQuote[this.tenPricesArr[i][0]] ;
				this.tenPricesRows[i].cells[1].innerHTML = price + " / " + volumn;
			}
			else {
				var nowPrice = this.dataQuote[3];
				this.tenPricesRows[5].cells[1].innerHTML = this.colorRender(nowPrice, quote_color);
			}
		};
	},
	tenPricesArr: [[28,29],[26,27],[24,25],[22,23],[20,21],3,[10,11],[12,13],[14,15],[16,17],[18,19]],
	titleTpl: '<table class="head">\
				<tbody>\
					<tr><th><h1>@FUNDNAME@</h1>@FUNDTYPE@ @FUNDCODE@</th><td>@LIPPER_CODE@<span class="toolbarbtn"><button id="tbtn02" onclick="window.location.href=\'http://vip.stock.finance.sina.com.cn/myfund/fund_quick_jia.php?symbol=@FUNDSYMBOL@&ru=@FUNDURL@\'">加入自选基金</button></span></td></tr>\
				</tbody>\
				</table>',
	compareHeadTpl:'@FUNDNAME@',
	futureTblTpl: '<table>\
					<tbody>\
						<tr><th rowspan="2"><h2 id="current_quote_big">@FUTURE_PRICE@</h2><h5>@CHANGE@ (@CHANGE_RATE@)</h5><h6>@LAST_UPDATE_TIME@</h6></th><td>昨收盘: @LAST_CLOSE@</td><td>今开盘: @OPEN_PRICE@</td><td>最高价: @HIGH_PRICE@</td><td>最低价: @LOW_PRICE@</td></tr>\
						<tr><td>总份额: @TOTALSHARE@</td><td>流通份额: @LTSHARE@</td><td>成交量(手): @VOLUME@</td><td>@PRICEOFF_RATE@</td></tr>\
					</tbody>\
					</table>',
	realThTpl: '<h4>最新净值: @REAL_PRICE@</h4><h4>累计净值: @REAL_TOTAL_PRICE@</h4><h5>周增长率：@REAL_CHANGE_RATE@ @REAL_UPDATE_TIME@</h5>',
	moneyRealThTpl: '<h4>最新净值: @REAL_PRICE@</h4><h4>7日年化收益率: @PROFIT_RATE@%</h4><h5>@REAL_UPDATE_TIME@</h5>'
}

//------------------------------------------------------------------------------
// Lipper begin
//------------------------------------------------------------------------------
var LipperControl = {
	generateCode: function () {
		this.sLipper = Lipper;

		if (this.sLipper == 0 || !this.sLipper) {
			return "";
		}
		var sCode = "<dl>";
		for (var i = 0; i < this.sLipper; i++) {
			sCode += "<dt></dt>";
		};
		for (var j = 0; j < 5 - this.sLipper; j++) {
			sCode += "<dd></dd>";
		};
		return sCode + '</dl><span><a href="http://biz.finance.sina.com.cn/fund/lipper/query.php" target="_blank">理柏基金评级</a>:</span>';
	}
}


//------------------------------------------------------------------------------
//fund compare
//------------------------------------------------------------------------------
var FundCompare = {
	code2: null,
	timeRange: null,
	radioIndexes: [],
	radioValue: null,
	codeFormat: /^(sh|sz)?\d{6}(\,(sh|sz)?\d{6})*,?$/,
	compareImg1: "http://biz.finance.sina.com.cn/fund/fund_page/cmp_img_kline.php?code=",
	compareImg2: "http://stock.finance.sina.com.cn/cgi-bin/chart/minline_s_new.cgi?code=",

	Init: function () {
		$("compareStart").onclick = this.start.BindForEvent(this);
//		$("toLargerPic").onclick = function () {
//			window.open("");
//		}
		$("compareCode").onblur = this.codeVerify.BindForEvent(this);

		var tempRadios = $("radios").childNodes;
		for (var i = 0; i < tempRadios.length; i++){
			if (tempRadios[i].nodeType == 1){
				this.radioIndexes.push(tempRadios[i]);
			}
		};
		for (var k = 0; k < this.radioIndexes.length; k++ ){
			this.radioIndexes[k].onclick = this.radioControl.BindForEvent(this,k);
			if (this.radioIndexes[k].checked == true) {
				this.radioIndexes[k].checked = false;
			}
		};

//		fundMarket.tabs[0].addEvent("click", this.rollBack.Bind(this));
		this.oriHtml = fundMarket.targets[1].innerHTML;
		addEvent(fundMarket.tabs[0], "click", this.rollBack.Bind(this));
	},
	codeVerify: function () {
		this.code2 = $("compareCode").value;
		if (!this.codeFormat.test(this.code2) && this.code2 != "") {
			$("compareTip").style.visibility = "hidden";
			$("compareErr").style.display = "";
		}
		else if ($("compareTip").style.visibility != "") {
			$("compareTip").style.visibility = "";
			$("compareErr").style.display = "none";
		}
	},
	radioControl: function (obj,_index) {
		if (this.radioIndexes[_index] == this.activeRadio) {
			this.radioIndexes[_index].checked = false;
			this.radioValue = null;
			this.activeRadio = null;
			return;
		}
		this.radioValue = this.radioIndexes[_index].value;
		this.activeRadio = this.radioIndexes[_index];
	},
	start: function (obj) {
		this.code2 = $("compareCode").value;
		this.timeRange = $("timeRange").value;
		if (this.codeFormat.test(this.code2) || (this.code2 == "" && this.radioValue != null)){
			fundMarket.showTab(fundMarket,1);
			if (this.timeRange) {
				var tempUrl = this.compareImg1 + FUNDCODE;
				tempUrl += "&ccode1=" + this.code2 + (this.radioValue ? "&ccode2=" + this.radioValue : "") + "&putday=" + this.timeRange;
			}
			else {
				var tempUrl = this.compareImg2 + FUNDCODE;
				tempUrl += "&ccode1=" + this.code2 + (this.radioValue ? "&ccode2=" + this.radioValue : "");
			}

			var imgCompare = new Image();
			imgCompare.src = tempUrl;

			fundMarket.targets[1].innerHTML = this.loadingTpl;

			imgCompare.onload = function () {
				fundMarket.targets[1].innerHTML = "";
				fundMarket.targets[1].appendChild(imgCompare);
			}
		}
		else if (this.code2 != ""){
			alert("基金代码输入有误!");
		}
	},
	rollBack: function () {
		if (fundMarket.targets[1].innerHTML == this.oriHtml) {
			return;
		}
		else {
			fundMarket.targets[1].innerHTML = this.oriHtml;
		}
	},
	loadingTpl: '<div class="loading">读取中,请稍候...</div>'
}


//------------------------------------------------------------------------------
//fund ranks
//------------------------------------------------------------------------------

var FundRanks = {
	apiUrl: "http://hq.sinajs.cn/format=text&list=",
	Init: function () {
		this.loadScript();
	},
	loadScript: function () {
		var tempScript = [];

		for (var i in this.moudles) {
			tempScript[i] = new IO.Script();
			tempScript[i].load((this.apiUrl + this.moudles[i].name),this.tblGenerate.Bind(this,this.moudles[i]));
		};
	},
	tblGenerate: function (rank) {
		var _data = window[rank.name];

		if (!_data) {
			var targetDiv = $("div_" + rank.name);
			targetDiv.innerHTML = this.errorTpl;
			return ;
		}

		var _table = $C("TABLE");

		var _thead = $C("THEAD");
		_table.appendChild(_thead);
		var _tr = _thead.insertRow(-1);
		for (var i = 0; i < rank.titles.length; i++) {
			var _th = $C("TH");
			_th.innerHTML = rank.titles[i][0];
			_tr.appendChild(_th);
		};

		var _tbody = $C("TBODY");
		_table.appendChild(_tbody);
		for (var j = 0; j < _data.length; j++) {
			var _tr = _tbody.insertRow(-1);
			for (var k = 0; k < rank.titles.length; k++) {
				var _cell = k < 2 ? $C("TH") : $C("TD");

				if (k == 0) {
					_cell.innerHTML = j + 1;
				}
				else if (rank.titles[k][0] == "名称") {
					var _a = $C("A");
					_a.href = fundUrlCheck(_data[j][0]);
//					_a.href = __FUND_URL.replace("__CODE__",_data[j][0]);
					_a.target = "_blank";
					_a.innerHTML = xSubString(_data[j][rank.titles[k][1]],16);
					_a.title = _data[j][rank.titles[k][1]];					
					
					_cell.appendChild(_a);
				}
				else {
					_cell.innerHTML = rank.titles[k][2] ? (_data[j][rank.titles[k][1]] + "%") : _data[j][rank.titles[k][1]];
				}
				
				_tr.appendChild(_cell);
			};
		};

		var _tfoot = $C("TFOOT");
		_table.appendChild(_tfoot);
		var _tr = _tfoot.insertRow(-1), _th = $C("TH"), _td = $C("TD");
		_tr.appendChild(_th);
		_tr.appendChild(_td);
		_th.colSpan = 3;
		_th.innerHTML = _data[0][4] ? _data[0][4] : "";
		_td.innerHTML = '<a href="' + rank.urlMore + '" target="_blank">更多>></a>';

		var targetDiv = $("div_" + rank.name);
		targetDiv.innerHTML = "";
		targetDiv.appendChild(_table);
	},
	moudles: {
		open_fund_up: {
			name: "of_up_10_d",
			titles: [["排名",""],["名称",1],["净值(元)",3],["收益率",2,true]],
			urlMore: "http://finance.sina.com.cn/fund/fund_ranks/open/netvalue_ranks6_1.html"
		},
		open_fund_down: {
			name: "of_down_10_d",
			titles: [["排名",""],["名称",1],["净值(元)",3],["收益率",2,true]],
			urlMore: "http://finance.sina.com.cn/fund/fund_ranks/open/netvalue_ranks6_0.html"
		},
		close_fund_up: {
			name: "fund_up_d_10",
			titles: [["排名",""],["名称",1],["最新价",3],["涨幅",2,true]],
			urlMore: "http://finance.sina.com.cn/fund/closefundmore.html"
		},
		close_fund_down: {
			name: "fund_down_d_10",
			titles: [["排名",""],["名称",1],["最新价",3],["涨幅",2,true]],
			urlMore: "http://finance.sina.com.cn/fund/closefundmore.html"
		},
	/*	close_fund_ts_up: {
			name: "cf_ts_up_10_d",
			titles: [["排名",""],["名称",1],["贴水值",3],["贴水率",2,true]]
		},*/
		close_fund_ts_down: {
			name: "cf_ts_down_10_d",
			titles: [["排名",""],["名称",1],["贴水值",3],["贴水率",2,true]],
			urlMore: "http://finance.sina.com.cn/fund/closefundmore.html"
		}
	},
	errorTpl: '<div style="height:242px; line-height:242px; text-align:center;">该排行榜目前不可用，请稍后刷新重试<div>'
}
//moudles格式说明
//排行榜简称: {
//	name: "排行榜变量名/sinajs对应参数/填充容器ID",
//	titles: ["表头名",表头对应数据项于数组中位置,是否带百分号]
//}

//------------------------------------------------------------------------------
// Realtime indexs begin
//------------------------------------------------------------------------------

function genRealtimeIndexs()
{
	if (!hq_str_sh000001 || !hq_str_sz399001 || !hq_str_sh000011 || !hq_str_sz399305) {
		return;
	}
	
	var _sh000001 = window["hq_str_sh000001"].split(",");
	var _sh000001_changerate = ((_sh000001[3] - _sh000001[2]) / _sh000001[2] * 100).toFixed(3);
	var _sz399001 = window["hq_str_sz399001"].split(",");
	var _sz399001_changerate = ((_sz399001[3] - _sz399001[2]) / _sz399001[2] * 100).toFixed(3);
	var _sh000011 = window["hq_str_sh000011"].split(",");
	var _sh000011_changerate = ((_sh000011[3] - _sh000011[2]) / _sh000011[2] * 100).toFixed(3);
	var _sz399305 = window["hq_str_sz399305"].split(",");
	var _sz399305_changerate = ((_sz399305[3] - _sz399305[2]) / _sz399305[2] * 100).toFixed(3);

	var _sh000001Color = getColorCode(_sh000001_changerate);
	var _sz399001Color = getColorCode(parseFloat(_sz399001[3] - _sz399001[2]));
	var _sh000011Color = getColorCode(_sh000011_changerate);
	var _sz399305Color = getColorCode(_sz399305_changerate);

	var _sh000001_prefix = '';
	if((_sh000001[3] - _sh000001[2]) > 0 ) _sh000001_prefix = "+" ;
	_sh000001_changerate = _sh000001_prefix + _sh000001_changerate ;
	var _sz399001_prefix = '';
	if((_sz399001[3] - _sz399001[2]) > 0 ) _sz399001_prefix = "+";
	_sz399001_changerate = _sz399001_prefix + _sz399001_changerate ;
	var _sh000011_prefix = '';
	if((_sh000011[3] - _sh000011[2]) > 0) _sh000011_prefix = "+";
	_sh000011_changerate = _sh000011_prefix + _sh000011_changerate ;
	var _sz399305_prefix = '';
	if((_sz399305[3] - _sz399305[2]) > 0) _sz399305_prefix = "+";
	_sz399305_changerate = _sz399305_prefix + _sz399305_changerate ;
	
	$('realtimeIdxs').innerHTML = '<span class="marginRight"><a href="http://finance.sina.com.cn/realstock/company/sh000001/nc.shtml" target="_blank">上证指数</a> <span style="color:' + _sh000001Color + '">' + parseInt(_sh000001[3] * 1) + ' ' + _sh000001_changerate +'%</span></span><span class="marginRight"><a href="http://finance.sina.com.cn/realstock/company/sz399001/nc.shtml" target="_blank">深证成指</a> <span style="color:' + _sz399001Color + '">' + parseInt(_sz399001[3]*1) + ' ' + _sz399001_changerate +'%</span></span><span class="marginRight"><a href="http://finance.sina.com.cn/realstock/company/sh000011/nc.shtml" target="_blank">上证基金</a> <span style="color:' + _sh000011Color + '">' + parseInt(_sh000011[3]*1) + ' ' + _sh000011_changerate +'%</span></span><span><a href="http://finance.sina.com.cn/fund/quotes/index399305.shtml" target="_blank">深证基金</a> <span style="color:' + _sz399305Color + '">' + parseInt(_sz399305[3]*1) + ' ' + _sz399305_changerate +'%</span></span>';
};

function showRealtimeIndexs()
{
	var sLoader = new IO.Script();
	sLoader.load(__REALTIME_INDEXS, genRealtimeIndexs);
};

//------------------------------------------------------------------------------
// Cookie begin
//------------------------------------------------------------------------------

var Cookie = function()
{
	this.Init.apply(this, arguments);
};

Cookie.prototype = {
	_items: {},
	_nItems: 0,
	
	Init: function() {
		
	},
	
	/**
	 * Initialize from cookie
	 */
	_init: function() {
		if (document.cookie.length == 0) {
			return;
		}
		
		var cookiesArr = document.cookie.split(';');
		var temp;
		this._nItems = cookiesArr.length;

		if (this._nItems == 0) {
			return;
		}
		
		for (var i = 0; i < this._nItems; i++) {
			temp = cookiesArr[i].split('=');
			if (temp.length != 2) {
				continue;
			}
			this._items[temp[0].trim()] = temp[1].trim();
		}
	},
	
	/**
	 * Get cookie contents by name
	 * 
	 * @param {String} name
	 * @return {String} Contents of the cookie
	 */
	get: function(name) {
		this._init();
		
		if (typeof this._items[name] != 'undefined') {
			return unescape(this._items[name]);
		}
		
		return '';
	},
	
	/**
	 * Set a cookie
	 * 
	 * @param {String} name Cookie name
	 * @param {String} value Cookie value
	 * @param {String} expire Cookie expire time, formatted as 'Fri, 21 Dec 1976 04:31:24 GMT'
	 * @param {String} path Cookie Path
	 * @param {String} domain Cookie domain
	 * @param {Boolean} secure Whether the cookie can only access in HTTPS
	 * @return {Boolean}
	 */
	set: function(name, value, expire, path, domain, secure) {
		if (typeof name == 'undefined') {
			return false;
		}
		
		if (typeof value == 'undefined') {
			return false;
		}
		
		var cookieStr = name + '=' + escape(value) + '; ';
		
		if (typeof expire != 'undefined') {
			cookieStr += 'expires=' + expire + '; '
		}
		
		if (typeof path != 'undefined') {
			cookieStr += 'path=' + path + '; '
		}
		
		if (typeof domain != 'undefined') {
			cookieStr += 'domain=' + domain + '; ';
		}
		
		if (secure == true) {
			cookieStr += 'secure;';
		}
		
		document.cookie = cookieStr;
	},
	
	/**
	 * Remove a cookie
	 * 
	 * @param {String} name
	 */
	remove: function(name) {
		document.cookie = name + "=; expires=Fri, 21 Dec 1976 04:31:24 GMT;";
	},
	
	/**
	 * Get cookie count
	 * 
	 * @return {Number}
	 */
	getCount: function() {
		this._init();
		return this._nItems;
	}
};


//------------------------------------------------------------------------------
// SINAJS quote parser begin
//------------------------------------------------------------------------------

var SinajsQuoteParser = {
	parse: function(code) {
		var quoteStr = window['hq_str_' + code];
		if (typeof quoteStr == 'undefined') {
			return null;
		}
		
		if (quoteStr.length == 0) {
			return null;
		}
		
		return quoteStr.split(',');
	}
};

var FundFormatter = {
	formatTitle: function(code, name, nameCut) {
		if (typeof nameCut == 'undefined') {
			nameCut = name.length;
		}
		if (name.length == 0) {
			name = code;
			nameCut = name.length;
		}
		return '<a href="' + __FUND_URL_CF.replace("__CODE__",codeTrim(code)) + '" title="' + name + '">' + name.substr(0, nameCut) + '</a>';
	},
	
	formatCurValue: function(quoteArr) {
		return '<span style="color:' + getColorCode(quoteArr[6]) + '">' + quoteArr[2] + '</span>';
	},
	
	formatLastPrice: function(quoteArr) {
		return '<span style="color:' + getColorCode(quoteArr[6]) + '">' + quoteArr[3] + '</span>';
	},
	
	formatCommon: function(value, checkValue, valueSuffix) {
		valueSuffix = (typeof valueSuffix == 'undefined') ? '' : valueSuffix;
		return '<span style="color:' + getColorCode(checkValue) + '">' + value + valueSuffix + '</span>';
	}
};

//------------------------------------------------------------------------------
// Last visited stocks begin
// Dependence: Cookie
//------------------------------------------------------------------------------

var VisitedStocks = function()
{
	this.Init.apply(this, arguments);
};

VisitedStocks.prototype = {
	_stocks: [],
	_cookie: null,
	
	Init: function() {
		this._cookie = new Cookie();
		
		var stocksStr = this._cookie.get(__VISITED_FUNDS_COOKIE_NAME);
		if (stocksStr.length != 0) {
			this._stocks = stocksStr.split('|');
		}
	},
	
	_findStock: function(code) {
		var nStocks = this._stocks.length;
		for (var i = 0; i < nStocks; i++) {
			if (this._stocks[i] == code) {
				return i;
			}
		}
		
		return -1;
	},
	
	set: function(code) {
		var pos = this._findStock(code);
		if (pos != -1) {
			this._stocks.splice(pos, 1);
		}
		
		this._stocks.unshift(code);
		
		if (this._stocks.length > __VISITED_FUNDS_NUM) {
			this._stocks.pop();
		}
		
		this._cookie.set(__VISITED_FUNDS_COOKIE_NAME, this._stocks.join('|'), 'Fri, 31 Dec 2099 23:59:59 GMT', '/', 'finance.sina.com.cn');
	},
	
	getAll: function() {
		return this._stocks;
	},
	
	clear: function() {
		this._cookie.remove(__VISITED_FUNDS_COOKIE_NAME);
	}
};

var VisitedStocksTable = {
	_hotStockList: ['sz184692','sz184722','sh500006','sh500002','sh500038','sz184691','sz184698','sz184705','sz184688','sh500008','sz184703','sz184689','sz184713','sz184701','sz184693','sz184690','sz184728','sh500005'],
	
	_getVisitedStocksTpl: function() {
		return '<table><thead><tr><th>名称</th><th>最新价</th><th>涨跌幅</th></tr>\
			</thead><tbody>{#CONTENTS#}</tbody></table>';
	},
	
	_getStockItemTpl: function(quote) {
		return '<tr><th>{#TITLE#}</th><td>{#PRICE#}</td><td>{#CHANGE_RATE#}</td></tr>';
	},
	
	_getHotStocksTpl: function() {
		return '<table><thead><tr><th colspan="3">以下为热门封基</th></tr></thead>\
				<tbody>{#CONTENTS#}</tbody></table>';
	},
	
	_getVisitedStocks: function() {
		var visited = new VisitedStocks();
		return visited.getAll();
	},
	
	_generateTable: function(visitedStocks, hotStocks) {
		var contents = '';
		var nVisitedStocks = visitedStocks.length;
		var nHotStocks = hotStocks.length;
		var quote = [];
		var quoteLink = '';
		var code = '';
		
		var item = '';
		var visitedItems = [];
		for (var i = 0; i < nVisitedStocks; i++) {
			code = visitedStocks[i];
			quote = SinajsQuoteParser.parse(code);
			
			if (quote == null) {
				continue;
			}
			var changeRate = (quote[3] == 0) ? "--" : ((quote[3] - quote[2]) / quote[2] * 100).toFixed(3);
			
			item = this._getStockItemTpl();
			item = item.replace(/\{#TITLE#\}/, FundFormatter.formatTitle(code, quote[0], 4));
			item = item.replace(/\{#PRICE#\}/, FundFormatter.formatCommon(quote[3], changeRate));
			item = item.replace(/\{#CHANGE_RATE#\}/, FundFormatter.formatCommon(changeRate, changeRate, "%"));
			
			visitedItems.push(item);
		}
		
		var hotItems = [];
		for (var i = 0; i < nHotStocks; i++) {
			code = hotStocks[i];
			quote = SinajsQuoteParser.parse(code);
			if (quote == null) {
				continue;
			}
			
			var changeRate = (quote[3] == 0) ? "--" : ((quote[3] - quote[2]) / quote[2] * 100).toFixed(3);
			
			item = this._getStockItemTpl();
			item = item.replace(/\{#TITLE#\}/, FundFormatter.formatTitle(code, quote[0], 4));
			item = item.replace(/\{#PRICE#\}/, FundFormatter.formatCommon(quote[3], changeRate));
			item = item.replace(/\{#CHANGE_RATE#\}/, FundFormatter.formatCommon(changeRate, changeRate, "%"));
			
			hotItems.push(item);
		}
		
		var visitedTbl = '';
		if (visitedItems.length != 0) {
			visitedTbl = this._getVisitedStocksTpl();
			visitedTbl = visitedTbl.replace(/\{#CONTENTS#\}/, visitedItems.join(''));
		}
		
		var hotTbl = '';
		if (hotItems.length != 0) {
			hotTbl = this._getHotStocksTpl();
			hotTbl = hotTbl.replace(/\{#CONTENTS#\}/, hotItems.join(''));
		}
		
		return visitedTbl + hotTbl;
	},
	
	_show: function(visitedStocks, hotStocks) {
		$('visited_funds_tbl').innerHTML = this._generateTable(visitedStocks, hotStocks);
	},
	
	show: function() {
		var visitedStocks = this._getVisitedStocks();
		var nVisitedStocks = visitedStocks.length;
		
		var nHotStocks = 0;
		var hotStocks = [];

		if (nVisitedStocks < __VISITED_FUNDS_NUM) {
			nHotStocks = __VISITED_FUNDS_NUM - nVisitedStocks;
			hotStocks = this._hotStockList.slice(0, nHotStocks - 1);
		}

		var stocks = visitedStocks.concat(hotStocks);
		var sinajsQuery = stocks.join(',');
		var sLoader = new IO.Script();
		sLoader.load(__SINAJS_URL + sinajsQuery, this._show.Bind(this, visitedStocks, hotStocks));
	}
};

//------------------------------------------------------------------------------
// imgController begin
//------------------------------------------------------------------------------
var ImgController = {
	imgArr: [],
	imgUrl: [],
	Init: function () {
//		$("marketImg").innerHTML = $("marketImg").innerHTML.replace(/__CODE__/g,FUNDCODE);

		for (var i = 0; i < this.imgs.length; i++) {
			this.imgArr.push($(this.imgs[i]));
			this.imgUrl.push(this.imgArr[i].src);
		};

		this.imgReflash = window.setInterval(this.update.Bind(this),60000);
	},
	update: function () {
		for (var i = 0; i < this.imgs.length; i++) {
			this.imgArr[i].src = this.imgUrl[i] + "?" + (new Date()).getTime();
		};
	},
	imgs: ["imgFund"]
}


//------------------------------------------------------------------------------
// imgController begin
//------------------------------------------------------------------------------
var PicSwitch = {
	dailyUrl: "http://image.sinajs.cn/newchart/daily/n/@CODE@.gif",
	weeklyUrl: "http://image.sinajs.cn/newchart/weekly/n/@CODE@.gif",
	monthlyUrl: "http://image.sinajs.cn/newchart/monthly/n/@CODE@.gif",
	techUrl: "http://image.sinajs.cn/newchart/macd/n/@CODE@.gif",
	techGlobal: "http://image.sinajs.cn/newchart/@TYPE@/n/@CODE@.gif",
	kLineUrl : "http://image.sinajs.cn/newchart/@TYPE@/n/@CODE@.gif",

	Init: function () {
		this.dailyUrl = this.dailyUrl.replace("@CODE@", FUNDCODE);
		this.weeklyUrl = this.weeklyUrl.replace("@CODE@", FUNDCODE);
		this.monthlyUrl = this.monthlyUrl.replace("@CODE@", FUNDCODE);
		this.techUrl = this.techUrl.replace("@CODE@", FUNDCODE);
		this.techGlobal = this.techGlobal.replace("@CODE@", FUNDCODE);
		this.kLineUrl   = this.kLineUrl.replace("@CODE@" , FUNDCODE);
		$("chartType").onchange = this.techImgChange.Bind(this);
		$("k_type").onchange = this.kLineChange.Bind(this);
	},

	show: function (imgType) {
		this.tempImg = $C("IMG");
		switch (imgType) {
		case "daily":
			this.hideMenu();
			this.tempImg.src = this.dailyUrl;
			this.tempTarget = imgSwitch.targets[1];
			break;
		case "weekly":
			this.hideMenu();
			this.tempImg.src = this.weeklyUrl;
			this.tempTarget = imgSwitch.targets[2];
			break;
		case "monthly":
			this.hideMenu();
			this.tempImg.src = this.monthlyUrl;
			this.tempTarget = imgSwitch.targets[3];
			break;
		case "tech":
			this.showMenu();
			this.tempImg.src = this.techUrl;
			this.tempTarget = imgSwitch.targets[4];
			break;
		}

		if (isIE) {
			this.tempImg.onreadystatechange = this.imgAppend.Bind(this);
		}
		else {
			this.tempImg.onload = this.imgAppend.Bind(this);
		}
		this.tempImg.onerror = this.imgError.Bind(this);
	},

	hideMenu: function () {
		if ($("switchMenu").style.display != "none") {
			$("switchMenu").style.display = "none";
		}
	},

	showMenu: function () {
		if ($("switchMenu").style.display == "none") {
			$("switchMenu").style.display = "";
		}
	},

	imgAppend: function () {
		if (this.tempImg.onreadystatechange) {
			if (this.tempImg.readyState != 'loaded' && this.tempImg.readyState != 'complete') {
				return;
			}
		}
		this.tempTarget.innerHTML = "";
		this.tempTarget.appendChild(this.tempImg);
	},

	imgError: function () {
		this.tempTarget.innerHTML = '<div style="height:250px; line-height:250px;">您所查看的图片不存在或目前不可用，请稍候刷新重试</div>';
	},

	showLoading: function (oTarget) {
		oTarget.innerHTML = '<div class="loading"></div>';
	},

	techImgChange: function () {
		this.showLoading(imgSwitch.targets[4]);
		var tempIMG = $C("IMG");
		tempIMG.src = this.techGlobal.replace("@TYPE@", $("chartType").value);
		tempIMG.onerror = this.imgError.Bind(this);
		imgSwitch.targets[4].innerHTML = "";
		imgSwitch.targets[4].appendChild(tempIMG);
	},
	kLineChange : function () {
		this.showLoading(imgSwitch.targets[4]);
		var tempIMG = $C("IMG");
		tempIMG.src = this.kLineUrl.replace("@TYPE@", $("k_type").value);
		tempIMG.onerror = this.imgError.Bind(this);
		imgSwitch.targets[4].innerHTML = "";
		imgSwitch.targets[4].appendChild(tempIMG);
	}
}


//------------------------------------------------------------------------------
// handstock begin
//------------------------------------------------------------------------------
var HandStockController = {
	codeArr: null,
	rowArr: null,
	Init: function () {
		if (!HANDSTOCK[0] || !HANDSTOCK) {
			return;
		}

		if (!this.rowArr) {
			this.rowArr = $("handstockTbl").tBodies[0].rows;
			this.codeArr = HANDSTOCK;
		}

		var sLoader = new IO.Script();
		var url = __SINAJS_URL + this.codeArr.join(",");
		sLoader.load(url, this.update.Bind(this));
	},
	update: function () {
		for (var i = 0; i < this.codeArr.length; i++) {
			var tempQuote = window["hq_str_" + this.codeArr[i]].split(",");
			if (tempQuote == "") {
				this.rowArr[i].cells[3].innerHTML = PLACEHOLDER;
				this.rowArr[i].cells[4].innerHTML = PLACEHOLDER;
				continue;
			}
			var changeRate = tempQuote[3] != 0 ? ((tempQuote[3] - tempQuote[2]) / tempQuote[2] * 100).toFixed(2) : 0;

			this.rowArr[i].cells[3].innerHTML = this.colorRender(tempQuote[3], changeRate);
			this.rowArr[i].cells[4].innerHTML = this.colorRender(changeRate + "%", changeRate);
		};
	},
	colorRender: function (targetText, change) {
		return '<span style="color:' + getColorCode(change) + ';">' + targetText + '</span>';
	}
}

//------------------------------------------------------------------------------
// quoteData begin
//------------------------------------------------------------------------------
var QuoteData = {
	rowArr: null,
	weibiArr: [10,12,14,16,18,20,22,24,26,28],

	show: function (quote) {
		var tempData = quote;
		for (var i = 0; i < this.weibiArr.length; i++) {
			tempData[this.weibiArr[i]] = parseInt(tempData[this.weibiArr[i]]);
		};

		var buyTotal = tempData[10] + tempData[12] + tempData[14] + tempData[16] + tempData[18];
		var sellTotal = tempData[20] + tempData[22] + tempData[24] + tempData[26] + tempData[28];
		var weibi = ((buyTotal - sellTotal) / (buyTotal + sellTotal) * 100).toFixed(2);
		if(isNaN(weibi)) weibi = PLACEHOLDER;
		else
		{
			weibi = weibi > 0 ? "+" + weibi : weibi;
		}
		var weibiHTML = '<span style="color:' + getColorCode(weibi) + '"> ' + weibi + '%</span>';
		var volumn = isNaN(tempData[8]) ? PLACEHOLDER : (tempData[8] / 100).toFixed(0);
		var turnover = isNaN(tempData[9]) ? PLACEHOLDER : (tempData[9] / 10000).toFixed(2);
		var amplitude = isNaN(tempData[4])||isNaN(tempData[5]||isNaN(tempData[2])||isNaN(tempData[3]))
			? PLACEHOLDER 
			: (Math.abs((tempData[4] - tempData[5])) / tempData[2] * 100).toFixed(2) + "%";
		var huanshoulv = isNaN(tempData[8]) ? PLACEHOLDER 
											: (tempData[8] / LTSHARE / 100).toFixed(2) + "%";
		this.update([
			volumn ,
			turnover ,
			tempData[11],
			tempData[21],
			weibiHTML,
			huanshoulv,
			amplitude ,
			TOTALSHARE,
			LTSHARE
		]);
	},

	update: function (quoteArr) {
		if (!this.rowArr) {
			this.rowArr = $("quoteData").tBodies[0].rows;
		}

		for (var i = 0; i < quoteArr.length; i++) {
			this.rowArr[i].cells[1].innerHTML = PLACEHOLDER;

			this.rowArr[i].cells[1].innerHTML = quoteArr[i];
		};
	}
}

//------------------------------------------------------------------------------
// suggest begin
//------------------------------------------------------------------------------
var Loader = function (url, mark, interval, callback, value) {
	this.url = url;
	this.mark = mark;
	this.interval = interval;
	this.callback = callback;
	this.value = value;
	this.container = null;
	this.thread = -1;
	this.init = function () {
		if (this.container) {
			return;
		}
		this.container = document.createElement("div");
		this.container.style.display = "none";
		document.body.appendChild(this.container);
	};
	this.start = function () {
		this.stop();
		this.load();
		this.thread = setInterval(this.load, this.interval);
	};
	this.stop = function () {
		if (this.thread != -1) {
			clearInterval(this.thread);
			this.thread = -1;
		}
	};
	this.load = function () {
		var loader = arguments.callee.loader;
		var element = document.createElement("script");
		element.type = "text/javascript";
		element.language = "javascript";
		element.charset = "gb2312";
		element.src = loader.url.replace(loader.mark, (new Date()).getTime());
		element[document.all ? "onreadystatechange" : "onload"] = loader.unload;
		element.callback = loader.callback;
		element.value = loader.value;
		loader.init();
		loader.container.appendChild(element);
	};
	this.load.loader = this;
	this.unload = function () {
		if (document.all && this.readyState != "loaded" && this.readyState != "complete") {
			return;
		}
		if (this.callback) {
			this.callback(this.value);
		}
		this.callback = null;
		this.value = null;
		this[document.all ? "onreadystatechange" : "onload"] = null;
		this.parentNode.removeChild(this);
	};
};

var Suggest = function (stringUrl, key) {
	this.stringKeySpliter = ":"
	this.stringRecordSpliter = "|";
	this.stringSystemKeys = "s,sh,sz,0,1,2,3,4,5,6,7,8,9";
	this.arraySystemKeys = new Array();
	this.arrayPrepareKeys = new Array();
	this.intPrepareKeysMaxLength = 50;
	this.stringData = new String();
	
	this.processData = function (valueKey) {
		var suggest = arguments.callee.suggest;
		suggest.stringData = suggest.stringRecordSpliter + window[valueKey];
		var arrayStringSystemKeys = suggest.stringSystemKeys.split(",");
		for (var i =0; i < arrayStringSystemKeys.length; i++) {
			var stringNearestData = suggest.getNearestData(arrayStringSystemKeys[i]);
			var arrayResult = stringNearestData == "" ?  suggest.getResult(suggest.stringData, arrayStringSystemKeys[i]) : suggest.getResult(stringNearestData, arrayStringSystemKeys[i]);
			arrayResult = arrayResult == null ? new Array() : arrayResult;
			suggest.arraySystemKeys.push(new Array(arrayStringSystemKeys[i], arrayResult.join("")));
		}
	};
	this.processData.suggest = this;
	this.loader = new Loader(stringUrl, "@RANDOM@", 0, this.processData, key);
	this.loader.load();
	
	this.getOffsetPos = function (element) {
		var flag = element.tagName.toUpperCase() == "INPUT" ? true : false;
		var posTop = 0, posLeft = 0;
		do {
			posTop += element.offsetTop || 0;
			posLeft += element.offsetLeft || 0;
			element = element.offsetParent;
		} while (element);
		if (navigator.appVersion.indexOf("MSIE 6.0") != -1 && flag) {
			posLeft++;
		}
		return [posLeft, posTop];
	};
	this.getResult = function (stringData, stringKey) {
		var stringRegExpSystem = "$()*+.[?\^{|";
		var stringKeySpliter = (stringRegExpSystem.indexOf(this.stringKeySpliter) < 0 ? "" : "\\") + this.stringKeySpliter;
		var stringRecordSpliter = (stringRegExpSystem.indexOf(this.stringRecordSpliter) < 0 ? "" : "\\") + this.stringRecordSpliter;
		var arrayMatchResult = stringData.match(new RegExp("" + stringRecordSpliter + (isNaN(parseInt(stringKey)) ? "" : "(s[hz])?") + stringKey + "[^\\" + stringRecordSpliter + "|" + stringKeySpliter + "]*" + stringKeySpliter + "[^\\" + stringRecordSpliter + "|" + stringKeySpliter + "|\n]*", "igm"));
		return arrayMatchResult == null ? new Array() : arrayMatchResult;
	};
	
	this.getNearestData = function (stringKey) {
		if (this.arrayPrepareKeys.length == 0) {
			return new String();
		}
		var arrayContainers = new Array();
		for (var i =0; i < this.arraySystemKeys.length; i++) {
			if (this.arraySystemKeys[i][0] == stringKey) {
				return this.arraySystemKeys[i][1];
			}
			if (stringKey.match(new RegExp("^" + this.arraySystemKeys[i][0], "igm")) != null) {
				arrayContainers.push(this.arraySystemKeys[i]);
			}
		}
		for (var i = 0; i < this.arrayPrepareKeys.length; i++) {
			if (this.arrayPrepareKeys[i][0] == stringKey) {
				return this.arrayPrepareKeys[i][1];
			}
			if (stringKey.match(new RegExp("^" + this.arrayPrepareKeys[i][0], "igm")) != null) {
				arrayContainers.push(this.arrayPrepareKeys[i]);
			}
		}
		if (arrayContainers.length == 0) {
			return new String();
		}
		else {
			arrayContainers.sort(
				function (arrayA, arrayB) {
					return arrayB[0].length - arrayA[0].length;
				}
			);
			return arrayContainers[0][1];
		}
	};
	
	this.getQuickResult = function (stringKey) {
		stringKey = stringKey.split(this.stringKeySpliter).join("").split(this.stringRecordSpliter).join("");
		if (stringKey == "") {
			return new Array();
		}
		var stringNearestData = this.getNearestData(stringKey);
		var arrayResult = stringNearestData == "" ?  this.getResult(this.stringData, stringKey) : this.getResult(stringNearestData, stringKey);
		arrayResult = arrayResult == null ? new Array() : arrayResult;
		var booleanIsInSystemKeys = false;
		for (var i = 0; i < this.arraySystemKeys.length; i++) {
			if (this.arraySystemKeys[i][0] == stringKey) {
				booleanIsInSystemKeys = true;
				break;
			}
		}
		var booleanIsInPrepareKeys = false;
		for (var i = 0; i < this.arrayPrepareKeys.length; i++) {
			if (this.arrayPrepareKeys[i][0] == stringKey) {
				booleanIsInPrepareKeys = true;
				break;
			}
		}
		if (!booleanIsInSystemKeys && !booleanIsInPrepareKeys) {
			this.arrayPrepareKeys.push(new Array(stringKey, arrayResult.join("")));
			if (this.arrayPrepareKeys.length > this.intPrepareKeysMaxLength) {
				this.arrayPrepareKeys.sort(
					function (arrayA, arrayB) {
						return arrayA[0].length - arrayB[0].length;
					}
				);
				this.arrayPrepareKeys.pop();
			}
		}
		return arrayResult;
	};
	this.load = function (stringKey) {
		if (stringKey.indexOf(",") != -1 && stringKey.indexOf(",") != 0 && stringKey.indexOf(",") != stringKey.length - 1) {
			var arrayStringKey = stringKey.split(",");
			stringKey = arrayStringKey[arrayStringKey.length - 1];
		}
		if (stringKey.indexOf("\\") != -1) {
			return new Array();
		}
		var stringRegExpSystem = "$()*+.[?^{|";
		for (var i = 0; i < stringRegExpSystem.length; i++) {
			if (stringKey.indexOf(stringRegExpSystem.substr(i, 1)) != -1) {
				return new Array();
			}
		}
		var stringMarket = new String();
		var arrayQuickResult = this.getQuickResult(stringKey);
		arrayQuickResult.length = arrayQuickResult.length > 10 ? 10 : arrayQuickResult.length;
		return arrayQuickResult;
	};
	this.show = function () {
		var element = arguments.callee.element;
		if (!element.booleanScan) {
			return;
		}
		if (element.stringLastValue != element.value && element.value != "基金代码/名称/拼音") {
			element.line = null;
			element.stringLastValue = element.value;
			var arrayResult = element.suggest.load(element.value);
			if (arrayResult.length > 0) {
				element.divHint.style.display = "block";
				var arrayPosition = element.suggest.getOffsetPos(element);
				element.divHint.style.left = arrayPosition[0] + "px";
				element.divHint.style.top = arrayPosition[1] + "px";
				element.divHint.style.marginTop = element.clientHeight + 1 + "px";
				element.divHint.style.width = element.clientWidth > 200 ? element.clientWidth : 200 + "px";
				var tableContainer = document.createElement("table");
				tableContainer.className = "tableSuggest";
				tableContainer.cellPadding = 0;
				tableContainer.cellSpacing = 0;
				var trHeader = tableContainer.insertRow(0);
				trHeader.className = "trHeader";
				var tdKey = trHeader.insertCell(0);
				tdKey.innerHTML = "选项";
				var tdCode = trHeader.insertCell(1);
				tdCode.innerHTML = "代码";
				var tdName = trHeader.insertCell(2);
				tdName.innerHTML = "名称";
				for (var i = 0; i < arrayResult.length; i++) {
					if (isNaN(parseInt(i))) {
						continue;
					};
					var arrayRecord = arrayResult[i].replace("|", "").split(":");
					var arrayCodeAndName = arrayRecord[1].split("-");
					var trRecord = tableContainer.insertRow(parseInt(i) + 1);
					var tdKey = trRecord.insertCell(0);
					tdKey.innerHTML = arrayRecord[0];
					var tdCode = trRecord.insertCell(1);
					tdCode.innerHTML = arrayCodeAndName[0] + arrayCodeAndName[1];
					var tdName = trRecord.insertCell(2);
					tdName.innerHTML = arrayCodeAndName[2];
					trRecord.stringFullCode = arrayCodeAndName[0] + arrayCodeAndName[1];
					trRecord.inputTarget = element;
					trRecord.onmouseover = function () {
						this.inputTarget.overLine = this;
						this.className = this.inputTarget.line == this ? "overSelectedLine" : "overLine";
					};
					trRecord.onmouseout = function () {
						this.inputTarget.overLine = null;
						this.className = this.inputTarget.line == this ? "selectedLine" : "";
					};
					trRecord.onmousedown = function () {
						this.inputTarget.booleanScan = true;
						this.inputTarget.setLine(this);
					};
				}
				element.divHint.innerHTML = "";
				element.divHint.appendChild(tableContainer);
				element.tableHint = tableContainer;
			}
			else {
				element.divHint.style.display = "none";
				element.divHint.innerHTML = "";
				element.tableHint = null;
			}
		}
	};
	this.bind = function (element) {
		element.suggest = this;
		element.show = this.show;
		element.show.element = element;
		element.intThread = -1;
		element.arrayData = new Array();
		element.value = "基金代码/名称/拼音";
		element.style.color = "#999999";
		element.booleanScan = true;
		element.autocomplete = "off";
		var divDataTable = document.createElement("div");
		divDataTable.style.display = "none";
		element.parentNode.insertBefore(divDataTable, element);
		element.divHint = divDataTable;
		element.tableHint = null;
		element.line = null;
		element.overLine = null;
		divDataTable.className = "suggest";
		element.onfocus = function () {
			if (this.value == "基金代码/名称/拼音" || this.value == "代码输入错误") {
				this.value = "";
				this.style.color = "";
			};
			this.stringLastValue = this.value;
			if (this.divHint.innerHTML != "") {
				this.divHint.style.display = "block";
				var arrayPosition = this.suggest.getOffsetPos(this);
				this.divHint.style.left = arrayPosition[0] + "px";
				this.divHint.style.top = arrayPosition[1] + "px";
				this.divHint.style.marginTop = this.clientHeight + 1 + "px";
				this.divHint.style.width = this.clientWidth > 200 ? this.clientWidth : 200 + "px";
			}
			this.intThread = setInterval(this.show, 10);
		};
		element.onblur = function () {
			if (this.value == "") {
				this.value = "基金代码/名称/拼音";
				this.style.color = "#999999";
			};
			this.divHint.style.display = "none";
			clearInterval(this.intThread);
			this.intThread = -1;
		};
		element.setLine = function (line) {
			var stringKeyFore = "";
			if (this.value.indexOf(",") != -1 && this.value.indexOf(",") != 0 && this.value.indexOf(",") != this.value.length - 1) {
				var arrayStringKeyFore = this.value.split(",");
				arrayStringKeyFore[arrayStringKeyFore.length - 1] = "";
				stringKeyFore = arrayStringKeyFore.join(",");
			}
			if (this.line != null) {
				this.line.className = this.overLine == this.line ? "overLine" : "";
			}
			this.line = line;
			line.className = this.overLine == line ? "overSelectedLine" : "selectedLine";
			this.value = stringKeyFore + line.stringFullCode;
		};
		element.onkeydown = function () {
			if (!this.tableHint) {
				return true;
			}
			var stringKeyFore = "";
			if (this.value.indexOf(",") != -1 && this.value.indexOf(",") != 0 && this.value.indexOf(",") != this.value.length - 1) {
				var arrayStringKeyFore = this.value.split(",");
				arrayStringKeyFore[arrayStringKeyFore.length - 1] = "";
				stringKeyFore = arrayStringKeyFore.join(",");
			}
			
			var event = arguments[0] || window.event;
			switch (event.keyCode) {
				case 38: //up
					this.booleanScan = false;
					if (this.line == null || this.line.rowIndex == 1) {
						this.setLine(this.tableHint.rows[this.tableHint.rows.length - 1]);
					}
					else {
						this.setLine(this.tableHint.rows[this.line.rowIndex - 1]);
					}
					return false;
					break;
				case 40: //down
					this.booleanScan = false;
					if (this.line == null || this.line.rowIndex == this.tableHint.rows.length - 1) {
						this.setLine(this.tableHint.rows[1]);
					}
					else {
						this.setLine(this.tableHint.rows[this.line.rowIndex + 1]);
					}
					return false;
					break;
				case 13: //Enter
					this.booleanScan = true;
					this.stringLastValue = stringKeyFore + this.value;
					this.divHint.style.display = "none";
					break;
				default:
					this.booleanScan = true;
					break;
			}
		};
	};
	this.getCode = function (value) {
		var result = this.load(value);
		if (result.length == 1) {
			var stock = result[0].split(":")[1].split("-");
			return stock[0] + stock[1];
		}
		else {
			return value;
		}
	};
};

function checkSuggest() {
	var value = document.getElementById('suggestInput').value;
	if (value=="基金代码/名称/拼音" || value=="") {
		return false;
	}
	return true;
}

function main () {
	var visitedFunds = new VisitedStocks();
	visitedFunds.set(FUNDCODE);

	window.nav = new Nav(
		[
			["http://finance.sina.com.cn/", "财经首页"],
			["http://finance.sina.com.cn/fund/", "基金首页"],
			["http://finance.sina.com.cn/fund/supermall/fundmall.html", "基金超市"],
			["http://stock.finance.sina.com.cn/", "行情"],
			["http://finance.sina.com.cn/column/jsy.html", "大盘"],
			["http://finance.sina.com.cn/column/ggdp.html", "个股"],
			["http://finance.sina.com.cn/column/ywgg.html", "要闻"],
			["http://finance.sina.com.cn/column/ssgs.html", "公司"],
			["http://finance.sina.com.cn/stock/newstock/index.shtml", "新股"],
			["http://finance.sina.com.cn/column/data.html", "数据"],
			["http://finance.sina.com.cn/stock/reaserchlist.shtml", "报告"],
			["http://finance.sina.com.cn/money/globalindex/index.shtml", "环球市场"],
			["http://finance.sina.com.cn/stock/usstock/index.shtml", "美股"],
			["http://finance.sina.com.cn/stock/hkstock/index.shtml", "港股"],
			["http://biz.finance.sina.com.cn/hq/", "行情中心"],
			["http://vip.stock.finance.sina.com.cn/portfolio/main.php", "自选股"]
		]
	);
	showRealtimeIndexs();
	window.setInterval('showRealtimeIndexs()',5000);

	window.suggestFund = new Suggest("http://finance.sina.com.cn/iframe/js/suggest_fund.js", "SuggestFundData");
	window.suggestFund.bind($("suggestInput"));
	
//	window.navLeft = new NavLeft();
	
	FundQuote.Init();
	ImgController.Init();
	window.fundMarket = new TabSwitch($("imgTabs"),$("marketImg"),$("marketData"));
	PicSwitch.Init();
	window.imgSwitch = new TabSwitch($("picSwitchTabs"),$("picSwitchContent"),null,[PicSwitch.hideMenu.Bind(PicSwitch), PicSwitch.show.Bind(PicSwitch, "daily"), PicSwitch.show.Bind(PicSwitch, "weekly"), PicSwitch.show.Bind(PicSwitch, "monthly"), PicSwitch.show.Bind(PicSwitch, "tech")]);
	FundCompare.Init();

//	window.fundIndexes = new TabSwitch($("fundIndexTabs"),$("fundIndex"));

	window.centerColumnPart1 = new TabSwitch($("centerColumnTabs1"),$("centerColumnContent1"));
	window.centerColumnPart2 = new TabSwitch($("centerColumnTabs2"),$("centerColumnContent2"));
	window.centerColumnPart3 = new TabSwitch($("centerColumnTabs3"),$("centerColumnContent3"));
	window.centerColumnPart4 = new TabSwitch($("centerColumnTabs4"),$("centerColumnContent4"));

	HandStockController.Init();
	window.setInterval('HandStockController.Init()',60000);

	window.rankOpenFund = new TabSwitch($("ranks1Tabs"),$("ranks1Content"));
	window.rankCloseFund = new TabSwitch($("ranks2Tabs"),$("ranks2Content"));
	//window.rankCloseFundTs = new TabSwitch($("ranks3Tabs"),$("ranks3Content"));

	FundRanks.Init();

	VisitedStocksTable.show();
}