
/*fullscreen layout control*/
var znzFullScreen = function(){
    this.mMinHeight = 530;   //min height
    this.mMinusHeight = 64;  //height to minus by total height 头加尾
    this.mMinWidth = 990;    //min width
    this.mMinusWidth = 0;    //width to minus by total width
    
    this.mHdTopHeight = 55;  //hd-top height
    
    //default value
    this.mVHeight = this.mMinHeight - this.mMinusHeight; 
    this.mVWidth = this.mMinWidth - this.mMinusWidth;
    
    //config for divs
    //最近访问，F10宽度
    this.mLeftBarWidth = 202;
    //成交明细列...的宽度
    this.mRightPandelWidth = 250;
    //控制条宽度
    this.mLeftControllWidth = 22;
    
    //成交明细部分以上高度
    this.mRightBoxHeight = 385;
    //成交明细列title高度
    this.mRightBoxTitleHeight = 20;
    
    //原先浏览器client部高度
    this.mOldHeight = 0;
    //原先浏览器client部宽度
    this.mOldWidth = 0;
    
    this.mContentDiv = $("content");

    this._init();

    if ((this.mVHeight > this.mMinHeight) && (this.mVWidth > this.mMinWidth) )
    {
        $('realstock-query-query').focus();
        window.setTimeout(function(){
                $('realstock-query-query').value = '代码/名称/拼音';
            }, 100);    
    }    
}

//calculate swf width, height
znzFullScreen.prototype.calSwfWH = function()
{
     //不显示左边框内容，但显示左边控制框，右边宽为
    var w = this.mVWidth - this.mLeftControllWidth;
    var h = this.mVHeight - this.mHdTopHeight;
    
    if ($("contentLeftBarContent").style.display != "none")
    {
        //显示左边框内容，不显示左边控制框时，右边宽为
        w = this.mVWidth - this.mLeftBarWidth;
        // hidden left bar controll
        $("contentLeftBarControll").style.display = "none";
    }
    else
    {
        // show left bar controll
        $("contentLeftBarControll").style.display = "block";
    }
    
    if ($("contentRight").style.display == "block")
        w -= this.mRightPandelWidth;
    return[w, h];
}

//resetLeft div left
znzFullScreen.prototype.resetLeft = function(getonly)
{
    var wh = this.calSwfWH();
    $("contentRight").style.width = this.mRightPandelWidth + "px";
    if ($("contentRight").style.display == "block")
    {
        $("contentLeft").style.width = (this.mVWidth - this.mRightPandelWidth) + "px";
    }
    else
    {
        $("contentLeft").style.width = (this.mVWidth) + "px";
        $("showNews").className = "addtonews1";
    }
    $("contentLeftBody").style.width = (wh[0]) + "px";
    $("stock-mystock-table").style.height = (this.mVHeight - 255) + "px";
    $("stock-boardInfo-table").style.height = '180px';
    this.resetSwf(wh[0] - 5, wh[1]);
}

znzFullScreen.prototype.resetRight = function()
{
    var h = this.mVHeight - this.mRightBoxHeight;
    if (h < 50)
    {
        $("hd-trade").style.display = "none";
    }
    else
    {
        $("hd-trade").style.display = "block";
        $("hd-trade").style.height = h + "px";
        $("hd-trade-table").style.height = (h - this.mRightBoxTitleHeight) + "px";
        $("hd-trade-pricetable").style.height = (h - this.mRightBoxTitleHeight) + "px";
    } 
}

// reset left right width
znzFullScreen.prototype.resetWH = function(force)
{
    if ((!force) && (this.mOldHeight == document.body.clientHeight)
       && (this.mOldWidth == document.body.clientWidth))
        return;

    this.mOldHeight = document.body.clientHeight;
    this.mOldWidth = document.body.clientWidth;
    
    this.mVHeight = document.body.clientHeight;
    this.mVWidth = document.body.clientWidth;
    
    this.mVHeight = (this.mVHeight > this.mMinHeight) ? this.mVHeight : this.mMinHeight;
    this.mVWidth = (this.mVWidth > this.mMinWidth) ? this.mVWidth : this.mMinWidth;
    
    this.mVHeight -= this.mMinusHeight;
    this.mVWidth -= this.mMinusWidth;
    this.mContentDiv.style.width = this.mVWidth + "px";
    $("topbar").style.width = this.mVWidth + "px";
    $("topbarslider").style.width = this.mVWidth + "px";
    $("bottombar").style.width = this.mVWidth + "px";
    
    if (this.mContentDiv.style.visibility != "hidden")
    {
        this.mContentDiv.style.height = this.mVHeight + "px";
    }
    else
    {
        this.mContentDiv.style.height = "2px";
    }

    $('realstock-swf').style.height = (this.mVHeight - this.mHdTopHeight)+"px";
    $('realstock-swf').style.background = "black";
    this.resetLeft();
    this.resetRight();
    this.reset6181();
    this.resetBlock();
}

znzFullScreen.prototype.reset6181 = function(){
    if (resize6181){
         resize6181(this.mVWidth - 20, this.mVHeight - 32);
    }
}
    
znzFullScreen.prototype.resetBlock = function(){
    if (resizeStockBlock){
        resizeStockBlock(this.mVWidth - 10, this.mVHeight - 2);
    }
}

znzFullScreen.prototype.resetSwf = function(w, h)
{
    
     if (znzReal)
     {
         znzReal.resize(w, h);
     }
}

//znzFullScreen's public function get enable part width
znzFullScreen.prototype.getW = function()
{
    return this.mVWidth;
}

//znzFullScreen's public function get enable part height
znzFullScreen.prototype.getH = function()
{
    return this.mVHeight;
}

//znzFullScreen's static function clear tab's className
znzFullScreen.prototype.resetTabs = function()
{
    $("hd-stock").className = "";
    $("hd-6181").className = "";
    $("hd-boardbtn").className = "";
    $("hd-timebox").style.display = "none";
    $("hd-indcbox").style.display = "none";
}

//znzFullScreen's private function fullscreen's element's click function add
znzFullScreen.prototype._fsEleEvtFuncInit = function()
{
    var fullScreen = this;
    $("contentLeftBarControll").onclick = function(){
        var divd = $("contentLeftBarContent");
        divd.style.display = "block";
        this.style.display = "none";
        iCookie.set("showleft", "true");
        fullScreen.resetLeft();
    };
    
    $("leftcontrolicon").onclick = function(){
        var divd = $("contentLeftBarContent");
        if (divd.style.display == "block"){
            divd.style.display = "none";
            this.style.display = "block";
            iCookie.set("showleft", "false");
        }else{
            divd.style.display = "block";
            this.style.display = "none";
            iCookie.set("showleft", "true");
        }
        fullScreen.resetLeft();
    };
    
    $("hd-stock").onclick = function(){
        if (this.className == "currentBtn")
            return;
        $("box6181").style.display = "none";
        $("stockblock").style.display = "none";            
        $("content").style.visibility = "visible";
        $("content").style.display = "block";
        
        fullScreen.resetWH(true);
        fullScreen.resetTabs();
        fullScreen.mCurrType = 0;
        this.className = "currentBtn";
    };

    $("hd-6181").onclick = function(){
        //if (this.className == "currentBtn")
            //return;

        $("content").style.visibility = "hidden";
        $("content").style.height = "2px";
        $("stockblock").style.display = "none";
        $("newsort-body").innerHTML = "";
        start6181(fs.getW() - 20, fs.getH() - 32);        
        $("box6181").style.display = "inline";        
        fullScreen.resetWH(true);
        fullScreen.resetTabs();;
        fullScreen.mCurrType = 2;
        this.className = "currentBtn";
    }
    
    $("hd-boardbtn").onclick = function(){
        if (this.className == "currentBtn")
            return;

        $("box6181").style.display = "none";
        $("content").style.visibility = "hidden";
        $("content").style.height = "2px";
        startStockBlock(fs.getW() - 10, fs.getH() - 2);

        $("stockblock").style.display = "inline";
        fullScreen.resetWH(true);
        fullScreen.resetTabs();
        fullScreen.mCurrType = 1;
        this.className = "currentBtn";
    }
    
    $("time0").onclick = function(){
        if (this.innerHTML.indexOf("分时") >= 0 )
        {
            //显示分时
            onKTypeChange(this);
            $("contentRight").style.display = "block";
            $("hd-selectors").style.display = "none";
            $("content").style.visibility = "visible";
            $("content").style.display = "block";
            $("realstock-values-state").style.display = "block";
            fullScreen.resetWH(true);
            this.innerHTML = "&nbsp;&nbsp;&nbsp;<a>K线</a>";
        }
        else
        {
            //显示K线
            $("time6").onclick();
            this.innerHTML = "&nbsp;&nbsp;<a>分时</a>";
            $("contentRight").style.display = "none";
            $("realstock-values-state").style.display = "none";
            fullScreen.resetWH(true);
        }           
    }

    for (var i = 1; i < times.length; i++)
    {
        $("time"+i).onclick = function(){
            onKTypeChange(this);
            $("hd-timeselect").innerHTML = this.innerHTML;
            $("hd-selectors").style.display = "block";
            for (var j = 1; j < times.length; j ++)
            {
                if (this.id == ("time" + j))
                {
                    $("time" + j).parentNode.className = "curli";                        
                }
                else
                {
                    $("time" + j).parentNode.className = "";
                }
            }
            $("hd-timebox").style.display = "none";
            $("hd-indcbox").style.display = "none";
            fullScreen.resetWH(true);
        }
    }
}

//znzFullScreen's private function init 
znzFullScreen.prototype._init = function()
{
    var fullScreen = this;
    var showleft = iCookie.get("showleft");
    if (showleft != "false")
    {
        $("contentLeftBarContent").style.display = "block";
    }
    else
    {
        $("contentLeftBarContent").style.display = "none";
    }
    $("showNews").className = "addtonews1";
    this._fsEleEvtFuncInit();
    this.resetWH(false);
    this.resetLeft(); 
    window.setInterval(function(){fullScreen.resetWH(false)}, 500);
}

//change event
var indcs = {};
var times = ["", "min1", "min5", "min15", "min30", "min60", "day", "week", "month"];
var currentTime = "";
var currentIndc = {"macd":"indc0"}
function onAddIndc(obj)
{
    var indKey = (obj.innerHTML.toLowerCase().replace("<span>","").replace("</span>","").replace(/^\s+/, "").replace(/\s+$/, ""));
    
    if (indcs[indKey])
        indKey = indcs[indKey];
        
    if (currentIndc[indKey])
    {
        znzReal.indRemove(indKey);
        currentIndc[indKey] = 0;
        return false;
    }
    else
    {
        currentIndc[indKey] = obj.id;
        znzReal.indAdd(indKey);
        return true;
    }
}

function onKTypeChange(obj)
{
    var idx = parseInt(obj.id.replace("time", ""));
    if (idx >= 0 && idx < times.length)
    {
        if (currentTime != times[idx])
        {
            if (znzReal)
            {
                znzReal.restart(times[idx]);
                znzReal.updateSpecial();
                currentTime = times[idx];
            }
        }
    }
}


var stockCode = '000001';
var stockType = 'SH';

var znzF10Instance = null;
var znzBoardInstance = null;
var znzReal = null;
var znzNews = null;
var znzLastView = null;
var fs = null;
var znzPriceTab = null;

function start(){
    if (!$("bottombar"))
    {
        window.setTimeout(start, 100);
    }
    else
    {
        try{            
            //parse parameters
            var tmpStockCode = getQueryString('code');
            if (tmpStockCode != '')
            {
                stockType = tmpStockCode.substring(0, 2).toUpperCase();
                stockCode = tmpStockCode.substr(2);
            }
            
            //create fullscreen calss
         
            fs = new znzFullScreen();            
            var whs = fs.calSwfWH();
            znzReal = new znzHDStock('znzKLineSWF', 'realstock-swf-real', stockCode, stockName, 
                stockType, onDataChange, 3 * 1000, realstock_data, whs[0], whs[1], null, null, "", true, 1, ["kline", "kline-ma", "vol", "macd"]);
            
            //资讯新闻
            if (stocknews_data.length < 10)
            {
                //如果没有资讯或新闻则资讯按钮则不显示
                $("hd-news").style.display = "none";
            }
            else
            {
                $("hd-news").style.display = "inline";
                znzNews = new znzStockNews('realstock-news-table', 'realstock-notice-table', 
                    60 * 1000, stockCode, stockType, false, stocknews_data, 'realstock-news-table2', 'realstock-notice-table2');
            }            

            //显示F10信息
            if (f10Arr != "[]")
            {
                znzF10Instance = new znzF10("stock-F10", stockCode, stockType, f10Arr);
                if (znzF10Instance){
                    $('hd-leftinfobox').style.display = 'inline';
                    $("realstock-F10-name").innerHTML = 'F10资料';
                    $("stock-F10-table").style.display = "block";
                }
            }
            
            //显示板块信息
            if(boardInfo != "[-1]0")
            {             
                znzBoardInstance = new znzBoard("stock-boardInfo", 30 * 1000, stockCode, stockType, boardInfo, boardSet);                   
                $("realstock-boardInfo-name").innerHTML = '所属板块';
                $('hd-leftinfobox').style.display = 'inline';
                if (!znzF10Instance)
                {
                    $("realstock-F10-name").className = "title-first";
                    $("realstock-boardInfo-name").className = "title-current";
                    $("stock-boardInfo-table").style.display = "block";
                }
            }
            
            //index stock
            znzIdx = new znzIdxSummary('stock-index-all', 10 * 1000, idxsumry_data, null, null, null, 'hd.php');
            //最近访问
            znzLastView = new znzLastVisit('stock-mystock-table', 10 * 1000, true, stockCode, stockType, 'hd.php');
            queryInit("hd.php", formSubmit);
            eventInit();            
        }
        catch(E)
        {            
        }
    }
}

function eventInit()
{
    //成交明细
     $('hd-trade-name').onclick = function(){
        if (!$('hd-trade-name').innerHTML){
            return;
        }
        if ($('hd-trade-name').innerHTML == "&nbsp;"){
            return;
        }
        $('hd-trade-pricetable').style.display = "none";
        $('hd-trade-table').style.display = "block";
        $('hd-trade-name').className = "title-current title-first";
        $('hd-trade-pricetablename').className = "";
    }
    
    //分价表click respone event
    $('hd-trade-pricetablename').onclick = function(){
        if (!$('hd-trade-pricetablename').innerHTML){
            return;
        }
        if ($('hd-trade-pricetablename').innerHTML == "&nbsp;"){
            return;
        }
        
        if ($('hd-trade-pricetable').style.display != "none"){
            znzPriceTab = new znzPriceTable(stockCode, stockType, onPriceTableChange, 60 * 1000);
        }
        $('hd-trade-pricetable').style.display = "block";
        $('hd-trade-table').style.display = "none";
        $('hd-trade-name').className = "title-first";
        $('hd-trade-pricetablename').className = "title-current";
    }
    
    //切换到F10资料
    $('realstock-F10-name').onclick = function(){
       
        if (!$('realstock-F10-name').innerHTML){
            return;
        }
        if ($('realstock-F10-name').innerHTML == "&nbsp;"){
            return;
        }
        
        $('stock-boardInfo-table').style.display = 'none';
        $('stock-F10-table').style.display = 'block';
        $('realstock-F10-name').className = "title-first title-current";
        $('realstock-boardInfo-name').className = "";
    }
    
    //切换到所属板块列表
    $('realstock-boardInfo-name').onclick = function(){

        if (!$('realstock-boardInfo-name').innerHTML){
            return;
        }
        if ($('realstock-boardInfo-name').innerHTML == "&nbsp;"){
            return;
        }
        $('stock-boardInfo-table').style.display = 'block';
        $('stock-F10-table').style.display = 'none';
        $('realstock-F10-name').className = "title-first";
        $('realstock-boardInfo-name').className = "title-current";
    }
    
    //显示关闭新闻公告
    $('showNews').onclick = function(){
        if ($("popBox").style.display == "inline"){
            $("popBox").style.display = "none";
            $("popBox2").style.display = "none";
        }else{
            $("realstock-news-table2").innerHTML = $("realstock-news-table").innerHTML;
            $("realstock-notice-table2").innerHTML = $("realstock-notice-table").innerHTML;
            $("popBox").style.display = "inline";
            $("popBox2").style.display = "inline";
        }
    }
    
    $("pop-close").onclick = $('showNews').onclick;
    
    $('realstock-notice-title').onclick = function(){
        znzNews.isNews = false;
        znzNews._refresh();
        $('realstock-notice-title').className = 'pop-cur';
        $('realstock-news-title').className = '';

        $('realstock-notice-table').style.display = 'block';
        $('realstock-notice-table2').style.display = 'block';
        $('realstock-news-table').style.display = 'none';
        $('realstock-news-table2').style.display = 'none';
    }
    $('realstock-news-title').onclick = function(){
        znzNews.isNews = true;
        znzNews._refresh();
        $('realstock-notice-title').className = '';
        $('realstock-news-title').className = 'pop-cur';

        $('realstock-notice-table').style.display = 'none';
        $('realstock-notice-table2').style.display = 'none';
        $('realstock-news-table').style.display = 'block';
        $('realstock-news-table2').style.display = 'block';
    }
    
    $("hd-timeselectdropdown").onclick = function(){
        if ($("hd-timebox").style.display == "block")
            $("hd-timebox").style.display = "none";
        else
            $("hd-timebox").style.display = "block";
    }
    
    $("hd-indcselectdropdown").onclick = function(){
        if ($("hd-indcbox").style.display == "block")
            $("hd-indcbox").style.display = "none";
        else{
            $("hd-indcbox").style.display = "block";
        }
    }
    
    
    for (var i = 0; ; i++){
        if (!$("indc"+i))
            break;
        $("indc"+i).onclick = function(){
            $("hd-indcselect").innerHTML = this.innerHTML;
            $("hd-indcbox").style.display = "none";

            if (onAddIndc(this)){
                this.parentNode.className = "curli";
            }else{
                this.parentNode.className = "";
            }
        }
    }
}

var notIndex = false;
var dataObj = null;

function onDataChange(obj)
{
    if ($('realstock-entrust-name').getAttribute("visible")&&notIndex){
        $('realstock-entrust-name').innerHTML = '龙虎看盘';
    }

    if (obj['ret'] == 'ERR_STOCK_CODE')
    {
        var stateInfo = "已退市";
        innerSet(document.getElementById('realstock-values-state'), stateInfo, null);
    }
    
    if (obj['ret'] != 'OK')
        return;
       
    dataObj = obj;
    try{
        valuesSet();
    }
    catch(E){}    
}

function onPriceTableChange(obj)
{
    if (!obj.length || obj.length < 1)
        return;
        
    var tableStr = '<table cellpadding=0 cellspacing=0><tr class=\'hasbtm\'><td align=\'left\'>成交价</td><td align=\'right\'>成交量</td><td align=\'right\'>内盘</td><td align=\'right\'>外盘</td></tr>';
    var maxArr = {};
    var maxVal = 0;
    for(var i=0; i < obj.length; i++)
    {
      var curVal = parseInt(obj[i][1][0]);
      if (curVal > maxVal){
        maxArr = {};
        maxVal = curVal;
      }
      if (curVal == maxVal){
        maxArr[i]=1;
      }      
    }

    for(var i=0; i < obj.length; i++)
    {
        var valColor = 'nocolor';
        if (gLastValue > 0){
          if(obj[i][0] > gLastValue)
              valColor = 'incolor';
              
          if(obj[i][0] < gLastValue)
              valColor = 'decolor';
        }
        if(i == obj.length-1)
            tableStr += '<tr><td align=\'left\' class=\''+valColor+'\' width=\'50px\'>' + (obj[i][0]) + '</td>';
        else          
            tableStr += '<tr class=\'hasbtm\'><td align=\'left\' class=\''+valColor+'\' width=\'50px\'>' + (obj[i][0]) + '</td>';
        tableStr += '<td align=\'right\'';
        if (maxArr[i]){
           tableStr += ' class=\'incolor\' ';
        }
        tableStr += '>'+obj[i][1][0].toFixed(0)+'</td>';
        tableStr += '<td align=\'right\' class=\'decolor\'>'+obj[i][1][1].toFixed(0)+'</td>';
        tableStr += '<td align=\'right\' class=\'incolor\'>'+obj[i][1][2].toFixed(0)+'</td>';
        tableStr += '</tr>';
        
        
    }
    tableStr +='</table>';
    innerSet(('hd-trade-pricetable'), tableStr, null);   
  
}

var gLastValue = -1;
var currDate = '00000000';
var avgVol = 0;
var totalVol = 0;
var kline = null;

var dataStrBuff = [];
var currItems = [];

function upd2KLine()
{
    if (!dataObj['info'])
        return;
        
    dataStrBuff.push(dataObj.toJSONString());

    updateKLineFunc();
}

function updateKLineFunc()
{
    if (dataStrBuff.length > 0){
        datastr = dataStrBuff[0];
        
        if (kline&&kline.update(datastr)){
            dataStrBuff.shift();
        }
    }
    if (dataStrBuff.length > 0)
        window.setTimeout(updateKLineFunc, 100);
}


function valuesSet(){
    
    function setStopValue()
    {
        var limitRate = 0.1;
        if(stockName.indexOf('ST') >= 0 || stockName.indexOf('PT') >= 0)
        {
            limitRate = 0.05;
        }
    
        var hlimitv = (lastv * (1 + limitRate));
        var llimitv = (lastv * (1 - limitRate));
        
        innerSet(document.getElementById('realstock-values-hlimit'), hlimitv.toFixed(nfix).toString(), hlimitv - lastv);
        innerSet(document.getElementById('realstock-values-hlimit2'), hlimitv.toFixed(nfix).toString(), hlimitv - lastv);
        innerSet(document.getElementById('realstock-values-llimit'), llimitv.toFixed(nfix).toString(), llimitv - lastv);
        innerSet(document.getElementById('realstock-values-llimit2'), llimitv.toFixed(nfix).toString(), llimitv - lastv);
    }
    
    function setPrice(){
        innerSet(('hd-marks-last'), lastv.toFixed(nfix), lastv - lastv);
        innerSet(('hd-marks-open'), openv.toFixed(nfix), openv - lastv);
        innerSet(('hd-marks-open2'), openv.toFixed(nfix), openv - lastv);
        innerSet(('hd-names-value'), currv.toFixed(nfix), currv - lastv);
        innerSet(('hd-bs-cvalue'), currv.toFixed(nfix), currv - lastv);
        innerSet(('hd-values-value2'), currv.toFixed(nfix), currv - lastv);
    }
    
    function setVA(){
        innerSet(('hd-names-amount'), amount.toString(), null);
        innerSet(('hd-marks-volumn'), volumn, null);
        innerSet(('hd-marks-volumn2'), volumn, null);
        
        innerSet(('hd-marks-amount2'), amount.toString(), null);
        innerSet(('hd-marks-amount22'), amount.toString(), null);
    
    }
    
    function setBuySellValue(){
        if (dataObj['info']&&dataObj['info']['items']&&dataObj['info']['items'].length>2&&dataObj['info']['items'][2].length > 0){
          var newamount = dataObj['info']['items'][2][dataObj['info']['items'][2].length-1];
          if (currDate != dataObj['info']['timeInfo'][0] && currDate != '00000000'){
            newamount = 0;
          }
          innerSet(('hd-bs-camount'), newamount[2], 0);
          innerSet(('hd-bs-camount2'), newamount[2], 0);
        }
        
    }
    
    function setHLA(){
        innerSet(('hd-marks-avag'), avag.toString(), null);
        innerSet(('hd-marks-high'), highv.toFixed(nfix).toString(), highv - lastv);
        innerSet(('hd-marks-low'), lowv.toFixed(nfix).toString(), lowv - lastv);
        innerSet(('hd-marks-high2'), highv.toFixed(nfix).toString(), highv - lastv);
        innerSet(('hd-marks-low2'), lowv.toFixed(nfix).toString(), lowv - lastv);
    }
    
    function setInOut(){
        innerSet(('hd-inout-in'), ina.toFixed(0).toString(), -1);
        innerSet(('hd-inout-out'), outa.toFixed(0).toString(), 1);
        if (ina+outa>0){
            $('hd-inout-outratio').style.width = parseInt(98*outa/(ina+outa))+"%";
            $('hd-inout-inratio').style.width = (98-parseInt(98*outa/(ina+outa)))+"%";
        }else{
            $('hd-inout-outratio').style.width = "49%";
            $('hd-inout-inratio').style.width = "49%";
        }
    }
    
    function setRate(){
        var rateStr = (rate*100).toFixed(2).toString() + '%';
        var deltaStr = delta.toFixed(nfix).toString();
        var rateStr2 = rateStr; 
        if (delta > 0)
            rateStr = '+' + deltaStr + ' ' + '+' + rateStr; 
        else
            rateStr = deltaStr + ' ' + rateStr;     
        innerSet(('hd-names-rate'), rateStr, delta);
        innerSet(('hd-values-rate2'), deltaStr, delta);
        innerSet(('hd-values-rate22'), deltaStr, delta);
        innerSet(('hd-values-rate3'), rateStr2, delta);
        innerSet(('hd-values-rate32'), rateStr2, delta);
    
    }
    
    function setBuySellRatio(){
        innerSet(('hd-analyst-sell'), sella.toFixed(0).toString(), -1);
        innerSet(('hd-analyst-buy'), buya.toFixed(0).toString(), 1);
        
        var bsRate;
        if (buya + sella !== 0)
            bsRate = (buya - sella)/(buya + sella);
        else
            bsRate = 0;
        var bsDelta = buya - sella;
        var bsRateStr = (bsRate * 100).toFixed(2).toString() + '%';
        innerSet(('hd-analyst-rate'), bsRateStr, bsDelta);
        innerSet(('hd-analyst-delta'), bsDelta.toFixed(0).toString(), bsDelta);
        innerSet(('hd-analyst-buysell'), bsDelta.toFixed(0)+"&nbsp;&nbsp;&nbsp;"+bsRateStr, bsDelta);
        for (var i = 0; i < 5; i++){
            if (typeof buyas[i] == "undefined")
                break;
            if (buya + sella !== 0){
                $('hd-bs-buyratio'+i).style.width = parseInt((buyas[5-i-1]/(buya + sella) * 190)) + 'px';
                $('hd-bs-sellratio'+i).style.width = parseInt((sellas[i]/(buya + sella) * 190)) + 'px';
            }else{
                $('hd-bs-buyratio'+i).style.width = '19px';
                $('hd-bs-sellratio'+i).style.width = '19px';
            }
        }
        $('hd-ibs-buyratio').style.width = ((98+parseInt(bsRate * 98))/2) + '%';
        $('hd-ibs-sellratio').style.width = (98-((98+parseInt(bsRate * 98))/2)) + '%';
    }
    
    function setStockData(){
        buya = 0;
        sella = 0;
        buyas = [];
        sellas = [];
    
        for(var i=0; i< 5; i++)
        {
            var bv = dataObj['info']['instant'][2 * i + 7];
            var ba = dataObj['info']['instant'][2 * i + 8];
            buya += ba;
            buyas[i] = ba;
            innerSet(('hd-bs-bvalue' + (i+1).toString()), bv.toFixed(nfix).toString(), bv - lastv); 
            innerSet(('hd-bs-bamount' + (i+1).toString()), ba.toString(), null);
            
            var sv = dataObj['info']['instant'][2 * i + 17];
            var sa =  dataObj['info']['instant'][2 * i + 18];
            sella += sa;
            sellas[i] = sa;
            innerSet(('hd-bs-svalue' + (i+1).toString()), sv.toFixed(nfix).toString(), sv - lastv); 
            innerSet(('hd-bs-samount' + (i+1).toString()), sa.toString(), null);
        }
        
        if(currDate != dataObj['info']['timeInfo'][0])
        {
            currDate = dataObj['info']['timeInfo'][0];
            currItems = [];
            
            innerSet(('hd-trade-table'), '', null);   
            var args = {
                method : 'get', onComplete : function(rep){
                    //set stock info
                    var ret = rep;
                    var retObj;
                    try{
                        retObj = KISSY.JSON.parse(ret);
                    }catch(E){
                        return;
                    }
    
                    if (retObj.length == 2)
                    {
                        var start = 0;
                        if (currDate == retObj[0][0][0])
                            start  = 1;
                        
                        var len = retObj[0].length - start;
                        
                        for (var i= start; i< start + len; i++)
                            avgVol += retObj[0][i][1];
                        avgVol /= len;
                        
                        if (currDate < retObj[1][0][0])
                            totalVol = retObj[1][1][1];
                        else
                            totalVol = retObj[1][0][1];
                            
                        energeSet();
                    }
                    
                    upd2KLine();
                    
                
                }
            };
            
            var infoURL;
            if ( stockType == 'SH')
                infoURL = 'http://' + rdmDataDomainNameGet() + '/test/info.py/handler?cmd=SHHQ' + stockCode + '|' + Math.random().toString();
            else
                infoURL = 'http://' + rdmDataDomainNameGet() + '/test/info.py/handler?cmd=SZHQ' + stockCode + '|' + Math.random().toString();
            
            var myAjaj = new Ajaj(infoURL, args); 
        }
        else
        {
            energeSet();
        } 
        

        $('hd-bs-table').style.display = 'block';
        $('hd-indec-table').style.display = 'none';
        $('hd-trade-pricetablename').innerHTML = '分价表';
    }

    function setDateTime(){
        var timeStr = timeStrGen(dataObj['info']['timeInfo'][1]);
        var dataStr = dataObj['info']['timeInfo'][0].toString();
        dataStr = dataStr.substring(0,4)+"-"+dataStr.substring(4,6)+"-"+dataStr.substring(6,8)+"";
        innerSet(('hd-names-time'), dataStr + ' ' + timeStr, null);
    }

    //parse data
    //price
    var lastv = dataObj['info']['instant'][0];
    var openv = dataObj['info']['instant'][1];
    var currv = dataObj['info']['instant'][2]||0;
    gLastValue = lastv;
    if (!currv||currv.toFixed(0) == 0){
        currv = lastv;
    }

    //amount
    var volumn = dataObj['info']['instant'][3];
    var amount = dataObj['info']['instant'][4];
    var highv = dataObj['info']['instant'][5];
    var lowv = dataObj['info']['instant'][6];
    if (lowv > 99900)
        lowv = 0;

    //avag
    var avag = 0;
    if (volumn > 0)
        avag = (amount*100/volumn).toFixed(2);
    if (amount > 10000){
        amount = (amount/10000).toFixed(2) + " 亿元";
    }else{
        amount = amount + " 万元";
    }

    var stateInfo = "已退市";
    var currTime = dataObj['info']['timeInfo'][1];
    
    if(currTime < "093000" || currTime > "150000" || currTime > "113000" && currTime < "130000")
    {
        stateInfo = "交易结束";
    }
    else
    {
        stateInfo = "交易中...";
        if(openv.toFixed(3) == 0.000)
            stateInfo = "停牌";
    }
    innerSet(document.getElementById('realstock-values-state'), stateInfo, null);

    //liangbi
    var ina = dataObj['info']['in'];
    var outa = dataObj['info']['out'];

    //other
    var isLongPrice = dataObj['info']['longPrice'];
    var nfix = (isLongPrice == 1)?3:2;
    
    //init
    var buya = 0;
    var sella = 0;
    var buyas = [];
    var sellas = [];

    //up down stop
    setStopValue();
    
    //set basic values
    setPrice();
    
    //set volumn and amount
    setVA();
    
    //set buy sell values
    setBuySellValue();
    
    //set avag and high/low
    setHLA();
    
    //set in and out
    setInOut();
    
    //calc other value
    var rate = (currv-lastv)/lastv;
    var delta = currv - lastv;
    setRate();
    
    //set time  
    setDateTime();  
    
    if ( dataObj['info']['index'] == false)
    {
        notIndex = true;
        var retarr = setStockData(dataObj, nfix, lastv);
    }
    else
    {
        notIndex = false;
        //上涨下跌平盘
        var nInc = dataObj['info']['instant'][7];
        var nEql = dataObj['info']['instant'][8];
        var nDec = dataObj['info']['instant'][9];
        
        innerSet(('hd-indec-inc'), nInc.toString(), 1);
        innerSet(('hd-indec-eql'), nEql.toString(), null);
        innerSet(('hd-indec-dec'), nDec.toString(), -1);
        
        $('hd-indec-incratio').style.width = parseInt(nInc/(nInc+nEql+nDec)*100)+"%";
        $('hd-indec-eqlratio').style.width = parseInt(nEql/(nInc+nEql+nDec)*100)+"%";
        $('hd-indec-decratio').style.width = parseInt(nDec/(nInc+nEql+nDec)*100)+"%";
        
        
        //委买委卖
        buya =  dataObj['info']['instant'][10];
        sella =  dataObj['info']['instant'][11];

        //$('hd-bs').style.display = 'block';
        $('hd-bs-table').style.display = 'none';
        $('hd-indec-table').style.display = 'block';
        $('hd-trade-pricetablename').innerHTML = '&nbsp;';//style.visibility = 'hidden';
        $('realstock-entrust-name').innerHTML = '&nbsp;';//.style.visibility = 'hidden';
    }
        
    //set buy sell ratio
    setBuySellRatio(buya, sella);

    //成交明细
    if (dataObj['info']&&dataObj['info']['items']&&dataObj['info']['items'].length>2)
    {
        var tmpbsV;
              
        for( var i=0; i< dataObj['info']['items'][2].length; i++)
        {                    
            if( currItems.length == 100)
            {
                tmpbsV = currItems[0][1];
                currItems.remove(0);
            }
            currItems.push(dataObj['info']['items'][2][i]);
        }
            
        var tableStr = '<table cellpadding=0 cellspacing=0>';
        for(i=currItems.length-1; i>= 0; i--)
        {
            var volColor = 'nocolor';
            var valColor = 'nocolor';
            
            if (currItems[i][3] == 'B' && dataObj['info']['index'] == false)
            {
                volColor = 'incolor';
            }
            if (currItems[i][3] == 'S' && dataObj['info']['index'] == false)
            {
                volColor = 'decolor';
            }
            
            if(currItems[i][1] > lastv)
                valColor = 'incolor';
                
            if(currItems[i][1] < lastv)
                valColor = 'decolor';
            
            if(i == 0)
                tableStr += '<tr><td align=\'left\' width=\'50px\'>' + timeStrGen(currItems[i][0]) + '</td>';
            else          
                tableStr += '<tr class=\'hasbtm\'><td align=\'left\' width=\'50px\'>' + timeStrGen(currItems[i][0]) + '</td>';
                
            tableStr += '<td align=\'right\' class=\'' + valColor + '\'>' + currItems[i][1].toFixed(nfix) + '</td>'
            if( i==0 && tmpbsV && currItems[i][1] > tmpbsV || i !=0 && currItems[i][1] > currItems[i-1][1])
                tableStr += '<td align=\'center\'><img src=\'images/inc_bg.gif\'/></td>';
            else if( i==0 && tmpbsV && currItems[i][1] < tmpbsV || i !=0 && currItems[i][1] < currItems[i-1][1])
                tableStr += '<td align=\'center\'><img src=\'images/dec_bg.gif\'/></td>';
            else
                tableStr += '<td align=\'center\'>&nbsp;&nbsp;</td>';
                
            tableStr += '<td align=\'right\' class=\'' + volColor + '\'>' + currItems[i][2] + '</td>';
            tableStr += '</tr>';            
        }
        tableStr +='</table>';
        innerSet(('hd-trade-table'), tableStr, null); 
    }  
    
    upd2KLine();  
}

function energeSet()
{
    if(avgVol == 0 || totalVol == 0)
        return;
    
    changeRate = (dataObj['info']['instant'][3]*100)/(totalVol*10000);
    
    var changeStr = (changeRate * 100).toFixed(2).toString() + '%';
    innerSet(('hd-energe-change'), changeStr, 0);

    
    var ticks = dataObj['info']['start'] + dataObj['info']['history'].length -1;
    var rateStr;
    if(ticks == 0)
        rateStr = '--';
    else
        rateStr = ((dataObj['info']['instant'][3]*100)/(avgVol*ticks/240)).toFixed(2).toString();
    
    innerSet(('hd-energe-rate'), rateStr, 0);
    
}

function boardSet(dataStr)
{
    if(!dataStr)
        return;
        
    var infoObj = KISSY.JSON.parse(dataStr);
    
    if(infoObj.length == 1 && infoObj[0] == -1)
        return;
        
    var boardList = [];
    for(var i in infoObj){
        if (i != "toJSONString")
        {
            boardList.push([i, infoObj[i][0], infoObj[i][1]]);
        }    
    }  
    
    function rateCmp(a, b)
    {
        return b[2] - a[2];
    }
        
    boardList.sort(rateCmp);
    
    var inne = "<table>";
    for(var i = 0; i< boardList.length; i++)
    {
        btm = "hasbtm";
        if(i == boardList.length -1)
            btm = "";
        inne += "<tr class='" + btm + "'><td><a href='javascript:void(0)' onclick='goBoard(\"\", \"\", \"" + boardList[i][0] + "\")'>" + decodeURIComponent(boardList[i][1]) + "</a></td>";
        color = "incolor";
        if(boardList[i][2] < 0)
          color = "decolor";
        inne += "<td class='" + color + "'>" + boardList[i][2].toFixed(2) + "%</td></tr>"
    }
    
    inne += "</table>";
    $("stock-boardInfo-table").innerHTML = inne;
}

function indClose(indcName){
    var indKey = indcName;
    
    if (znzReal){
        znzReal.indRemove(indcName, true); 
    }
    
    if (currentIndc[indKey]){
        if ($(currentIndc[indKey]))
        {
            $(currentIndc[indKey]).parentNode.className = "";
        }
        currentIndc[indKey] = 0;
    }
}


//start();

function restartKLine(){
    if (znzReal){
        znzReal.restart();
        znzReal.updateSpecial();
    }
}

function flashkeyup(args){
    var ev = {};
    ev.charCode = args;
    document.onkeypress(ev);
}

/*-------------------排行-------------------------*/
var started6181 = false;
var gSort = null;
var gOrder = null;
var gMarket = null;
var gType = null;
var gBoardNo = null;
var newSortPreData = null;
function start6181(cWidth, cHeight)
{
    if (started6181)
    {
        if(!sortInstance)
            return;
        // default sort col is ratio
        sortInstance.mMetric = gSort || "ratio";
        sortInstance.mOrder = gOrder || "desc";

        parseParams(gMarket, gType, gBoardNo);
        gMarket = null;
        gType = null;
        gBoardNo = null;
        defaultShow(pid, cid, sortStockType);
        if (gSort && ((gSort == "turnover") || (gSort == "ratio5") ||
         (gSort == "weibi") ||(gSort == "zhenfu")))
        {
            window.setTimeout(function(){sortInstance.fixtable.move(5,0);}, 500);
        } 
        else
        {
            window.setTimeout(function(){sortInstance.fixtable.move(- sortInstance.fixtable.rx,0)}, 500);
        }
        return;
    }
    started6181 = true;
    
    startNewSort(cWidth, cHeight, gMarket, gType, gBoardNo, gSort, gOrder, null, "hd.php");     
    $("newsort-subheader").style.display = "none";
    $("newsort-body").style.height = cHeight + 'px';
    $("newsort-body").style.width = cWidth + 'px';    
}

function resize6181(cWidth, cHeight){
    //alert(cHeight);
    winResize(cWidth, cHeight);
}

function goBoard(market, mtype, boardNo, sort, order){
     gMarket = market;
     gType = mtype;
     gBoardNo = boardNo;
     gOrder = order;
     gSort = sort;
   
    window.setTimeout($("hd-6181").onclick.bind($("hd-6181")), 100);
}


newSort.prototype._formatA = function(market, mtype, order, sort)
{
    var formatStr = 'href=\"javascript:void(0)\" onclick=\"goBoard(\'';
    formatStr += market + '\', \'' + mtype + '\', \'\', \'' + order + '\', \'' + sort + '\' )\"'; 
    return formatStr;
}

/*-------------------------------板块---------------------------------------*/
var up = true;
var startedBlock = false;
function startStockBlock(cWidth, cHeight)
{
    if (startedBlock)
        return;
        
    startedBlock = true;
    
    ts = new cateBoards("stockblock-body", boardInstance[3],
        boardstockInterval, "sortData", null, 0, boardName[3]);
    boardInstance[3] = ts;
    ts.start();
    $("stockblock-top").style.display = "block";
    $("stockblock-main").style.width = (cWidth - 140) + 'px';
    $("stockblock-main").style.height = cHeight + 'px';
    $("stockblock-body").style.height = "auto";
}

function changeBoard(idx)
{
    ts.running = false;
    if (boardInstance[idx])
    {
        if (boardInstance[idx].showTable)
        {
            ts = boardInstance[idx];
            $("stockblock-body").innerHTML = "加载中...";
        }
        else
        {
            ts = new cateBoards("stockblock-body", boardInstance[idx],  boardstockInterval, "sortData", null, 6, boardName[idx], false);
            ts.start();
            $("stockblock-body").innerHTML = "加载中...";
            boardInstance[idx] = ts;
        }
        window.setTimeout(ts._refresh.bind(ts), 100);
        ts.running = true;
        $("stockblock-top").style.display = "block";
        $("stockblock-body").style.height = "auto";
    }
    resetTab(idx);
}

//浏览器窗口大小变化时如果窗口显示内容为板块时显示
function resizeStockBlock(cWidth, cHeight)
{
    if (!startedBlock)
        return;
        
    $("stockblock-main").style.width = (cWidth - 140) + 'px';
    $("stockblock-main").style.height = cHeight + 'px';   
}

var $boardOld = cateBoards.prototype.showTable;
/* show table*/
cateBoards.prototype.showTable = function(){
    if(!this.running)
    {
        return;
    }
    
    var i, j;
    var div = "<table cellspacing='1' cellpadding=5 border='0'><tr><th>序号</th>";
    for (i = 0; i < this.colNames.length; i ++){
        div += "<th>";
        if (this.sortable[i])
        {
            div += "<a id='sortli" + i + "' href='javascript:void(0)' onclick='" + this.funcName + "(" + ( i - 1) + ")'>";
        }
        div += this.colNames[i];

        if (this.colNum == i - 1)
        {
            if (!this.up)
            {
                div += "↓"
            }
            else
            {
                div += "↑"
            }
        }
        if (this.sortable[i])
        {
            div += "</a>";
        }
        div += "</th>";
    }
    div += "</tr>";

    for(i = 0; i < this.cateBoardData.length; i ++)
    {
        div += "<tr>";
        div += "<td>" + (i + 1) + "</td>";
        div += "<td><a href='javascript:void(0)' onclick=\"goBoard('', '', '";
        div += this.cateBoardData[i][2] + "')\">";
        div += decodeURIComponent(this.cateBoardData[i][0]) + "</a></td>";
        for(j = 0 ; j < this.cateBoardData[i][1].length; j ++)
        {
            var colorClass = "nocolor";
            if (this.colorArray[j])
            {
                colorClass = this.colorArray[j];
            }
            else
            {
                if (this.cateBoardData[i][1][6]>0)
                {
                    colorClass = "incolor";
                }
                else
                {
                    if (this.cateBoardData[i][1][6]<0)
                    {
                        colorClass = "decolor";
                    }
                }
            }

            div += "<td class='" + colorClass + "'>" + ((j == 0) ? this.cateBoardData[i][1][j].toFixed(2) + "%" : this.cateBoardData[i][1][j].toString())+"</td>";
        }
        div += "</tr>";
    }
    div += "</table>";

    //add to web page
    innerSet(document.getElementById(this.divID), div, null);
    innerSet($('stockblock-pagebar'), "", null);
}

/*------------------query init-------------------*/
function formSubmit(stock8161)
{
    if(!stock8161)
    {
        return true;
    }
    goBoard(stock8161.substring(3), stock8161.substr(2, 1));
    return false;
}

/*---------------page start----------------------*/
window.onload = start;

