// Globals
var znzIdx = null;
var znzLast = null;
var znzHot = null;
var znzDS = null;
var znzAD1 = null;
var znzAD2 = null;
var znzAD3 = null;
var znzAD4 = null;
var znzAD5 = null;
var znzAD6 = null;

var znzMystocks = null;
var znzMystockview = null;
    
function start()
{
    var onloadtime = new Date().getTime();
    
    var sugReal = new suggestQuery('realstock-query-query', 'realstock-query-select', 'realstock-query-code', 'realstock-query-form', null, null, null, true);
    
    var znzReals = [];
    var znzRealIds = [];
    
    var titleMargin = [2, 53, 101, 150, 194, 265];
    var swfW = 384;
    var swfH = 210;
    znzIdx = new znzIdxSummary('stock-index-all', 10 * 1000, idxsumry_data);
    //znzHot = new znzHotStock('stock-hot-table', 10 * 1000);
    znzDS = new znzDDZSort('stock-ddzsort-table', 10 * 1000, 'stock-ddzsort-order', ddzsort_data);
    znzLast = new znzLastVisit('stock-lastv-table', 10 * 1000, false, null, null);
    
    //znzMystocks = new znzMyStock('stock-mystock-table', 10 * 1000, true);
    //znzMystocks.running = false;
    
    znzMystockview = new znzStockViews(10 * 1000, swfW, swfH, titleMargin);
    znzMystocks =  new  znzMyStock('stock-mystock-table-content', 10 * 1000, 'znzMystocks');
    //special
    eventInit();
    var inittime = new Date().getTime();    
    
    //pingback
    //pingback.pv(null, null, starttime, onloadtime, inittime);
    
}

function eventInit()
{
    if($('stock-lastv-name'))
    {
        $('stock-lastv-name').onclick = function()
        {
            this.className = 'title-current';
            $('stock-mystock').className = "title-uncurr";
            
            $('stock-lastv-table').style.display = "block";
            $('stock-mystock-table').style.display = "none";
        }
    }
    
    if($('stock-mystock'))
    {
        $('stock-mystock').onclick = function()
        {
            this.className = 'title-current';
            $('stock-lastv-name').className = "title-uncurr";
            
            $('stock-lastv-table').style.display = "none";
            $('stock-mystock-table').style.display = "block";
        }
    }
}

function onDataChange(dataStr)
{
    
}

window.onload = start;

// for query
var suggestQueryStockView = function(queryDivId, selectDivId, codeInputId, formDivId, nameDivId, realswf, realswfid, realswfname, updateFunc, sid, sname, formSubmit){
    this.currLine = -1;
    this.currTRs = [];
    this.querydiv = $(queryDivId);    
    this.selectdiv = $(selectDivId);
    this.tableid = "";
    this.codeinput = $(codeInputId);
    this.formdiv = $(formDivId);
    
    this.formdiv.onsubmit = formSubmit || this.queryStock.bind2(this);
    
    this.oldid = realswfid || null;
    this.realswf = realswf || null;
    this.realswfname = realswfname || null;
    this.namediv = $(nameDivId);
    if(this.namediv)
        this.namediv.innerHTML = sname;
    
    this.updateFunc = updateFunc || null;
    this.sid = sid || 0;
    
    this.init();
}

suggestQueryStockView.prototype.init = function()
{
    this.querydiv.value = '代码/名称/拼音';
    
    this.querydiv.onfocus = function()
    {
        oninput = true;
        if(this.value == '代码/名称/拼音')
            this.value = '';            
    }
    
    this.querydiv.onblur = function(){oninput = false;}
    
    this.querydiv.onkeyup = function (ev)
    {
        ev = ev||window.event;
        
        if(ev.keyCode == 38 || ev.keyCode == 40 )    // key is up or down
        {
            if (this.currTRs)
            {
                var newLine = this.currLine;
                if(ev.keyCode == 38)
                {
                    if(this.currLine > 0)
                        newLine = this.currLine -1;
  
                }
                else
                {
                    if(this.currLine < this.currTRs.length -1)
                        newLine = this.currLine +1;
                }
                
                this.selectChange(newLine);

            }
        }
        else
        {
            var query = this.querydiv.value;
            query = query.replace(' ', '');
            if(query == '') 
            {
                this.selectdiv.innerHTML = '';
                this.selectdiv.style.display = "none";
                return;
            }
    
            var args = {
                method : 'get', onComplete : this.onSugRecved.bind(this)
            };
            
            query = encodeURIComponent(query); 
            query = 'http://' + WEB_SERVER + '/pyui/suggestion.py/handler?query=' + query;
            var myAjaj = new Ajaj(query, args); 
        }
    }.bind(this);
}

suggestQueryStockView.prototype.onSugRecved = function(rep)
{
    var ret = decodeURIComponent(rep);
    var lines = ret.split('|');
    this.tableid = "select-table-"+Math.random();
    var content = '<table id=\''+this.tableid+'\' class=\'modview-select-table\'>'
    for(var i=0; i< lines.length; i++)
    {
        var stocks = lines[i].split(';');
        if(stocks.length != 4 )
            continue;
        content += '<tr class=\'realstock-query-select-unselected\'>';        
        content += '<td>' + stocks[0] + '</td>' + '<td class=\'hide\'>' + stocks[1] + '</td>' + '<td>' + stocks[2] + '</td>' + '<td>' + stocks[3] + '</td>';
        content += '</tr>';
    }
    
    content += '</table>';
    this.selectdiv.innerHTML = content;
    this.selectdiv.style.display = "block";
    
    window.setTimeout(this.selectInit.bind(this), 100);
}

suggestQueryStockView.prototype.selectInit = function()
{
    var table = $(this.tableid||"");
    var that = this;
    if (table)
    {
        if (table.childNodes[0])
        {
            this.currTRs = table.childNodes[0].childNodes;
            this.selectChange(0)
            for (var i=0; i< this.currTRs.length; i++)
            {
                this.currTRs[i].onmouseover = function()
                {
                    var j = 0;
                    for(j =0; j< that.currTRs.length; j++)
                    {
                        if(that.currTRs[j] == this)
                            break;
                    }
                    if (j < that.currTRs.length);
                      that.selectChange(j);
                }
                
                this.currTRs[i].onclick = function()
                {
                    that.formdiv.onsubmit();
                }
            }
        }
    }    
}

suggestQueryStockView.prototype.selectChange = function(newLine)
{
    if (this.currLine < 0 || this.currLine > this.currTRs.length -1)
        this.currLine = 0;
        
    this.currTRs[this.currLine].className = "realstock-query-select-unselected";
    this.currTRs[newLine].className = "realstock-query-select-selected";

    this.currLine = newLine;
    
    // set input values
    var tds = this.currTRs[this.currLine].childNodes;      
    var stype = tds[1].innerHTML;
    if(stype == 'SH')
        this.codeinput.value = 'sh|' + tds[0].innerHTML+"|"+tds[2].innerHTML;
    else
        this.codeinput.value = 'sz|' + tds[0].innerHTML+"|"+tds[2].innerHTML;

}

suggestQueryStockView.prototype.queryStock = function()
{
   if(this.codeinput.value == '')
      return false;
   var codes = this.codeinput.value.split("|");
   //this.realswf.destroy();
   //delete this.realswf;
   //this.realswf = new znzRealStock(this.oldid, this.realswfname, codes[1], codes[2], codes[0].toUpperCase(), onDataChange, 10*1000);
   this.realswf.restart(codes[1], codes[2], codes[0].toUpperCase());
   this.updateFunc(this.sid, codes);
   this.namediv.innerHTML = codes[2];
   this.selectdiv.innerHTML = "";
   this.querydiv.value = '';
   this.codeinput.value = '';
   return false;
}

Function.prototype.bind2 = function(object) {
  var __method = this;
  return function() {
    return (__method.apply(object, arguments));
  }
}

var znzStockViews = function(interval, swfW, swfH, titleMargins){
    this.interval = interval;
    //this.passport = new Passport();
    //if (!this.passport.isPassportGet()){
    //    this.passport.getPassport();
    //}
    this.mSwfW = swfW;
    this.mSwfH = swfH;
    this.mTitleMargins = titleMargins;
    this.stocknames = {};
    this._init();
    
}

znzStockViews.prototype._init = function(){    
    this.defaultstocks = [['000001', 'sh', '上证指数'],['399001', 'sz', '深证成指'],['000300', 'sh', '沪深300'],['000016', 'sh', '上证50']];
    this._resetAll();
}

znzStockViews.prototype._resetAll = function()
{    
    //while (!this.passport.isPassportGet()){
    //    window.setTimeout(this._resetAll.bind(this), 100);
    //    return;
    //}
    // get stock name
    //if (this.passport.isLogin()){
    if (false){
        this.stocks = [];
        if (this.passport.getType("stockview")&&this.passport.getType("stockview").clone){
            this.stocks = this.passport.getType("stockview").clone();
        }
        if(this.stocks.length >=1)
        {
            this._getName(this._setAll.bind(this));   
        }else{
            if (this.passport.getType("mystock")&&this.passport.getType("mystock").clone){
                this.stocks = this.passport.getType("mystock").clone().concat(this.defaultstocks).slice(0,4);
                if(this.stocks.length > 3){
                    this._getName(this._setAll.bind(this));   
                }else{
                    this.stocks = this.defaultstocks;
                    this._setAll();
                }
            }
        }
    }else{
        this.stocks = this.defaultstocks;
        this._setAll();
    }
}

znzStockViews.prototype._getName = function(callback){
    var needfetch = false;
    for(var i = 0; i< this.stocks.length; i++)
    {   
        if (this.stocknames[this.stocks[i][1].toLowerCase() + this.stocks[i][0]]){
            this.stocks[i][2] = this.stocknames[this.stocks[i][1].toLowerCase() + this.stocks[i][0]];
        }else{
            needfetch = true;
            break;
        }
    }
    if (!needfetch){
        callback();
        return;
    }
    var args = {
        method : 'get', onComplete : function(rep){
            var ret = rep;
            
            var retObj = ret.parseJSON();
            for(var i = 0; i< this.stocks.length; i++)
            {
                if(retObj[this.stocks[i][1].toLowerCase() + this.stocks[i][0]]){
                    this.stocks[i][2] = (decodeURIComponent(retObj[this.stocks[i][1].toLowerCase() + this.stocks[i][0]]));
                    this.stocknames[this.stocks[i][1].toLowerCase() + this.stocks[i][0]] = this.stocks[i][2];
                }
            }
            if (callback)
                callback();
        }.bind(this)
    };
 
    var infoURL = '';
    for(var i = 0; i< this.stocks.length; i++)
    {   
        infoURL += this.stocks[i][1].toLowerCase() + this.stocks[i][0] + ',';
    }
    
    infoURL = 'http://' + rdmDataDomainNameGet() + '/test/sCode.py/get.znzDo?cmd=' + infoURL + '|' + Math.random().toString();  

    var myAjaj = new Ajaj(infoURL, args); 
}

znzStockViews.prototype._setAll = function(){
    var znzRealSH = new znzRealStock('shStock', 'shStock-swf', this.stocks[0][0],
        this.stocks[0][2], this.stocks[0][1].toUpperCase(), onDataChange, this.interval, null, this.mSwfW, this.mSwfH, this.mTitleMargins);
    var znzRealSZ = new znzRealStock('szStock', 'szStock-swf', this.stocks[1][0],
        this.stocks[1][2], this.stocks[1][1].toUpperCase(), onDataChange, this.interval, null, this.mSwfW, this.mSwfH, this.mTitleMargins);
    var znzRealHS300 = new znzRealStock('hsStock', 'hsStock-swf', this.stocks[2][0],
        this.stocks[2][2], this.stocks[2][1].toUpperCase(), onDataChange, this.interval, null, this.mSwfW, this.mSwfH, this.mTitleMargins);
    var znzRealS50 = new znzRealStock('s50Stock', 's50Stock-swf', this.stocks[3][0],
        this.stocks[3][2], this.stocks[3][1].toUpperCase(), onDataChange, this.interval, null, this.mSwfW, this.mSwfH, this.mTitleMargins);
    
    var znzReals = [znzRealSH, znzRealSZ, znzRealHS300, znzRealS50];
    var znzRealIds = ['shStock', 'szStock', 'hsStock', 's50Stock'];
    var znzRealNames = ['shStock-swf', 'szStock-swf', 'hsStock-swf', 's50Stock-swf'];

    for (var i = 0; i < 4; i++){
        new suggestQueryStockView('realstock-query-query'+i,'realstock-query-select'+i,'realstock-query-code'+i,'realstock-query-form'+i,
            'modview-name'+i, znzReals[i], znzRealIds[i], znzRealNames[i], this.stockupdate.bind(this), i, this.stocks[i][2]);
    }
}

znzStockViews.prototype.stockupdate = function(sid, inf){
    this.stocks[sid] = [inf[1], inf[0].toLowerCase()];
    //this.updatePassport();
}

znzStockViews.prototype.updatePassport = function(){
    var tmp = [];
    for (var i = 0; i < 4; i++){
        tmp.push([this.stocks[i][0], this.stocks[i][1].toLowerCase()]);
    }
    this.passport.setType("stockview", tmp);
    this.passport.setPassport(this.logined.bind(this));
}

znzStockViews.prototype.logined = function(succ, reason){
    if (succ){
    }else{
        var isReg = false;
        if (reason == 'Err_pwdCheck'){
            reason = "用户名或密码错误";
        }else if (reason == 'Err_passportExists'){
            isReg = true;
            reason = "用户名已存在";
        }else if (reason == 'Err_noSession'){
            reason = "超时，请重新登陆";
        }else if (reason == 'OK'){
            reason = "已经登出";
        }else if (reason == 'NeedLogin'){
            reason = "请登陆";
        }else{
            reason = "出错了，请稍候再试";
        }
    }
}
