/*-------------------------------------
boardBlock.js
    @Copyright compass.cn P.R.China, All rights resevered
    @Description
        show new sort list
    @History
        2010/01/21 by liang huang create
---------------------------------------*/
var DATA_SERVEAR_LIST = [
    'data01.znz.finance.bj1.aliyk.com',
    'data02.znz.finance.bj1.aliyk.com',
    'data03.znz.finance.bj1.aliyk.com',
    //'data04.znz.finance.bj1.aliyk.com',
    'data05.znz.finance.bj1.aliyk.com'
    ];

var WEB_SERVER = 'w01.znz.finance.bj1.aliyk.com';


var SWF_SERVER = rdmDataDomainNameGet();

// Global function
function rdmDataDomainNameGet()
{
    var dmName = '';            
    dmName = DATA_SERVEAR_LIST[parseInt(Math.random()*4)];
    return dmName;
}

/*
    json.js
    2007-03-20

    Public Domain

    This file adds these methods to JavaScript:

        array.toJSONString()
        boolean.toJSONString()
        date.toJSONString()
        number.toJSONString()
        object.toJSONString()
        string.toJSONString()
            These methods produce a JSON text from a JavaScript value.
            It must not contain any cyclical references. Illegal values
            will be excluded.

            The default conversion for dates is to an ISO string. You can
            add a toJSONString method to any date object to get a different
            representation.

        string.parseJSON(filter)
            This method parses a JSON text to produce an object or
            array. It can throw a SyntaxError exception.

            The optional filter parameter is a function which can filter and
            transform the results. It receives each of the keys and values, and
            its return value is used instead of the original value. If it
            returns what it received, then structure is not modified. If it
            returns undefined then the member is deleted.

            Example:

            // Parse the text. If a key contains the string 'date' then
            // convert the value to a date.

            myData = text.parseJSON(function (key, value) {
                return key.indexOf('date') >= 0 ? new Date(value) : value;
            });

    It is expected that these methods will formally become part of the
    JavaScript Programming Language in the Fourth Edition of the
    ECMAScript standard in 2008.

    This file will break programs with improper for..in loops. See
    http://yuiblog.com/blog/2006/09/26/for-in-intrigue/

    This is a reference implementation. You are free to copy, modify, or
    redistribute.

    Use your own copy. It is extremely unwise to load untrusted third party
    code into your pages.
*/

// Augment the basic prototypes if they have not already been augmented.

if (!Object.prototype.toJSONString) {

    Array.prototype.toJSONString = function () {
        var a = ['['],  // The array holding the text fragments.
            b,          // A boolean indicating that a comma is required.
            i,          // Loop counter.
            l = this.length,
            v;          // The value to be stringified.

        function p(s) {

// p accumulates text fragments in an array. It inserts a comma before all
// except the first fragment.

            if (b) {
                a.push(',');
            }
            a.push(s);
            b = true;
        }

// For each value in this array...

        for (i = 0; i < l; i += 1) {
            v = this[i];
            switch (typeof v) {

// Serialize a JavaScript object value. Ignore objects thats lack the
// toJSONString method. Due to a specification error in ECMAScript,
// typeof null is 'object', so watch out for that case.

            case 'object':
                if (v) {
                    if (typeof v.toJSONString === 'function') {
                        p(v.toJSONString());
                    }
                } else {
                    p("null");
                }
                break;

// Otherwise, serialize the value.

            case 'string':
            case 'number':
            case 'boolean':
                p(v.toJSONString());

// Values without a JSON representation are ignored.

            }
        }

// Join all of the fragments together and return.

        a.push(']');
        return a.join('');
    };


    Boolean.prototype.toJSONString = function () {
        return String(this);
    };


    Date.prototype.toJSONString = function () {

// Ultimately, this method will be equivalent to the date.toISOString method.

        function f(n) {

// Format integers to have at least two digits.

            return n < 10 ? '0' + n : n;
        }

        return '"' + this.getFullYear() + '-' +
                f(this.getMonth() + 1) + '-' +
                f(this.getDate()) + 'T' +
                f(this.getHours()) + ':' +
                f(this.getMinutes()) + ':' +
                f(this.getSeconds()) + '"';
    };


    Number.prototype.toJSONString = function () {

// JSON numbers must be finite. Encode non-finite numbers as null.

        return isFinite(this) ? String(this) : "null";
    };


    Object.prototype.toJSONString = function () {
        var a = ['{'],  // The array holding the text fragments.
            b,          // A boolean indicating that a comma is required.
            k,          // The current key.
            v;          // The current value.

        function p(s) {

// p accumulates text fragment pairs in an array. It inserts a comma before all
// except the first fragment pair.

            if (b) {
                a.push(',');
            }
            a.push(k.toJSONString(), ':', s);
            b = true;
        }

// Iterate through all of the keys in the object, ignoring the proto chain.

        for (k in this) {
            if (this.hasOwnProperty(k)) {
                v = this[k];
                switch (typeof v) {

// Serialize a JavaScript object value. Ignore objects that lack the
// toJSONString method. Due to a specification error in ECMAScript,
// typeof null is 'object', so watch out for that case.

                case 'object':
                    if (v) {
                        if (typeof v.toJSONString === 'function') {
                            p(v.toJSONString());
                        }
                    } else {
                        p("null");
                    }
                    break;

            case 'string':
            case 'number':
            case 'boolean':
                    p(v.toJSONString());

// Values without a JSON representation are ignored.

                }
            }
        }

// Join all of the fragments together and return.

        a.push('}');
        return a.join('');
    };


    (function (s) {

// Augment String.prototype. We do this in an immediate anonymous function to
// avoid defining global variables.

// m is a table of character substitutions.

        var m = {
            '\b': '\\b',
            '\t': '\\t',
            '\n': '\\n',
            '\f': '\\f',
            '\r': '\\r',
            '"' : '\\"',
            '\\': '\\\\'
        };


        s.parseJSON = function (filter) {

// Parsing happens in three stages. In the first stage, we run the text against
// a regular expression which looks for non-JSON characters. We are especially
// concerned with '()' and 'new' because they can cause invocation, and '='
// because it can cause mutation. But just to be safe, we will reject all
// unexpected characters.

            try {
                if (/^("(\\.|[^"\\\n\r])*?"|[,:{}\[\]0-9.\-+Eaeflnr-u \n\r\t])+?$/.
                        test(this)) {

// In the second stage we use the eval function to compile the text into a
// JavaScript structure. The '{' operator is subject to a syntactic ambiguity
// in JavaScript: it can begin a block or an object literal. We wrap the text
// in parens to eliminate the ambiguity.

                    var j = eval('(' + this + ')');

// In the optional third stage, we recursively walk the new structure, passing
// each name/value pair to a filter function for possible transformation.

                    if (typeof filter === 'function') {

                        function walk(k, v) {
                            if (v && typeof v === 'object') {
                                for (var i in v) {
                                    if (v.hasOwnProperty(i)) {
                                        v[i] = walk(i, v[i]);
                                    }
                                }
                            }
                            return filter(k, v);
                        }

                        j = walk('', j);
                    }
                    return j;
                }
            } catch (e) {

// Fall through if the regexp test fails.

            }
            throw new SyntaxError("parseJSON");
        };


        s.toJSONString = function () {

// If the string contains no control characters, no quote characters, and no
// backslash characters, then we can simply slap some quotes around it.
// Otherwise we must also replace the offending characters with safe
// sequences.

            if (/["\\\x00-\x1f]/.test(this)) {
                return '"' + this.replace(/([\x00-\x1f\\"])/g, function(a, b) {
                    var c = m[b];
                    if (c) {
                        return c;
                    }
                    c = b.charCodeAt();
                    return '\\u00' +
                        Math.floor(c / 16).toString(16) +
                        (c % 16).toString(16);
                }) + '"';
            }
            return '"' + this + '"';
        };
    })(String.prototype);
}



/*
ajax.js
*/
function Ajax(url, args) {
    this.url = url || "";
    if (this.url.indexOf('?') != -1)
       this.url = this.url + '&from=' + window.location.host;	
    else
    	 this.url = this.url + '?from=' + window.location.host;
    
    this.params = args.parameters || "";
    this.mime = args.mime || "text/html";
    this.onComplete = args.onComplete || this.defaultOnCompleteFunc;
    this.onLoading= args.onLoading || this.defaultOnLoadingFunc;
    this.onError = args.onError || this.defaultOnErrorFunc;
    this.onTimeout = args.onTimeout || this.defaultOnTimeoutFunc;
    this.timeout = args.timeout || 0;
    this.method = args.method || "post";

    if (typeof(args.sync) == "undefined" || args.sync == null)
    { 
	      this.sync = true;
    }
    else
    {
	      this.sync = args.sync ? true : false; 
    }
    this.loadData();
    this.timer = null;
    if (this.timeout){
        this.timer = window.setTimeout(this.onTimeout, this.timeout);
    }
}

Ajax.prototype = {
    READY_STATE_COMPLETE : 4,
    getRequest : function () {
        var funcs = [
           function() {return new ActiveXObject('Msxml2.XMLHTTP')},
           function() {return new ActiveXObject('Microsoft.XMLHTTP')},
           function() {return new XMLHttpRequest()},
        ];

        var req = null;
    	  for (var i = 0; i < funcs.length; i++) {
    	      var f = funcs[i];
    	      try {
    		        req = f();
    		        break;
    	      }
    	      catch (e) {}
    	  }
    
    	  return req || false;
    },

    //NOTE: yinwm -- convert paramater map to string 
    parseParams : function () {
        if (typeof (this.params) == "string") {
    	      return this.params;
    	  }
    	  else
    	  {
    	      var s = "";
    	      for (var k in this.params)
    	      {
    		        s += k + "=" + this.params[k] + "&";
    	      }
    	      return s;
    	  }
    },

    loadData : function () {
    	  this.req = this.getRequest();
    	
    	  if (this.req) {
    	      this.onLoading();
    	      try {
    		        var loader = this;
    		        this.req.onreadystatechange = function () {
        			      if (loader.req.readyState == loader.READY_STATE_COMPLETE)
        			      {
        			          window.clearTimeout(loader.timer);
        			          try
        			          {
        			              loader.onComplete.call(loader, loader.req);
        			          }
        			          catch(E)
        			          {   			        
        			          }
        			      }
    		        }
    		        this.req.open(this.method, this.url, this.sync);
    
    		        if (this.method == "post") {
    		            this.req.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
    		        }
    
    		        if (this.req.overrideMimeType)
    		        {
    		            this.req.overrideMimeType(this.mime);
    		        }
    		        this.req.send(this.method == "post" ? this.parseParams(this.params) : null);
    	      }
    	      catch(e)
    	      {
    		        
    		        window.clearTimeout(this.timer);
    		        this.onError.call(this, e);
    	      }
    	  }
    },

    defaultOnCompleteFunc : function () {	
    },

    defaultOnLoadingFunc : function () {
    },

    defaultOnErrorFunc : function (error) {	
    },
    
    defaultOnTimeoutFunc : function () {	
    }
}

/* ajaj.js */
AJAJ_CALLBACKS = {};

function AJAJ_ON_READYSTATE_CHANGE(ajajID, dataStr)
{
    if(AJAJ_CALLBACKS[ajajID])
    {
        try
        {
            AJAJ_CALLBACKS[ajajID](dataStr);
        }
        catch(E)
        {
        }
    }
}

function Ajaj(url, args) {
	  this.id=Number(new Date()).toString()+parseInt(10*Math.random())+parseInt(10*Math.random())+parseInt(10*Math.random());
    this.url = url || "";
    this.params = args.parameters || {};
    this.onComplete = args.onComplete || this.defaultOnCompleteFunc;
    this.onLoading= args.onLoading || this.defaultOnLoadingFunc;
    this.onError = args.onError || this.defaultOnErrorFunc;
    
    this._start();
}
Ajaj.prototype = {
    _start : function () {
    	  this.sender = document.createElement("SCRIPT");
        this.sender.id = this.sender.name = "SCRIPT_REQUESTER_" + this.id;
        this.sender.type = 'text/javascript';
        document.getElementsByTagName("head")[0].appendChild(this.sender);

        this.loadData();
    },
    
    parseParams : function () {

        var s = "";
    		if(this.params)
    		{
    			for (var k in this.params) 
    			{
    			    if(k == 'toJSONString') continue;
    			    s += k + "=" + this.params[k] + "&";
    			}
    	    }
    	    s += 'crossdomain=' + this.id + '&from=' + window.location.host;	
    	    return s;
    },

    loadData : function () {
            
    		if (this.sender) {
    		      
    			  this.onLoading();
			      try {
			          AJAJ_CALLBACKS[this.id] = null;
			          
    			      AJAJ_CALLBACKS[this.id] = function (jsReturn) {
    			            
    				        this.onComplete(jsReturn);
    				        window.setTimeout(this.destroy.bind(this), 100);
    			      }.bind(this);
    			      //alert(this.id);
    			      this.sender.onreadystatechange = this.sender.onload =  function () {};

                        			
    			      var paras=this.parseParams(this.params);
    			      var srcURL = '';
    			      if (this.url.indexOf('?') != -1)
    			          srcURL = this.url + '&' + paras;
    			      else
    			          srcURL = this.url + '?' + paras;
    			
    			      this.sender.src = srcURL;
    			      
			      }
			      catch (E)
			      {
			          this.onError(e);
			      }
    		}
    },

    defaultOnCompleteFunc : function (a) {
    },

    defaultOnLoadingFunc : function () {
    },

    defaultOnErrorFunc : function (error) {
    },
    destroy : function () {
        this.onComplete = function(){};
		    delete AJAJ_CALLBACKS[this.id];
		    if(this.sender)
		        document.getElementsByTagName("head")[0].removeChild(this.sender);
		    this.sender = null;
    }
}



/* bind.js */
Function.prototype.bind = function(object) {
    var __method = this;
    return function() {
        return __method.apply(object, arguments);
    }
}

Function.prototype.bind2 = function(object) {
    var __method = this;
   
    var argu = Array.prototype.slice.call(arguments,1);
    return function() {
        return __method.apply(object, argu, arguments);
    }
}


/*
* array.js
*/
Array.prototype.remove=function(dx)
{
    if(isNaN(dx)||dx<0||dx>this.length){return false;}
    for(var i=0,n=0;i<this.length;i++)
    {
        if(this[i]!=this[dx])
        {
            this[n++]=this[i]
        }
    }
    this.length-=1
}

Array.prototype.indexOf=function(v, nostrict){
    for(var i=0;i<this.length;i++){
        if(this[i]===v){
            return i;
        }
        if(nostrict&&(this[i]==v)){
            return i;
        }        
    }
    return -1;
}
Array.prototype.clone = function() {
  var newObj = (this instanceof Array) ? [] : {};
  for (i in this) {
    if (i == 'clone') continue;
    if (this[i] && typeof this[i] == "object") {
      newObj[i] = this[i].clone();
    } else newObj[i] = this[i]
  } return newObj;
};

/*
znzlib.js
*/
function innerSet(obj, str, delta, css)
{
    if (typeof obj == "string")
        obj = $(obj);

    if(!obj)
        return;
    css = css || {};
    obj.innerHTML = null;
    obj.innerHTML = str;
    if (typeof delta != "undefined" && delta != null && typeof delta != 'string')
    {
        obj.className = null;
        if(delta > 0)
            obj.className = css['up'] || 'incolor';
            
        if(delta == 0)        
            obj.className = css['keep'] || 'nocolor';
        
        if(delta < 0)        
            obj.className = css['down'] || 'decolor';
    }
    else if(typeof delta == 'string')
    {
        obj.className = delta;
    }
}

function timeStrGen(timeStr)
{
    var retStr = '';
    
    retStr += timeStr.substr(0, 2) + ':' +  timeStr.substr(2, 2) + ':' +  timeStr.substr(4, 2);
    
    return retStr;
}

function dateStrGen(dateStr)
{
    var retStr = '';
    
    retStr += dateStr.substr(0, 4) + '-' +  dateStr.substr(4, 2) + '-' +  dateStr.substr(6, 2);
    
    return retStr;
}

function getQueryString(queryStringName)
{
    var returnValue="";
    var URLString=new String(document.location);
    var serachLocation=-1;
    var queryStringLength=queryStringName.length;
    do
    {
        serachLocation=URLString.indexOf(queryStringName+"\=");
        if (serachLocation!=-1)
        {
            if ((URLString.charAt(serachLocation-1)=='?') || (URLString.charAt(serachLocation-1)=='&'))
            {
                URLString=URLString.substr(serachLocation);
                break;
            }
            URLString=URLString.substr(serachLocation+queryStringLength+1);
        }
  
    }
    while (serachLocation!=-1)
        if (serachLocation!=-1)
        {
            var seperatorLocation=URLString.indexOf("&");
            if (seperatorLocation==-1)
            {
                returnValue=URLString.substr(queryStringLength+1);
            }
            else
            {
                returnValue=URLString.substring(queryStringLength+1,seperatorLocation);
            } 
        }
        return returnValue;
}

function activeSet(el, htmlCode) 
{
    var ua = navigator.userAgent.toLowerCase();
    if (ua.indexOf('msie') >= 0 && ua.indexOf('opera') < 0) 
    {
        htmlCode = '<div style="display:none">for IE</div>' + htmlCode;
        htmlCode = htmlCode.replace(/<script([^>]*)>/gi,
        '<script$1 defer>');
        el.innerHTML = null;
        el.innerHTML = htmlCode;
        el.removeChild(el.firstChild);
    } 
    else 
    {
        var el_next = el.nextSibling;
        var el_parent = el.parentNode;
        el_parent.removeChild(el);
        el.innerHTML = null;
        el.innerHTML = htmlCode;
        if (el_next)
        {
            el_parent.insertBefore(el, el_next)
        }
        else
        {
            el_parent.appendChild(el);
        }
    }
}

/*
*  cookie.js
*/
var iCookie = {};
iCookie.cookiename = "default";
iCookie.get=function(name){
    name = name || iCookie.cookiename;
    var start=document.cookie.indexOf(name+"=");
    if(start==-1)return null;
    
    var len=start+name.length+1;
    if((!start)&&(name!=document.cookie.substring(0,name.length))){
        return null;
    }
    
    var end=document.cookie.indexOf(";",len); 
    if(end==-1)end=document.cookie.length;
    ckstr = document.cookie.substring(len,end);
    return (ckstr);
};    

iCookie.set=function(name,value){
    name = name || iCookie.cookiename;
    var expires = "expires=Sun, 1 Jan 2036 00:00:00 UTC;";
    //alert(document.domain);
    document.cookie=name+"="+(value)+";"+expires+"Path=/;Domain="+document.domain;
    //document.cookie=name+"="+(value)+";"+expires+"Path=/;Domain=.znz888.com";
}; 

/*
* pingback.js
*/
pingback  = {};
pingback.prefix = 'http://211.154.254.20/';
pingback.img=document.createElement('img');

pingback.pv = function(code, stype, starttime, onloadtime, inittime)
{
    var page = new String(document.location);
    page = page.split('?')[0];
    
    var pbURL = pingback.prefix + 'pv.gif?zuid=' + iCookie.get('ZUID');
    
    pbURL += '&url=' + page;
    
    if(code && stype)
        pbURL += '&stock=' + stype.toLowerCase() + code;
        
    if(starttime && onloadtime && inittime)
        pbURL += '&onloadtime=' + (onloadtime - starttime) + '&inittime=' + (inittime - onloadtime);
    
    pbURL += '&rmd=' + Math.random().toString();    
    pingback.img.src = pbURL;   
    
}

pingback.online = function()
{
    var page = new String(document.location);
    page = page.split('?')[0];
    
    if(page.indexOf('mod') > 0 || page.indexOf('ifeng') > 0 || page.indexOf('www.17fc.com') > 0 || page.indexOf('sortblock') > 0)
        return
    
    var pbURL = pingback.prefix + 'pv.gif?zuid=' + iCookie.get('ZUID');
    pbURL += '&rmd=' + Math.random().toString();    
    pingback.img.src = pbURL;   
    
    window.setTimeout(pingback.online, 10 * 1000);
}

//pingback.online();

/*
* md5.js
*/
var hexcase = 0; /* hex output format. 0 - lowercase; 1 - uppercase */ 
var b64pad = ""; /* base-64 pad character. "=" for strict RFC compliance */ 
var chrsz = 8; /* bits per input character. 8 - ASCII; 16 - Unicode */ 

/* 
* These are the functions you'll usually want to call 
* They take string arguments and return either hex or base-64 encoded strings 
*/ 
function hex_md5(s){ return binl2hex(core_md5(str2binl(s), s.length * chrsz));} 
function b64_md5(s){ return binl2b64(core_md5(str2binl(s), s.length * chrsz));} 
function hex_hmac_md5(key, data) { return binl2hex(core_hmac_md5(key, data)); } 
function b64_hmac_md5(key, data) { return binl2b64(core_hmac_md5(key, data)); } 

/* Backwards compatibility - same as hex_md5() */ 
function calcMD5(s){ return binl2hex(core_md5(str2binl(s), s.length * chrsz));} 

/* 
* Perform a simple self-test to see if the VM is working 
*/ 
function md5_vm_test() 
{ 
return hex_md5("abc") == "900150983cd24fb0d6963f7d28e17f72"; 
} 

/* 
* Calculate the MD5 of an array of little-endian words, and a bit length 
*/ 
function core_md5(x, len) 
{ 
/* append padding */ 
x[len >> 5] |= 0x80 << ((len) % 32); 
x[(((len + 64) >>> 9) << 4) + 14] = len; 

var a = 1732584193; 
var b = -271733879; 
var c = -1732584194; 
var d = 271733878; 

for(var i = 0; i < x.length; i += 16) 
{ 
var olda = a; 
var oldb = b; 
var oldc = c; 
var oldd = d; 

a = md5_ff(a, b, c, d, x[i+ 0], 7 , -680876936); 
d = md5_ff(d, a, b, c, x[i+ 1], 12, -389564586); 
c = md5_ff(c, d, a, b, x[i+ 2], 17, 606105819); 
b = md5_ff(b, c, d, a, x[i+ 3], 22, -1044525330); 
a = md5_ff(a, b, c, d, x[i+ 4], 7 , -176418897); 
d = md5_ff(d, a, b, c, x[i+ 5], 12, 1200080426); 
c = md5_ff(c, d, a, b, x[i+ 6], 17, -1473231341); 
b = md5_ff(b, c, d, a, x[i+ 7], 22, -45705983); 
a = md5_ff(a, b, c, d, x[i+ 8], 7 , 1770035416); 
d = md5_ff(d, a, b, c, x[i+ 9], 12, -1958414417); 
c = md5_ff(c, d, a, b, x[i+10], 17, -42063); 
b = md5_ff(b, c, d, a, x[i+11], 22, -1990404162); 
a = md5_ff(a, b, c, d, x[i+12], 7 , 1804603682); 
d = md5_ff(d, a, b, c, x[i+13], 12, -40341101); 
c = md5_ff(c, d, a, b, x[i+14], 17, -1502002290); 
b = md5_ff(b, c, d, a, x[i+15], 22, 1236535329); 

a = md5_gg(a, b, c, d, x[i+ 1], 5 , -165796510); 
d = md5_gg(d, a, b, c, x[i+ 6], 9 , -1069501632); 
c = md5_gg(c, d, a, b, x[i+11], 14, 643717713); 
b = md5_gg(b, c, d, a, x[i+ 0], 20, -373897302); 
a = md5_gg(a, b, c, d, x[i+ 5], 5 , -701558691); 
d = md5_gg(d, a, b, c, x[i+10], 9 , 38016083); 
c = md5_gg(c, d, a, b, x[i+15], 14, -660478335); 
b = md5_gg(b, c, d, a, x[i+ 4], 20, -405537848); 
a = md5_gg(a, b, c, d, x[i+ 9], 5 , 568446438); 
d = md5_gg(d, a, b, c, x[i+14], 9 , -1019803690); 
c = md5_gg(c, d, a, b, x[i+ 3], 14, -187363961); 
b = md5_gg(b, c, d, a, x[i+ 8], 20, 1163531501); 
a = md5_gg(a, b, c, d, x[i+13], 5 , -1444681467); 
d = md5_gg(d, a, b, c, x[i+ 2], 9 , -51403784); 
c = md5_gg(c, d, a, b, x[i+ 7], 14, 1735328473); 
b = md5_gg(b, c, d, a, x[i+12], 20, -1926607734); 

a = md5_hh(a, b, c, d, x[i+ 5], 4 , -378558); 
d = md5_hh(d, a, b, c, x[i+ 8], 11, -2022574463); 
c = md5_hh(c, d, a, b, x[i+11], 16, 1839030562); 
b = md5_hh(b, c, d, a, x[i+14], 23, -35309556); 
a = md5_hh(a, b, c, d, x[i+ 1], 4 , -1530992060); 
d = md5_hh(d, a, b, c, x[i+ 4], 11, 1272893353); 
c = md5_hh(c, d, a, b, x[i+ 7], 16, -155497632); 
b = md5_hh(b, c, d, a, x[i+10], 23, -1094730640); 
a = md5_hh(a, b, c, d, x[i+13], 4 , 681279174); 
d = md5_hh(d, a, b, c, x[i+ 0], 11, -358537222); 
c = md5_hh(c, d, a, b, x[i+ 3], 16, -722521979); 
b = md5_hh(b, c, d, a, x[i+ 6], 23, 76029189); 
a = md5_hh(a, b, c, d, x[i+ 9], 4 , -640364487); 
d = md5_hh(d, a, b, c, x[i+12], 11, -421815835); 
c = md5_hh(c, d, a, b, x[i+15], 16, 530742520); 
b = md5_hh(b, c, d, a, x[i+ 2], 23, -995338651); 

a = md5_ii(a, b, c, d, x[i+ 0], 6 , -198630844); 
d = md5_ii(d, a, b, c, x[i+ 7], 10, 1126891415); 
c = md5_ii(c, d, a, b, x[i+14], 15, -1416354905); 
b = md5_ii(b, c, d, a, x[i+ 5], 21, -57434055); 
a = md5_ii(a, b, c, d, x[i+12], 6 , 1700485571); 
d = md5_ii(d, a, b, c, x[i+ 3], 10, -1894986606); 
c = md5_ii(c, d, a, b, x[i+10], 15, -1051523); 
b = md5_ii(b, c, d, a, x[i+ 1], 21, -2054922799); 
a = md5_ii(a, b, c, d, x[i+ 8], 6 , 1873313359); 
d = md5_ii(d, a, b, c, x[i+15], 10, -30611744); 
c = md5_ii(c, d, a, b, x[i+ 6], 15, -1560198380); 
b = md5_ii(b, c, d, a, x[i+13], 21, 1309151649); 
a = md5_ii(a, b, c, d, x[i+ 4], 6 , -145523070); 
d = md5_ii(d, a, b, c, x[i+11], 10, -1120210379); 
c = md5_ii(c, d, a, b, x[i+ 2], 15, 718787259); 
b = md5_ii(b, c, d, a, x[i+ 9], 21, -343485551); 

a = safe_add(a, olda); 
b = safe_add(b, oldb); 
c = safe_add(c, oldc); 
d = safe_add(d, oldd); 
} 
return Array(a, b, c, d); 

} 

/* 
* These functions implement the four basic operations the algorithm uses. 
*/ 
function md5_cmn(q, a, b, x, s, t) 
{ 
return safe_add(bit_rol(safe_add(safe_add(a, q), safe_add(x, t)), s),b); 
} 
function md5_ff(a, b, c, d, x, s, t) 
{ 
return md5_cmn((b & c) | ((~b) & d), a, b, x, s, t); 
} 
function md5_gg(a, b, c, d, x, s, t) 
{ 
return md5_cmn((b & d) | (c & (~d)), a, b, x, s, t); 
} 
function md5_hh(a, b, c, d, x, s, t) 
{ 
return md5_cmn(b ^ c ^ d, a, b, x, s, t); 
} 
function md5_ii(a, b, c, d, x, s, t) 
{ 
return md5_cmn(c ^ (b | (~d)), a, b, x, s, t); 
} 

/* 
* Calculate the HMAC-MD5, of a key and some data 
*/ 
function core_hmac_md5(key, data) 
{ 
var bkey = str2binl(key); 
if(bkey.length > 16) bkey = core_md5(bkey, key.length * chrsz); 

var ipad = Array(16), opad = Array(16); 
for(var i = 0; i < 16; i++) 
{ 
ipad[i] = bkey[i] ^ 0x36363636; 
opad[i] = bkey[i] ^ 0x5C5C5C5C; 
} 

var hash = core_md5(ipad.concat(str2binl(data)), 512 + data.length * chrsz); 
return core_md5(opad.concat(hash), 512 + 128); 
} 

/* 
* Add integers, wrapping at 2^32. This uses 16-bit operations internally 
* to work around bugs in some JS interpreters. 
*/ 
function safe_add(x, y) 
{ 
var lsw = (x & 0xFFFF) + (y & 0xFFFF); 
var msw = (x >> 16) + (y >> 16) + (lsw >> 16); 
return (msw << 16) | (lsw & 0xFFFF); 
} 

/* 
* Bitwise rotate a 32-bit number to the left. 
*/ 
function bit_rol(num, cnt) 
{ 
return (num << cnt) | (num >>> (32 - cnt)); 
} 

/* 
* Convert a string to an array of little-endian words 
* If chrsz is ASCII, characters >255 have their hi-byte silently ignored. 
*/ 
function str2binl(str) 
{ 
var bin = Array(); 
var mask = (1 << chrsz) - 1; 
for(var i = 0; i < str.length * chrsz; i += chrsz) 
bin[i>>5] |= (str.charCodeAt(i / chrsz) & mask) << (i%32); 
return bin; 
} 

/* 
* Convert an array of little-endian words to a hex string. 
*/ 
function binl2hex(binarray) 
{ 
var hex_tab = hexcase ? "0123456789ABCDEF" : "0123456789abcdef"; 
var str = ""; 
for(var i = 0; i < binarray.length * 4; i++) 
{ 
str += hex_tab.charAt((binarray[i>>2] >> ((i%4)*8+4)) & 0xF) + 
hex_tab.charAt((binarray[i>>2] >> ((i%4)*8 )) & 0xF); 
} 
return str; 
} 

/* 
* Convert an array of little-endian words to a base-64 string 
*/ 
function binl2b64(binarray) 
{ 
var tab = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; 
var str = ""; 
for(var i = 0; i < binarray.length * 4; i += 3) 
{ 
var triplet = (((binarray[i >> 2] >> 8 * ( i %4)) & 0xFF) << 16) 
| (((binarray[i+1 >> 2] >> 8 * ((i+1)%4)) & 0xFF) << 8 ) 
| ((binarray[i+2 >> 2] >> 8 * ((i+2)%4)) & 0xFF); 
for(var j = 0; j < 4; j++) 
{ 
if(i * 8 + j * 6 > binarray.length * 32) str += b64pad; 
else str += tab.charAt((triplet >> 6*(3-j)) & 0x3F); 
} 
} 
return str; 
}

/*
    set $ instead of document.getElementbyID
*/
if ( typeof $ != "undefined" )
	_$ = $;

var $ = function (id){
    return document.getElementById(id)||null;
};

if(typeof $T != "undefined")
    _$T = $T;
var $T = function(el, tag, c)
{
    if(typeof el == 'string')
        el = $(el);
    if(c)
    {
        var childrens = el.childNodes;
        var ret = [];
        for(var i = 0; i < childrens.length; i ++)
        {
            var elTagName = childrens[i].tagName || "";
            if(elTagName.toLowerCase() == tag)
            {
                ret.push(childrens[i]);
            }
        }
        return ret;
    }
    if(el && tag && el.getElementsByTagName)
    {
        return el.getElementsByTagName(tag.toString());
    }
    return null;
}

/*
* Number.js
*/
//*** This code is copyright 2004 by Gavin Kistner, gavin@refinery.com
//*** It is covered under the license viewable at http://phrogz.net/JS/_ReuseLicense.txt
//*** Reuse or modification is free provided you abide by the terms of that license.
//*** (Including the first two lines above in your source code mostly satisfies the conditions.)


// Rounds a number to a specified number of decimals (optional)
// Inserts the character of your choice as the thousands separator (optional)
// Uses the character of your choice for the decimals separator (optional)
//
// It's not a highly optimized speed demon, but it gives the right result...
// ...do you really care how speedy it is? :)
//
// !!Note!! IEWin gets (-0.007).format(2) WRONG, claiming that it's "0.00"
// This is a bug in IEWin's Number.toFixed() function.


Number.prototype.format=function(decimalPoints,thousandsSep,decimalSep){
 var val=this+'',re=/^(-?)(\d+)/,x,y;
 if (decimalPoints!=null) val = this.toFixed(decimalPoints);
 if (thousandsSep && (x=re.exec(val))){
  for (var a=x[2].split(''),i=a.length-3;i>0;i-=3) a.splice(i,0,thousandsSep);
  val=val.replace(re,x[1]+a.join(''));
 }
 if (decimalSep) val=val.replace(/\./,decimalSep);
 return val;
}
if (typeof Number.prototype.toFixed!='function' || (.9).toFixed()=='0' || (.007).toFixed(2)=='0.00') Number.prototype.toFixed=function(f){
 if (isNaN(f*=1) || f<0 || f>20) f=0;
 var s='',x=this.valueOf(),m='';
 if (this<0){ s='-'; x*=-1; }
 if (x>=Math.pow(10,21)) m=x.toString();
 else{
  m=Math.round(Math.pow(10,f)*x).toString();
  if (f!=0){
   var k=m.length;
   if (k<=f){
    var z='00000000000000000000'.substring(0,f+1-k);
    m=z+m;
    k=f+1;
   }
   var a = m.substring(0,k-f);
   var b = m.substring(k-f);
   m = a+'.'+b;
  }
 }
 if (m=='0') s='';
 return s+m;
}

/* stock index */
function isStockIndex(sCode, sType)
{
    if (sType.toLowerCase() == 'sh' && sCode < "001000") 
        return true;
        
    if (sType.toLowerCase() == 'sz' && (sCode.substr(0, 3) == '399' ||  sCode.substr(0, 3) == '395'))
        return true;
        
    return false;
    
}

// check browser type
function getBrowser() 
{ 
     var OsObject = ""; 
    if(navigator.userAgent.indexOf("MSIE")>0) { 
         return "MSIE"; 
    } 
    if(isFirefox=navigator.userAgent.indexOf("Firefox")>0){ 
         return "Firefox"; 
    } 
    if(isSafari=navigator.userAgent.indexOf("Safari")>0) { 
         return "Safari"; 
    }  
    if(isCamino=navigator.userAgent.indexOf("Camino")>0){ 
         return "Camino"; 
    } 
    if(isMozilla=navigator.userAgent.indexOf("Gecko/")>0){ 
         return "Gecko"; 
    } 
   
} 

var znzBrowser = getBrowser();

//iframe height auto fit
function ifrHeiAutoFit(iframeId)
{
    var iframeObj = $(iframeId);
    
    if(!iframeObj || window.opera)
        return;
        
    // for firefox
    if(iframeObj.contentDocument)
    {
       
        var sMaxY = iframeObj.contentWindow.scrollMaxY ;
        var offHeight = iframeObj.contentDocument.body.offsetHeight;
        var eleHeight = iframeObj.contentDocument.documentElement.offsetHeight;
        iframeObj.height = Math.max(sMaxY, offHeight, eleHeight);
        
    }
    else if(iframeObj.Document && iframeObj.Document.body.scrollHeight)// for IE
    {
        iframeObj.height = iframeObj.Document.body.scrollHeight;
    }
    
    // bin onload events to iframe
    if(iframeObj.addEventListener)
    {
        iframeObj.addEventListener("load", resizeFrame, false);
    }
    else
    {
        iframeObj.attachEvent("onload", resizeFrame);
    }
}

function resizeFrame(evt)
{
    evt = (evt) ? evt : window.event;
    var targetObj = (evt.target)? evt.target : evt.srcElement;
    
    // take care of W3C event processing from iframe's root document
    if(targetObj && targetObj.nodeType && targetObj.nodeType == 9)
    {
        if(evt.currentTarget && evt.currentTarget.tagName.toUpperCase() == "IFRAME")
        {
            targetObj = targetObj.currentTarget;
        }
    }
    
    if(targetObj)
    {
        ifrHeiAutoFit(targetObj.id);
    }
}

// caculate stock profit
function stockProfitGet(stockCode, stockType, buyPrice, buyAmount, commisionPercent, currPrice)
{
    
    var stockCost = stockCostGet(stockCode, stockType, buyPrice, buyAmount, commisionPercent);
    var totalCost = stockCost * buyAmount;
    var totalPrice = currPrice * buyAmount;
    var stockProfit = totalPrice - totalCost;
    return stockProfit;

}

function stockCostGet(stockCode, stockType, buyPrice, buyAmount, commisionPercent)
{
     var totalPrice = buyPrice * buyAmount;
     var transferFee = 0;
     if ( stockType.toUpperCase() == 'SH')
        transferFee = (buyAmount * 0.001) < 1 ? 1 : (buyAmount * 0.001);
     var commision = (totalPrice * commisionPercent ) < 5 ? 5 : (totalPrice * commisionPercent );
     var stampTax = totalPrice * 0.001;
     var stockCost = ( (transferFee + commision + stampTax ) / buyAmount ) + buyPrice;
     return stockCost;

}

function number_format( number, decimals, dec_point, thousands_sep ) {
    // http://kevin.vanzonneveld.net
    // +   original by: Jonas Raoni Soares Silva (http://www.jsfromhell.com)
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +     bugfix by: Michael White (http://getsprink.com)
    // +     bugfix by: Benjamin Lupton
    // +     bugfix by: Allan Jensen (http://www.winternet.no)
    // +    revised by: Jonas Raoni Soares Silva (http://www.jsfromhell.com)
    // +     bugfix by: Howard Yeend
    // +    revised by: Luke Smith (http://lucassmith.name)
    // +     bugfix by: Diogo Resende
    // +     bugfix by: Rival
    // %        note 1: For 1000.55 result with precision 1 in FF/Opera is 1,000.5, but in IE is 1,000.6
    // *     example 1: number_format(1234.56);
    // *     returns 1: '1,235'
    // *     example 2: number_format(1234.56, 2, ',', ' ');
    // *     returns 2: '1 234,56'
    // *     example 3: number_format(1234.5678, 2, '.', '');
    // *     returns 3: '1234.57'
    // *     example 4: number_format(67, 2, ',', '.');
    // *     returns 4: '67,00'
    // *     example 5: number_format(1000);
    // *     returns 5: '1,000'
    // *     example 6: number_format(67.311, 2);
    // *     returns 6: '67.31'
 
    var n = number, prec = decimals;
    n = !isFinite(+n) ? 0 : +n;
    prec = !isFinite(+prec) ? 0 : Math.abs(prec);
    var sep = (typeof thousands_sep == "undefined") ? ',' : thousands_sep;
    var dec = (typeof dec_point == "undefined") ? '.' : dec_point;
 
    var s = (prec > 0) ? n.toFixed(prec) : Math.round(n).toFixed(prec); //fix for IE parseFloat(0.55).toFixed(0) = 0;
 
    var abs = Math.abs(n).toFixed(prec);
    var _, i;
 
    if (abs >= 1000) {
        _ = abs.split(/\D/);
        i = _[0].length % 3 || 3;
 
        _[0] = s.slice(0,i + (n < 0)) +
              _[0].slice(i).replace(/(\d{3})/g, sep+'$1');
 
        s = _.join(dec);
    } else {
        s = s.replace('.', dec);
    }
 
    return s;
}

// CollectGarbage
function znzCollectGarbage()
{
    if (znzBrowser != "MSIE")
        return;
        
    CollectGarbage();
        
    window.setTimeout(znzCollectGarbage, 10* 1000);
}

znzCollectGarbage();


// check is hangqing time
var hqTimeFlag = true;
var hqTimeCallBacks = [];
function inHqTime()
{
    return hqTimeFlag;
}

function hqTimeCheck()
{
    var args = {
        method : 'get', onComplete : function(rep){
            
                dateStr = rep.responseText;
                var dt = dateStr.split(' ');
                if(dt[1] < '091000' || dt[1] > '152000')
                    hqTimeFlag = false;
                else
                    hqTimeFlag = true;
                var i = 0;
                var len = hqTimeCallBacks.length;
                for(i = 0; i < len; i ++)
                {
                    if(typeof hqTimeCallBacks[i] == 'function')
                        hqTimeCallBacks[i](dateStr);
                }
            }
        };
        
    var infoURL = './time.php?rdm=' + Math.random().toString();  

    var myAjax = new Ajax(infoURL, args); 
    
    window.setTimeout(hqTimeCheck, 60* 1000);    
    
}

hqTimeCheck();
// for index summary
function znzIdxSummary(interval, data)
{
    this.interval = interval;
    if(typeof data != 'undefined' && data)   
        this.data = data.substr(0, data.length -1);

    this.inited = false;
    this.mAjaj = null;
    this.mTimer = null;
    this.mListeners = [];
    this.mDataObj = null;
    this.mRunning = false;
}
znzIdxSummary.prototype.addEventListener = function(callBack)
{
    if(typeof callBack != 'function')
        return;
    this.mListeners.push(callBack);
    if(this.mDataObj != null)
        callBack(this.mDataObj);
}
znzIdxSummary.prototype._fire = function()
{
    if(this.mDataObj == null)
        return;
    var len = this.mListeners.length;
    var i = 0;
    for(i = 0; i < len; i ++)
    {
        this.mListeners[i](this.mDataObj);
    }
}
znzIdxSummary.prototype.start = function()
{
    if(this.mRunning)
    {
        return;
    }
    this.mRunning = true;
    this._init();
}

znzIdxSummary.prototype._init = function()
{
    this._update();  
    this.inited = true;
}

znzIdxSummary.prototype._update = function()
{
    if(this.mTimer)
        window.clearTimeout(this.mTimer);
    
    if(this.data)
    {
        this._set(this.data);
        this.data = null;
        this._fire();
    }
    else
    {
        if(!this.inited || inHqTime())
            this._refresh();
    }    
    this.mTimer = window.setTimeout(this._update.bind(this), this.interval);
}

znzIdxSummary.prototype._refresh = function()
{    
     var args = {
        method : 'get', onComplete : function(rep){
            this._set(rep);
            this._fire();
        }.bind(this)
    };
   
    infoURL = 'http://' + rdmDataDomainNameGet()+ '/test/data.py/prices.znzDo?cmd=sh000001,sz399001,sh000300|' + Math.random().toString(); 
    var myAjaj = new Ajaj(infoURL, args);
}

znzIdxSummary.prototype._set = function(dataStr)
{
    try
    {
        var retObj = dataStr.parseJSON();             
    }
    catch(e)
    {
        return false;;
    }
    this.mDataObj = retObj;
    return true;
}

znzIdxSummary.prototype.stop = function()
{
    if(this.mTimer != null)
        window.clearTimeout(this.mTimer);
    if(this.mAjaj)
    {
        this.mAjaj.destroy();
        this.mAjaj.onComplete = function(){};
    }
    this.mRunning = false;
}
var znzIdxBlock = function(interval, preData){
    this.interval = interval;
    if(typeof preData != 'undefined' && preData)   
        this.mPreData = preData.substr(0, preData.length - 1);
    this.running = false;
    this.inited = false;
    this.mAjaj = null;
    this.mTimer = null;
    this.mDataObj = null;
    this.mListeners = [];
}
znzIdxBlock.prototype.addEventListener = function(callBack)
{
    if(typeof callBack != 'function')
        return;
    this.mListeners.push(callBack);
    if(this.mDataObj != null)
        callBack(this.mDataObj);
}
znzIdxBlock.prototype._fire = function()
{
    if(this.mDataObj == null)
        return;
    var len = this.mListeners.length;
    var i = 0;
    for(i = 0; i < len; i ++)
    {
        this.mListeners[i](this.mDataObj);
    }
}
znzIdxBlock.prototype.start = function()
{
    if (!this.running){
        this.running = true;
        this._update();
        this.inited = true;
    }    
}

znzIdxBlock.prototype._update = function(){
    if(this.mTimer)
        window.clearTimeout(this.mTimer);
    
    if(this.mPreData)
    {
        this._set(this.mPreData);
        this.mPreData = null;
        this._fire();
    }
    else
    {        
        if(!this.inited || inHqTime())
            this._refresh();
    }
    this.mTimer = window.setTimeout(this._update.bind(this), this.interval);
}

znzIdxBlock.prototype._refresh = function(){
    var args = {
       method : 'get', onComplete : function(rep){    
            this._set(rep);
            this._fire();
        }.bind(this)
    };
     
    var infoURL = 'http://'+rdmDataDomainNameGet()+'/test/board.py/topBoards.znzDo?cmd=' + Math.random().toString();  
    this.mAjaj = new Ajaj(infoURL, args); 
}
        
znzIdxBlock.prototype._set = function(rep){
    var retObj = null;
    try
    {
        retObj = rep.parseJSON();
    }
    catch(e)
    {
        return false;
    }
    this.mDataObj = retObj;
    return true;
}
znzIdxBlock.prototype.stop = function()
{
    if(this.mTimer != null)
        window.clearTimeout(this.mTimer);
    if(this.mAjaj)
    {
        this.mAjaj.destroy();
        this.mAjaj.onComplete = function(){};
    }
    this.running = false;
}
//for ddz sort
function znzDDZSort(divID, interval, ctrID, data, oConfig)
{
    this.divID = divID;
    interval = interval||60000;
    if (!(interval < 60000))
        interval = 60000;

    this.interval = interval;
    this.ctrID = ctrID;
    this.topOrder = true;
    this.dataObj = null;
    if(data)
        this.data = data.substr(0, data.length -1);
    for(var p in oConfig)
        if(p != 'toJSONString')
            this[p] = oConfig[p];
    this.inited = false;
    this.mRunning = false;
    this.mTimer = null;
    this.mAjaj = null;
    //this._init();
}
znzDDZSort.prototype.start = function()
{
    if(!this.mRunning)
    {
        this._init();
        this.mRunning = true;
    }
}
znzDDZSort.prototype._init = function()
{
    var ctr = $(this.ctrID);
    
    if(ctr)
    {
        ctr.onclick = function()
        {            
            if (this.topOrder == true)
            {
                this.topOrder = false;
                this.innerHTML = '切换至排行前十';
                this.className = 'incolor';
            }
            else
            {
                this.topOrder = true;
                this.innerHTML = '切换至排行后十';
                this.className = 'decolor';
            }
            
            this.mTimer = window.setTimeout(this._refresh.bind(this), 100);
            
        }.bind(this)
    }
    
    this._update();
    this.inited = true;
}

znzDDZSort.prototype._update = function()
{
    if(this.data)
    {
        this._set(this.data);
        this.data = null;
    }
    else
    {
        if(!this.inited || inHqTime())
            this._refresh();  
    }
    if(this.mTimer)
        window.clearTimeout(this.mTimer);
    this.mTimer = window.setTimeout(this._update.bind(this), this.interval);
}

znzDDZSort.prototype._refresh = function()
{
     var args = {
        method : 'get', onComplete : function(rep)
        {            
            this._set(rep);   
        }.bind(this)
    };

    var infoURL;
    if(this.topOrder == true)
        infoURL = 'http://' + rdmDataDomainNameGet() + '/test/ddz.py/history_top10.znzDo?cmd=' + Math.random().toString();  
    else
        infoURL = 'http://' + rdmDataDomainNameGet() + '/test/ddz.py/history_last10.znzDo?cmd='+ Math.random().toString(); 
      
    this.mAjaj = new Ajaj(infoURL, args); 
}

znzDDZSort.prototype._set = function(dataStr){
    
    var retObj = dataStr.parseJSON();

    div = '';
    div += '<table>\n';
    div += ' <tr class=\'hasbtm\'><td class=\'table-center\'>名&nbsp;&nbsp;称</td><td class=\'table-center\'>价&nbsp;&nbsp;格</td><td class=\'table-center\'>&nbsp;主力动向</td></tr>'

    if(retObj[0] == -1)
    {
        return;
    }
    
    for(var i=0; i< retObj.length; i++)
    {
        div += '<tr class=\'hasbtm\'>';
        var currValue;
        var lastValue;
        var stockName;
        var stockCode;
        var ddzValue;
        
        currValue = retObj[i][4]; 
        lastValue = retObj[i][3];
        if (currValue == null || lastValue == null){
            return;
        }
        stockName = decodeURIComponent(retObj[i][2]);  
        stockCode = retObj[i][0];
        ddzValue = retObj[i][1]; 
      
        var valueColor = 'nocolor';
        if (currValue > lastValue)
            valueColor = 'incolor';
        if (currValue < lastValue)
            valueColor = 'decolor';
            
        var ddzColor = 'nocolor';
        if (ddzValue > 0)
            ddzColor = 'incolor';
        if (ddzValue < 0)
            ddzColor = 'decolor';
              
        div += '<td class=\'table-left\'><div class=\'stock-name\'><a href=\'./realstock.php?code=sh' + stockCode + '\'>' + stockName + '</a></div></td>';
        div += '<td class=\'' + valueColor + ' table-right\'>' + currValue.toFixed(2).toString() + '</td>';
        div += '<td class=\'' + ddzColor + ' table-right\'>' + ddzValue.toFixed(2).toString() + '</td>';
        
        div += '</tr>\n';
    }
    
    div += '</table>'; 
    innerSet($(this.divID), div, null);             
}


znzDDZSort.prototype.stop = function()
{
    if(this.mTimer != null)
        window.clearTimeout(this.mTimer);
    if(this.mAjaj)
    {
        this.mAjaj.destroy();
        this.mAjaj.onComplete = function(){};
    }
    this.mRunning = false;
}
function znzMarketBigTradeStock(interval, stockType, oConfig)
{
    //this.divID = divID;
    this.interval = interval;
    this.stockType = stockType.toLowerCase() || 'sh';
    this.sNumber = 0;
    this.dateTime = "00000000";
    this.tradeItems = [];
    this.mTimer = null;
    this.inited = false;
    
    this.mListeners = [];
    var p;
    for(p in oConfig)
        if(p != 'toJSONString')
            this[p] = oConfig[p];
    this.mRunning = false;
    this.mTimer = null;
    this.mAjaj = null;
    this.mCount = 0;
    //this._init();
}
znzMarketBigTradeStock.prototype.start = function()
{
    this.mCount ++;
    if(!this.mRunning)
    {
        this.mRunning = true;
        this._init();
    }
}
znzMarketBigTradeStock.prototype._init = function()
{           
   this._update();
   this.inited = true;    
}

znzMarketBigTradeStock.prototype._update = function()
{
    if(this.mTimer)
        window.clearTimeout(this.mTimer);
    if(this.mRunning)
    {
        if(!this.inited || inHqTime())
            this._refresh();
            
        this.mTimer = window.setTimeout(this._update.bind(this), this.interval);        
    } 
}

znzMarketBigTradeStock.prototype._refresh = function()
{
    var args = {
        method : 'get', onComplete : function(rep){
    
            var ret = rep;
            var retObj = ret.parseJSON();
            
            if( !retObj || retObj.length != 2 || retObj[1].length != 3)
                return;
                
            if(retObj[0] != this.dateTime)
            {
                this.dateTime = retObj[0];
                this.tradeItems = [];
            }
            
            this.sNumber = retObj[1][1];
            this.dataObj = retObj; 
            this.tradeItems = this.tradeItems.concat(this.dataObj[1][2]);
                
            // limit length to 50
            while(this.tradeItems.length > 50)
            {
                this.tradeItems.shift();
            }          
            //this._set();
            this._fire();
         }.bind(this)
     };
    
     var infoURL = 'http://' + rdmDataDomainNameGet()+ '/test/data.py/bigTradeMarket.znzDo?cmd=' + this.stockType + '|' + this.dateTime + '|' + this.sNumber + '|' + Math.random().toString();
     //alert(infoURL);
     var myAjaj = new Ajaj(infoURL, args);
}

znzMarketBigTradeStock.prototype._set = function()
{    
    //alert(this.tradeItems.length);    
    var tableStr = '<table cellpadding=0 cellspacing=0>';
    for(i=this.tradeItems.length -1; i>= 0; i--)
    {
        var volColor = 'nocolor';
        var valColor = 'nocolor';
    
        if (this.tradeItems[i][1][3] == 'B')
            volColor = 'incolor';
        if (this.tradeItems[i][1][3] == 'S')
            volColor = 'decolor';
        if(i == 0)
            tableStr += '<tr><td align=\'left\' width=\'50px\'>' + timeStrGen(this.tradeItems[i][1][0]) + '</td>';
        else
            tableStr += '<tr class=\'hasbtm\'><td align=\'left\' width=\'50px\'>' + timeStrGen(this.tradeItems[i][1][0]) + '</td>';
            
        tableStr += '<td align=\'left\' style=\'padding-left: 5px;\'><a href="./realstock.php?code=' + this.stockType.toLowerCase() + this.tradeItems[i][0] +'">' + decodeURIComponent(this.tradeItems[i][2]) + '</a></td>'    
        tableStr += '<td align=\'right\' class=\'' + valColor + '\'>' + this.tradeItems[i][1][1].toFixed(2) + '</td>'
        tableStr += '<td align=\'right\' class=\'' + volColor + '\'>' + this.tradeItems[i][1][2] + '</td>';
        tableStr += '</tr>';    
    }
    
    tableStr +='</table>';
    innerSet($(this.divID + '-table'), tableStr, null);
    $(this.divID).style.display = "block";
}
znzMarketBigTradeStock.prototype._fire = function()
{
    var i = 0;
    for(i = 0; i < this.mListeners.length; i ++)
    {
        this.mListeners[i](this.tradeItems);
    }
}

znzMarketBigTradeStock.prototype.addEventListener = function(func)
{
    this.mListeners.push(func);
}

znzMarketBigTradeStock.prototype.stop = function()
{
    this.mCount --;
    if(this.mCount < 1)
        return;
    this.mRunning = false;
    if(this.mTimer)
        window.clearTimeout(this.mTimer);
    if(this.mAjaj)
    {
        this.mAjaj.destroy();
        this.mAjaj.onComplete = function(){};
    }
}

znzMarketBigTradeStock.prototype.restart = function()
{
    this.mRunning = true;
    this._update();
}
function znzHotStock(stockList, interval, count)
{
    this.mInterval = typeof interval == 'undefined' ?  30 * 1000 : interval;
    if(typeof stockList == 'undefined')
    {
        this.inited  = false;
        return;
    }
    this.mStockList = stockList;
    this.inited = true;
    this.mListeners = [];
    this.mCurrentData = null;
    this.mCount = typeof count == 'undefined' ? 5 : count;
    this.mStockListStr = this._fmtStockListStr();
    this.mFirst = false;
    this.mRunning = false;
    this.mTimer = null;
    this.mAjaj = null;
}
znzHotStock.prototype._fmtStockListStr = function()
{
    var retStr = '';
    var i = 0;
    for(i = 0; i < this.mStockList.length && i < this.mCount; i ++)
    {
        retStr += this.mStockList[i][0] + ",";
    }
    return retStr;
}
znzHotStock.prototype.start = function()
{
    if(!this.mRunning)
    {
        if(!this.inited)
            return;
        this._update()
        this.mFirst = true;
        this.mRunning = true;
    }
}

znzHotStock.prototype._update = function()
{
    if(this.inited && ( inHqTime() || !this.mFirst ))
        this._refresh();
    if(this.mTimer)
        window.clearTimeout(this.mTimer);
        
    this.mTimer = window.setTimeout(this._update.bind(this), this.mInterval);   
}

znzHotStock.prototype._refresh = function()
{
    var args = {
        method : 'get', onComplete : function(rep){
            this.mCurrentData = rep;
            this._fire();
         }.bind(this)
     };
     var infoURL = 'http://' + rdmDataDomainNameGet()+ '/test/data.py/prices.znzDo?cmd=' + this.mStockListStr + '|' + Math.random().toString();
     this.mAjaj = new Ajaj(infoURL, args);
}

znzHotStock.prototype.addEventListener = function(listener)
{
    this.mListeners.push(listener);
}

znzHotStock.prototype._fire = function()
{
    if(!this.mCurrentData)
        return;
    var i = 0;
    for(i = 0; i < this.mListeners.length; i ++)
    {
        this.mListeners[i](this.mCurrentData);
    }
}

znzHotStock.prototype.stop = function()
{
    if(this.mTimer != null)
        window.clearTimeout(this.mTimer);
    if(this.mAjaj)
    {
        this.mAjaj.destroy();
        this.mAjaj.onComplete = function(){};
    }
    this.mRunning = false;
}
function znzNewSortRequest(dtype, subType, stype, interval, initData)
{
    this.mConstruct = false;
    this.mInited = false;
    if(typeof dtype == 'undefined' || subType == "undefined")
        return;
    this.mType = dtype;
    this.mSubType = subType;
    this.mSType = stype;
    this.mInitData = typeof initData == 'undefined' || !initData ? null : initData.substring(0, initData.length - 1);
    this.mTimer = null;
    this.mAjaj = null;
    this.mRunning = false;    
    this.mListeners = {};
    this.mData = null;
    this.mFlags = {};
    this.mFlags[dtype]= {};
    this.mFlags[dtype][subType] = {};
    this.mFlags[dtype][subType][stype] = false;
    this.mInterval = interval || 3 * 1000;
    this.mHash = [this._summaryABUrlJust.bind(this), this._summaryUrlJust.bind(this), 
        this._sortListMCUrlJust.bind(this), this._sortListBoardUrlJust.bind(this)];
    this.mConstruct = true;
}

// stock sort list of market and category
znzNewSortRequest.prototype.sortListUrl = "http://" + rdmDataDomainNameGet() + "/test/sort2.py/sortList.znzDo?cmd=";
// stock sort list of board
znzNewSortRequest.prototype.sortBoardStockUrl = "http://" + rdmDataDomainNameGet() + "/test/board.py/boardStocks.znzDo?cmd=";
// summary order url of summary AB
znzNewSortRequest.prototype.summaryABUrl = "http://" + rdmDataDomainNameGet() + "/test/sort2.py/summaryAB?cmd=";
// summary order url accordding to market and category
znzNewSortRequest.prototype.summaryUrl = "http://" + rdmDataDomainNameGet() +  "/test/sort2.py/sortSummary?cmd=";

// fmt summary AB order
znzNewSortRequest.prototype._summaryABUrlJust = function(p)
{
    return this.summaryABUrl + Math.random();
}

// fmt summary order 
znzNewSortRequest.prototype._summaryUrlJust = function(p)
{
    if(typeof p == 'undefined' || p == null || typeof p['m|c'] == 'undefined' || p['m|c'] == null)
        return;
    var marketCategory = p['m|c']
    var mc = marketCategory.split("|");
    if(mc[0].toLowerCase().indexOf("sh") != -1)
    {
        mc[0] = "sh";
    }
    else
    {
        mc[0] = "sz";
    }
    
    var retUrl = "";
    if(mc.length != 2)
    {
        retUrl = this.summaryUrl + "sh|A|";
    }
    else
    {
        retUrl = this.summaryUrl + mc[0] + "|" + mc[1] + "|";
    }
    return retUrl + Math.random();  
}

// fmt stock sort list url of market and category
znzNewSortRequest.prototype._sortListMCUrlJust = function(p)
{
    var retUrl = this.sortListUrl;
    var marketCategory = p['m|c'];
    var mc = marketCategory.split("|");
    var order = p['order'];
    var start = p['start'];
    var showNum = p['num'];
    var metric = p['metric'];
    // mc[0]= sz || sh,  mc[1] = A||B....
    retUrl += [mc[0], mc[1], order, start, 
         showNum + 3, metric, Math.random()].join("|");
    return retUrl;
}

// fmt stock sort list url of board
znzNewSortRequest.prototype._sortListBoardUrlJust = function(p)
{
    var retUrl = this.sortBoardStockUrl;    
    var marketCategory = p['m|c'];
    var order = p['order'];
    var start = p['start'];
    var showNum = p['num'];
    var metric = p['metric'];
    retUrl += [marketCategory, order, start, 
        showNum + 3, metric, Math.random()].join("|");
    return retUrl;    
}

znzNewSortRequest.prototype.restart = function(dtype, subType, stype, params, force)
{
    if(this.mType == dtype && this.mSubType == subType && this.mSType == stype  && !force)
        return;
    
    this.stop();
    if(typeof this.mFlags[dtype] == "undefined")
            this.mFlags[dtype] = {};
    if(typeof this.mFlags[dtype][subType]== "undefined")
        this.mFlags[dtype][subType] = {};
    if(typeof force != 'undefined' && !!force)
    {
        this.mFlags[dtype][subType][stype] = false;
    }
    this.mType = dtype;
    this.mSubType = subType;
    this.mSType = stype;
    this.start(params);
}

znzNewSortRequest.prototype.start = function(p)
{
    if(!this.mConstruct) // construct fail
        return;

    if(!this.mRunning)
    {
        this.mRunning = true;
        this.mParams = p;
        this._update();
        this.mInited = true;
    }
}

znzNewSortRequest.prototype._fire = function()
{
    if(this.mData == null)
        return;
    var i = 0;
    
    if(this.mListeners['all'])
    {
        var allListeners = this.mListeners['all'];
        for(i = 0; i < allListeners.length; i ++)
        {
            allListeners[i](this.mType, this.mData);
        }
    }
    if(typeof this.mListeners[this.mType] == 'undefined')
        return;
    
    var len = this.mListeners[this.mType].length;    
    for(i = 0; i < len; i ++)
    {
        this.mListeners[this.mType][i](this.mType, this.mData);
    }
}

znzNewSortRequest.prototype.addEventListener = function(type, cb)
{
    if(typeof cb != 'function')
        return;
    
    if(typeof type == 'undefined')
        return;
    if(typeof this.mListeners[type] == 'undefined' || this.mListeners[type] == null)
        this.mListeners[type] = [];
    this.mListeners[type].push(cb);
}

znzNewSortRequest.prototype._update = function()
{
    if(this.mRunning)
    {
        if(this.mInitData)
        {
            try
            {
                this.mData = this.mInitData.parseJSON();
            }
            catch(e)
            {
                this.mData = null;
            }            
            this._fire();
            this.mInitData = null;
        }
        else
        {
            
            if(!this.mFlags[this.mType][this.mSubType][this.mSType] || !this.mInited || inHqTime())
            {
                this._refresh();
            }
        }
        this.mInited = true;
        this.mFlags[this.mType][this.mSubType][this.mSType] = true;
        if(this.mTimer)
            window.clearTimeout(this.mTimer);
        var interval = this.mParams['interval'] || this.mInterval;
        this.mTimer = window.setTimeout(this._update.bind(this), interval);
    }    
}

znzNewSortRequest.prototype._refresh = function()
{
    var args = {
        method : "get",
        onComplete : function(re)
        {
            if(re == "[-1]")
                return;
            try
            {
                this.mData = re.parseJSON();
            }
            catch(e)
            {
                this.mData = null;
            }
            this._fire();
        }.bind(this)
    }
    var infoUrl = this.mHash[this.mType](this.mParams);
    this.mAjaj = new Ajaj(infoUrl, args);
}

znzNewSortRequest.prototype.stop = function()
{
    this.mRunning = false;
    if(this.mTimer)
    {
        window.clearTimeout(this.mTimer);
    }
    if(this.mAjaj)
    {
        this.mAjaj.destroy();
        this.mAjaj.onComplete = function(){};
    }    
}
function fixHeaderTable(tabledata, fixedRow, fixedCol, displayRow, displayCol, divId, dwidth, dheight, getDataFunc){
    this.getDataFunc = getDataFunc;
    this.tabledata = tabledata;
    this.fixedRow = fixedRow;
    this.fixedCol = fixedCol;
    this.displayRow = displayRow;
    this.displayCol = displayCol;
    this.dwidth = dwidth;
    this.dheight = dheight;

    this.rx = 0;
    this.ry = 0;
    this.div = $(divId);
    this.divId = divId;
    this.dragging = false;
    window[divId+"movefunc"] = this.move.bind(this);
    window[divId+"mousedownfunc"] = this.startdrag.bind(this);

    window.setTimeout(function(){
        if (this.div){
            if (this.div.addEventListener){
                this.div.addEventListener('DOMMouseScroll', this._mousewheel.bind(this), false);
            }
            this.div.onmousewheel = this._mousewheel.bind(this);
        }
    }.bind(this),600);

}

fixHeaderTable.prototype._mousewheel = function(event){
    if (this.stopped)
        return;
    var delta = 0;
    if (!event) /* For IE. */
            event = window.event;
    if (event.wheelDelta) { /* IE/Opera. */
        delta = event.wheelDelta/120;
        if (window.opera)
                delta = -delta;
    } else if (event.detail) { /** Mozilla case. */
        delta = -event.detail/3;
    }
    if (delta){
        window[this.divId+"movefunc"](0,-delta*(delta*delta));
    }
    if (event.preventDefault)
            event.preventDefault();
    event.returnValue = false;
}

fixHeaderTable.prototype._showCol = function(rx, ry){
    if (this.tabledata[ry].length <= rx){
        return "<li>--</li>";
    }

    var div = "<li";
    if (this.tabledata[ry][rx].length > 1){
        div += " class='"+(this.tabledata[ry][rx][1]||"")+"'";
    }
    if (this.tabledata[ry][rx].length > 2){
        div += "><a href='"+(this.tabledata[ry][rx][2]||"").replace(/'/g, "\'")+"'>";
        div += this.tabledata[ry][rx][0]+"</a>";
    }else{
        div += ">"+this.tabledata[ry][rx][0];
    }
    return div+"</li>";
}

fixHeaderTable.prototype._showRow = function(rx, ry){
    if (this.tabledata.length <= ry){
        return "";
    }
    var div = '';
    if(ry%2 == 0 && ry != 0)
        div = '<ul class="huebg">';
    else
        div = '<ul>';
        
    var i = 0;
    for (; i < this.fixedCol; i++){
        div += this._showCol(i, ry);
    } 
    for (; i < this.displayCol; i++){
        div += this._showCol(i+rx, ry);
    }
    div += "</ul>";
    return div;
}

fixHeaderTable.prototype.showBox = function(){
    var rx = this.rx;
    var ry = this.ry;
    var div = "<div class='fixTableMain' style='height:"+this.dheight+"px;width:" + this.dwidth + "px'>";
    div += "<div class='fixTableHeader'>";
    var i = 0;
    for (; i < this.fixedRow; i++){
        div += this._showRow(rx, i);
    }
    div += "</div>";
    div += "<div class='fixTableBody'>";
    for (; i < this.displayRow&&(i+ry<this.tabledata.length) ; i++){
        var tmp = this._showRow(rx, ry+i);
        div += tmp;
    }
    div += "</div></div>";
    return div;
}

fixHeaderTable.prototype.showTable = function(notupdate){
    if (this.stopped)
        return;
    var div = this.olddiv||"";
    if (!notupdate){
        div = this.showBox();
        this.olddiv = div;
    }
    div += "<div class='fixTableLeftScroll' style='height:"+this.dheight+"px'>";
    div += this._showLeftBar(this.ry);
    div += "</div>";
    div += "<div class='fixTableBottomScroll'>";
    div += this._showBottomBar(this.rx);
    div += "</div>";

    innerSet(this.div, div, null);
    return div;
}

fixHeaderTable.prototype._showLeftBar = function(ry){
    var div = "<ul>";
    var totallen = this.tabledata.length;
    if (totallen < this.displayRow){
        totallen = this.displayRow;
    }
    var heightc = ((this.dheight-36)/totallen);
    var barheight = heightc*this.displayRow;
    if (barheight < 20){
        barheight = 20;
    }
    if (totallen - this.displayRow > 0)
        heightc = (this.dheight-36-barheight)/(totallen - this.displayRow);
    else{
        barheight = this.dheight-36;
        heightc = 0;
    }
    this.oneheight = heightc;
    var liwidth = (this.dheight-barheight-(heightc*(totallen - this.displayRow)))/2;

    div += "<li style='height: "+liwidth+"px;' class='fixtable-up' onclick='window[\""+this.divId+"movefunc\"](0,-1);'><div></div></li>";

    var direction = 0-(this.displayRow-2);
    if (ry > 0)
        div += "<li style='height: "+(heightc*(ry))+"px;' class='fixtable-bg' onclick='window[\""+this.divId+"movefunc\"](0,"+direction+");'></li>";
    div += "<li id='scrollleftblock"+this.divId+"' style='height: "+(barheight)+"px;' class='fixtable-bar' onmousedown='window[\""+this.divId+"mousedownfunc\"](1, this.id, arguments);return false;'><div></div></li>";
    direction = this.displayRow-2;
    if (totallen > (ry+this.displayRow))
    div += "<li style='height: "+(heightc*(totallen-(ry+this.displayRow)))+"px;' class='fixtable-bg' onclick='window[\""+this.divId+"movefunc\"](0,"+direction+");'></li>";
    
    div += "<li style='height: "+liwidth+"px;' class='fixtable-down' onclick='window[\""+this.divId+"movefunc\"](0,1);'><div></div></li>";
    return div+"</ul>";
}

fixHeaderTable.prototype._showBottomBar = function(rx){
    var div = "<ul>";
    var totallen = this.tabledata[0].length;
    if (totallen <= 0){
        totallen = 1;
    }
    var heightc = ((this.dwidth-36)/totallen);
    var liwidth = (this.dwidth-(heightc*totallen))/2;
    this.onewidth = heightc;
    
    div += "<li style='width: "+liwidth+"px;' class='fixtable-left' onclick='window[\""+this.divId+"movefunc\"](-1, 0);'><div></div></li>";

    var direction = 0-(this.displayCol-2);
    if (rx > 0)
        div += "<li style='width: "+(heightc*(rx))+"px;' class='fixtable-bg2' onclick='window[\""+this.divId+"movefunc\"]("+direction+",0);'></li>";
    div += "<li id='scrollleftblock' style='width: "+(heightc*this.displayCol)+"px;' class='fixtable-bar2' onmousedown='window[\""+this.divId+"mousedownfunc\"](0, this.id, arguments);return false;'><div></div></li>";
    direction = this.displayCol-2;
    if (totallen > (rx+this.displayCol))
    div += "<li style='width: "+(heightc*(totallen-(rx+this.displayCol)))+"px;' class='fixtable-bg2' onclick='window[\""+this.divId+"movefunc\"]("+direction+",0);'></li>";

    div += "<li style='width: "+liwidth+"px;' class='fixtable-right' onclick='window[\""+this.divId+"movefunc\"](1, 0);'><div></div></li>";
    return div+"</ul>"
}

fixHeaderTable.prototype.move = function(mx, my, notupdate){
    if(isNaN(my))
    {
        return;
    }
    
    this.rx += mx;
    this.ry += my;

    if (this.rx < 0) this.rx = 0;
    var totallen = this.tabledata[0].length-this.displayCol;
    if (totallen < 0){
        totallen = 0;
    }
    if (this.rx > totallen) this.rx = totallen;
    
    if (this.ry < 0) this.ry = 0;
    totallen = this.tabledata.length-this.displayRow;
    if (totallen < 0){
        totallen = 0;
    }
    if (this.ry > totallen) this.ry = totallen;
    
    if (!notupdate){
        for (var i = this.ry; i-this.ry < this.displayRow&&(i+this.fixedRow<this.tabledata.length) ; i++){
            if (this.tabledata[i].length == 0){
                if (this.getDataFunc){
                    //refetch data
                    window.setTimeout(function(){
                        this.getDataFunc(i);
                        this.showTable();
                    }.bind(this), 100);
                    return "fail";
                }
            }
        }
    }    
    this.showTable(notupdate);
}

fixHeaderTable.prototype.setTableData = function(tabledata){
    this.tabledata = tabledata;
}

fixHeaderTable.prototype.getMsPosition = function (ev){
        ev = ev||window.event;
        var pos = {};
        if (this.isUpdown){
            pos.y = ev.pageY || (ev.clientY +
                   (document.documentElement.scrollTop || document.body.scrollTop));
        }else{
            pos.y = ev.pageX || (ev.clientX +
               (document.documentElement.scrollLeft || document.body.scrollLeft));
        }
        return pos;
};


fixHeaderTable.prototype.startdrag = function(isUpdown, elemid,  ev){
    ev = ev[0];
    if ((ev&&(ev.button != 0))||((!ev)&&(window.event.button != 1)))
        return;  // not left click
    
    if (typeof(document.onselectstart) != "undefined")
        document.onselectstart = function (){return false};

    
    this.backupDocument = document.onmouseup;
    this.backupDocument2 = document.onmousemove;
    this.dragging = true;
    this.isUpdown = isUpdown;
    this.moveDirect = 0;
    var pos = this.getMsPosition(ev);
    var tpos = this.getPosition($(elemid));
    this.pos = pos;
    this.diff = tpos-pos.y;
    this.elemid = elemid;
    document.onmouseup = function(){
        if (typeof(document.onselectstart) != "undefined")
            document.onselectstart = function (){return true};

        this.dragging = false;
        this.move(0, 0);
        document.onmouseup = this.backupDocument;
        document.onmousemove = this.backupDocument2;
    }.bind(this);
    document.onmousemove = function(ev){
        if (this.dragging){
            this.pos = this.getMsPosition(ev);
        }
    }.bind(this);
    window.setTimeout(this.drag.bind(this), 10);
}


fixHeaderTable.prototype.drag = function(isUpdown, ev){
    if (this.dragging){
        var tpos = this.getPosition($(this.elemid));
        var diff2 = tpos-this.pos.y;

        if (this.isUpdown){
            if (diff2-this.diff < 0-this.oneheight){
                this.move(0, parseInt((this.diff-diff2)/this.oneheight), true);
            }
            if (diff2-this.diff > this.oneheight){
                this.move(0, parseInt((this.diff-diff2)/this.oneheight), true);
            }
        }else{
            if (diff2-this.diff < -this.onewidth){
                this.move(parseInt((this.diff-diff2)/this.onewidth), 0, true);
            }
            if (diff2-this.diff > this.onewidth){
                this.move(parseInt((this.diff-diff2)/this.onewidth), 0, true);
            }
        }
        this.moveDirect = 0;
        window.setTimeout(this.drag.bind(this), 10);
    }
};

fixHeaderTable.prototype.getPosition = function (e){
	var left = 0;
	var top  = 0;
	//while (e!=null)
	while (e!=null)
	{
		left += e.offsetLeft;
		top  += e.offsetTop;
		e     = e.offsetParent;
	}
	if (this.isUpdown){
	    return top;
	}else{
	    return left;
	}
};
/* znzNewSort construct function
 * data request class
 */
function znzNewSort(req, p)
{
    this.mConstruct = false;
    if(typeof p == 'undefined' || p == null)
        p = {};
    if(!this._init(p))
        return;
    if(typeof req == 'undefined' || !req)
    {
        var interval = 3 * 1000;
        if(typeof p['interval'] != 'undefined')
            interval = p['interval'];

        var preData = null;
        if(typeof p['preData'] != 'undefined' && p['preData'])
            preData = p['preData'];

        var that = this;
        function cb(t, d){that._setFunc(t,d);};
        req = new znzNewSortRequest(-1, -1, '', interval, preData);
        req.addEventListener('all', cb);
    }
    
    this.mReq = req;
    this.mConstruct = true;
    if(p['start'])
    {
        this._start();
    }
    this.mParams = p;
}

znzNewSort.prototype._setFunc = function(t, d)
{
    this.mSetFunHash[t](d);
}

// SUMMARY AB
znzNewSort.SUMTYPE = 0;
// SUMMARY
znzNewSort.CLASSTYPE = 1;
// MARKET CATEGORY
znzNewSort.CLASSSTOCKTYPE = 2;
// BOARD
znzNewSort.BOARDSTOCKTYPE = 3;

/* init class znzNewSort's member value
 * parameters same as construct
 */
znzNewSort.prototype._init = function(p)
{
    if(typeof p['divId'] == 'undefined' || !p['divId'])
        return false;
    this.mDivId = p['divId'];
    this.mDivObj = $(this.mDivId); 
    // no this html element 
    if(!this.mDivObj)
        return false;
    
    if(typeof p['divHeight'] == 'undefined' || !p['divHeight'])
        return false;    
    this.mDivHeight = p['divHeight'];
    
    if(typeof p['showRowNum'] == 'undefined' || !p['showRowNum'])
        return false;
    this.mShowRowNum = p['showRowNum'];
    
    //hash set function
    this.mSetFunHash = [this._ABSet.bind(this), this._inteOrderset.bind(this),
        this._tableSet.bind(this), this._tableSet.bind(this)];
    this.mJumpUrl = "realstock.php";    
    if(typeof this.mJumpUrl == 'undefined')
        this.mJumpUrl = p['jmpUrl'];
    
    this.mCurrType = ""
    this.mParentID = 0;
    this.mChildID = 0;    
    this.mTotalRowNum = 0;
    this.mStartNum = 0;
    this.mMetric = "ratio";
    if(typeof p['metric'] != 'undefined')
        this.mMetric = p['metric'];
    this.mOrder = "desc";
    if(typeof p['order'] != 'undefined')
        this.mOrder = p['order'];
    var twidth = 922;
    if(typeof p['width'] != 'undefined')
        twidth = p['width'];
    var defCol = 14;
    if(typeof p['colNum'] != 'undefined')
        defCol = p['colNum'];
    this.mReqParams = {'order':this.mOrder, 'metric': this.mMetric, 'num':this.mShowRowNum, 'start':this.mStartNum};    
    this.fixtable = new fixHeaderTable([[]], 1, 3, this.mShowRowNum, defCol, this.mDivId, twidth, this.mDivHeight, this._tableCallBackFunc.bind(this));
    return true;
}

znzNewSort.prototype._tableCallBackFunc = function()
{
    if(this.mParentID != znzNewSort.CLASSSTOCKTYPE && this.mParentID != znzNewSort.BOARDSTOCKTYPE)
    {
        return;
    }
    this.mStartNum = this.fixtable.ry;
    this.mReqParams['start'] = this.mStartNum;
    this.mReq.restart(this.mParentID, this.mChildID, this.mCurrType, this.mReqParams, true);
    //this._refresh();
}

//default start function
znzNewSort.prototype._start = function()
{
    this.changeType(0, 0, "summary|");
}

/*切换显示类型*/
znzNewSort.prototype.changeType = function(parentID, childID, stockType)
{

    this.mParentID = parentID;
    this.mChildID = childID;
    this.mCurrType = stockType;
    
    if(this.isList())
    {
        this._clearTableData();
    }
    this.mReqParams['m|c'] = this.mCurrType;
    this.mReqParams['start'] = this.mStartNum;
    this.mReq.restart(parentID, childID, stockType, this.mReqParams, true);
}

/*clear table data*/
znzNewSort.prototype._clearTableData = function()
{
    this.fixtable.ry = 0;
    this.mStartNum = 0;
}

/* format <a>*/
znzNewSort.prototype._formatA = function(market, mtype, sort, order)
{
    var formatStr = 'href=\'newsort.php?market=' + market + '&type=' + mtype + '&sort=' + sort + '&order=' + order + '\'';
    return formatStr;
}

/* judge znzNewSort current show type */
znzNewSort.prototype.isList = function()
{
    if(this.mParentID != znzNewSort.CLASSSTOCKTYPE && this.mParentID != znzNewSort.BOARDSTOCKTYPE)
    {
        return false;
    }
    return true;
}

/* navigator showed body size has change*/
znzNewSort.prototype.sizeRefresh = function()
{
    //this.mCurrDataURL = this.mCurrJustFunc();
    //this._refresh();
    this.mReqParams['num'] = this.mShowRowNum;
    
    this.mReq.restart(this.mParentID, this.mChildID, this.mCurrType, this.mReqParams, true);
    
}

// 沪深综合排名显示列表顺序
znzNewSort.prototype.szABListOrder = ["ratio_inc", "ratio_dec", "volume", "amount", "price_inc", "price_dec", "turnover", "zhenfu"];

// 沪深综合排名显示列表顺序title 中文名
znzNewSort.prototype.szABListName = ["涨幅前10", "跌幅前10", "总量前5", "总额前5", "高价股前5", "低价股前5", "换手前5", "振幅前5"];

// 沪深综合排名显示列表中最后一列title中文名
znzNewSort.prototype.szABColName = ["涨幅 &nbsp; &nbsp;", "跌幅 &nbsp; &nbsp;", "成交量(手)", "成交额(万)", "涨跌幅", "涨跌幅", "换手率", "振幅 &nbsp; &nbsp;"];

// 沪深综合排名显示列表中最后一列后缀名
znzNewSort.prototype.szABColUint = ["%", "%", "", "", "%", "%", "%", "%"];

// 沪深综合排名显示列表中最后一列后颜色属性 -1根据自己的正负值确定自己的颜色0为黑色
znzNewSort.prototype.szABColColors = [-1, -1, 0, 0, -1, -1, 0, 0]

/* 沪深综合排名 */
znzNewSort.prototype._ABSet = function(d)
{
    var retObj = d;
    var sh = retObj["sh"];
    var sz = retObj["sz"];
    var shA = sh["A"].parseJSON();
    var shB = sh["B"].parseJSON();
    var szA = sz["A"].parseJSON();
    var szB = sz["B"].parseJSON();
    
    var abList = [shA, szA, shB, szB];
    var abListName = ["shA", "szA", "shB", "szB"];
    var abListCName = ["沪A", "深A", "沪B", "深B"];
    
    // format div inner html
    var divArr = [];
    var div = divArr.push('<ul class="up-down-rankA fixfloat">');
    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('<li><div class="fin-mod01">');
            divArr.push('<div class="hd"><a class="more-link" ' + formata + '>更多</a><h2><span>' + abListCName[j] + typename + '</span></h2></div>');
            divArr.push('<div class="bd">');
            divArr.push('<table class="table-style1"><thead><tr><th>&nbsp;</th><th>股票名称</th><td>价格</th><td>');
            divArr.push(this.szABColName[i] + "</td></tr></thead><tbody>");
            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><th>" + ( k + 1 ) + "</th>");
                divArr.push("<th><a href='" + this.mJumpUrl+ "?code="+ stocktype + stockcode +"'>" + decodeURIComponent(cur[1]) + "</a></th>");
                
                //color for new price
                var curlast = cur[2];
                var valueclass = "nocolor";
                if (curlast < cur[3]){
                    valueclass = "red";
                }
                if (curlast > cur[3]){
                    valueclass = "green";
                }                 
                
                divArr.push("<td><span class='" + valueclass + "'>" + cur[3].toFixed(cur[5] ? 3 : 2) + "</span></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 = "red";
                        }
                        if (cur[4] < 0){
                            valueclass = "green";
                        }
                    }
                }

                var conStr = cur[4].toFixed(cur[5] ? 3 : 2);
                if(itname == "volume")
                {
                    conStr = cur[4];
                }                
                divArr.push("<td><span class='" + valueclass + "'>" + conStr + this.szABColUint[i] + "</span></td></tr>");
            }
            divArr.push("</tbody></table></div></div></li>");
        }

       
    }
    
    divArr.push('</ul>');    
    div = divArr.join("");    
    innerSet(this.mDivObj, div, null);
}

// format table 报价牌
/*some default value for sort*/
znzNewSort.prototype.metrics = ["price", "volume", "amount", "ratio", "liangbi", "turnover", "ratio5", "weibi", "zhenfu"];

//传入数据的各列对应的含义
znzNewSort.prototype.cols = ["代码", "昨收", "今开", "现价", "总量(手)",   "总额(万)", "最高", "最低", "买入价",
     "卖出价",   "涨幅", "量比", "换手率", "5分钟涨幅", "isLongPrice",   "股票名称", "委比", "振幅"];

//该列是否可以排序,>0为对应的metric id+1
znzNewSort.prototype.colSortable = [0, 0, 0, 1, 2,   3, 0, 0, 0, 0,   4, 5, 6, 7, 0,   0, 8, 9];

//该列是否显示变化的颜色，0为不显示，-1为根据自身的值显示，1为根据昨收显示
znzNewSort.prototype.colColor = [0, 0, 1, 1, 0,   0, 1, 1, 1, 1,   -1, 0, 0, -1, 0,   0, -1, 0];

//该列是否以标准的小数显示, 1为小数，-1为百分比
znzNewSort.prototype.colToFix = [0, 1, 1, 1, 0,   0, 1, 1, 1, 1,   -1, 1, -1, -1, 0,  0, -1, -1];

//显示的列的顺序
znzNewSort.prototype.colpos = ["代码", "股票名称", "昨收", "今开", "现价",   "总量(手)", "总额(万)", "最高",
     "最低", "买入价",   "卖出价", "涨幅", "量比", "换手率", "5分钟涨幅",   "委比", "振幅"];

znzNewSort.prototype.sort = function(sortid)
{
    // if current show is not list
    if(this.mParentID != znzNewSort.CLASSSTOCKTYPE && this.mParentID != znzNewSort.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.mReqParams['start'] = this.mStartNum;
    this.mReqParams['order'] = this.mOrder;
    this.mReqParams['metric'] = this.mMetric;
    this.mReq.restart(this.mParentID, this.mChildID, this.mCurrType, this.mReqParams, true);
}

/*parse Obj*/
znzNewSort.prototype._parseTableData = function(d){
    var reObj = d;    
    //如果是板块股票列表 
    if(this.mParentID == znzNewSort.BOARDSTOCKTYPE)
    {
        this.mTotalRowNum = reObj[2];
        reObj = reObj[3].parseJSON();
    }
    else
    {       
        //全股票列表
        this.mTotalRowNum = reObj[0];
        reObj = reObj[1].parseJSON();
    }
     
    return reObj;
}

/*set table header*/
znzNewSort.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*/
znzNewSort.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*/
znzNewSort.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*/
znzNewSort.prototype._tableSet = function(d)
{

    var reObj = this._parseTableData(d);
    //table header
    this.tabledata = this._setTableHeader(reObj);;
    var i;
    //table body
    //top body
    for(i = 0; i < this.mStartNum; i ++)
    {
        this.tabledata.push([]);
    }
    
    //middle data
    for(i = 0; i < reObj.length; i ++)
    {
        this.tabledata.push([]);
        this._setItem(this.tabledata.length - 1, reObj[i]);
    }
    
    //bottom empty
    for(i = reObj.length + this.mStartNum; i < this.mTotalRowNum; i ++)
    {
        this.tabledata.push([]);
    }

    //add to web page
    this.fixtable.setTableData(this.tabledata);
    this.fixtable.showTable();
}

// 综合排名
// 综合排名显示列表序列
znzNewSort.prototype.types = ["ratio_inc", "ratio_dec", "ratio5_inc", "ratio5_dec", "weibi_inc", "zhenfu", "liangbi", "amount"];
// 综合排名显示列表序列中文名
znzNewSort.prototype.typenames = ["今日涨幅排名", "今日跌幅排名",  "5分钟涨幅排名", "5分钟跌幅排名", "今日委比排名", "今日振幅排名", "今日量比排名", "今日总金额排名"];
// 综合排名显示列表最后一列对应颜色
znzNewSort.prototype.colListColor = [-1, -1, -1, -1, -1, -1, -1, 0, 0];
// 综合排名显示列表最后一列对应后缀
znzNewSort.prototype.colEnd = ["%", "%", "%", "%", "%", "%", "%", ""];
// 综合排名显示列表最后一列对应中文名
znzNewSort.prototype.colName = ["涨跌幅", "涨跌幅", "涨跌幅", "涨跌幅", "委比", "振幅", "量比", "金额(万)"];

/* show data in format of table
 */
znzNewSort.prototype._inteOrderset = function(d)
{   
    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 = d;
    var div = '<ul class="up-down-rankA fixfloat">';
    for (var i = 0; i < this.types.length; i++){
        var typename = this.typenames[i];
        var nowtype = this.types[i];
        if(qzindex && nowtype == "amount")
        {
            divUnit = 10000;
        }
        
        var typen = nowtype.split("_");
        if (typen.length != 2)
            typen[1] = "desc";
        if (typen[1] == "dec")
            typen[1] = "asc";
        else
            typen[1] = "desc";
            
        if (!reObj[nowtype]){
            continue;
        }
        div += '<li><div class="fin-mod01">';
        div += '<div class="hd"><a class="more-link" ' + this._formatA(this.mCurrType.substring(2, 4), this.mCurrType.substring(5), typen[0], typen[1]) + '>更多</a><h2><span>' + typename + '</span></h2></div>';
        div += '<div class="bd">';
        div += '<table class="table-style1"><thead><tr><th>&nbsp;</th><th>股票名称</th><td>价格</td><td>';
        div += this.colName[i] + "</td></tr></thead><tbody>";
        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><th>"+(j+1)+"</th>";
            div += "<th><a href='" + this.mJumpUrl + "?code="+ stocktype + stockcode +"'>" + decodeURIComponent(cur[1]) + "</a></th>";
            
            //color for new price
            var curlast = cur[2];
            var valueclass = "nocolor";
            if (curlast < cur[3]){
                valueclass = "red";
            }
            if (curlast > cur[3]){
                valueclass = "green";
            }
            div += "<td><span class='" + valueclass + "'>" + cur[3].toFixed(cur[5] ? 3 : 2) + "</span></td>";
            
            //color for value            
            if (this.colListColor[i] <= 0){
                valueclass = "noclor";
                if (this.colListColor[i] < 0){
                    if (cur[4] > 0){
                        valueclass = "red";
                    }
                    if (cur[4] < 0){
                        valueclass = "green";
                    }
                }
            }
            
            div += "<td><span class='"+valueclass+"'>"+(cur[4] / divUnit).toFixed(2)+this.colEnd[i]+"</span></td></tr>";
        }
        div += "</tbody></table></div></div></li>";
    }
    
    div +="</ul>";
    
    innerSet(this.mDivObj, div, null);
    return div;
}
if(typeof znz_init_funcs == 'undefined' || !znz_init_funcs)
{
    znz_init_funcs = [];
}

function znz_init_func_call()
{
    var i = 0;
    var len = znz_init_funcs.length;
    for(i = 0; i < len; i ++)
    {
        znz_init_funcs[i]();
    }
}

var search_curr_li = "search_li_stock";
function search_navi_change(li_id)
{
    if(search_curr_li != li_id)
    {
        document.getElementById(search_curr_li).className = "";
        document.getElementById(li_id).className = "act";
        search_curr_li = li_id;
    }
    if(li_id == 'search_li_special')
    {
        var inp = document.getElementById('s');
        var sel = document.getElementById('teseshuju_select');
        if(inp && sel)
        {
            inp.style.width = '270px';
            sel.style.display = 'inline';
        }
    }
    else
    {
        var inp = document.getElementById('s');
        var sel = document.getElementById('teseshuju_select');
        if(inp && sel)
        {
            inp.style.width = '370px';
            sel.style.display = 'none';
        }
    }
}

function nav_search_sumbit()
{
    var f = document.getElementById('chaxun_form');
    if(f)
    {
        switch(search_curr_li)
        {
            case 'search_li_stock':                 
            case 'search_li_fund': f.action = 'http://finance.cn.yahoo.com/fin/finance_search_result.html';
                                   break;
            case 'search_li_special':f.action = document.getElementById('teseshuju_select').value;
                                   break;
        }
        f.submit();
    }
}

function addFavorite(url,title){
    var t = document.getElementsByTagName('title');
    title = t[0].innerHTML;
    if (document.all){
       window.external.addFavorite(url,title);
    }else if (window.sidebar){
       window.sidebar.addPanel(title, url, "");
    }
}
function setHomepage(url)
{
    if (document.all){
        document.body.style.behavior='url(#default#homepage)';
        document.body.setHomePage(url);
    }
    else if (window.sidebar){
        if(window.netscape){
            try{
                netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
            }catch (e){
                alert( "该操作被浏览器拒绝，如果想启用该功能，请在地址栏内输入 about:config,然后将项 signed.applets.codebase_principal_support 值该为true" );
            }
        }
        var prefs = Components.classes['@mozilla.org/preferences-service;1'].getService(Components.interfaces.nsIPrefBranch);
        prefs.setCharPref('browser.startup.homepage',url);
    }
    return false;
}
function znzLastVisitFmtTbl()
{
    //set last visit stock valuses
    var start = this.lastVisit.length - this.numShow;
    if(start < 0)
        start = 0;
 
    var div = '<table width="100%" border="0"><tr><td>名称</td><td>价格</td><td>涨跌幅</td></tr>';
    for(var i = start; i < this.lastVisit.length; i++)
    {
        var color = '';
        var nfix = 2;
        var curValue;
        var curRate;
        
        div += '<tr>'; 
        if(this.lastVisit[i][3])
        {
            if (this.lastVisit[i][3][0] == 1)
                nfix = 3;

            if(this.lastVisit[i][3][2] > this.lastVisit[i][3][1])
                color = 'red';
 
            if(this.lastVisit[i][3][2] < this.lastVisit[i][3][1])
                color = 'green';   

            if(this.lastVisit[i][3][2] == 0)
            {
                curValue = '--';       
                curRate  = '--%';
                color = '';
            }
            else
            {
                curValue = this.lastVisit[i][3][2].toFixed(nfix);
                var tmpVal = (this.lastVisit[i][3][2] - this.lastVisit[i][3][1]) / this.lastVisit[i][3][1];
                if ( tmpVal > 10.00)
                    curRate = tmp.toFixed(2);
                else
                    curRate = (tmpVal * 100).toFixed(2) + '%';
                if(tmpVal > 0)
                {
                    curRate = "+" + curRate;
                } 
            }
        }
        else
        {
            curValue = '--';       
            curRate = '--%';
            color = '';
        }
                    
        div += '<td><a href="./' + this.mJumpURL + '?code=' + this.lastVisit[i][1].toLowerCase() + this.lastVisit[i][0] + '" >' + decodeURIComponent(this.lastVisit[i][2]) + '</a></td>';
        div += '<td><span class="' + color + '">' + curValue + '</span></td>';
        div += '<td><span class="' + color + '">' + curRate  + '</span></td>';
        div += '</tr>';
    }          
    div += '</table>';
    return div;           
}

function znzF10Set()
{
    var inner_html = "";
    var infoLen = this.infoarr.length;
    for(var i = 0; i < infoLen; i++)
    {
        inner_html += "<li><a target='_blank' href='./F10.php?code=" + this.stockType.toLowerCase() + this.stockCode + "&type=" + this.infoarr[i][1] + "'>"+decodeURIComponent(this.infoarr[i][0])+"</a></li>";
    }
    
    $(this.divID).innerHTML = inner_html;
}

function znzWBFmtTbl()
{
    var div = '<table width="100%" bgcolor="#FFFFFF" cellspacing="1"><tr bgcolor="#e3ebee"><td>名称</td><td>价格</td><td>涨跌幅</td><td>名称</td><td>价格</td><td>涨跌幅</td></tr><tr bgcolor="#f5f5f5">';
    var retObj = this.mRetObj;
    var BWStockList = znzBWStock.BWStockList;
    var BWNameList = znzBWStock.BWNameList;
    for(var i = 0; i< this.mShowNum; i++)
    {
        var color = '';
        var nfix = 2;
        var curValue;
        var curRate;
        
        if(retObj[BWStockList[i]])
        {
            if (retObj[BWStockList[i]][0] == 1)
                nfix = 3;
    
            if(retObj[BWStockList[i]][2] > retObj[BWStockList[i]][1])
                color = 'red';
            if(retObj[BWStockList[i]][2] < retObj[BWStockList[i]][1])
                color = 'green';
    
            if (retObj[BWStockList[i]][2] == 0)
            {
                curValue = '--';
                curRate = '--';
                color = '';
            }
            else
            {
                curValue = retObj[BWStockList[i]][2].toFixed(nfix).toString();
                var tmpVal = (retObj[BWStockList[i]][2] - retObj[BWStockList[i]][1]) / retObj[BWStockList[i]][1];
                if (tmpVal > 10.00)
                    curRate = tmpVal.toFixed(2);
                else
                    curRate = (tmpVal * 100).toFixed(2);
                if(tmpVal > 0)
                {
                    curRate = "+" + curRate;
                }
             }
        }
        else
        {
            curValue = '--';
            curRate = '--';
            color = '';
        }
    
        div += '<td ><a href="./realstock.php?code=' + BWStockList[i] + '">' + BWNameList[i] + '</a></td>';
        div += '<td ><span class ="' + color + '">' + curValue  + '</span></td>';
        div += '<td ><span class ="' + color + '">' + curRate  + '%</span></td>';
    
        if(i % 2 == 1 && i < this.mShowNum - 2)
            div += '</tr><tr bgcolor="#f5f5f5">';
    }
    
    div += '</tr></table>';
    return div;
}
function znzIdxSortSetDiv(prefix, dataType, retList)
{    
    if(this.mStockType.toLowerCase() == prefix.toLowerCase())
    {
        var list = this.mList;
        
        var j = 0;
        for(j = 0; j < this.mList.length; j ++)
        {
            if(dataType == this.mList[j]['dataType'])
            {
                var div = "";
                div += '<table width="100%" bgcolor="#FFFFFF" cellspacing="1"><tr bgcolor="#e3ebee"><td>名称</td><td>价格</td><td>涨跌幅</td><td>名称</td><td>价格</td><td>涨跌幅</td></tr><tr bgcolor="#f5f5f5">';
                while (retList.length > this.count)
                    retList.pop();
               
                var rLen = retList.length;
                for (var i = 0; i < rLen; i++)
                {
                    var stockcode = retList[i][0].toLowerCase().replace("hq","");
                    
                    div += "<td><a href='realstock.php?code=" + stockcode + "'>"+decodeURIComponent(retList[i][1])+"</a></td>";
                    var classN = "";
                    var ratio = retList[i][4].toFixed(retList[i][5] ? 3 : 2);
                    if (retList[i][2] < retList[i][3])
                    {
                        classN = "red";
                        ratio = "+" + retList[i][4].toFixed(retList[i][5] ? 3 : 2);
                    }
                    if (retList[i][2] > retList[i][3])
                        classN = "green";
                    
                    div += "<td><span class='" + classN + "'>" + parseFloat( retList[i][3]).toFixed(retList[i][5] ? 3 : 2) + "</td>";                                
                    div += "<td><span class='" + classN + "'>" + ratio + "%</span></td>";
                    if(i % 2 == 1 && i < rLen - 2)
                        div += '</tr><tr bgcolor="#f5f5f5">';
                    
                }
                div += "</tr></table>";
                var divId = this.mList[j]['divID']
                
                innerSet($(divId), div, null);                
                return;
            }
        }
    }
}

function znzIndecFmtTbl(divId, retObj)
{
    var codeList = [['000001'], ['399001'], ['000002', '399002'], ['000003', '399003']];
    var nameList = ['上海：', '深圳：', 'A 股：', 'B 股：'];
    var dataList = [];
    var div = "";
    var i, j;
    for(i = 0; i < codeList.length; i ++)
    {
        var indc = 0;
        var keep = 0;
        var dec = 0;
        for(j =0; j < codeList[i].length; j ++)
        {
            if(retObj[codeList[i][j]] != null)
            {
                indc += retObj[codeList[i][j]][2];
                keep += retObj[codeList[i][j]][3];
                dec += retObj[codeList[i][j]][4];
            }
        }
        div += '<p class="b_bb"><b>' + nameList[i] + '</b>' +
            '<span class="red">上涨/' + indc + '家</span> ' +
            '<span>平盘/' + keep + '家</span> ' +
            '<span class="green">下跌/' + dec + '家</span> '
    }
    $(divId).innerHTML = div;
}

// for mystock
function yhMyStock(divID, interval)
{
    this.divID = divID;
    this.interval = interval;
    this.dataObj = null;
    this.AStockList = [];
    this.mInited = false;
    this._init();
}

yhMyStock.prototype._init = function()
{
    // get stock list from yahoo
     var args = {
        method : 'get', onComplete : function(rep)
        {
            this._initSet(rep);
            
        }.bind(this)
    };
   
    var infoURL = 'http://finance.cn.yahoo.com/fin/finance_hangqing20090309_iframe_mystock.html?rnd=' + Math.random().toString();       
    var myAjaj = new Ajaj(infoURL, args); 
}

yhMyStock.prototype._initSet = function(dataStr)
{
    if(dataStr == '-1')
    {
        var loginUrl ="https://edit.bjs.yahoo.com/config/login?.intl=cn&.done=" + encodeURIComponent('http://finance.cn.yahoo.com/fin/cn_finance_yahoo_login_redirect.html?url=' + window.location);
        $(this.divID).innerHTML = '<br/><div class="ft" style="text-align: center;"><a href="' + loginUrl + '">登录雅虎自选股</a></div><br/>';
        return;
    }
    
    this.dataObj = dataStr.parseJSON();
    
    for(var i = 0; i< this.dataObj.length; i++)
    {
        if(this.dataObj[i]['id'].substr(-2) == 'ss')
            this.AStockList.push('sh' + this.dataObj[i]['id'].substr(0, 6));
            
        if(this.dataObj[i]['id'].substr(-2) == 'sz')
            this.AStockList.push('sz' + this.dataObj[i]['id'].substr(0, 6));
    }
    
    this._update();
    this.mInited = true;
}

yhMyStock.prototype._update = function()
{
    if(!this.mInited || inHqTime())
    {
        
        this._refresh();    
    }     
    window.setTimeout(this._update.bind(this), this.interval);
}

yhMyStock.prototype._refresh = function()
{
     var args = {
        method : 'get', onComplete : function(rep)
        {
            this._set(rep);
            
        }.bind(this)
    };
   
   
    var infoURL = '';
    for(var i = 0; i< this.AStockList.length; i++)
    {   
        infoURL += this.AStockList[i] + ',';
    }
    
    infoURL = 'http://' + rdmDataDomainNameGet()+ '/test/data.py/prices.znzDo?cmd=' + infoURL + '|' + Math.random().toString();  
        
    var myAjaj = new Ajaj(infoURL, args); 

}

yhMyStock.prototype._set = function(dataStr)
{
    
    var retObj = dataStr.parseJSON();

    if(retObj[0] == -1)
    {
        return;
    }

    for(var i=0; i< this.dataObj.length; i++)
    {
        var yhCode = this.dataObj[i]['id'];
        
        var znzCode = '';
        
        if(yhCode.substr(-2) == 'ss')
            znzCode = 'sh' + yhCode.substr(0, 6);
        
        if(yhCode.substr(-2) == 'sz')
            znzCode = 'sz' + yhCode.substr(0, 6);
        
        if(znzCode && retObj[znzCode])
        {
            var nfix = 2;
            if(retObj[znzCode][0] == 1)
                nfix = 3;
            
            this.dataObj[i]['price'] = retObj[znzCode][2].toFixed(nfix);
            this.dataObj[i]['change'] = Math.abs((retObj[znzCode][2] -  retObj[znzCode][1])).toFixed(nfix);
            this.dataObj[i]['percent'] = Math.abs(((retObj[znzCode][2] -  retObj[znzCode][1]) * 100 / retObj[znzCode][1])).toFixed(2) + '%';
            
            var stat = 1;
            if((retObj[znzCode][2] -  retObj[znzCode][1]) > 0)
                stat = 2;
            if((retObj[znzCode][2] -  retObj[znzCode][1]) < 0)
                stat = 0;
                
            this.dataObj[i]['chg_stat'] = stat;   
        }
    }
    
    var div = '<table width="100%" border="0"><tr><td>名称</td><td>价格</td><td>涨跌幅</td></tr>';    
    for(var i = 0; i< this.dataObj.length; i++)
    {
        var color = '';      
        var minus = '';
        
        div += '<tr>';
 
        color = '';
        if(this.dataObj[i]['chg_stat'] == 2 && this.dataObj[i]['price'])
            color = 'red';
 
        if(this.dataObj[i]['chg_stat'] == 0 && this.dataObj[i]['price'])
        {
            color = 'green';   
            minus = '-';
        }
    
   
        div += '<td><a href="http://finance.cn.yahoo.com/q?s=' + this.dataObj[i]['id'] + '" >' + this.dataObj[i]['name'] + '</a></td>';
        div += '<td><span class = "' + color + '">' + (this.dataObj[i]['price']? this.dataObj[i]['price'] : '--') + '</span></td>';
        div += '<td><span class = "' + color + '">' + (this.dataObj[i]['price']? (minus + this.dataObj[i]['percent']) : '--%') + '</span></td>';
        div += '</tr>';

    }
             
    div += '</table>'; 
    var logoutUrl ="http://edit.bjs.yahoo.com/config/login?.intl=cn&logout=1&.direct=1&.done=" + encodeURIComponent('http://finance.cn.yahoo.com/fin/cn_finance_yahoo_login_redirect.html?url=' + window.location);
    
    div += '<div   style="text-align: left; margin-left: 5px;"><a href="http://mystock.cn.yahoo.com" style="color: green;">管理我的自选股</a>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="' + logoutUrl + '" >登出</a></div>';
       
    $(this.divID).innerHTML = div;                 
}
var znzShBigTradeMarket = null;
var znzSzBigTradeMarket = null;
var znzDDZSortIn = null;
var znzDDZSortOut = null;
var znzHotStockObj = null;
var znzIdx = null;
var znzIndcBoard = null;
var currList = [];
function idxSummaryFmt(d, div, codeList)
{
    var tableStr = '<li class="tt">A股指数</li>';
    var i = 0;
    var len = codeList.length;
    for(i = 0; i < len; i ++)
    {
        var stockCode = codeList[i][0];
        var stockName = codeList[i][1];
        
        var color = '';
        var flag = "+";
        var currPrice = d[stockCode][2];
        var lastPrice = d[stockCode][1];
        var amount = d[stockCode][3];
        if (currPrice > lastPrice)
            color = 'red';
        if (currPrice < lastPrice)
        {
            color = 'green';      
            flag = "";
        }
        
        tableStr += '<li style="width: ' + (i == len - 1 ? '270' : '271')+ 'px"><a href="./realstock.php?code=' + stockCode +'">' + stockName + '</a>';
        tableStr += '<span class="'+ color + '">' + currPrice.toFixed(2) + '　　</span>';
        tableStr += '<span class="'+ color + '">' + flag + (currPrice - lastPrice).toFixed(2)+ '　　</span>';
        tableStr += '<span>' +  (amount / 10000).toFixed(2) + '亿元</span></li>';
    }
    tableStr += '<li class="set"><a href="#" onclick="return header_showCustomDiv()" style="text-align:center">设置</a></li>';
    innerSet(div, tableStr);
}

function indcBoardFmt(d, div, c)
{
    var count = c || 5;
    var retList = d["inc"];
    var len = retList.length;
    var tableStr = '<li class="tt">领涨板块</li>';
    for(i = 0; i < len && count > 0; i ++, count --)
    {        
        tableStr += "<li style='width:" + ( (i == len - 1 || count == 1) ? '134' : '135') + "px'><a style='width:80px' href='./newsort.php?boardNo=" + retList[i][0] + "'>" + decodeURIComponent(retList[i][2]) + "</a>";
        var classN = "";
        if (retList[i][1][6] > 0)
            classN = "red";
        if (retList[i][1][6] < 0)
            classN = "green";
        tableStr += '<span class="' + classN + '"> ' + (retList[i][1][6]).toFixed(2) + '%</span></li>';
    }
    tableStr += '<li class="set"><a href="javascript:void(0)" style="text-align:center" >  </a></li>';
    innerSet(div , tableStr);
} 

function znzMarketBigTradeStockCommonSet(divID, stockType, dataList, c)
{
    var count = c || 5;
    var tableStr = '<li class="tt">' + (stockType == 'sh' ? '沪市' : '深市') + '大单</li>';
    for(i = dataList.length - 1; i>= 0 && count > 0; i--, count --)
    {
        var volColor = '';
        if (dataList[i][1][3] == 'B')
            volColor = 'up';
        if (dataList[i][1][3] == 'S')
            volColor = 'down';
            
        tableStr += '<li><a href="./realstock.php?code=' + stockType + dataList[i][0] +'">' + decodeURIComponent(dataList[i][2]) + '</a>'    
        tableStr += '<span class="span1"> ' + dataList[i][1][1].toFixed(2) + '</span>';
        tableStr += '<span class="' + volColor + ' span2"> ' +  dataList[i][1][2] + '</span></li>';
    }
    tableStr += '<li class="set"><a href="#" onclick="return hide_li(\'header_'+ stockType +'_big_trade\')" style="text-align:center" >关闭</a></li>';
    innerSet(divID , tableStr);
}

function znzDDZSortSet(dataStr)
{
    
    var retObj = null;
    try
    {
        retObj = dataStr.parseJSON();
    }
    catch(e)
    {
        return;
    }
    
    if(retObj[0] == -1 || retObj.length <= 0)
    {
        return;
    }
    var count = this.mCount || 5;
    div = '<li class="tt">' + (this.topOrder ? '资金流入':'资金流出') + '</li>';
    for(var i=0; i< retObj.length && i < count; i++)
    {
        var currValue;
        var lastValue;
        var stockName;
        var stockCode;
        var ddzValue;
        
        currValue = retObj[i][4]; 
        lastValue = retObj[i][3];
        if (currValue == null || lastValue == null){
            return;
        }
        stockName = decodeURIComponent(retObj[i][2]);  
        stockCode = retObj[i][0];
        ddzValue = retObj[i][1]; 
      
        var valueColor = '';
        if (currValue > lastValue)
            valueColor = 'up';
        if (currValue < lastValue)
            valueColor = 'down';
            
        var ddzColor = '';
        if (ddzValue > 0)
            ddzColor = 'up';
        if (ddzValue < 0)
            ddzColor = 'down';
              
        div += '<li><a href="./realstock.php?code=sh' + stockCode + '">' + stockName + '</a>';
        div += '<span class="' + valueColor + ' span1">' + currValue.toFixed(2).toString() + '</span>';
        div += '<span class="' + ddzColor + ' span2">' + ddzValue.toFixed(2).toString() + '</span></li>';
    }  
    div += '<li class="set"><a href="#" onclick="return hide_li(\'header_captial_' + (this.topOrder ? 'in':'out') + '\')" style="text-align:center" >关闭</a></li>';
    
    innerSet(this.divID, div, null);    
}

function znzHotStockUIFmt(dataStr)
{
    
    var retObj = null;
    try
    {
        retObj = dataStr.parseJSON();
    }
    catch(e)
    {
        return;
    }
    
    var icount = typeof count == 'undefined' ? 5 : count;
    div = '<li class="tt">关注最高</li>';
    for(var i=0; i < hotStocks.length && i < icount; i++)
    {
       
        var stockCode = hotStocks[i][0];
        var stockName = decodeURIComponent(hotStocks[i][1]);
        var currValue = retObj[stockCode][2];
        var lastValue = retObj[stockCode][1];
        var longPrice = retObj[stockCode][0] ? 3 : 2;      
        var valueColor = '';
         
        if (currValue != 0 && currValue > lastValue)
            valueColor = 'up';
        if (currValue != 0 && currValue < lastValue)
            valueColor = 'down';
        var currRatio = 0;
        if(currValue == 0)
        {
            currValue = "--";
            currRatio = "--%"
        }
        else
        {
            var diff = currValue - lastValue;
            currRatio = (diff / lastValue * 100).toFixed(longPrice);
            if(diff > 0)
                currRatio = "+" + currRatio;
            currValue = currValue.toFixed(longPrice);
        }
        div += '<li><a href="./realstock.php?code=' + stockCode + '">' + stockName + '</a>';
        div += '<span class="' + valueColor + '">' + currValue ;
        div += ' ' + currRatio + '</span></li>';
    }  
    div += '<li class="set"><a href="#" onclick="return hide_li(\'header_hot_stock\')" style="text-align:center" >关闭</a></li>';
    $('top-addtion-5').innerHTML = div;
}
function header_showCustomDiv()
{
    
    var el = $('header_user_custom_div');
    if(el == null || el.style.display == 'block')
        return false;
    var elf = $('heaher_hangqing_custom_form');
    var selectList;
    if(typeof elf.list != 'undefined')
        selectList = elf.list;
    else
        return false;
    
    var len = 1;
    if(selectList.length)
    {
        len = selectList.length;
    }
    else
    {
        selectList = [selectList];
    }
    var i = 0;
    
    for(i = 0; i < len; i ++)
    {
        var val = selectList[i].value;
        if(currList.indexOf(val) > -1)
        {
            selectList[i].checked = true;
        }
        else
            selectList[i].checked = false;
    }
    el.style.display = "block";
    return false;
}
function show_li(val)
{      
    switch(val)
    {
        case 'header_captial_in': $('capital-in').style.display = "block";
                                znzDDZSortIn.start();
                                break;
        case 'header_captial_out': $('capital-out').style.display = "block";
                                znzDDZSortOut.start();
                                break;
        case 'header_sh_big_trade':$('sh-big-trade').style.display = "block";
                                
                                znzShBigTradeMarket.start();
                                break;
        case 'header_sz_big_trade':$('sz-big-trade').style.display = "block";                                
                                znzSzBigTradeMarket.start();
                                break;
        case 'header_hot_stock':$('top-addtion-5').style.display = "block";
                                
                                znzHotStockObj.start();
                                break;
    }
}

function hide_li(val)
{   
    var idx = currList.indexOf(val);
    if(idx > -1)
        currList.remove(idx);

    switch(val)
    {
        case 'header_captial_in': $('capital-in').style.display = "none";
                                if(znzDDZSortIn != null)
                                    znzDDZSortIn.stop();
                                break;
        case 'header_captial_out': $('capital-out').style.display = "none";
                                if(znzDDZSortOut != null)
                                    znzDDZSortOut.stop();
                                break;
        case 'header_sh_big_trade':$('sh-big-trade').style.display = "none";
                                if(znzShBigTradeMarket != null)
                                    znzShBigTradeMarket.stop();
                                break;
        case 'header_sz_big_trade':$('sz-big-trade').style.display = "none";
                                if(znzSzBigTradeMarket != null)
                                    znzSzBigTradeMarket.stop();
                                break;
        case 'header_hot_stock':$('top-addtion-5').style.display = "none";
                                if(znzHotStockObj != null)
                                    znzHotStockObj.stop();
                                break;
    }
    return false;
}
function header_initEvent()
{
    var el = $('header_hangqing_cancle');
    if(el != null)
        el.onclick = function()
        {
            var el_div = $('header_user_custom_div');
            if(el_div != null)
                el_div.style.display = "none";
        }
    
    var el_sure = $('header_hangqing_sure');
    if(el_sure != null)
        el_sure.onclick = function()
        {
            var elf = $('heaher_hangqing_custom_form');
            var selectList;
            if(typeof elf.list != 'undefined')
                selectList = elf.list;
            else
                return false;
            
            var len = 1;
            if(selectList.length)
            {
                len = selectList.length;
            }
            else
            {
                selectList = [selectList];
            }
            var i = 0;
            for(i = 0; i < len; i ++)
            {
                var val = selectList[i].value;
                var idx = currList.indexOf(val);
                if(selectList[i].checked == true && idx < 0)
                {
                    currList.push(val);
                    show_li(val);
                }
                else if(selectList[i].checked == false && idx > -1)
                {   
                    currList.remove(idx);
                    hide_li(val);
                }
            }
            $('header_user_custom_div').style.display = 'none';
        }
}

function initFunc()
{
    znzIdx = new znzIdxSummary(40 * 1000, idxsumry_data);
    var stockList = [['sh000001', '上证指数'],['sz399001', '深证成指'], ['sh000300', '沪深300']];
    znzIdx.addEventListener(function(d){idxSummaryFmt(d, 'stock-index-all',stockList)});
    znzIdx.start();
    
    znzIndcBoard = new znzIdxBlock(40 * 1000, indcBoard);
    znzIndcBoard.addEventListener(function(d){indcBoardFmt(d, 'stock-led-inc-board', 6)});
    znzIndcBoard.start();
    
    var ddzConfig = {'_set':znzDDZSortSet, 'mCount':5, 'topOrder':true};
    if(znzDDZSortIn == null)
    {
        znzDDZSortIn = new znzDDZSort('capital-in', 20 * 1000, null, null, ddzConfig);
    }
    
    if(znzDDZSortOut == null)
    {
        ddzConfig['topOrder'] = false;
        znzDDZSortOut = new znzDDZSort('capital-out', 20 * 1000, null, null, ddzConfig);
    }
    
    if(znzShBigTradeMarket == null)
    {
        znzShBigTradeMarket = new znzMarketBigTradeStock(20 * 1000, 'sh');        
    }
    znzShBigTradeMarket.addEventListener(function(d){znzMarketBigTradeStockCommonSet('sh-big-trade', 'sh', d, 5)});
    
    if(znzHotStockObj == null)
    {
        znzHotStockObj = new znzHotStock(hotStocks);
        znzHotStockObj.addEventListener(znzHotStockUIFmt);
    }
    
    if(znzSzBigTradeMarket == null)
    {
        znzSzBigTradeMarket = new znzMarketBigTradeStock(20 * 1000, 'sz');        
    }
    znzSzBigTradeMarket.addEventListener(function(d){znzMarketBigTradeStockCommonSet('sz-big-trade', 'sz', d, 5)});
      
    header_initEvent();
}

if(typeof znz_init_funcs == 'undefined' || !znz_init_funcs)
{
    znz_init_funcs = [];
}
znz_init_funcs.push(initFunc);

function initTree(){
	var _dom = YAHOO.util.Dom;
	var _event = YAHOO.util.Event;
	function treeInit() { 
		var tree = new YAHOO.widget.TreeView("tree-menu-box", naviNode);
		tree.render();
		tree.subscribe("collapse", treeClick);
		tree.subscribe("expand", treeClick);
		tree.subscribe("clickEvent", treeClickLabel);
	}
	_event.onContentReady('tree-menu-box', treeInit);
}

var divHeight = 300;
var boardstockInterval = 15 * 1000;
var sortInstance = null;

// 三级目录列表
// 每个二级目录有不同的数据源，设置函数
// 每个三级目录有一组显示数据源，每个原子都其代码和列表
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
var headerArray = ["index", "industry", "concept", "region"];
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 = header_data.substring(0, header_data.length - 1).parseJSON();
    if(tmpHeaderData){
        var curPosi = [];
        var i;
        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 == znzNewSort.BOARDSTOCKTYPE)
    {
        var dataUrl = "http://" + rdmDataDomainNameGet() + "/test/board.py/boardStocks.znzDo?cmd=" + [stocktype, "desc", 0, 1, "ratio", Math.random()].join("|");
        var args = {
            method : "get",
            onComplete : function(jsonStr){    
                if(jsonStr == "[-1]")
                    callBack("");
                var reObj = jsonStr.parseJSON();            
                changeType(parentID, childID, stocktype, decodeURIComponent(reObj[1]));
            }.bind(this)
        }   
        var myAjaj = new Ajaj(dataUrl, args);
    }
    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, 235, 410, 498, 592, 678, 560, 792];
// get submenu data through ajaj
function menuDataGet(parentID, childID)
{
    //get submenu data
    var args = {
        method : "get",
        onComplete : function(re){
            var ret = re.parseJSON();
            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 == znzNewSort.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 == znzNewSort.CLASSSTOCKTYPE || parentID == znzNewSort.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 pid = znzNewSort.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 > 30)
        showRowNum = 30;
    
    divHeight = showRowNum * 25;
    gSort = sort || gSort || null;  //gSort 全局变量定义在newsort.php
    gOrder = order || gOrder || null; //gOrder 全局变量定义在newsort.php
    
    var p = {'divHeight':divHeight, 'metric':gSort, 
        'order':gOrder, 'showRowNum':showRowNum,
        'interval':boardstockInterval, 'start':false,
        'preData':newSortPreData, 'jmpUrl':sortJumpUrl, 
        'divId':"newsort-body", 'preData':gNewSortPreData,
        'width':747, 'colNum':11};
   
    sortInstance = new znzNewSort(null, p);
    if(typeof cw != 'undefined')
        sortInstance.fixtable.dwidth = cw - 35;
    
    parseParams(market, mtype, boardNo);
    defaultShow(pid, cid, sortStockType);    
    if (gSort && ((gSort == "turnover") || (gSort == "liangbi") || (gSort == "ratio") || (gSort == "ratio5") ||
         (gSort == "weibi") ||(gSort == "zhenfu")))
    {
        window.setTimeout(function(){sortInstance.fixtable.move(7,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;
        var clsType = znzNewSort.CLASSTYPE;     
        //81
        for(i = 0; i < subheader_data[clsType].length; i ++)
        {
            for(j = 0; j < subheader_data[clsType][i].length; j ++)
            {
                if(subheader_data[clsType][i][j][0] == (gMarket + "|" + gType))
                {
                    havaFind = true;
                    sortStockType = subheader_data[clsType][i][j][0];
                    pid = clsType;
                    cid = i;
                    break;
                }
            }
            if(havaFind)
                break;
        }
        
        //61
        clsType = znzNewSort.CLASSSTOCKTYPE;
        for(i = 0; i < subheader_data[clsType].length; i ++)
        {
            for(j = 0; j < subheader_data[clsType][i].length; j ++)
            {                
                if(subheader_data[clsType][i][j][0] == (gMarket + "|" + gType))
                {
                    havaFind = true;
                    sortStockType = subheader_data[clsType][i][j][0];
                    pid = clsType;
                    cid = i;
                    break;
                }
            }            
            if(havaFind)
                break;
        }       
    }
    
    //板块
    if(gBoardNo != "")
    {
        pid = znzNewSort.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 > 30)
        showRowNum = 30;    

    newHeight = showRowNum * 25;    
    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();
        }               
    }
}

function start()
{
    HeaderInit('newsort-headerul');
    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);
    }
    
    init();
    initTree();
    znz_init_func_call();
}