var PLACEHOLDER = "--";//定义过存续期／封闭期的行情数据占位符

//{{{    base function
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 left
//------------------------------------------------------------------------------
var NavLeft = function () {
	this.tempHtml = $("navLeft").innerHTML;
	this.tempHtml = this.tempHtml.replace(/@CODE@/g,FUNDCODE);
	$("navLeft").innerHTML = this.tempHtml;
}

//}}}
// 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';
//头部的基金行情


//{{{ 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);
	
	$('realtimeIdxs').innerHTML = '<span class="marginRight"><a href="http://finance.sina.com.cn/realstock/company/sh000001/nc.shtml" target="_blank">上证指数</a> <span style="color:' + _sh000001Color + '">' + _sh000001[3] + ' ' + _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 + '">' + _sz399001[3] + ' ' + _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 + '">' + _sh000011[3] + ' ' + _sh000011_changerate +'%</span></span><span><a href="http://finance.sina.com.cn/fund/quotes/index399305.shtml" target="_blank">深证基金</a> <span style="color:' + _sz399305Color + '">' + _sz399305[3] + ' ' + _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(',');
	}
};
//}}}

//{{{		FundFormatter
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] - 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] - 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));
	}
};
//}}}

//{{{			CFFundQuote
var CFFundQuote = {
	dataQuote: [],
	dataReal: [],
	Init: function () {
		this.futureTblTpl = this.futureTblTpl.replace("@TOTALSHARE@", TOTALSHARE).replace("@LTSHARE@", LTSHARE);
		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)
			? "0"
		   	: ((this.dataQuote[3] - this.dataReal[1]) / this.dataReal[1] * 100).toFixed(2);
		var changePrice = (this.dataQuote[3]==PLACEHOLDER)||(this.dataQuote[2]==PLACEHOLDER) 
						? PLACEHOLDER 
						:(this.dataQuote[3] - this.dataQuote[2]).toFixed(3) ;
		var changeRate = (this.dataQuote[3]==PLACEHOLDER)||(this.dataQuote[2]==PLACEHOLDER) 
						? 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($("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]]
			]);


		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);
	},

	titleTpl: '<table class="head">\
				<tbody>\
					<tr><th><h1>@FUNDNAME@</h1>@FUNDTYPE@ @FUNDCODE@</th><td><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>'
}
//}}}
//{{{main 
function main () {
	var visitedFunds = new VisitedStocks();
	visitedFunds.set(FUNDCODE);
	showRealtimeIndexs();
	window.setInterval('showRealtimeIndexs()',5000);
	if(FUNDTYPE == '封闭式基金')
		CFFundQuote.Init();
	else
		OFFundQuote.Init();
	VisitedStocksTable.show();
}
//}}}
//{{{	OFFundQuote
//------------------------------------------------------------------------------
var OFFundQuote = {
	dataFuture: [],
	dataReal: [],
	Init: function () {
		this.fundTrackTpl = this.fundTrackTpl.replace("@TOTALSHARE@", TOTALSHARE).replace("@LTSHARE@", LTSHARE);
		this.scriptLoader();
		this.tplReplace($("fundTitle"),this.titleTpl,[
				["@FUNDNAME@",FUNDNAME],
				["@FUNDTYPE@",FUNDTYPE],
				["@FUNDCODE@",FUNDCODE],
				["@FUNDSYMBOL@",FUNDCODE],
				["@FUNDURL@",window.location.href]
			]);
		var quoteInterval = window.setInterval(this.scriptLoader.Bind(this),60000);
	},
	scriptLoader: function () {
		var sLoader = new IO.Script();
		var url = __SINAJS_URL + "fu_" + FUNDCODE + ",f_" + FUNDCODE ;
		//如果BOURSE没有定义，则不需要取行情数据
		if(FUNDTYPE == 'LOF基金' || FUNDTYPE == 'ETF基金')
		{
			url += "," + BOURSE + FUNDCODE;
		}
		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.dataFuture = [];
		this.dataReal = [];
		//如果hq_str_fu_FUNDCODE不存在，则说明该基金没有预测值，表头不显示
		if(window["hq_str_fu_" + FUNDCODE]){ 
			var tempDF = window["hq_str_fu_" + FUNDCODE].split(",");
			for (var i = 0; i < tempDF.length; i++) {
				this.dataFuture.push(tempDF[i] ? tempDF[i] : PLACEHOLDER)
			};
		}
		else var tempDF = false;

		var tempDR = window["hq_str_f_" + FUNDCODE].split(",");
		for (var i = 0; i < tempDR.length; i++) {
			this.dataReal.push(tempDR[i] ? tempDR[i] : PLACEHOLDER)
		};
		var fu_color = getColorCode(this.dataFuture[6]);
		var f_color = getColorCode(this.dataReal[1] - this.dataReal[3]);


		if (FUNDTYPE != "货币型基金" ) {
			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]]
				]);
			if(tempDF == false) 
				this.tplReplace($("futureTbl"),'',[]);
			else
			this.tplReplace($("futureTbl"),this.futureTblTpl,[
					[/@FUTURE_PRICE@/g,this.colorRender(this.dataFuture[2],fu_color)],
					[/@CHANGE@/g,this.colorRender((this.dataFuture[2] * this.dataFuture[6] / 100).toFixed(4),fu_color)],
					[/@CHANGE_RATE@/g,this.colorRender((this.dataFuture[6] + "%"),fu_color)],
					["@LAST_UPDATE_TIME@",this.dataFuture[1]],
					["@LAST_CLOSE@",this.dataFuture[3]],
					["@TOTAL_PRICE@",this.dataFuture[4]],
					["@CHANGE_SPEED@",this.dataFuture[5]]
				]);
			if(QDIIFlag==1)
			{
				$("moneyFund").style.display = "";
				$("futureTbl").style.display = "none";
				$("fundTrack").style.display = "none";
			}
		}
		else if (FUNDTYPE == "货币型基金"){
			this.tplReplace($("realTh"),this.moneyRealThTpl,[
					["@REAL_PRICE@",this.dataReal[1]],
					["@PROFIT_RATE@",this.dataReal[2]],
					["@REAL_UPDATE_TIME@",this.dataReal[4]]
				]);
			$("moneyFund").style.display = "";
			$("futureTbl").style.display = "none";
			$("fundTrack").style.display = "none";
		}
		/*
		 * 如果是LOF基金
		 * 2007-12-24  
		 * junliang add
		 */
		if(FUNDTYPE == 'ETF基金')
		{
			this.dataQuote = [];
			var fundTrackData = window["hq_str_" + BOURSE+FUNDCODE].split(",");
			for (var i = 0; i < fundTrackData.length; i++) {
				this.dataQuote.push(fundTrackData[i] ? fundTrackData[i] : PLACEHOLDER)
			};
			for(var i=0;i<32;i++)
			{
				this.dataQuote[i] = typeof this.dataQuote[i]=='undefined' 
					? PLACEHOLDER 
					: this.dataQuote[i];
			}
			var quote_color = getColorCode(this.dataQuote[3] - this.dataQuote[2]);

			var priceOff = (this.dataQuote[3]==PLACEHOLDER)||(this.dataQuote[1]==PLACEHOLDER)
				? "0"
				: ((this.dataQuote[3] - this.dataReal[1]) / this.dataReal[1] * 100).toFixed(2);
			var changePrice = (this.dataQuote[3]==PLACEHOLDER)||(this.dataQuote[2]==PLACEHOLDER) 
							? PLACEHOLDER 
							:(this.dataQuote[3] - this.dataQuote[2]).toFixed(3) ;
			var changeRate = (this.dataQuote[3]==PLACEHOLDER)||(this.dataQuote[2]==PLACEHOLDER) 
							? 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($("fundTrack"),this.fundTrackTpl,[
				["@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 + "%"]
			]);

			if (this.lastPrice != this.dataQuote[3] || !this.lastPrice) {
				this.lastPrice = this.dataQuote[3];
			}
			else {
				return ;
			}
			this._twinkle(0);
			$("moneyFund").style.display = "none";
			$("futureTbl").style.display = "none";
			$("fundTrack").style.display = "";
		}

	},
	_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);
	},

	/*统一头模板
	 * 2007-12-13  junliang
	 */
	titleTpl: '<table class="head">\
				<tbody>\
					<tr><th><h1>@FUNDNAME@</h1>@FUNDTYPE@ @FUNDCODE@ </th><td style="width:130px;"></td><td><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@',
	/*当日预测表头模板
	 * 2007-12-13  junliang
	 */
	futureTblTpl: '<table>\
					<tbody>\
						<tr><th rowspan="2"><h2>@FUTURE_PRICE@</h2><h5>@CHANGE@ (@CHANGE_RATE@)</h5><h6>@LAST_UPDATE_TIME@</h6></th><td>最新估值: @FUTURE_PRICE@</td><td>昨日净值: @LAST_CLOSE@</td><td>累计净值: @TOTAL_PRICE@</td></tr>\
						<tr><td>涨跌幅: @CHANGE_RATE@</td><td>涨跌额: @CHANGE@</td><td>五分钟涨速: @CHANGE_SPEED@</td></tr>\
					</tbody>\
					</table>',
	realThTpl : '<span class="moneyH4">最新净值: @REAL_PRICE@</span><span class="moneyH4">累计净值: @REAL_TOTAL_PRICE@</span><span class="moneyH4">净值增长率：@REAL_CHANGE_RATE@  &nbsp;&nbsp;&nbsp;@REAL_UPDATE_TIME@</span>',
	moneyRealThTpl : '<span class="moneyH4">最新万份收益: @REAL_PRICE@</span><span class="moneyH4">7日年化收益率: @PROFIT_RATE@%</span><span class="moneyH4">@REAL_UPDATE_TIME@</span>',
	/*
	 * 基金走势表头模板
	 * 2007-12-13 junliang
	 */
	compareHeadTpl:'@FUNDNAME@',
	fundTrackTpl: '<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>'
}