/**********************************************************
 *    boardBlock.js
 *    @Copyright compass.cn P.R.China, All rights resevered
 *    @Description
 *        沪深综合排行 沪综合排行 深综合排行 沪深排序 板块排序
 *    @History
 *        2008/08/04 by bu hailiang create
 *        2008/12/29 by liang huang modify
************************************************************/

// flag const varible
//沪深综合
var SUMTYPE = 0;
//综合排名
var CLASSTYPE = 1;
//全股票列表
var CLASSSTOCKTYPE = 2;
//板块股票列表
var BOARDSTOCKTYPE = 3;

//全股票数据url
var sortListUrl = "http://" + rdmDataDomainNameGet() + "/test/sort2.py/sortList.znzDo?cmd=";
//板块数据url
var sortBoardStockUrl = "http://" + rdmDataDomainNameGet() + "/test/board.py/boardStocks.znzDo?cmd=";
//沪深综合url
var summaryUrl = "http://" + rdmDataDomainNameGet() + "/test/sort2.py/summaryAB?cmd=";
//综合排名
var classUrl = "http://" + rdmDataDomainNameGet() +  "/test/sort2.py/sortSummary?cmd=";

/* newSort construct function
 *  divId : div object's id which will formated html code
 *  divHeight: div object's height
 *  metric: sort col name
 *  order: sort director
 *  showRowNum: data row num per page
 *  interval: date update time interval
 *  start: default start or not 
 *  preData: pre fetch data
 */
function newSort(divId, divHeight, divWidth, metric, order, showRowNum, interval, start, preData, jmpUrl)
{
    this._init(divId, divHeight, divWidth, metric, order, showRowNum, interval, preData, jmpUrl);
    if(start)
    {
        this._start();
    }
}

/* init class newSort's member value
 * parameters same as construct
 */
newSort.prototype._init = function(divId, divHeight, divWidth, metric, order, showRowNum, interval, preData, jmpUrl)
{
    this.mDivId = divId;
    this.mDivObj = $(this.mDivId);    
    // no this html element 
    if(!this.mDivObj)
        return;
    
    this.mDivHeight = divHeight;
    this.mInterval = interval;
    
    if(preData)
    {
        this.mPreData = preData.substring(0, preData.length - 1);
    }

    //hash set function
    this.mSetFunHash = [this._ABSet, this._inteOrderset,
        this._tableSet, this._tableSet];
    
    //hash url function
    this.mJustFunHash = [this._ABUrlJust, this._inteOrderUrlJust,
    this._totalListUrlJust, this._boardListUrlJust];
    this.mJumpUrl = jmpUrl || "realstock.php";    
    this.mCurrType = ""
    this.mCurrDataURL = "";
    this.mCurrCallBack = null;
    this.mCurrJustFunc = null;
    this.mParentID = 0;
    this.mChildID = 0;    
    this.mAjaj = null;
    
    // record stock list rows num
    this.mShowRowNum = showRowNum;
    this.mTotalRowNum = 0;
    // default sort col is ratio
    this.mMetric = metric || "ratio";
    this.mOrder = order || "desc";
    this.mStartNum = 0;
    this.mTimer = null;
    this.fixtable = new fixHeaderTable([[]], 1, 3, this.mShowRowNum, 14, divId, divWidth, this.mDivHeight, this._tableCallBackFunc.bind(this)); 
}

newSort.prototype._tableCallBackFunc = function()
{
    if(this.mParentID != CLASSSTOCKTYPE && this.mParentID != BOARDSTOCKTYPE)
    {
        return;
    }
    this.mStartNum = this.fixtable.ry;
    this.mCurrDataURL = this.mCurrJustFunc();
    this._refresh();
}

//default start function
newSort.prototype._start = function()
{
    this.running = true;
    this.changeType(0, 0, "summary|");
}

//沪深综合排名 格式化数据源请求接口url
newSort.prototype._ABUrlJust = function()
{
    return summaryUrl + Math.random();
}

//格式化综合排名数据源URL 
newSort.prototype._inteOrderUrlJust = function()
{
    var mc = this.mCurrType.split("|");
    if(mc[0].toLowerCase().indexOf("sh") != -1)
    {
        mc[0] = "sh";
    }
    else
    {
        mc[0] = "sz";
    }
    
    var retUrl = "";
    if(mc.length != 2)
    {
        retUrl = classUrl + "sh|A|";
    }
    else
    {
        retUrl = classUrl + mc[0] + "|" + mc[1] + "|";
    }
    
    return retUrl + Math.random();  
}

//格式化全列表接口数据源接口
newSort.prototype._totalListUrlJust = function()
{
    var retUrl = sortListUrl;
    var mc = this.mCurrType.split("|");
    
    // 预取三条  mc[0]= sz || sh,  mc[1] = A||B....
    retUrl += [mc[0], mc[1], this.mOrder, this.fixtable.ry, 
        this.mShowRowNum + 3, this.mMetric, Math.random()].join("|");
    return retUrl;
}

/*板块全列表接口*/
newSort.prototype._boardListUrlJust = function()
{
    var retUrl = sortBoardStockUrl;
    
    // 预取三条  this.mCurrType=板块号
    retUrl += [this.mCurrType, this.mOrder, this.fixtable.ry, 
        this.mShowRowNum + 3, this.mMetric, Math.random()].join("|");
    return retUrl;    
}

/*切换显示类型*/
newSort.prototype.changeType = function(parentID, childID, stockType)
{
    this.mParentID = parentID;
    this.mChildID = childID;
    this.mCurrType = stockType;
    
    if(this.isList())
    {
        this._clearTableData();
    }
    
    this.running = true;  
    // record curr just func
    this.mCurrJustFunc = this.mJustFunHash[parentID];    
    this.mCurrDataURL = this.mCurrJustFunc();
    this.mCurrCallBack = this.mSetFunHash[parentID];
    
    this._update();
}

/*clear table data*/
newSort.prototype._clearTableData = function()
{
    this.fixtable.ry = 0;
    this.mStartNum = 0;
}


/*control update*/
newSort.prototype._update = function()
{
    
    //sure only one thread is running clear time signal handler
    if(this.mTimer)
        window.clearTimeout(this.mTimer);
    
    if(this.running)
    {
        if(this.mPreData)
        {
            this.mCurrCallBack(this.mPreData);
            this.mPreData = null;
        }
        else
        {           
            this.mCurrDataURL = this.mCurrJustFunc();
            this._refresh();
        }
    }
    
    var timeInterval = this.mInterval;
    if(this.mParentID == SUMTYPE)
    {
        timeInterval = 30 * 1000;
    }
    //this.mTimer = window.setTimeout(this._update.bind(this), timeInterval);
}

/* new ajaj fetch data */
newSort.prototype._refresh = function()
{
    if (this.myAjaj){
        this.myAjaj.destroy();
    }
   
    var args = {
        method : "get",
        onComplete : function(re){                 
            try{ this.mCurrCallBack(re);}catch(E){}            
        }.bind(this)
    }
    this.myAjaj = new Ajaj(this.mCurrDataURL, args);
}

/* format <a>*/
newSort.prototype._formatA = function(market, mtype, sort, order)
{
    var formatStr = 'href=\'newsort.php?market=' + market + '&type=' + mtype + '&sort=' + sort + '&order=' + order + '\'';
    return formatStr;
}

/* judge newSort current show type */
newSort.prototype.isList = function()
{
    if(this.mParentID != CLASSSTOCKTYPE && this.mParentID != BOARDSTOCKTYPE)
    {
        return false;
    }
    return true;
}

/* navigator showed body size has change*/
newSort.prototype.sizeRefresh = function()
{
    this.mCurrDataURL = this.mCurrJustFunc();
    this._refresh();
}

/* 获得板块列表名称 */
newSort.prototype.getName = function(dataUrl, callBack)
{
    var args = {
        method : "get",
        onComplete : function(jsonStr){    
            if(jsonStr == "[-1]")
                callBack("");
            var reObj = KISSY.JSON.parse(jsonStr);
            callBack(decodeURIComponent(reObj[1]));
        }.bind(this)
    }   
    var myAjaj = new Ajaj(dataUrl, args);
}

// 沪深综合排名显示列表顺序
newSort.prototype.szABListOrder = ["ratio_inc", "ratio_dec", "volume", "amount", "price_inc", "price_dec", "turnover", "zhenfu"];

// 沪深综合排名显示列表顺序title 中文名
newSort.prototype.szABListName = ["涨幅前10", "跌幅前10", "总量前5", "总额前5", "高价股前5", "低价股前5", "换手前5", "振幅前5"];

// 沪深综合排名显示列表中最后一列title中文名
newSort.prototype.szABColName = ["涨幅 &nbsp;", "跌幅 &nbsp;", "成交量(手)", "成交额(万)", "涨跌幅", "涨跌幅", "换手率", "振幅 &nbsp;"];

// 沪深综合排名显示列表中最后一列后缀名
newSort.prototype.szABColUint = ["%", "%", "", "", "%", "%", "%", "%"];

// 沪深综合排名显示列表中最后一列后颜色属性 -1根据自己的正负值确定自己的颜色0为黑色
newSort.prototype.szABColColors = [-1, -1, 0, 0, -1, -1, 0, 0]

/* 沪深综合排名 */
newSort.prototype._ABSet = function(re)
{
    // data error
    if(re == "[-1]")
    {
        return;
    }
    var retObj = KISSY.JSON.parse(re);
    var sh = retObj["sh"];
    var sz = retObj["sz"];
    var shA = KISSY.JSON.parse(sh["A"]);
    var shB = KISSY.JSON.parse(sh["B"]);
    var szA = KISSY.JSON.parse(sz["A"]);
    var szB = KISSY.JSON.parse(sz["B"]);
    
    var abList = [shA, szA, shB, szB];
    var abListName = ["shA", "szA", "shB", "szB"];
    var abListCName = ["沪A", "深A", "沪B", "深B"];
    
    // format div inner html
    var div = "";
    var divArr = [];
    var i, j, k;
    var it = null;
    for(i = 0; i < this.szABListOrder.length; i ++)
    {
        
        var itname = this.szABListOrder[i];
        var typen = itname.split("_");
        if (typen.length != 2)
            typen[1] = "desc";
        if (typen[1] == "dec")
            typen[1] = "asc";
        else
            typen[1] = "desc";
        var typename = this.szABListName[i];
        
        for(j = 0; j < abList.length; j ++)
        {
            it = abList[j][itname];
            var formata = this._formatA(abListName[j].substring(0, 2), abListName[j].substring(2), typen[0], typen[1]);
            //i == 0 && j== 0 ? alert(formata) : "";
            divArr.push('<div class="mod81">');
            divArr.push('<div class="mod81-title"><ul><li>&nbsp;' + abListCName[j] + typename + '</li></ul>&nbsp;<a ');
            divArr.push( formata + ' >更多&gt;&gt;</a></div>');
            divArr.push('<div class="mod81-content">');
            divArr.push("<table><tr><th width='15%'>排名</th><th width='32%'>股票名称</th><th style='text-align: right;'>价格</th><th style='text-align: right'>");
            divArr.push(this.szABColName[i] + "</th></tr>");
            for(k = 0; k < it.length; k ++)
            {
                var cur = it[k];
                var stockcode = cur[0];
                var stocktype = stockcode.substr(0,2).toLowerCase();
                stockcode = stockcode.substr(4);
    
                divArr.push("<tr class='hastop'><td>" + ( k + 1 ) + "</td>");
                divArr.push("<td><a href='" + this.mJumpUrl+ "?code="+ stocktype + stockcode +"'>" + decodeURIComponent(cur[1]) + "</a></td>");
                
                //color for new price
                var curlast = cur[2];
                var valueclass = "nocolor";
                if (curlast < cur[3]){
                    valueclass = "incolor";
                }
                if (curlast > cur[3]){
                    valueclass = "decolor";
                }                 
                
                divArr.push("<td style='text-align: right' class='" + valueclass + "'>" + cur[3].toFixed(cur[5] ? 3 : 2) + "</td>");
                
                if(typen[0] == 'price')
                {
                    cur[4] = (cur[3] - cur[2]) / cur[2] * 100;
                }
                
                //color for value            
                if (this.szABColColors[i] <= 0){
                    valueclass = "noclor";
                    if (this.szABColColors[i] < 0){
                        if (cur[4] > 0){
                            valueclass = "incolor";
                        }
                        if (cur[4] < 0){
                            valueclass = "decolor";
                        }
                    }
                }

                var conStr = cur[4].toFixed(cur[5] ? 3 : 2);
                if(itname == "volume")
                {
                    conStr = cur[4];
                }                
                divArr.push("<td style='text-align: right' class='" + valueclass + "'>" + conStr + this.szABColUint[i] + "</td></tr>");
            }
            divArr.push("</table></div></div>");
        }

       
    }
    div = divArr.join("");
    
    innerSet(this.mDivObj, div, null);
}

// format table 报价牌
/*some default value for sort*/
newSort.prototype.metrics = ["price", "volume", "amount", "ratio", "liangbi", "turnover", "ratio5", "weibi", "zhenfu"];

//传入数据的各列对应的含义
newSort.prototype.cols = ["代码", "昨收", "今开", "现价", "总量(手)",   "总额(万)", "最高", "最低", "买入价",
     "卖出价",   "涨幅", "量比", "换手率", "5分钟涨幅", "isLongPrice",   "股票名称", "委比", "振幅"];

//该列是否可以排序,>0为对应的metric id+1
newSort.prototype.colSortable = [0, 0, 0, 1, 2,   3, 0, 0, 0, 0,   4, 5, 6, 7, 0,   0, 8, 9];

//该列是否显示变化的颜色，0为不显示，-1为根据自身的值显示，1为根据昨收显示
newSort.prototype.colColor = [0, 0, 1, 1, 0,   0, 1, 1, 1, 1,   -1, 0, 0, -1, 0,   0, -1, 0];

//该列是否以标准的小数显示, 1为小数，-1为百分比
newSort.prototype.colToFix = [0, 1, 1, 1, 0,   0, 1, 1, 1, 1,   -1, 1, -1, -1, 0,  0, -1, -1];

//显示的列的顺序
newSort.prototype.colpos = ["代码", "股票名称", "昨收", "今开", "现价",   "总量(手)", "总额(万)", "最高",
     "最低", "买入价",   "卖出价", "涨幅", "量比", "换手率", "5分钟涨幅",   "委比", "振幅"];

newSort.prototype.sort = function(sortid)
{
    // if current show is not list
    if(this.mParentID != CLASSSTOCKTYPE && this.mParentID != BOARDSTOCKTYPE)
    {
        return;
    }
    
    var metric = this.metrics[sortid - 1] || this.metrics[0];
    if (this.mMetric == metric){
        this.mOrder = (this.mOrder == "desc") ? "asc" : "desc";
        this.mStartNum = 0;
        this.fixtable.ry = 0;
    }else{
        this.mMetric = metric;
        this.mOrder = "desc";
    }
    
    this._update();
}

/*parse Obj*/
newSort.prototype._parseTableData = function(jsonStr){
    var reObj = KISSY.JSON.parse(jsonStr);
    
    //如果是板块股票列表 
    if(this.mParentID == BOARDSTOCKTYPE)
    {
        this.mTotalRowNum = reObj[2];
        reObj = KISSY.JSON.parse(reObj[3]);
    }
    else
    {       
        //全股票列表
        this.mTotalRowNum = reObj[0];
        reObj = KISSY.JSON.parse(reObj[1]);
    }
     
    return reObj;
}

/*set table header*/
newSort.prototype._setTableHeader = function(reObj){
    var tabledata = [];
    tabledata.push([["序号"]]);
    for(var j = 0; j < this.colpos.length; j ++)
    {
        // get col name
        var itext = this.colpos[j];
        //找出所排列在传入序列中的位置
        var idx = this.cols.indexOf(itext);
        
        if (idx >= 0 && this.colSortable[idx])
        {
            if (this.mMetric == this.metrics[this.colSortable[idx] - 1 ]){
                
                if (this.mOrder == "desc")
                    itext += "↓";
                else
                    itext += "↑";
            }
            tabledata[0].push([itext, 'nocolor', "javascript:sortCol(" + this.colSortable[idx] + "," + j + ");void(0);"]);
        }
        else
        {
            tabledata[0].push([itext]);
        }
    }
    return tabledata;
}

/*set color for a td*/
newSort.prototype._setColor = function(idx, nowprice, lastprice, fixNum)
{
    if (idx < 0)
        return ["--"];
    
    var coltype = this.colColor[idx];
    var colfix = this.colToFix[idx];
    var ret = [];
    if (coltype != 0)
    {
        var classn = "nocolor";
        if (coltype > 0)
        {
            if (nowprice > 99990)
                nowprice = 0;
            if (nowprice > 0)
            {
                if (nowprice > lastprice)
                    classn = "incolor";
                if (nowprice < lastprice)
                    classn = "decolor";
            }
        }
        else
        {
            if (nowprice > 0)
                classn = "incolor";
            if (nowprice < 0)
                classn = "decolor";
        }
        ret.push(classn);
    }
    
    if (colfix > 0)
    {
        nowprice = nowprice.toFixed(fixNum || 0);
    }
    
    if (colfix < 0)
    {
        nowprice = nowprice.toFixed(2) + "%";
    }
    else
    {
        if (nowprice == 0)
        {
            nowprice = "--";
        }
    }
    ret.unshift(nowprice);
    return ret;
}

/*set a row data to table*/
newSort.prototype._setItem = function(arrayId, oData){
    var ret = [[arrayId]];
    var stockcode = oData[0];
    var stocktype = stockcode.substring(0,2).toLowerCase();
    stockcode = stockcode.substring(4);
    var lastprice = oData[1];
    var amount = oData[4];
    if (amount == 0){
        oData[10] = 0;
    }
    var isLongPrice = oData[14] > 0.1 ? 3 : 2;
    ret.push([stockcode]);
    ret.push([decodeURIComponent(oData[this.cols.indexOf(this.colpos[1])]) || "&nbsp;",
              'nocolor',
              this.mJumpUrl + "?code=" + stocktype + stockcode]);
    
    for(var i = 2 ; i < this.colpos.length; i ++)
    {
        var idx = this.cols.indexOf(this.colpos[i]);
        ret.push(this._setColor(idx, oData[idx], lastprice, isLongPrice));
    }
    this.tabledata[arrayId] = ret;
    return ret;
}

/*show data in format of table*/
newSort.prototype._tableSet = function(jsonStr){

    // if data error or not running then return
    if(jsonStr == "[-1]" || !this.running)
        return "";
    var reObj = this._parseTableData(jsonStr);
    
    //table header
    this.tabledata = this._setTableHeader(reObj);;
    
    var i;
    //table body
    //top body
    for(i = 0; i < this.mStartNum; i ++)
    {
        this.tabledata.push([]);
    }
    
    //middle data
    for(i = 0; i < reObj.length; i ++)
    {
        this.tabledata.push([]);
        this._setItem(this.tabledata.length - 1, reObj[i]);
    }
    
    //bottom empty
    for(i = reObj.length + this.mStartNum; i < this.mTotalRowNum; i ++)
    {
        this.tabledata.push([]);
    }

    //add to web page
    this.fixtable.setTableData(this.tabledata);
    this.fixtable.showTable();
}


// 综合排名
// 综合排名显示列表序列
newSort.prototype.types = ["ratio_inc", "ratio_dec", "ratio5_inc", "ratio5_dec", "weibi_inc", "zhenfu", "liangbi", "amount"];
// 综合排名显示列表序列中文名
newSort.prototype.typenames = ["今日涨幅排名", "今日跌幅排名",  "5分钟涨幅排名", "5分钟跌幅排名", "今日委比排名", "今日振幅排名", "今日量比排名", "今日总金额排名"];
// 综合排名显示列表最后一列对应颜色
newSort.prototype.colListColor = [-1, -1, -1, -1, -1, -1, -1, 0, 0];
// 综合排名显示列表最后一列对应后缀
newSort.prototype.colEnd = ["%", "%", "%", "%", "%", "%", "%", ""];
// 综合排名显示列表最后一列对应中文名
newSort.prototype.colName = ["涨跌幅", "涨跌幅", "涨跌幅", "涨跌幅", "委比", "振幅", "量比", "金额(万)"];

/* show data in format of table
 */
newSort.prototype._inteOrderset = function(jsonStr)
{    
    if(jsonStr == "[-1]" || !this.running)
        return "";
    
    var qzindex = false;
    if(this.mCurrType.indexOf("|Z") != -1 || this.mCurrType.indexOf("|Q") != -1)
    {
        qzindex = true;        
        this.colName[7] = this.colName[7].replace("万", "亿");
    }
    var divUnit = 1;
    var reObj = KISSY.JSON.parse(jsonStr);
    var div = "";
    for (var i = 0; i < this.types.length; i++){
        var typename = this.typenames[i];
        var nowtype = this.types[i];
        var typen = nowtype.split("_");
        if(qzindex && nowtype == "amount")
        {
            divUnit = 10000;
        }
        if (typen.length != 2)
            typen[1] = "desc";
        if (typen[1] == "dec")
            typen[1] = "asc";
        else
            typen[1] = "desc";
            
        if (!reObj[nowtype]){
            continue;
        }
        div += '<div class="mod81">';
        div += '<div class="mod81-title"><ul><li>&nbsp;&nbsp;' + typename + '</li></ul>&nbsp;<a ';
        div += this._formatA(this.mCurrType.substring(2, 4), this.mCurrType.substring(5), typen[0], typen[1]) + '">更多&gt;&gt;</a></div>';
        div += '<div class="mod81-content">';
        div += "<table><tr><th>排名</th><th>股票名称</th><th style='text-align: right'>价格</th><th style='text-align: right'>";
        div += this.colName[i] + "</th></tr>";
        for(var j = 0; j < reObj[nowtype].length; j ++){
            var cur = reObj[nowtype][j];
            var stockcode = cur[0];
            var stocktype = stockcode.substring(0,2).toLowerCase();
            stockcode = stockcode.substring(4);

            div += "<tr class='hastop'><td>"+(j+1)+"</td>";
            div += "<td><a href='" + this.mJumpUrl + "?code="+ stocktype + stockcode +"'>" + decodeURIComponent(cur[1]) + "</a></td>";
            
            //color for new price
            var curlast = cur[2];
            var valueclass = "nocolor";
            if (curlast < cur[3]){
                valueclass = "incolor";
            }
            if (curlast > cur[3]){
                valueclass = "decolor";
            }
            div += "<td style='text-align: right' class='" + valueclass + "'>" + cur[3].toFixed(cur[5] ? 3 : 2) + "</td>";
            
            //color for value            
            if (this.colListColor[i] <= 0){
                valueclass = "noclor";
                if (this.colListColor[i] < 0){
                    if (cur[4] > 0){
                        valueclass = "incolor";
                    }
                    if (cur[4] < 0){
                        valueclass = "decolor";
                    }
                }
            }
            
            div += "<td style='text-align: right' class='"+valueclass+"'>"+ (cur[4] / divUnit).toFixed(2)+this.colEnd[i]+"</td></tr>";
        }
        div += "</table></div></div>";
    }
    innerSet(this.mDivObj, div, null);
    return div;
}


var boardstockInterval = 6 * 1000;
var sortInstance = null;
var oldoc = function(){return true;};
var headerArray = ["index", "industry", "concept", "region"];

// 三级目录列表
// 每个二级目录有不同的数据源，设置函数
// 每个三级目录有一组显示数据源，每个原子都其代码和列表
var subheader_data = [
                        //second
                        [
                            //three
                            [
                                // elements
                                ['summary|', '沪深综合']
                            ]
                        ],
                        //second
                        [
                            // three
                            [
                                // elements
                                ['81sh|A', '沪A综合'],
                                ['81sh|B', '沪B综合'],
                                ['81sh|G', '沪债综合'],
                                ['81sh|J', '沪基综合'],
                                ['81sh|KJ', '开基综合'],
                                ['81sh|Z', '沪指综合'],
                                ['81sh|Q', '沪权综合']
                            ],
                            // three
                            [
                                // elements
                                ['81sz|A', '深A综合'],
                                ['81sz|B', '深B综合'],
                                ['81sz|G', '深债综合'],
                                ['81sz|J', '深基综合'],
                                ['81sz|KJ', '开基综合'],
                                ['81sz|Z', '深证指综合'],
                                ['81sz|Q', '深权综合'],
                                ['81sz|C', '中小综合']
                            ]
                        ],
                        // second
                        [
                            // three
                            [
                                //elements
                                ['sh|A', '上证A股'],
                                ['sh|B', '上证B股'],
                                ['sh|G', '上证债券'],
                                ['sh|J', '上证基金'],
                                ['sh|KJ', '上证开基'],
                                ['sh|Z', '上证指数'],
                                ['sh|Q', '上证权证']
                            ],
                            
                            // three
                            [
                                //elements
                                ['sz|A', '深证A股'],
                                ['sz|B', '深证B股'],
                                ['sz|G', '深证债券'],
                                ['sz|J', '深证基金'],
                                ['sz|KJ', '深证开基'],
                                ['sz|Z', '深证指数'],
                                ['sz|Q', '深证权证'],
                                ['sz|C', '中小板块'],
                                ['sz|Y', '创业板']
                            ]
                        ]
                   ];

$_old_newsort_setAB = newSort.prototype._ABSet;
/* 沪深综合排名 */
newSort.prototype._ABSet = function(re)
{
    // data error
    if(re == "[-1]")
    {
        return;
    }
    var retObj = KISSY.JSON.parse(re);
    var sh = retObj["sh"];
    var sz = retObj["sz"];
    var shA = KISSY.JSON.parse(sh["A"]);
    var shB = KISSY.JSON.parse(sh["B"]);
    var szA = KISSY.JSON.parse(sz["A"]);
    var szB = KISSY.JSON.parse(sz["B"]);
    
    var abList = [shA, szA, shB, szB];
    var abListName = ["shA", "szA", "shB", "szB"];
    var abListCName = ["沪A", "深A", "沪B", "深B"];
    
    // format div inner html
    var div = "";
    var divArr = [];
    var i, j, k;
    var it = null;
    for(i = 0; i < this.szABListOrder.length; i ++)
    {        
        var itname = this.szABListOrder[i];
        var typen = itname.split("_");
        if (typen.length != 2)
            typen[1] = "desc";
        if (typen[1] == "dec")
            typen[1] = "asc";
        else
            typen[1] = "desc";
        var typename = this.szABListName[i];
        
        for(j = 0; j < abList.length; j ++)
        {
            it = abList[j][itname];
            
            var formata = this._formatA(abListName[j].substring(0, 2), abListName[j].substring(2), typen[0], typen[1]);
            //i == 0 && j== 0 ? alert(formata) : "";
            divArr.push('<div class="h_sh_top' + ((j != abList.length - 1) ? "" : "1" ) + '">');
            divArr.push('<div class="title">');
            
            /*var img = "";
            if(typen[1] == "asc")
                img = '<img src="agents/zhicheng/images/up1.gif" width="9" height="9" />';
            else
                img = '<img src="agents/zhicheng/images/down1.gif" width="9" height="9" />';
            divArr.push(img);*/
            divArr.push('<a ');
            
            divArr.push(formata);
            divArr.push(' >');
            divArr.push(abListCName[j] + typename);
            divArr.push("</a></div>");
            divArr.push('<table border="0" cellpadding="0" cellspacing="0"><tr class="h_sh_top_tdtop"><td width="12"><div align="left"></div></td><td><div align="center">名&nbsp;&nbsp;称</div></td><td>价&nbsp;格</td><td>');
            divArr.push(this.szABColName[i] + "</td></tr>");
            
            for(k = 0; k < it.length; k ++)
            {
                var cur = it[k];
                var stockcode = cur[0];
                var stocktype = stockcode.substr(0,2).toLowerCase();
                stockcode = stockcode.substr(4);
    
                divArr.push("<tr><td align='left'>" + ( k + 1 ) + "</td>");
                divArr.push("<td align='left'><a href='" + this.mJumpUrl+ "?code="+ stocktype + stockcode +"'>" + decodeURIComponent(cur[1]) + "</a></td>");
                
                //color for new price
                var curlast = cur[2];
                var valueclass = "nocolor";
                if (curlast < cur[3]){
                    valueclass = "incolor";
                }
                if (curlast > cur[3]){
                    valueclass = "decolor";
                }                 
                
                divArr.push("<td style='text-align: right' class='" + valueclass + "'>" + cur[3].toFixed(cur[5] ? 3 : 2) + "</td>");
                
                if(typen[0] == 'price')
                {
                    cur[4] = (cur[3] - cur[2]) / cur[2] * 100;
                }
                
                //color for value            
                if (this.szABColColors[i] <= 0){
                    valueclass = "noclor";
                    if (this.szABColColors[i] < 0){
                        if (cur[4] > 0){
                            valueclass = "incolor";
                        }
                        if (cur[4] < 0){
                            valueclass = "decolor";
                        }
                    }
                }

                var conStr = cur[4].toFixed(cur[5] ? 3 : 2);
                if(itname == "volume")
                {
                    conStr = cur[4];
                }
                divArr.push("<td style='text-align:right; font-size:11px;' class='" + valueclass + "'>" + conStr + this.szABColUint[i] + "</td></tr>");
            }
            divArr.push("</table></div></div>");
        }       
    }
    
    div = divArr.join("");    
    innerSet(this.mDivObj, div, null);
}

//综合排名
newSort.prototype._inteOrderset = function(jsonStr)
{    
    if(jsonStr == "[-1]" || !this.running)
        return "";
    
    var qzindex = false;
    if(this.mCurrType.indexOf("|Z") != -1 || this.mCurrType.indexOf("|Q") != -1 || this.mCurrType.indexOf("|G") != -1)
    {
        qzindex = true;        
        this.colName[7] = this.colName[7].replace("万", "亿");
    }
    var divUnit = 1;
    var reObj = KISSY.JSON.parse(jsonStr);
    var div = "";
    for (var i = 0; i < this.types.length; i++){
        var typename = this.typenames[i];
        var nowtype = this.types[i];
        var typen = nowtype.split("_");
        if(qzindex && nowtype == "amount")
        {
            divUnit = 10000;
        }
        if (typen.length != 2)
            typen[1] = "desc";
        if (typen[1] == "dec")
            typen[1] = "asc";
        else
            typen[1] = "desc";
            
        if (!reObj[nowtype]){
            continue;
        }
        div += '<div class="h_sh_top' + ( (i % 4) != 3 ? "" : "1" ) + '">';
        div += '<div class="title"><a ';
        div += this._formatA(this.mCurrType.substring(2, 4), this.mCurrType.substring(5), typen[0], typen[1]) + '>' + typename + '</a></div>';
        div += '<table border="0" cellpadding="0" cellspacing="0"><tr class="h_sh_top_tdtop"><td width="12"><div align="left"></div></td><td><div align="center">名&nbsp;&nbsp;称</div></td><td>价&nbsp;格</td><td>';
        div += this.colName[i] + "</td></tr>";
        for(var j = 0; j < reObj[nowtype].length; j ++){
            var cur = reObj[nowtype][j];
            var stockcode = cur[0];
            var stocktype = stockcode.substring(0,2).toLowerCase();
            stockcode = stockcode.substring(4);

            div += "<tr><td align='left' style='width:5px;padding-left:2px;'>"+(j+1)+"</td>";
            div += "<td align='left' style='padding-left:0px;'><a href='" + this.mJumpUrl + "?code="+ stocktype + stockcode +"'>" + decodeURIComponent(cur[1]) + "</a></td>";
            
            //color for new price
            var curlast = cur[2];
            var valueclass = "nocolor";
            if (curlast < cur[3]){
                valueclass = "incolor";
            }
            if (curlast > cur[3]){
                valueclass = "decolor";
            }
            div += "<td style='text-align: right' class='" + valueclass + "'>" + cur[3].toFixed(cur[5] ? 3 : 2) + "</td>";
            
            //color for value            
            if (this.colListColor[i] <= 0){
                valueclass = "noclor";
                if (this.colListColor[i] < 0){
                    if (cur[4] > 0){
                        valueclass = "incolor";
                    }
                    if (cur[4] < 0){
                        valueclass = "decolor";
                    }
                }
            }
            
            div += "<td style='text-align: right' class='"+valueclass+"'>"+ (cur[4] / divUnit).toFixed(2)+this.colEnd[i]+"</td></tr>";
        }
        div += "</table></div></div>";
    }
    innerSet(this.mDivObj, div, null);
    return div;
}

newSort.prototype._setItem = function(arrayId, oData){
    var ret = [[arrayId, "tdnoend first"]];
    var stockcode = oData[0];
    var stocktype = stockcode.substring(0,2).toLowerCase();
    stockcode = stockcode.substring(4);
    var lastprice = oData[1];
    var amount = oData[4];
    if (amount == 0){
        oData[10] = 0;
    }
    var isLongPrice = oData[14] > 0.1 ? 3 : 2;
    ret.push([stockcode, "tdnoend"]);
    ret.push([decodeURIComponent(oData[this.cols.indexOf(this.colpos[1])]) || "&nbsp;",
              'tdnoend',
              this.mJumpUrl + "?code=" + stocktype + stockcode]);
    
    for(var i = 2 ; i < this.colpos.length; i ++)
    {
        var idx = this.cols.indexOf(this.colpos[i]);
        ret.push(this._setColor(idx, oData[idx], lastprice, isLongPrice));
    }
    this.tabledata[arrayId] = ret;
    return ret;
}

/*set table header*/
newSort.prototype._setTableHeader = function(reObj){
    var tabledata = [];
    tabledata.push([["序号", "toptd first"]]);
    for(var j = 0; j < this.colpos.length; j ++)
    {
        // get col name
        var itext = this.colpos[j];
        //找出所排列在传入序列中的位置
        var idx = this.cols.indexOf(itext);
        
        var bgCss = "";
        if(j == this.colpos.length -1)
            bgCss = "toptdend";
        else
            bgCss = "toptd"
        
        if (idx >= 0 && this.colSortable[idx])
        {
            if (this.mMetric == this.metrics[this.colSortable[idx] - 1 ]){
                
                if (this.mOrder == "desc")
                    itext += "<span><img height='9' style='margin-top:7px' width='9' src='./agents/zhicheng/images/sheng.gif'/></span>";
                else
                    itext += "<span><img height='9' style='margin-top:7px' width='9' src='./agents/zhicheng/images/jiang.gif'/></span>";
            }
            tabledata[0].push([itext, 'nocolor ' + bgCss, "javascript:sortCol(" + this.colSortable[idx] + "," + j + ");void(0);"]);
        }
        else
        {
            tabledata[0].push([itext, bgCss]);
        }
    }
    return tabledata;
}

/*set color for a td*/
newSort.prototype._setColor = function(idx, nowprice, lastprice, fixNum)
{
    if (idx < 0)
        return ["--"];
    
    var coltype = this.colColor[idx];
    var colfix = this.colToFix[idx];
    var ret = [];
    var classn = "nocolor";
    if (coltype != 0)
    {        
        if (coltype > 0)
        {
            if (nowprice > 99990)
                nowprice = 0;
            if (nowprice > 0)
            {
                if (nowprice > lastprice)
                    classn = "incolor";
                if (nowprice < lastprice)
                    classn = "decolor";
            }
        }
        else
        {
            if (nowprice > 0)
                classn = "incolor";
            if (nowprice < 0)
                classn = "decolor";
        }
    }
    if(this.mMetric == this.metrics[this.colSortable[idx] - 1 ])
    {
        classn += " currbg";
    }
    var tdend = "";
    if(idx == this.cols.length -1)
    {
        tdend = " tdend";
    }
    else
    {
        tdend = " tdnoend";
    }
    ret.push(classn + tdend);

    
    if (colfix > 0)
    {
        nowprice = nowprice.toFixed(fixNum || 0);
    }
    
    if (colfix < 0)
    {
        nowprice = nowprice.toFixed(2) + "%";
    }
    else
    {
        if (nowprice == 0)
        {
            nowprice = "--";
        }
    }
    ret.unshift(nowprice);
    return ret;
}

/*show data in format of table*/
newSort.prototype._tableSet = function(jsonStr){

    // if data error or not running then return
    if(jsonStr == "[-1]" || !this.running)
        return "";
    $('newsort-body').style.width = "777px";
    $('c_cr').style.width = "777px";
    $('c_cr').className = "newsort_border";
    $('newsort-title').style.display = "block";
    var curr_date = currTimeStr();
    $('curr-time').innerHTML = curr_date;
    var reObj = this._parseTableData(jsonStr);
    
    //table header
    this.tabledata = this._setTableHeader(reObj);;
    
    var i;
    //table body
    //top body
    for(i = 0; i < this.mStartNum; i ++)
    {
        this.tabledata.push([]);
    }
    
    //middle data
    for(i = 0; i < reObj.length; i ++)
    {
        this.tabledata.push([]);
        this._setItem(this.tabledata.length - 1, reObj[i]);
    }
    
    //bottom empty
    for(i = reObj.length + this.mStartNum; i < this.mTotalRowNum; i ++)
    {
        this.tabledata.push([]);
    }

    //add to web page
    this.fixtable.setTableData(this.tabledata);
    this.fixtable.showTable();
}


// set head default show and newsort-body default show
function defaultShow(parentID, childID, stocktype)
{
     // default show is board list
    if (parentID == BOARDSTOCKTYPE)
    {
        dataUrl = sortBoardStockUrl + [stocktype, "desc", 0, 1, "ratio", Math.random()].join("|");       
        sortInstance.getName(dataUrl, function(re){curName = re; changeType(parentID, childID, stocktype, curName);});
    }
    else
    {  
        var i; 
        for(i = 0; i < subheader_data[parentID][childID].length; i ++)
        {
            if(subheader_data[parentID][childID][i][0] == stocktype)
                break;
        }
        
        // now find will show list
        if(i == subheader_data[parentID][childID].length)
        {
            stocktype = subheader_data[parentID][childID][0][0];
            i = 0;
        }      
        changeType(parentID, childID, stocktype, subheader_data[parentID][childID][i][1]);
    }    
}

//code for select menu
var currParent = -1;
var currChild = -1;
var calTime = false;
var curSortId = null;
function sortCol(sortid, colid)
{    
    if (sortInstance)
    {
        curSortId = sortid;
        if(!calTime)
        {
            window.setTimeout(sortStart, 200);
            calTime = true;
        }
    }
}

function sortStart()
{
    if(sortInstance)
    {
        sortInstance.sort(curSortId);
        calTime = false;
    }
}

function changeType(parentID, childID, stocktype, stockName)
{    
    if(sortInstance != null)
    {
        pid = parentID;
        cid = childID;
        sortStockType = stocktype;
        if(parentID == CLASSSTOCKTYPE || parentID == BOARDSTOCKTYPE)
        {
            sortInstance.fixtable.stopped = false;
        }
        else
        {
            sortInstance.fixtable.stopped = true;
        }
        window.setTimeout(function(){sortInstance.changeType(parentID, childID, stocktype);}, 100);
    }
}

var znzIdx = null;
var divHeight = 300;
//page main function
function start()
{
    // start index summary
    znzIdx = new znzIdxSummary('stock-index-all', 10 * 1000, idxsumry_data);
    scrollDiv('stock-index-all', 3*1000, 3, 22);
    //默认打开以及菜单
    showFirstNav($('root_hsgs'),'hsgs')
    queryInit();
    if(gMarketType)
    {
        gType = gMarketType.substr(0, 1);
        gMarket = gMarketType.substring(1);
    }
    startNewSort();   
    oldoc = document.onclick||function(){return true;};
    
}

var pid = SUMTYPE;
var cid = 0;
var sortStockType = 'summary|';
function startNewSort(cw, ch, market, mtype, boardNo, sort, order, newSortPreData, sortJumpUrl)
{
    // set body's height
    divHeight = 700;
    
    var showRowNum = parseInt(divHeight / 25);
    if (showRowNum > 27)
        showRowNum = 27;
    divHeight = showRowNum * 25;    

    gSort = sort || gSort || null;  //gSort 全局变量定义在newsort.php
    gOrder = order || gOrder || null; //gOrder 全局变量定义在newsort.php
    sortInstance = new newSort("newsort-body", divHeight - 25, (922 - 162), gSort, gOrder, showRowNum - 1, boardstockInterval, false, newSortPreData, sortJumpUrl);
    if(cw)
        sortInstance.fixtable.dwidth = cw - 35;
    
    parseParams(market, mtype, boardNo);
    defaultShow(pid, cid, sortStockType);
    
    if (gSort && ((gSort == "turnover") || (gSort == "ratio5") ||
         (gSort == "weibi") ||(gSort == "zhenfu")))
    {
        window.setTimeout(function(){sortInstance.fixtable.move(5,0);}, 500);
    }
}

//解析参数为节点类型
function parseParams(market, mtype, boardNo)
{
    //parse get paramemters
    gMarket = market || gMarket || "";
    gType = mtype || gType || "";
    gBoardNo = boardNo || gBoardNo || "";

    //如果参数全为空则默认为沪深综合
    if(!gMarket && !gType && !gBoardNo)
    {
        return;
    }
    
    if(gBoardNo == "")
    {
        
        var i, j;
        var havaFind = false;
        
        //81
        havaFind = false;
        for(i = 0; i < subheader_data[CLASSTYPE].length; i ++)
        {
            for(j = 0; j < subheader_data[CLASSTYPE][i].length; j ++)
            {
                if(subheader_data[CLASSTYPE][i][j][0] == (gMarket + "|" + gType))
                {
                    havaFind = true;
                    sortStockType = subheader_data[CLASSTYPE][i][j][0];
                    pid = CLASSTYPE;
                    cid = i;
                    break;
                }
            }
            if(havaFind)
                break;
        }
        
        //61
        for(i = 0; i < subheader_data[CLASSSTOCKTYPE].length; i ++)
        {
            for(j = 0; j < subheader_data[CLASSSTOCKTYPE][i].length; j ++)
            {                
                if(subheader_data[CLASSSTOCKTYPE][i][j][0] == (gMarket + "|" + gType))
                {
                    havaFind = true;
                    sortStockType = subheader_data[CLASSSTOCKTYPE][i][j][0];
                    pid = CLASSSTOCKTYPE;
                    cid = i;
                    break;
                }
            }            
            if(havaFind)
                break;
        }       
    }
    
    //板块
    if(gBoardNo != "")
    {
        pid = BOARDSTOCKTYPE;
        
        if( (gBoardNo.toLowerCase()).indexOf("s") == 0)
        {
            cid = 0;
        }
        else
        {
            try
            {
                cid = parseInt(gBoardNo.substring(0, 1));                
            }
            catch(E)
            {
                cid = 0;                
            }
        }
        sortStockType = gBoardNo;
    }
}

window.onload = start;
