MxTable.SpreadNChart=Class.create();
MxTable.SpreadNChart.prototype={
    initialize: function(options){
        this.meta_cache={};
        this.setOptions(options);
    },

    setOptions: function(options) {
        this.options = $H({
            metaFieldList:[
                            { id: "SHORTNAME", type: 'string'} ,
                            { id: "LAST", trend_by: "LASTCHANGEPRCNT", type: 'number'} ,
                            { id: "LASTCHANGEPRCNT", has_percent: 'true' , is_signed: 'true', trend_by: "LASTCHANGEPRCNT", type: 'number'},
                            { id: "UPDATETIME", type: 'time'}
                          ],
            selectFrom:  ['-1d', '-7d','-1M','-12M', 'all'],
            metaHelper:   undefined,
            preloadMeta:  undefined,
            metaName:     'small',
            helper:       undefined,
            holder:       $('holder'),
            header:       $('header'),
            footer:       $('foter'),
            table:        $('table'),
            shield:       $('shield'),
            chartHolder:  $('chart-holder'),
            chartShield:  $('chart-shield'),
            issParameters:{},
            parameters:   {},
            selectedRow:  {},
            selectFirstRow: true,
            limit         :        5,
            selectorClass:         '',
            listSelectorClass:     'period-selector float-container',
            lastSelectorClass:     'last',
            selectedSelectorClass: 'selected',
            firstSelectorClass:    '',
            leftElementClass:      '',
            timeLineHelper:        '/issrpc/marketdata/chart/timeline2',
            //chartHelper:           '/marketdata/analysis/chart_preview',
            chartHelper:           '/cs_compat',
            onClickChart:          undefined,
            refreshTime:           0,
            spread_options:	$H(),
            
            passportMarker:	'X-MicexPassport-Marker',
            passportInfoBar:	undefined

        }).merge(this.options);
        this.options.merge(options);
    },

    _processMeta: function(json,meta){
        var fields=json[this.options.metaName+'_field_list']||json.preview_field_list;
        var _metas=$A(this.options.metaFieldList||[]);
        fields.each(function(e){
            if(_metas.indexOf(e['id'])>=0){
                meta.push(e);
            }else if(this.options.metaFieldList==undefined){
                meta.push(e);
            }
        }.bind(this));
        this.meta_cache[this.options.metaHelper]=meta;
        
    },

    run: function(){
        var meta= this.meta_cache[this.options.metaHelper] || $A(new Array());
        if(meta.size()==0)
            if(!this.options.preloadMeta)
                new Ajax.Request(this.options.metaHelper, {
                    method: 'get',
                    onComplete: function(transport,json){
                            if(!json){
                                json = transport.responseText.evalJSON(false);
                            }
                            this._processMeta(json,meta);
                            this._createTable(meta);
                    }.bind(this)
                });
            else{
                this._processMeta(this.options.preloadMeta,meta);
                this.options.preloadMeta=undefined;
                this._createTable(meta);
            }
        else
            this._createTable(meta);
    },

    _createTable: function(meta){
        var options=   $H({

            fieldsMeta:    meta,
            onClickField: 'SHORTNAME',

            //shield:        new MxTable.Shield($($(this.options).shield), { opacity: 1.0, duration: 0.2}),
            shield:        $(this.options).shield,

            refreshTime:   this.options.refreshTime,
            limit:         this.options.limit,
            url:           this.options.helper+'/result.json',
            downloadUrl:   undefined,
            countUrl:      undefined,
            preloadData:   this.options.preloadData,
            preloadCount:  this.options.preloadCount,
            issParameters: this.options.issParameters,
            parameters:    this.options.parameters,
            responseWarn:  this.options.responseWarn,

            noLinked:          '',
            selectedRow:       'selected',
            firstRow:          'first',
            onClickField:      'SHORTNAME',
            upCell:            'delta up',
            downCell:          'delta down',
            arrowUpCell:       'amount up',
            arrowDownCell:     'amount down',
            stayCell:          'delta',
            arrowStayCell:     'amount',
            dateColumn:        'time',

            hideThead:     true,
            
//            passportMarker:	this.options.passportMarker,
//            passportInfoBar:	this.options.passportInfoBar,

            beforeSelect: function(){
                this.lock();
                return true;
            },

            onOrder: function(){
                this.order_proccessing=true;
                return true;
            },

            onPage: function(){
                this.order_proccessing=true;
                return true;
            },

            afterSelect: function(){
                if(this.order_proccessing)
                    this.unlock();
                this.order_proccessing=false;
                return true;
            },

            onSelect: function(){
                try{
                    if($(this.table).selected_row) {
                        if(!$(this.table).order_proccessing){
// ttt[
	try{
		var element = this.table.table_body.getElementsBySelector('tr[key="'+this.table._selectedRowID()+'"]')[0]
		if(element.readAttribute('market')){
			this.table.options.issParameters.market = element.readAttribute('market');
		}
	} catch(e){alert(e);}
// ]ttt
                            this._viewIndexChart();
                        }
                    }
                    else{
                        $(this.table).unlock();
                    }
                    $(this.table).unlock();
                }catch(e){alert('onSelect: '+e);}
                return true;
            }.bind(this),

            onClick: function(){
                this._popupSelector();
                return false;
            }.bind(this),

            onLoad: function(){
                if(this.table.isEmpty)
                    if($(this.chart)) $(this.chart).hide();
                return true;
            }.bind(this)
        });
        options.merge(this.options.spread_options);

        this.options.merge(options);
                
        this.table=new MxTable.Spread(
            $(this.options.holder),
            $(this.options.header),
            $(this.options.table),
            $(this.options.footer),
            this.options
         );

        if(this.options.selectFirstRow){
            this.table.selectFirstRow();
        }
        else if(this.options.selectedRow) this.table.selectRow(this.options.selectedRow.boardid,this.options.selectedRow.secid);

        this.table.run();
    },

    _viewIndexChart: function(){
        if(!this.options.chartHolder) return;
        if(!this.chart){
            try{
            this.chart=new MxChart.Preview.Tab($(this.options.chartHolder),{
                shield:           $(this.options.chartShield),
                parameters:        {secid: this.table.selected_row.secid, boardid: this.table.selected_row.boardid},
                issParameters:      this.options.issParameters,
                selectedSpan:       this.options.selectedSpan,
                candleInterval:     this.options.candleInterval,
                selectFrom:         this.options.selectFrom,
                warnConsole:        this.options.chartWarnConsole,
                selectorClass:      this.options.selectorClass,
                listSelectorClass:  this.options.listSelectorClass,
                leftElementClass:   this.options.leftElementClass,
                selectedClass:      this.options.selectedSelectorClass,
                firstSelectorClass: this.options.firstSelectorClass,
                lastSelectorClass:  this.options.lastSelectorClass,
                timeLineHelper:     this.options.timeLineHelper,
                chartHelper:        this.options.chartHelper,
                onClick:            this.options.onClickChart
            });

            if(this.options.chartTemplate)
                this.chart.setOptions({chartTemplate: this.options.chartTemplate});
            if(this.options.candleInterval)
                this.chart.setOptions({candleInterval: this.options.candleInterval});

            this.chart.run();

            }catch(e){alert('_viewIndexChart:' + e);}
        }
        else{
            this.chart.setOptions({
                parameters:   {secid: this.table.selected_row.secid, boardid: this.table.selected_row.boardid}
            });
            this.chart.reload();
        }
    },

    _popupSelector: function(){
        new Mx.PopupSelector.create($(this.table), $($(this.options).issParameters).trade_engine, $($(this.options).issParameters).market);
    }
}

