MxChart.Preview = {};

MxChart.Preview.Tab= Class.create()

MxChart.Preview.Tab.prototype = {
    
    initialize: function(holder, options) {
    
        this.holder=$(holder);
        this.setOptions(options);
        if(!this.options.selectedSpan)
            this.options.selectedSpan='-1d';
        this.selectedSpan=this.options.selectedSpan;
        this._buildSelector();
        
        if(this.options.shield && !(this.options.shield instanceof Mx.Shield)){
            this.shield=new MxTable.Shield(this.options.shield);
            this.shield.setOptions({parent: $(this.holder)});
        }
        else if(this.options.shield instanceof Mx.Shield){
            this.shield=this.options.shield;
            this.shield.setOptions({parent: $(this).holder});
        }
    },
    
    setOptions: function(options) {
        this.options = $H({
            shield:             $('chart-shield'),
            selectFrom:         ['-1d', '-7d','-1M','-1y', 'all'],
            selectedSpan:       '-1d',
            firstSelectorClass: '', 
            lastSelectorClass:  '', 
            selectorClass:      'chart-preview-selector',
            listSelectorClass:  '',
            leftElementClass:   'no-left-border',
            selectedClass:      'selected',
            refreshTime:        0, /*no refresh*/
            timeLineHelper:     '/issrpc/marketdata/chart/timeline',
            //chartHelper:        '/marketdata/analysis/chart_preview',
            chartHelper:        '/cs_compat',
            warnConsole:        undefined,
            parameters:         {secid: 'MICEXINDEXCF', boardid: 'SNDX'},
            issParameters:      {market: 'index', trade_engine: 'stock'},
            candleInterval:     undefined,
            chartTemplate:      'micexpreview',
            onClick:                undefined
        }).merge(this.options);
        this.options.merge(options);
    },
    
    hide: function() { $(this.holder).hide();},
    show: function() { $(this.holder).show();},
            
    _buildSelector: function(){
        if(this.options.selectFrom && this.options.selectFrom.size()>0){
            this.selector=Builder.node('div', {className: this.options.selectorClass},[
                    this.list=Builder.node('ul', {className: this.options.listSelectorClass, id: $(this.holder).id+'-list'})
            ]);
            this._buildList();
            $(this.holder).appendChild(this.selector);
        }
    },
    
    _buildList: function(){
        var list=$A(this.options.selectFrom);
        list.each(function(e,index){
            var title=new Date.getTimeSpanById(e).short_title;//.toLowerCase();
            var li=Builder.node('li', {className: (index==0?this.options.leftElementClass:'')},
                Builder.node('a',{href:'#', name: e}, title)
            );
            
            this.list.appendChild(li);
            
            if(e==this.selectedSpan)
                $(li).addClassName(this.options.selectedClass);
            if(index==list.length-1)
                $(li).addClassName(this.options.lastSelectorClass);
            if(index==0)
                $(li).addClassName(this.options.firstSelectorClass);
        }.bind(this));
        
        if(!this.links){
            this.links = $(this.list).getElementsBySelector('a[name]');
            this._observe();
        }
    },
    
    _observe: function(){
        this.onSelectListener = this.onSelectListener || this.onSelect.bindAsEventListener(this);
        $A(this.links).invoke('observe', 'click', this.onSelectListener);
    },
    
    onSelect: function(e){
        Event.stop(e);
        
        var sel=Event.element(e);
        var sli=sel.up();
        if(sli.hasClassName(this.options.selectedClass))
            return;
        
        this.lock();
        
        $(this.links).each(function(a){
            var li=a.up();
            if(li.hasClassName(this.options.selectedClass))
                li.removeClassName(this.options.selectedClass);
            if(a.name==sel.name)
                li.addClassName(this.options.selectedClass);
        }.bind(this));
        
        this.onChange(sel.name);
    },
        
    onChange: function(span){
        this.selectedSpan=span;
        var days=new Number(new Date().addTimeSpanString(this.selectedSpan).daysTillNow());  if (days==1) days+=1;
        this._getTimeLine(days.valueOf());
    },
    
    _viewWarnConsole: function(){
        if(this.options.warnConsole){
            $(this.options.warnConsole).show();
            if(this.selector) $(this.selector).hide();
            if(this.chart_image) $(this.chart_image).hide();
        }
        this.unlock();
    },
    
    _spanToInterval: $H({'-1d': 10, '-7d': 60, '-3M': 24, '-1M': 24, '-1y':7, '-12M': 7, 'all': 31}),
    
    _getTimeLine: function(days){
    
        this._interval= this._spanToInterval[this.selectedSpan] || this.options.candleInterval || 10;
        
        if(this.options.timeLineHelper){
            new Ajax.Request(this.options.timeLineHelper+'/result.json', {
                method: 'get',
                parameters: $H({
                        candle_interval: this._interval,
                        secid: this.options.parameters.secid, 
                        boardid: this.options.parameters.boardid, 
                        market: this.options.issParameters.market, 
                        trade_engine: this.options.issParameters.trade_engine,
                        days: days
                    }),
                onSuccess: function(transport, json){
                            json=transport.responseText.evalJSON(false);
                            if(!json){
                                this._viewWarnConsole();
                                return;
                            }
                            var data=$H(json[1]);
                            if(!data['end'] || !data['start']){
                                this._viewWarnConsole();
                                this.hide();
                                return;
                            }
                            this.timeLine=data['start']+'-'+data['end'];
                            this.show();
                            this._getAndDrawChart();
                        }.bind(this),
                onFailure: function(transport, json){
                        return;
                }
            });
        }
        else{
            this.timeLine='';
            this._getAndDrawChart();
        }
    },
    
    
    _idle_time: function(idle){ //sec
        var t=(new Date()).getTime();
        return (t-t%(idle*1000));
    },
    
    _getAndDrawChart: function(){
        try{
            var parameters=$H(new Hash(this.options.parameters));
            
            parameters.merge({
                market: this.options.issParameters.market,
                trade_engine: this.options.issParameters.trade_engine,
                template: this.options.chartTemplate, 
                timeline: this.timeLine, 
                interval: this._interval,
                period:   this.selectedSpan, 
                ltime:    this._idle_time(60),
                lang:     LC_LANG
            });
            
            var src   = this.options.chartHelper+'?'+parameters.toQueryString();
            
            if(!this.chart_image){
            
                this.chart_image=Builder.node('img', {src: src, name: ($(this.holder).id+'chart-image')});
                
                $(this.holder).appendChild(this.chart_image);
                
                Event.observe($(this.chart_image), 'load', function(event){
                    Event.stop(event);
                    this.chart_image.show();
                    this.unlock();
                }.bind(this));
                
                Event.observe($(this.chart_image), 'click', function(event){
                    Event.stop(event);
                    this.onClick();
                }.bind(this));
            }
            
            $(this.chart_image).src=src;
            $(this.chart_image).setStyle({cursor: 'pointer'});
            
            if(!$(this.holder).visible())
                $(this.holder).show();
                
            if(this.selector) $(this.selector).show();
            $(this.holder).show();
            
        }catch(e){
        }
    },
        
    run: function(){
        if(!this.timeLine)
            this.reload();
         if(this.options.refreshTime){
            if(this.image_updater) this.image_updater.stop();
                this.image_updater=new PeriodicalExecuter( function(pe){
                        this.onChange(this.selectedSpan);
                    }.bind(this),
                    this.options.refreshTime
                );
         }
    },
    
    stop: function(){
        if(this.image_updater) this.image_updater.stop();
    },
    
    reload: function(){
        this.lock();
       	if (!this.selectedSpan)
       		this.selectedSpan = "-1d";
       	this.onChange(this.selectedSpan);
    },
    
    _defaultClick: function(){
        var p=$H({
            secid: $(this.options).parameters.secid,
            boardid: $(this.options).parameters.boardid,
            linetype: 'candles',
            period: '-1d'
        })
        window.location='/marketdata/analysis?'+p.toQueryString();
    },
    
    onClick: function(){
        (this.options.onClick || this._defaultClick).bind(this)();
    },
    
    lock: function(){
        if(this.shield)  this.shield.show();
    },
    
    unlock: function(){
        if(this.shield)  this.shield.hide();
    }
}