/**********************************************************
 *    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, metric, order, showRowNum, interval, start, preData, jmpUrl)
{
    this._init(divId, divHeight, 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, 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;
    this.mForce = true;
    // record stock list rows num
    this.mShowRowNum = showRowNum;
    //alert(this.mShowRowNum);
    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, 922, this.mDivHeight, this._tableCallBackFunc.bind(this)); 
}

newSort.prototype._tableCallBackFunc = function()
{
    if(this.mParentID != CLASSSTOCKTYPE && this.mParentID != BOARDSTOCKTYPE)
    {
        return;
    }
    this.mForce = true;
    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("|");
    
    //alert(this.mShowRowNum);
    // 预取三条  mc[0]= sz || sh,  mc[1] = A||B....
    var num = this.mShowRowNum + 3;
    if(num > 30)
        num = 30;
    retUrl += [mc[0], mc[1], this.mOrder, this.fixtable.ry, 
        num, this.mMetric, Math.random()].join("|");
    //alert(retUrl);
    
    return retUrl;
}

/*板块全列表接口*/
newSort.prototype._boardListUrlJust = function()
{
    var retUrl = sortBoardStockUrl;
    var num = this.mShowRowNum + 3;
    if(num > 30)
        num = 30;
    // 预取三条  this.mCurrType=板块号
    retUrl += [this.mCurrType, this.mOrder, this.fixtable.ry, 
        num, 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.mForce = true;
    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();
    }
    if(inHqTime() || this.mForce){
        this.mForce = false;
        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; &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.mForce = true;

    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);
    if(reObj['ret'] && reObj['ret'] == 'ERROR')
        return;
    //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([]);
    }

    //alert(this.tabledata.length);
    //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', '创业板']
                            ]
                        ]
                   ];

// init head navigator
function HeaderInit(divID){        
    var div = "<div id='newsort-zonghe'><div class='newsort-zonghehead'>综合排行</div><ul>"
    
    div += "<li id='subheader00' onclick='changeType(0, 0, \"summary|\", \"沪深综合\")' class='newsort-namediv'>沪深综合</li>";
    
    div += "<li id='subheader10' onclick='changeType(1, 0, \"81sh|A\", \"沪A综合\")' class='newsort-namediv'>沪A综合</li>";
    div += "<li id='subheaderd10' onclick='openmenu(1, 0)' class='newsort-dropdown'>▼</li>";
    div += "<li id='subheader11' onclick='changeType(1, 1, \"81sz|A\", \"深A综合\")' class='newsort-namediv'>深A综合</li>";
    div += "<li id='subheaderd11' onclick='openmenu(1, 1)' class='newsort-dropdown'>▼</li>";

    div += "</ul></div><div id='newsort-baojia'><div class='newsort-zonghehead'>报价牌</div><ul>";

    div += "<li id='subheader20' onclick='changeType(2, 0, \"sh|A\", \"上证A股\")' class='newsort-namediv'>上证A股</li>";
    div += "<li id='subheaderd20' onclick='openmenu(2, 0)' class='newsort-dropdown'>▼</li>";
    div += "<li id='subheader21' onclick='changeType(2, 1, \"sz|A\", \"深证A股\")' class='newsort-namediv'>深证A股</li>";
    div += "<li id='subheaderd21' onclick='openmenu(2, 1)' class='newsort-dropdown'>▼</li>";

    div += '<li class="newsort-split"></li>';
    
    var tmpHeaderData = KISSY.JSON.parse(header_data.substring(0, header_data.length - 1));
    
    var i;
    if(tmpHeaderData){
        var curPosi = [];
        for(i = 0; i < headerArray.length; i ++){
            curPosi.push([]);
            var cur = tmpHeaderData[headerArray[i]];
            if (cur && cur.length && cur.length == 2)
            {
                div += "<li id='subheader3" + i + "' onclick='changeType(3, " + i + ", \"" + cur[0] +"\", \"" + 
                    decodeURIComponent(cur[1]) + "\")' class='newsort-namediv'>" +
                    decodeURIComponent(cur[1]) + "</li>";
                div += "<li id='subheaderd3" + i +"' onclick='openmenu(3, " + i + ")' class='newsort-dropdown'>▼</li>";
            }
        }
        subheader_data.push(curPosi);
    }
    div += "</ul></div>";
    innerSet($(divID), div, null);
}

// 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 open_sleft = [0, 148, 237, 404, 493, 589, 648, 562, 795];
// get submenu data through ajaj
function menuDataGet(parentID, childID)
{
    //get submenu data
    var args = {
        method : "get",
        onComplete : function(re){
            var ret = KISSY.JSON.parse(re);
            var retArr = [];
            for (var i = 0; i < ret.length; i ++){
                if (ret[i] && ret[i].length && ret[i].length > 1){
                    retArr.push([ret[i][0], decodeURIComponent(ret[i][1])]);
                }
            }
            if(!subheader_data[parentID])
            {
                subheader_data[parentID] = [];
            }
            subheader_data[parentID][childID] = retArr;
            openmenu(parentID, childID);
        }
    }
    var infoUrl = "http://" + rdmDataDomainNameGet() + "/test/board.py/cateBoardNames.znzDo?cmd=";
    infoUrl += [headerArray[childID], Math.random()].join("|");
    this.myAjaj = new Ajaj(infoUrl, args);
}

function openmenu(parentID, childID)
{
    if(parentID == BOARDSTOCKTYPE)
    {
        if(parentID >= 0 && childID >= 0  && 
            (!subheader_data[parentID] || !subheader_data[parentID][childID]
             || subheader_data[parentID][childID].length == 0))
        {    
            // if not data then get data
            menuDataGet(parentID, childID);        
            return;
        }
    }

    var i, j;
    var parentNodeNum = subheader_data.length;
    var chNodeNum = 0;
    // close menu
    if (currParent == parentID && currChild == childID)
    {   
        // close opened menu
        $("newsort-subheader").style.display = "none";
        for (i = 0; i < parentNodeNum; i++)
        {
            chNodeNum = subheader_data[i].length;
            for(j = 0; j < chNodeNum; j ++)
            {
                if ($("subheaderd" + i + "" + j))
                {
                    $("subheaderd" + i + "" + j).className = $("subheaderd" + i + "" + j).className.replace(" newsort-curheader3", "");
                    $("subheaderd" + i + "" + j).innerHTML = "▼";
                }
            }
        }
        currParent = -1;
        currChild = -1;
    }
    else
    {
        $("newsort-subheader").style.display = "block";
        var count = -1;
        var posiIndex = 0;     
        for (i = 0; i < parentNodeNum; i ++)
        {
            chNodeNum = subheader_data[i].length;
            
            for(j = 0; j < chNodeNum; j ++)
            {
                count ++;
                if ($("subheaderd" + i + "" + j)){
                                 
                    // click is not current html li
                    $("subheaderd" + i + "" + j).className = $("subheaderd" + i + "" + j).className.replace(" newsort-curheader3", "");
                    $("subheaderd" + i + "" + j).innerHTML = "▼";
                    
                    // click is current html li
                    if (i == parentID && j == childID)
                    {             
                        $("subheaderd" + i + "" + j).innerHTML = "▲";
                        posiIndex = count;
                    }
                   
                }
            }
        }
        
        // set newsort-subheader left position
        $("newsort-subheader").style.left = open_sleft[posiIndex] + "px";
       
        // format show content
        var div = "<ul>";
        for (j = 0; j < subheader_data[parentID][childID].length; j ++){
            if (j > 0 && j % 16 == 0){
                div += "</ul><ul>";
            }
            div += "<li onclick='changeType(" + parentID + "," + childID + ", \"" + subheader_data[parentID][childID][j][0] + "\", \"" 
                + subheader_data[parentID][childID][j][1] + "\")'><a href='javascript:void(0)'>"
                + subheader_data[parentID][childID][j][1] + "</a></li>";
        }
        
        div += "</ul>";
        innerSet($("newsort-subheader"), div, null);
        currParent = parentID;
        currChild = childID;
    }
}

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;
        }
        $("subheader" + parentID + "" + childID).innerHTML = stockName;
        var i, j;
        var secondNodeNum = subheader_data.length;
        var threeNodeNum = 0;
        for(i = 0; i < secondNodeNum; i ++)
        {
            threeNodeNum = subheader_data[i].length;
            for(j = 0; j < threeNodeNum; j ++)
            {
                if($("subheader" + i + "" + j))
                {
                    $("subheader" + i + "" + j).className = "newsort-namediv";
                    if($("subheaderd" + i + "" + j))
                    {
                        $("subheaderd" + i + "" + j).className = "newsort-dropdown";
                        $("subheaderd" + i + "" + j).innerHTML = "▼";
                    }
                    if (i == parentID && j == childID)
                    {
                        $("subheader" + i + "" + j).className += " newsort-curheader";
                        if($("subheaderd" + i + "" + j))
                        {
                            $("subheaderd" + i + "" + j).className += " newsort-curheader2";
                        }
                        $("subheader" + i + "" + j).onclick = function(){changeType(parentID, childID, stocktype, stockName)};
                    }
                }
            }
        }
        window.setTimeout(function(){sortInstance.changeType(parentID, childID, stocktype);}, 100);
        $("newsort-subheader").style.display = "none";
    }
}

var znzIdx = null;
var divHeight = 300;
//page main function
function start()
{
    // start index summary
    znzIdx = new znzIdxSummary('stock-index-all', 10 * 1000, idxsumry_data);
    var sugReal = new suggestQuery('realstock-query-query', 'realstock-query-select', 'realstock-query-code', 'realstock-query-form', null, null, null, true);
    if(gMarketType)
    {
        gType = gMarketType.substr(0, 1);
        gMarket = gMarketType.substring(1);
    }
    startNewSort();
    
    window.onresize = function(){
        var newHeight = (document.compatMode == "CSS1Compat") ? document.documentElement.clientHeight : document.body.clientHeight;
        newHeight -= 200;
        winResize(0, newHeight);
    }    
    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
    var h = (document.compatMode == "CSS1Compat") ? document.documentElement.clientHeight : document.body.clientHeight;
    divHeight = ch ? ch : h - 200;
    divHeight = (divHeight < 300) ? 300 : divHeight;

    var showRowNum = parseInt(divHeight / 25);
    
    if (showRowNum > 31)
        showRowNum = 31;
    
    showRowNum --;
    divHeight = showRowNum * 25;
    gSort = sort || gSort || null;  //gSort 全局变量定义在newsort.php
    gOrder = order || gOrder || null; //gOrder 全局变量定义在newsort.php
    sortInstance = new newSort("newsort-body", divHeight, gSort, gOrder, showRowNum, boardstockInterval, false, newSortPreData, sortJumpUrl);
    if(cw)
        sortInstance.fixtable.dwidth = cw - 35;
    
    parseParams(market, mtype, boardNo);
    HeaderInit('newsort-headerul');
    defaultShow(pid, cid, sortStockType);
    
    if (gSort && ((gSort == "turnover") || (gSort == "ratio5") ||
         (gSort == "weibi") ||(gSort == "zhenfu")))
    {
        window.setTimeout(function(){sortInstance.fixtable.move(5,0);}, 500);
    }   
    
    $("newsort-subheader").style.display = "none";
}

//解析参数为节点类型
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;
    }
}

function winResize(cw, ch)
{
    //alert(ch);
    var newHeight = (ch < 300) ? 300 : ch;
    var showRowNum = parseInt(newHeight/ 25);
    if (showRowNum > 31)
        showRowNum = 31;
    
    showRowNum --;
    newHeight = showRowNum * 25;
    
    //if (newHeight != divHeight){
        if (sortInstance && sortInstance.sort){
            divHeight = newHeight + 25;
            sortInstance.mDivHeight = newHeight;
            sortInstance.fixtable.dheight = newHeight;
            sortInstance.fixtable.displayRow = showRowNum;
            sortInstance.mShowRowNum = showRowNum;
            if (sortInstance.mShowRowNum > 30)
                sortInstance.mShowRowNum = 30;
            if ($("newsort-body").style.height != "")
                    $("newsort-body").style.height = ch + "px";
            if (sortInstance.isList()){
                
                sortInstance.sizeRefresh();
            }               
        }
   // }
}

window.onload = start;
