Mx.Popup = Class.create();
Mx.Popup.prototype = {
    
    initialize: function(options){
        this.body=$(options.parent||window.document.body);
        this.setOptions(options);
        this._build();
        this._observeBodyShield();
        this._observeClose();
    },
    
    setOptions: function(options) {
        this.options = $H({
            id:                'mx_popup',
            title:             '',
            subTitle:          '', 
            className:         '',
            linksClassName:    '',
            outsetClassName:   '',
            disabledClassName: 'disabled',
            shieldOpacity:      0.5,
            shieldBackground:  '#fff',
            value:             'X'
            
                           
        }).merge(this.options);
        this.options.merge(options);
        
        this.options.title=this.options.title.unescapeHTML();
         this.options.subTitle=this.options.subTitle.unescapeHTML();
    },
    
    _build: function() {
        this.body_shield=Builder.node('div', {
                    id: this.options.id+'-shield'
                } 
        );
        
        $(window.document.body).appendChild($(this.body_shield));
        
        $(this.body_shield).setStyle({background: this.options.shieldBackground, opacity: this.options.shieldOpacity, border: 'solid 0px', width: '0px', height: '0px', 'z-index': 100});
        
        var title=this.options.title;
        
        this.popup_selector=Builder.node('div',{
                id: this.options.id,
                className: this.options.className
            },
            [
                Builder.node('h1', { title: this.options.title},
                    [
                    this.title=Builder.node('strong', {id: this.options.id+'-title'},[
                            title, 
                            this.options.subTitle?' | ':'',
                            this.subTitle=Builder.node('span', {id: this.options.id+'-subtitle'}, this.options.subTitle)
                        ]
                    ),
                    this.close=Builder.node('img',{id: this.options.id+'-close', 'src': '/images/close.gif'}),
                    ]
                ),
                this.data = Builder.node('div', {className: this.options.linksClassName}),
                
                this.outset=Builder.node('div', {className: this.options.outsetClassName, id: this.options.id+'-outset'})
            ]
        );
        
        $(this.popup_selector).setStyle({'z-index': 101, display: 'none', 'background': '#fff'});
        this.data.update('X');
        $(this.body).appendChild(this.popup_selector);
        
        
    },
               
    show: function(link_element){
            
        $(this.popup_selector).show();
            
    },
            
    hide: function(){
        $(this.body_shield).setStyle({width: '0px', height: '0px'});
        $(this.body_shield).hide();
        $(this.popup_selector).hide();
    },
            
    _observeBodyShield: function(){
        this.onClickBodyShieldListener = this.onClickBodyShieldListener || this.onClose.bindAsEventListener(this);
        Event.observe($(this.body_shield),'click', this.onClickBodyShieldListener);
    },
    
    _observeClose: function(){
        this.onClickCloseListener = this.onClickCloseListener || this.onClose.bindAsEventListener(this);
        Event.observe($(this.close),'click', this.onClickCloseListener);
    },
            
    onClose: function(){
        this.hide();
    }    
    
};

Mx.PopupSelector=Class.create();
Mx.PopupSelector.prototype={

    initialize: function(options){
        this.body=$(options.parent||window.document.body);
        this.setOptions(options);
        this._build();
        this._observeBodyShield();
        this._observeClose();
    },
    
    setOptions: function(options) {
        this.options = $H({
            id:                'new-popup-selector',
            title:             'Инструмент',
            subTitle:          '', 
            className:         'popup-selector',
            linksClassName:    'links',
            outsetClassName:   'outset',
            leftClassName:     'left',
            rightClassName:    'right',
            disabledClassName: 'disabled',
            shieldOpacity:      0.5,
            shieldBackground:  '#fff',
            
            leftList: [
                            {id: 'daily',    title: 'Ход торгов', hidden: false, disabled: false, url: '/marketdata/quotes', parameters: {}},
                            {id: 'history',  title: 'Результаты торгов', hidden: false, disabled: false, url: '/marketdata/quotes', parameters: {}},
                            {id: 'analisys', title: 'Технический анализ', hidden: false, disabled: false, url: '/marketdata/quotes', parameters: {}}
                       ],
            rightList: [
                            {id: 'passport', title: 'Паспорт ценной бумаги', hidden: false, disabled: false, url: '/marketdata/info', parameters: {}},
                            {id: 'emmitent', title: 'Эммитент', hidden: false, disabled: false, url: '/marketdata/info', parameters: {}},
                            {id: 'emmitent-news', title: 'Новости эммитента', hidden: false, disabled: false, url: '/marketdata/info', parameters: {}}
                       ]
            
        }).merge(this.options);
        this.options.merge(options);
        /* dosn't work in Chrome/IE*/
        this.options.title=this.options.title.unescapeHTML().gsub('&#x0026;','&');
         this.options.subTitle=this.options.subTitle.unescapeHTML().gsub('&#x0026;','&');
    },
    
    
    _buildList: function(list, ol){
        var count=0;
        $A(ol).each(function(e){
            if(!e.hidden){
                var a; count++;
                var li;
                var id=this.options.id+'-'+e.id;
                $(list).appendChild(li=Builder.node(
                    'li',
                    a=Builder.node('a', {id: id, name: id, href: e.url+($H(e.parameters).size()>0?'?':'')+$H(e.parameters).toQueryString()}, e.title)
                ));
                if(e.disabled){
                    a.className=this.options.disabledClassName;
                    a.href='#'+id;
                }
            }
        }.bind(this));
        return count;
    },
    
    _build: function() {
        this.body_shield=Builder.node('div', {
                    id: this.options.id+'-shield'
                } 
        );
        
        $(window.document.body).appendChild($(this.body_shield));
        
        $(this.body_shield).setStyle({background: this.options.shieldBackground, opacity: this.options.shieldOpacity, border: 'solid 0px', width: '0px', height: '0px', 'z-index': 100});
        
        
        var title=''; 
        var sl=this.options.subTitle?this.options.subTitle.length:0;
        if(this.options.title.length+sl>32) {title+=this.options.title.substr(0,10)+'...'; title+=this.options.title.substr(this.options.title.length-10,10);}
        else title=this.options.title;
            
        this.popup_selector=Builder.node('div',{
                id: this.options.id,
                className: this.options.className
            },
            [
                Builder.node('h1', { title: this.options.title},
                    [
                    this.title=Builder.node('strong', {id: this.options.id+'-title'},[
                            title, 
                            this.options.subTitle?' | ':'',
                            this.subTitle=Builder.node('span', {id: this.options.id+'-subtitle'}, this.options.subTitle)
                            /*this.close=Builder.node('a',{id: this.options.id+'-close', 'href': '#'}, (LC_LANG=='ru'?'x':'x'))*/
                        ]
                    ),
                    this.close=Builder.node('img',{id: this.options.id+'-close', 'src': '/images/close.gif'}),
                    ]
                ),
                this.linksBox=Builder.node('div', {className: this.options.linksClassName}, [
                    this.leftList=Builder.node('ul', {className: this.options.leftClassName, id: this.options.id+'-leftlist'}),
                    this.rightList=Builder.node('ul', {className: this.options.rightClassName, id: this.options.id+'-rightlist'})
                ]),
                this.outset=Builder.node('div', {className: this.options.outsetClassName, id: this.options.id+'-outset'})
            ]
        );
        
        $(this.popup_selector).setStyle({'z-index': 101, display: 'none', 'background': '#f00'});
        
        $(this.body).appendChild(this.popup_selector);
        
        this._buildList($(this.leftList), this.options.leftList);
        this._buildList($(this.rightList), this.options.rightList);
    },
    
    _lock_body: function(){
        Position.absolutize($(this.body_shield));
        Position.overlay($(this.body_shield));
        $(this.body_shield).show();
    },
            
    show: function(link_element){
            
        if(!link_element) return ;
            
        this._lock_body();
        $(this.popup_selector).setStyle({opacity:0.0, left:0, top:0, margin:0, padding:0});
        $(this.popup_selector).show();
        
        // fix||IE linksBox
        var h=$(this.leftList).getHeight();
        if($(this.rightList).getHeight()>h)
            h=$(this.rightList).getHeight();
            
        var w=$(this.leftList).getWidth()+$(this.rightList).getWidth();

        var titleWidth = $(this.title).getWidth() + 40;
        if (w < titleWidth) w = titleWidth;
        
        $(this.linksBox).setStyle({height: (h+1)+'px', width: w+'px'});
        
        h=$(this.popup_selector).getHeight();
        Position.absolutize(this.popup_selector);
        var outset_left=parseFloat($(this.outset).getStyle('left')  || 0);
        var link_w=$(link_element).getWidth();
        var offset_link=(link_w>=(outset_left+link_w/2)?0:(outset_left-link_w/2)*(-1));
            
        Position.clone($(link_element), $(this.popup_selector), {setWidth: false, setHeight: false, offsetLeft:offset_link , offsetTop: h*(-1)-2-link_element.getHeight()/2}); 
        
        $(this.popup_selector).show();
        $(this.popup_selector).setStyle({opacity:1.0}); 
    },
            
    hide: function(){
        $(this.body_shield).setStyle({width: '0px', height: '0px'});
        $(this.body_shield).hide();
        $(this.popup_selector).hide();
    },
            
    _observeBodyShield: function(){
        this.onClickBodyShieldListener = this.onClickBodyShieldListener || this.onClose.bindAsEventListener(this);
        Event.observe($(this.body_shield),'click', this.onClickBodyShieldListener);
    },
    
    _observeClose: function(){
        this.onClickCloseListener = this.onClickCloseListener || this.onClose.bindAsEventListener(this);
        Event.observe($(this.close),'click', this.onClickCloseListener);
    },
            
    onClose: function(){
        this.hide();
    }
            
};
            
Mx.PopupSelector.create = function (table, trade_engine, market){
    var parameters={secid: table.selected_row.secid, boardid: table.selected_row.boardid, trade_engine: trade_engine, market: market};
    var popup_selector=new Mx.PopupSelector({
        shieldOpacity: 0.0, 
        title:    table.selected_row.title, 
        subTitle: table.selected_row.secid,
        leftList: [
                    {id: 'daily',   title: [['Ход торгов'],['Market Data']][LC_Index], url: '/marketdata/quotes', parameters: $H(new Hash(parameters)).merge({data_type: 'daily'})},
                    {id: 'history', title: [['Результаты торгов'],['Statistics      ']][LC_Index], url: '/marketdata/quotes', parameters: $H(new Hash(parameters)).merge({data_type: 'history'})}
                ],
        rightList:[
                    {id: 'card',   title: [['Описание инструмента'],['Description']][LC_Index], url: '/marketdata/quotes', parameters: $H(new Hash(parameters)).merge({type_of_info: 'instrument-info-passport'})},
                    {id: 'analisys', title: [['Технический анализ'],['Technical Analysis']][LC_Index], url: '/marketdata/analysis', 
                        parameters: $(new Hash(parameters)).merge({linetype:'candle', period:'-1M'})}
                ]
    });
    
    popup_selector.show($(table.selected_link));
};
    

MxCalendar = Class.create();
MxCalendar.prototype = {

	added: false,
	visible: false,

	monthTitles: [[
		"Январь",
		"Февраль",
		"Март",
		"Апрель",
		"Май",
		"Июнь",
		"Июль",
		"Август",
		"Сентябрь",
		"Октябрь",
		"Ноябрь",
		"Декабрь"
	],[
		"January",
		"February",
		"March",
		"April",
		"May",
		"June",
		"July",
		"August",
		"September",
		"Oktober",
		"Novermber",
		"December"
        ]][LC_Index],

	show: function() {
		if (this.anchor)
			this.setPosition();
		this.element.show();
		this.element.focus();
		this.visible=true;

		this.iframe = $(Builder.node('iframe'));
		this.element.setStyle({'z-index': 200});
		this.iframe.setStyle({'z-index': 1, position: 'absolute', border: 'none'});
		document.body.appendChild(this.iframe);
		Position.clone(this.element, this.iframe);

		this._window_click = this.window_click.bind (this);
		Event.observe (window, "click", this._window_click);
	},

	hide: function() {
		this.element.hide();
		this.visible=false;
		if (this._window_click) {
			Event.stopObserving (window, "click", this._window_click);
			this._window_click = undefined;
		}
		this.iframe.remove();
	},

	bindToAnchor: function(anchor) {
		this.anchor = anchor;
		this.element.hide();
		if (!this.added) {
			this.added=true;
			document.body.appendChild(this.element);
		}
	},

	setPosition: function() {
		var style=$H();
		style["left"] = Position.cumulativeOffset(this.anchor)[0]+"px";
		style["top"] = (Position.cumulativeOffset(this.anchor)[1]+this.anchor.getHeight())+"px";
		this.element.setStyle(style);
	},

	initialize: function() {
		this.initDefault();
		this.element = Element.extend(document.createElement("table"));
		this.element.addClassName("calendar2");

		this.build();
	},

	initDefault: function() {
		var date = new Date();
		this.year = date.getYear();
		if (this.year<1900) this.year+=1900;
		this.month = date.getMonth();
	},

	rebuild: function() {
		this.destroy();
		this.build();
	},

	destroy: function() {
		this.element.immediateDescendants().each (function(item) {item.remove();});
	},

	buildHeader: function() {
		var thead = Element.extend(document.createElement("thead"));
		this.element.appendChild(thead);


		var head_tr = thead.insertRow(thead.rows.length);

		var td = Element.extend(document.createElement("td"));
		var a = Element.extend(document.createElement("a"));
		a.update("‹‹");
		a.href="#";
		td.appendChild(a);
		td.addClassName("navbutton");
		td.setStyle({cursor: "pointer"});
		head_tr.appendChild(td);
		Event.observe(td,"click", function(e) {
			Event.stop(e);
			this.year--;
			this.rebuild();
		}.bind(this));

		var td = Element.extend(document.createElement("td"));
		var a = Element.extend(document.createElement("a"));
		a.update("‹");
		a.href="#";
		td.appendChild(a);
		td.addClassName("navbutton");
		td.setStyle({cursor: "pointer"});
		head_tr.appendChild(td);
		Event.observe(td,"click", function(e) {
			Event.stop(e);
			this.month--;
			if (this.month<0) {
				this.month=11;
				this.year--;
			}
			this.rebuild();
		}.bind(this));

		var td = Element.extend(document.createElement("td"));
		td.update(this.monthTitles[this.month]+" "+this.year);
		head_tr.appendChild(td);

		var td = Element.extend(document.createElement("td"));
		var a = Element.extend(document.createElement("a"));
		td.appendChild(a);
		td.addClassName("navbutton");
		a.href="#";
		a.update("›");
		td.setStyle({cursor: "pointer"});
		head_tr.appendChild(td);
		Event.observe(td,"click", function(e) {
			Event.stop(e);
			this.month++;
			if (this.month>11) {
				this.month=0;
				this.year++;
			}
			this.rebuild();
		}.bind(this));

		var td = Element.extend(document.createElement("td"));
		var a = Element.extend(document.createElement("a"));
		td.appendChild(a);
		td.addClassName("navbutton");
		a.href="#";
		a.update("››");
		td.setStyle({cursor: "pointer"});
		head_tr.appendChild(td);
		Event.observe(td,"click", function(e) {
			Event.stop(e);
			this.year++;
			this.rebuild();
		}.bind(this));
	},

	buildBody: function() {
		var tbody = Element.extend(document.createElement("tbody"));
		this.element.appendChild(tbody);
		var h_tr = Element.extend(document.createElement("tr"));
		tbody.appendChild(h_tr);
		var h_td = Element.extend(document.createElement("td"));
		h_td.colSpan=5;
		h_tr.appendChild(h_td);


		var table = Element.extend(document.createElement("table"));
		h_td.appendChild(table);

		var table_header = Element.extend(document.createElement("thead"));
		table.appendChild(table_header);
		var table_header_tr = table_header.insertRow(table_header.rows.length);

		[["пн","вт","ср","чт","пт","сб","вс"],["mo","tu","we","th","fr","sa","su"]][LC_Index].each (function(item) {
			var th = Element.extend (document.createElement("th"));
			th.update(item);
			this.appendChild(th);
		}.bind(table_header_tr));



		var table_data = Element.extend(document.createElement("tbody"));
		table.appendChild(table_data);
		tr = table_data.insertRow(table_data.rows.length);


		var builderDate = new Date();
		builderDate.setYear(this.year);
		builderDate.setMonth(this.month);
		builderDate.setDate(1);

		var prependDays = builderDate.getDay()-1;
		if (prependDays<0) prependDays+=7;

		for (var i=0;i<prependDays;i++) {
			var td = Element.extend(document.createElement("td"));
			tr.appendChild(td);
			td.update("&nbsp;");
		}
		while (builderDate.getMonth() == this.month) {

			if ((builderDate.getDay()==1) && (tr.cells.length>0)) {
				tr = table_data.insertRow(table_data.rows.length);
			}

			td = Element.extend(document.createElement("td"));
			var a = Element.extend(document.createElement("a"));
			a.href="#";
			td.appendChild(a);
			td.monthDay = builderDate.getDate();
			td.setStyle({cursor: "pointer"});
			a.update (builderDate.getDate());
			tr.appendChild(td);
			Event.observe(td,"click",function(item,e) {
				Event.stop(e);
				this.date=item.monthDay;
				if (this.onSelect)
					this.onSelect();
			}.bind(this,td));
			if ((builderDate.getDay()<6) & (builderDate.getDay()>0)) {
				Event.observe(td,"mouseover", function(e) {
					this.addClassName("hover");
				}.bind(td));
				Event.observe(td,"mouseout", function(e) {
					this.removeClassName("hover");
				}.bind(td));
			}
			else {
				td.addClassName("weekend");
			}

			var today = new Date();

			if (this.selected &&
				(builderDate.getDate() == this.selected.getDate()) &&
				(builderDate.getMonth() == this.selected.getMonth()) &&
				(builderDate.getYear() == this.selected.getYear())) {

					td.addClassName("selected");

				}
			else if ( (today.getYear() == builderDate.getYear()) &&
				 (today.getMonth() == builderDate.getMonth()) &&
				 (today.getDate() == builderDate.getDate()))

				 td.addClassName("today");

			builderDate.setDate(builderDate.getDate()+1);
		}

		while (builderDate.getDay()!=1) {
			td = Element.extend(document.createElement("td"));
			td.update ("&nbsp;");
			tr.appendChild(td);
			builderDate.setDate(builderDate.getDate()+1);
		}
	},

	buildFooter: function() {
		var tfoot = Element.extend(document.createElement("tfoot"));
		this.element.appendChild(tfoot);

		var tr = Element.extend (document.createElement("tr"));
		tfoot.appendChild(tr);

		var td = Element.extend (document.createElement("td"));
		tr.appendChild(td);
		td.colSpan=5;

		var a = Element.extend (document.createElement("a"));
		td.appendChild(a);
		a.href="#";
		a.update([["Сегодня"],["Today"]][LC_Index]);

		Event.observe(a,"click",function(e) {
			Event.stop(e);
			this.selected = new Date();
			this.year = this.selected.getYear();
			if (this.year<1900) this.year+=1900;
			this.month = this.selected.getMonth();
			this.rebuild();
		}.bind(this));
	},

	build: function () {

		this.buildHeader();
		this.buildBody();
		this.buildFooter();

	},

	window_click: function(e) {
		Event.stop(e);
		this.hide();
	}

};

MxCalendar.create = function (a, textfield,element) {
	var calendar = new MxCalendar();
	a.calendar = calendar;
	calendar.textfield=textfield;
	calendar.lElement=element;

	Event.observe(a,"click",function(calendar, e) {
	    Event.stop(e);

		if (calendar.visible) {
			calendar.hide();
		}
		else {
			calendar.bindToAnchor(this);

			if (calendar.textfield.disabled) return;
			var d = Finder.Date.stringDBToDate(calendar.lElement.getValue());
			calendar.year = d.getYear();
			if (calendar.year<1900) calendar.year+=1900;
			calendar.month = d.getMonth();
			calendar.selected=d;
			calendar.rebuild();
			calendar.show();
		}
	}.bind(a,calendar));

	calendar.onSelect = function () {
		var newDate = new Date(this.year, this.month, this.date);
		this.hide();
		this.lElement.setValue(Finder.Date.dateToString(newDate));
		this.lElement.dateValue = newDate;
		this.lElement.manualSelected = true;
		this.lElement.update();
		this.lElement.manualSelected = false;
	};
}
MxChart={};
MxChart.Transport={};
MxChart.Interface={};
MxChart.Helper={};
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();
    }
}
var MxTable={
    IssUrl: '/issrpc/marketdata'
};

MxTable.Shield=Mx.Shield;

MxTable.Spread=Class.create();
MxTable.Spread.prototype = {
    default_fieldsMeta: [
        { id: "#NUM#",      title: "№",                  short_title: "№", type: 'string'} ,
        { id: "SHORTNAME",  title: "Краткое наименование", short_title: "Наименование" , is_ordered: 'true' , type: 'string'} ,
        { id: "SECID",      title: "Название инструмента", short_title: "Инструмент" ,   is_ordered: 'true' , type: 'string'} ,
        { id: "BOARDID",    title: "Режим",              short_title: "Режим" , type: 'string'} ,
        { id: "BID",        title: "Спрос",               short_title: "Спрос" , type: 'number'} ,
        { id: "OFFER",      title: "Предложение",         short_title: "Предложение" , type: 'number'} ,
        { id: "LAST",       title: "Последняя",           short_title: "Последняя" ,   trend_by: "LASTCHANGEPRCNT" ,
                            is_ordered: 'true' , type: 'number'} ,
        { id: "LASTCHANGEPRCNT",  title: "Изменение цены последней сделки к цене предыдущего дня, %",
                            short_title: "Изменение к цене пред. дня, %" ,             trend_by: "LASTCHANGEPRCNT" ,
                            is_ordered: 'true' ,
                            has_percent: 'true' ,
                            is_signed: 'true' , type: 'number'} ,
        { id: "VALTODAY",   title: "Объем за сегодня",           short_title: "Объем за сегодня" , is_ordered: 'true' , type: 'number'} ,
        { id: "UPDATETIME", title: "Время последнего обновления", short_title: "Время" ,           is_ordered: 'true' , type: 'time'}
    ],

    initialize: function(holder, header, table, footer, options) {

            this._is_digit=/^\s?(\-|\+)?[0-9]+\.?[0-9]*\s?$/;

            this.setOptions(options);

            this.holder = $(holder);

            this.holder.appendChild(Builder.node('div', {id: 'table-console'},''));

            this.header = $(header);
            this.table  = $(table);

            this.footer = $(footer);

            this.current_page=1;
            this.pages=0;

            this.sort_order_counter=0;

            this._makeTabelHeader();
            if($(this.options).shield){
                if($(this.options.shield) && !($(this.options.shield) instanceof MxTable.Shield)){
                    this.shield=new MxTable.Shield($(this.options.shield));
                    $(this.shield).setOptions({parent: $(this.holder)});
                }
                else if($(this.options.shield) instanceof MxTable.Shield){
                    this.shield=$(this.options.shield);
                    $(this.shield).setOptions({parent: $(this).holder});
                }
            }

            $(this.holder).makePositioned();

            this.lock_count=0;
            this.last_response_time = {};

            this._retriesReset();

            this.cookies = new Mx.Cookies();
    },

    hide: function(){
        Effect.Fade(this.holder, {duration: 0.2});
    },

    setOptions: function(options) {
        this.options = $H({

            shield:          $('table-shield'),

            hideThead:       false,

            pager:           $('pager'),
            pagerPrev:       $('pager-prev'),
            pagerNext:       $('pager-next'),
            pagerList:       $('pager-list'),
            verticalBar:     $('vertical-bar'),
            rowCount:        $('table-row-count'),

            downloader:      $('table-downloader'),
            maxDownloadRows: 10000,

            responseWarn:     undefined,

            linked:            '',
            selectedPage:      'selected',
            selectedBearField: 'selectedbear',
            selectedBulField:  'selectedbul',
            unselectable:      true,
            column:            '',
            row:               '',
            leftColumn:        '',
            rightColumn:       '',
            onClickColumn:     'shortname',
            rowIndexColumn:    'position',

            sortOrderAction:   'action',
            sortOrderField:    undefined,
            sortOrderDesc:     undefined,
            sortOrderOverList: undefined,
            sortOrderOverKeys: ['BOARDID','SECID'],

            noLinked:          'disabled',
            selectedRow:       'selected',
            firstRow:          'first',

            onClickField:      undefined,
            rowIndex:          ['BOARDID','SECID','TRADEDATE'],

            amountClass:       'amount',
            numberClass:       'value',
            stringClass:       '',
            timeClass:         'time',
            deltaClass:        'delta',
            upClass:           'up',
            downClass:         'down',
            stayClass:         'stay',

            fieldsMeta:    this.default_fieldsMeta,

            customHandlers: {},

            pagerLength:   10,
            limit:         10,//rows
            refreshTime:   0, //seconds
            url:           '/issrpc/marketdata/stock/shares/daily/preview/result.json',
            countUrl:      '/issrpc/marketdata/count/daily/result.json',
            downloadUrl:   '/issrpc/marketdata/stock/shares/daily/preview',
            preloadData:   undefined,
            preloadMarker: undefined,
            preloadCount:  undefined,

            retriesLimiter:  5,

            passportMarker:  'X-MicexPassport-Marker',
            passportInfoBar: undefined,

            parameters:     {collection_id: 12, board_group_id: 6},

            issParameters:  {market: 'shares', trade_engine: 'stock'},

            onOrder: function(){
                this._remakeNavigator(1);
                return true;
            },

            onSelect: function(){
                return true;
            },

            onClick: function(){
                return true;
            },

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

            afterSelect: function(){
                this.unlock();
                this.resume();
                return true;
            },

            onPage: function(){
                return true;
            },

            onLoad: function(){
                return true;
            },

            onFailureLoad: function(transport){
                return true;
            }

        }).merge(this.options);
        this.options.merge(options);
        this.sort_order_field=this.options.sortOrderField;
        this.sort_order_desc=this.options.sortOrderDesc;
        this.on_click_field=this.options.onClickField;

        if(!this.sort_order_field || !this.sort_order_desc || !this.on_click_field){
            this.options.fieldsMeta.each(function(f){
                if(f.is_default_sort) this.sort_order_field=(this.sort_order_field||f.id)||'';
                if(f.sort_order) this.sort_order_desc=(this.sort_order_desc||f.sort_order)||'';
                if(f.is_linked) this.on_click_field=(this.on_click_field||f.id)||'';
            }.bind(this));
        }

        this.on_click_fields=$A([]);
        try{
            this.on_click_field.scan(/\w+/, function(match){ this.on_click_fields.push(match[0])}.bind(this));
        }catch(e){}
        if(!this.on_click_fields) this.on_click_fields.push[''];
    },


    _startUpdater: function(){
        if(!this.periodical_updater){
            if(this.options.refreshTime>0)
                this.periodical_updater=new PeriodicalExecuter( function(pe){
                        this._loadAjaxData();
                    }.bind(this),
                    this.options.refreshTime * this._retriesMultiplier()
                );
        }
    },

    _stopUpdater: function(){
        if(this.periodical_updater){
            this.periodical_updater.stop();
            this.periodical_updater=undefined;
        }
    },

    run: function(){
            this._loadAjaxData();
            this._startUpdater();
    },

    suspend: function(){
        this._stopUpdater();
    },

    resume: function(){
        if(!this.links){
            if(this.table_body) this.links = $(this.table_body).getElementsBySelector('a[name]','td[name]');
            this._observe();
        }
        this._startUpdater();
    },

    clear: function(){
        this.suspend();
        this.current_page=1;
        $(this.table).getElementsBySelector('thead').each(function(th){
            $(th).up().removeChild(th); delete th;
        });
        this._clearTable();
        if(this.footer) $(this.footer).hide();
        if(this.options.verticalBar) this.options.verticalBar.setStyle({width: '0px', height: '0px'});
    },

    reload: function(){
        try{
            this.current_page=1;
            this.pages=0;
            this.last_response_time = {};
            this.lock_count=0;
            this.suspend();
            this.lock();
            this.current_page=1;
            this.header_columns=undefined;
            this._deleteAllPageLinks();
            this._makeTabelHeader();
            this.table_body=undefined;
            this._loadAjaxDataRowCount(true);
            this._loadAjaxData();
            this.resume();
        }catch(e){alert('reload:'+e);}
    },

    update: function(){
        this._loadAjaxData();
        this.resume();
    },

    lock: function(){
    	this.lock_count++;
        if(this.shield && this.table_body && this.lock_count>=0) this.shield.show();
    },
    unlock: function(){
        if(this.lock_count>=0) {this.lock_count--;
        if(this.shield && this.lock_count<=0) this.shield.hide();}
    },

    _observeHeader: function(){
        this.onClickHeaderListener = this.onClickHeaderListener || this.onClickHeader.bindAsEventListener(this);
        $A(this.headerLinks).invoke('observe', 'click', this.onClickHeaderListener);
    },

    _makeTabelHeader: function(){

        if(!this.header_columns){
            $(this.table).getElementsBySelector('thead').each(function(th){
                $(th).up().removeChild(th); delete th;
            });


            if(this.options.hideThead){
                this._resizeBar(true);
                return ;
            }

            $(this.table).appendChild((this.table_head=Builder.node('thead', (this.header_columns = Builder.node('tr')))));

            $(this.options.fieldsMeta).each(function(c,ci) {
                var order_class='';

                if (c.id==this.sort_order_field){
                    if(this.sort_order_desc=='desc')
                        order_class=this.options.selectedBulField;
                    else
                        order_class=this.options.selectedBearField;
                }

                var th=Builder.node('th',{'title': c['title']||''});

                $(th).addClassName(order_class);

                if(c.id=='#NUM#')
                    $(th).addClassName(this.options.rowIndexColumn);

                else //if(c.id==this.on_click_field)
                    if(this.on_click_fields.include(c.id))
                    $(th).addClassName(this.options.onClickColumn);

                else if(c.type=='time')
                    $(th).addClassName(this.options.timeClass)
                else if(c.type=='string')
                    $(th).addClassName(this.options.stringClass)
                else if(c.type=='number')
                    $(th).addClassName(this.options.numberClass)
                else
                    $(th).addClassName(this.options.numberClass);

		if (c.customClass)
		    $(th).addClassName(c.customClass);

                if(ci==0)
                    $(th).addClassName(this.options.leftColumn);
                else if(ci==($A(this.options.fieldsMeta).length-1))
                    $(th).addClassName(this.options.rightColumn);

                if(c['is_ordered']){
                    a=Builder.node('a',
                        {'href':  '#',
                        'name':  'order_field',
                        'id':    $(this.table).id+'-field-order-by-'+c['id']
                        },
                        c['short_title']||''
                    );
                    $(a).addClassName($(this.options).sortOrderAction);
                    $(th).appendChild(a);
                }
                else{
                    $(th).innerHTML=c['short_title']||'';
                }
                this.header_columns.appendChild($(th));

            }.bind(this));

            this.headerLinks = $(this.table_head).getElementsBySelector('a[name]');
            this._observeHeader();
        }
        else{
            $(this.header_columns).getElementsBySelector('th').each(function(th) {
                var a=th.down();
                th.removeClassName(this.options.selectedBulField);
                th.removeClassName(this.options.selectedBearField);
                if(a && a.id==$(this.table).id+'-field-order-by-'+this.sort_order_field){
                    if(this.sort_order_desc=='desc')
                        th.addClassName(this.options.selectedBulField);
                    else
                        th.addClassName(this.options.selectedBearField);
                }
            }.bind(this));
        }
        this._resizeBar(true);
    },

    setUrl: function(helper){
        this.options['url']=helper;
    },

    setParameters: function(parameters){
        this.options['parameters']=parameters;
    },

    _observe: function() {
        this.onClickListener = this.onClickListener || this.onClick.bindAsEventListener(this);
        $A(this.links).invoke('observe', 'click', this.onClickListener);
    },

    _stopObserve: function() {
        $A(this.links).invoke('stopObserving', 'click', this.onClickListener);
        delete this.links; this.links=undefined;
    },


    _toSiteString: function (cell,prec){
        if (this._is_digit.test(new String(cell))){
            return new Number(cell).toSiteString(prec);
        }
        return cell;
    },

    _linkID: function(obj){
        return $A(this.options.rowIndex).collect(function(e,index){ return new String((obj[e]||'undefined')).unescapeHTML().gsub('&#x0026;','&');  }).join(':').sub(':$','');
    },

    _selectedRowID: function(){
        if (!this.selected_row) return undefined;
        var h=$H(this.selected_row);
        var id  = h['boardid'] + ':' + h['secid']+':'+h['tradedate'];
        return id;
    },

    _rowID: function(id){
        var splited_id=new String(id).split(':'); id=splited_id[0]+':'+splited_id[1]+':'+splited_id[2];
        return id;
    },



    _processRow: function(_td, ri, ci, c, row, rownum){
        var td=$(_td);
        var inner_object=td;


        //if(c.id==this.on_click_field){
         if(this.on_click_fields.include(c.id)){
            td.addClassName(this.options.onClickColumn);
            if(!td.innerHTML){
                td.setAttribute('name','load_info_cell');
                td.setStyle({cursor: 'pointer'});
            }
            td.getElementsBySelector('a').each(function(e){
                $(e).up().removeChild(e);
            });
            td.appendChild((inner_object=Builder.node('a', {name: 'load_info', id: this._linkID($(row)), href: '#'})));
        }

        td.addClassName(this.options.column);
        if(c.id=='#NUM#'){
            inner_object.innerHTML=rownum;
            td.addClassName(this.options.rowIndexColumn);
        }
        else{

    	    if(c.customClass)
    		td.addClassName(c.customClass);

            if(c.is_datetime){
                td.addClassName(this.options.timeClass);
                inner_object.innerHTML= new Date().fromDbString(row[c.id]).toSiteDateString();
            }
            else if(c.type=='time'){
                td.addClassName(this.options.timeClass);
                inner_object.innerHTML= row[c.id];
            }
            else if(c.type=='date'){
                td.addClassName(this.options.timeClass);
                inner_object.innerHTML= new Date().fromDbString(row[c.id]).toSiteDateString();
            }
            else{
                if (c.type=='number'){
                    var decimals=(c.has_percent?2:(row['DECIMALS']?row['DECIMALS']:4));
                    var value_src=new Number(row[c.id]).toFixed(decimals);
                    var value= this._toSiteString(row[c.id],decimals);

                    if(!value)
                        value='-';

                    var inner_object_old=inner_object.innerHTML;

                    inner_object.innerHTML='<nobr>'+
                        (c.is_signed?(value_src>=0?(value_src==0?'':'+'):''):'')+
                        value+
                        (c.has_percent?(value!='-'?'%':''):'')+'</nobr>';

                    td.addClassName(this.options.numberClass);

                    var trend=value_src;
                    if (c.trend_by!=c.id){
                        td.removeClassName(this.options.deltaClass);
                        td.addClassName(this.options.amountClass);
                        trend=new Number(row[c.trend_by]).toFixed(decimals);
                    }
                    else{
                        td.removeClassName(this.options.amountClass);
                        td.addClassName(this.options.deltaClass);
                    }
                    if (c.trend_by) {
                    	if(trend>0){
	                        td.removeClassName(this.options.downClass);
                        	td.removeClassName(this.options.stayClass);
                        	td.addClassName(this.options.upClass);
                        	if(inner_object_old!=inner_object.innerHTML)
                        		new Effect.Highlight(td, {
                        			duration: 1.0,
                        			startcolor: '#3488B1',
                        			opacity:.5,
                        			afterFinish: function() {
                        				this.setStyle({'background-color': ''});
                        			}.bind(td)
                        		});
                    	}
                    	else if(trend<0){
	                        td.removeClassName(this.options.upClass);
                        	td.removeClassName(this.options.stayClass);
                        	td.addClassName(this.options.downClass);
                        	if(inner_object_old!=inner_object.innerHTML)
                        		new Effect.Highlight(td, {
                        			duration: 1.0,
                        			startcolor: '#3488B1',
                        			opacity:.5,
                        			afterFinish: function() {
                        				this.setStyle({'background-color': ''});
                        			}.bind(td)
                        		});
                    	}
                    	else{
	                        td.removeClassName(this.options.downClass);
                        	td.removeClassName(this.options.upClass);
                        	td.addClassName(this.options.stayClass);
                    	}
                    }
                }
                else {
                    td.addClassName(this.options.stringClass);
                    inner_object.innerHTML= row[c.id]?new String(row[c.id]).replace(/&(?!(#x\d+;|amp;))/g,'&amp;'):'-';
                }
            }

            if(this.options.customHandlers[c.id])
                this.options.customHandlers[c.id](_td, ri, ci, c, row, rownum, this);
        }
        if(ci==0)
            td.addClassName(this.options.leftColumn);
        else if(ci==($A(this.options.fieldsMeta).length-1))
            td.addClassName(this.options.rightColumn);
        if(ri==0)
            td.addClassName(this.options.firstRow);
        return td;
    },

    _clearTable: function(){
        this.links=undefined;
        $(this.table).getElementsBySelector('tbody').each(function(tb){
            $(tb).up().removeChild(tb); delete tb;
        });
        this.table_body=undefined;
    },


    _sortByOverList: function(data){
        var new_data=$A();
        this.options.sortOrderOverList.each(function(e){
            try{
            data.each(function(d){
                var k=(new String(d[this.options.sortOrderOverKeys[0]])+':'+new String(d[this.options.sortOrderOverKeys[1]]));
                /*string.unescapeHTML() - dosn't work in Chrome/IE :(*/
                if(k.gsub('&#x0026;','').gsub('&','')==e.gsub('&#x0026;','').gsub('&','')) {
                    new_data.push(d);
                }
            }.bind(this));
            }catch(e){}
        }.bind(this));
        return new_data;
    },

    _processAjaxData: function(json){

        this.isEmpty=false;
        var data = json.shift(); data=json;

        this._loadAjaxDataRowCount();

        if($A(data).size()==0 || !$A(data)[0]/*fix IE*/){
            $(this.table).hide();
            this.footer?$(this.footer).hide():{};
            if(this.options.responseWarn) $(this.options.responseWarn).show();
            this.isEmpty=true;
            if((this.options.onLoad || Prototype.emptyFunction).bind(this)()){
                this.unlock();
            }
            return;
        }

        if(!this.table_body){
            this._clearTable();
            this.table_body=Builder.node('tbody');
            $(this.table).appendChild(this.table_body);
        }

        var handleOnSelect=false;

        if(this.options.sortOrderOverList) data=this._sortByOverList(data);


        data.each(function(row,row_index){
            var num=(this.current_page-1)*this.options.limit+1+row_index;
            var rkey=this._rowID(this._linkID(row));
            var trid='tr-'+$(this.table).id+'-'+row_index;
            var tr=$(trid);

            if(!tr){

                $(this.table_body).appendChild((tr=Builder.node('tr', {id: trid, className: this.options.row})));
                $A(this.options.fieldsMeta).each(function(c,column_index){
                    var title_op=row['title0xf00'+c.id];
                    title_op=this.options.hideThead?{title: title_op?title_op:c.title?c.title:''}:'';
                    $(tr).appendChild(this._processRow(Builder.node('td', title_op), row_index, column_index,c,row,num));
                }.bind(this));
                handleOnSelect=true;

                $(tr).addClassName(row_index%2?'even':'odd');
            }
            else
                $(tr).getElementsBySelector('td').each(function(td,column_index){
                    this._processRow(td,row_index, column_index,this.options.fieldsMeta[column_index],row,num);
                }.bind(this));

            $(tr).setAttribute('key', rkey);

            if(this.selectedRowIndex==num-1){
                this.selected_row=this._getIdByRowIndex();
                this.selectedRowIndex=undefined;
                handleOnSelect=true;
            }

            $(tr).removeClassName(this.options.selectedRow);
            if(rkey!='undefined:undefined:undefined' && rkey==this._rowID(this._selectedRowID()))
                $(tr).addClassName(this.options.selectedRow);

			if(row['market']!=undefined){
				tr.setAttribute('market', row['market'])
			}

            //if(row[this.on_click_field])
            if(row[this.on_click_fields[0]])
                $(tr).setAttribute('name', row[this.on_click_fields[0]]);

        }.bind(this));

        this._makeDownLoader();

        if((this.options.onLoad || Prototype.emptyFunction).bind(this)()){
            this.resume();
            this.unlock();
        }

        if(!$(this.holder).visible())  Effect.Appear($(this.holder), {duration: 0.3});

        if(!$(this.table).visible())  $(this.table).show();

        if(this.options.responseWarn && $(this.options.responseWarn).visible()) Effect.Fade($(this.options.responseWarn), {duration: 0.2});


        if(handleOnSelect && this.selected_row){
            var eid=this._selectedRowID();
            $(this.table_body).getElementsBySelector('tr').each(function(tr){
                if(this._rowID(eid)==$(tr).readAttribute('key')){
                    var title=$(tr).readAttribute('name');
                    var selected_=new String(eid).split(':');
                    this.selected_row=$H({boardid: selected_[0], secid: selected_[1], tradedate: (selected_[2]=='undefined'?undefined:selected_[2]), trade_engine: this.options.issParameters.trade_engine, market: this.options.issParameters.market, title: title});
                }
            }.bind(this));

            (this.options.beforeSelect || Prototype.emptyFunction).bind(this)();
            (this.options.onSelect || Prototype.emptyFunction).bind(this)();
            (this.options.afterSelect || Prototype.emptyFunction).bind(this)();
        }

        this._resizeBar();
    },

    _resizeBar: function(no_show){
        this.options.verticalBar?$(this.options.verticalBar).setStyle({height: $(this.table).getHeight() + 'px'}):{};
        if(!no_show)
            this.footer?$(this.footer).show():{};
    },
    
    _loadAjaxData_complete: function(transport, json){
        try{
    	    
    	    this.last_response_time.data=new Date().getTime();

            this.passport_marker=this.data_request.getHeader(this.options.passportMarker);

	    if(this.options.passportInfoBar && transport.status==200) {
    	        if( this.passport_marker=='denied') this.options.passportInfoBar.show();
        	else this.options.passportInfoBar.hide();
            }

	    if(!json){
    	        json = transport.responseText.evalJSON(false);
            }

	    if(!json)
    	        throw 'Errors evaluating json';

            this._processAjaxData(json);
		this._retriesReset()

        }catch(e){
            alert(e);
            throw e;
            if(this.options.responseWarn){
                Effect.Appear($(this.options.responseWarn), {duration: 0.2});
                Effect.Fade($(this.table), {duration: 0.2});
            }
            else
                throw e;
        }
    },

    _loadAjaxData: function(){
        try{
        if(this.options.url){
            if( this.options.refreshTime>0 && (new Date().getTime() - (this.last_response_time.data || 0)) < this.options.refreshTime*1000)
                return;

            this.suspend();

            var parameters=$H(new Hash(this.options.parameters));

            parameters.merge({
                limit: $(this.options.limit),
                start: new Number(this.current_page-1).valueOf()*this.options.limit
            });

            if(this.sort_order_field)
                parameters['sort_order']=this.sort_order_field;
            if(this.sort_order_desc)
                parameters['sort_order_desc']=this.sort_order_desc?this.sort_order_desc:'';

            if(LC_LANG)
                parameters['lang']=LC_LANG;

            if(!this.options.preloadData)
            {
                this.data_request = new Ajax.Request(this.options.url, {
                    method: 'get',
                    parameters: parameters,
                    onComplete: function(transport, json) {
                        
                        setTimeout(function(){this._loadAjaxData_complete(transport,json)}.bind(this,transport, json), 100);
                        
                    }.bind(this),

                    onFailure: function(transport){
                        alert ("table.ajax.failure");
                    try{
						if (this._retryOnServerFailure(transport))
							return;
                        this.isEmpty=true;
                        (this.options.onFailureLoad || Prototype.emptyFunction).bind(this)(transport);
                    }catch(e){alert('_loadAjaxData:'+e);}
                    }.bind(this)

                });
            }
            else{
                this._processAjaxData(this.options.preloadData);
                if(this.options.passportInfoBar){
                    if(this.options.preloadMarker[this.options.passportMarker]=='denied') this.options.passportInfoBar.show();
                    else this.options.passportInfoBar.hide();
                }
                this.options.preloadData=undefined;
            }
        }
        }catch(e) {       }
    },

	_retryOnServerFailure: function(transport){
		if (this.options.retriesLimiter == 0 || transport.status != 500)
			return false;

		this._retriesCounter += 1;

		if ((this.options.retriesLimiter!=-1) && (this.options.retriesLimiter <= this._retriesCounter))
			return false;

		this.resume();
		return true;
	},

	_retriesMultiplier: function(){
		return this._retriesCounter+1;
	},

	_retriesReset: function(){
		this._retriesCounter = 0;
	},

    _parametersMerge: function (parameters){
        if(this.options.data_type=='history'){
            if(this.options.date)
                parameters.merge({
                    date_from: this.options.date,
                    date_till: this.options.date
                });
            else if(this.options.date_from && this.options.date_till)
                    parameters.merge({
                        date_from: this.options.date_from,
                        date_till: this.options.date_till
                    });

            parameters.merge({
                    boardid: this.options.boardid,
                    secid: this.options.secid
            });
        }
        return parameters;
    },

    _currentPager: function(){
        return new Number(Math.ceil(this.current_page/this.options.pagerLength-1)*this.options.pagerLength+1);
    },

    _replaceClassName: function(element,oldclass,newclass){
        element.removeClassName(oldclass);
        element.addClassName(newclass);
    },

    _observeNavigator: function(){
        this.onClickNavigatorListener = this.onClickNavigatorListener || this.onClickNavigator.bindAsEventListener(this);
        $A(this.navigatorLinks).invoke('observe', 'click', this.onClickNavigatorListener);
    },

    _deleteAllPageLinks: function(){
        if(this.options.pagerList){
             if($(this.navigatorLinks)) $A(this.navigatorLinks).invoke('stopObserving', 'click', this.onClickNavigatorListener);
            $(this.options.pagerList).getElementsBySelector('li').each(function(e){
                $(this.options.pagerList).removeChild(e); delete e;
            }.bind(this));
         }
        this.navigatorLinks=undefined;
    },

    _clearNavigator: function(new_page){

        var current_pager=this._currentPager();

        if(new_page<(current_pager) || new_page>=current_pager+this.options.pagerLength){
            this._deleteAllPageLinks();
            return true;
        }
        return false;
    },

    _remakeNavigator: function (new_page){

        if(!$(this.options.pagerList)) return false;

        if(this.pages<=1) {
            $(this.options.pager).hide();
            return false;
        }

        if(this._clearNavigator(new_page)){
            delete this.navigatorLinks; this.navigatorLinks=undefined;
            this.current_page=new Number(new_page).valueOf();
            this._makeNavigator();
            return true;
        }

        this.current_page=new_page;

        $(this.options.pagerPrev).name=this.current_page-1;
        $(this.options.pagerNext).name=this.current_page+1;

        if(new Number($(this.options.pagerPrev).name).valueOf()==0){
            $(this.options.pagerPrev).className=this.options.noLinked;
        }
        else
            $(this.options.pagerPrev).className=this.options.linked;
        if(new Number($(this.options.pagerNext).name).valueOf()>this.pages){
            $(this.options.pagerNext).className=this.options.noLinked;
        }
        else
            $(this.options.pagerNext).className=this.options.linked;

        $(this.options.pagerList).getElementsBySelector('li').each(function(e){

            var epage=e.readAttribute('name');

            if(this.current_page==epage){

                $(e).addClassName(this.options.selectedPage);
                $(e).getElementsBySelector('a').each(function(a){ a.className=this.options.noLinked; }.bind(this));
            }
            else{
                $(e).className=this.options.linked;
                $(e).getElementsBySelector('a').each(function(a){ a.className=this.options.linked; }.bind(this));
            }
        }.bind(this));

        return true;
    },

    _makeNavigator: function(){

        if(this.pages<=1){
            $(this.options.pager).hide();
            return ;
        }
        else $(this.options.pager).show();

        var pagerlist=$(this.options.pagerList);
        var current_pager=this._currentPager();

        $(this.options.pagerPrev).name=this.current_page-1;
        $(this.options.pagerNext).name=this.current_page+1;

        if(this.current_page>1) $(this.options.pagerPrev).className=this.options.linked;
        else                    $(this.options.pagerPrev).className=this.options.noLinked;

        if(this.current_page<this.pages)  $(this.options.pagerNext).className=this.options.linked;
        else                    $(this.options.pagerNext).className=this.options.noLinked;


        if (current_pager>1){
            var a=Builder.node('a', {href: '#', name: current_pager-1}); a.innerHTML='&hellip;';
            pagerlist.appendChild(Builder.node('li', {name: current_pager-1}, a));
        }

        for(var i=current_pager, icount=1; i <= this.pages &&  icount<=(this.options.pagerLength+1); i++, icount++){
            var li = Builder.node('li', {name: i}), a;

            if(icount<=this.options.pagerLength){
                a   = Builder.node('a', {href: '#', name: i});
                a.innerHTML=i;
            }
            else{
                a   = Builder.node('a', {href: '#', name: i});
                a.innerHTML='&hellip;';
            }
            if (this.current_page==i){
                $(li).addClassName(this.options.selectedPage);
                $(a).addClassName(this.options.noLinked);
            }

            li.appendChild(a);
            pagerlist.appendChild(li);
        }

        if(!this.navigatorLinks){
            this.navigatorLinks = $(this.options.pager).getElementsBySelector('a[name]','li[name]');
            this._observeNavigator();
        }

        return this.options.pagerList;
    },

    _processNavigator: function(json){
        try{
            var data = json.shift(); data=json;

            this.rowCount=new Number(data[0]['COUNT']);
        }catch(e){
            this.rowCount = json
        }

        $(this.options.rowCount)?this.options.rowCount.innerHTML=this.rowCount:{};

        this.pages=new Number(Math.ceil(this.rowCount/this.options.limit));

        if(this.pagerList)
            this._deleteAllPageLinks();

        this.pagerList=this._makeNavigator();
    },

    _loadAjaxDataRowCount: function(doit){
        if(!this.options.countUrl || !this.options.pager)
            return;

        if(!doit){
            if(this.footer && $(this.footer).visible())
                return;
        }else if(this.footer && $(this.footer).visible()){
            delete this.navigatorLinks; this.navigatorLinks=undefined;
            this.current_page=1;
        }

        var parameters=$H(new Hash(this.options.parameters));

        parameters=this._parametersMerge(parameters);

        parameters.merge(this.options.issParameters);

        delete parameters['start'];
        delete parameters['limit'];

        if( this.options.refreshTime>0 && (new Date().getTime() - (this.last_response_time.count || 0)) < this.options.refreshTime*1000)
            return;

        if(!this.options.preloadCount)
            new Ajax.Request(this.options.countUrl, {
                method: 'get',
                parameters: parameters,
                onComplete: function(transport,json){
                    try{

                        this.last_response_time.count=new Date().getTime();

                        if(!json){
                            json = transport.responseText.evalJSON(false);
                        }
                        if(!json)
                            throw 'Errors evaluating json';

                        this._processNavigator(json);

                    }catch(e){
                        if(this.options.responseWarn){
                            Effect.Appear($(this.options.responseWarn), {duration: 0.2});
                            Effect.Fade($(this.table), {duration: 0.2});
                        }
                        else
                            alert('_loadAjaxDataRowCount: '+e);
                    }
                }.bind(this)
            });
        else{
            this._processNavigator(this.options.preloadCount);
            this.options.preloadCount=undefined;
        }
    },

    _dateAsFileName: function(){

        var current_date=undefined;
        if(this.options.parameters['date'])
            current_date=new String(this.options.parameters['date']).replace('-','_','g');
        else if(this.options.parameters['date_from'] && this.options.parameters['date_till'])
            current_date=new String(this.options.parameters['date_from']).replace('-','_')+'-'+new String(this.options.parameters['date_till']).replace('-','_','g');
        else
            current_date=new Date().toFileNameString();
        return current_date;
    },

    _downloadParameters: function(){
        var parameters=$H({}).merge(new Hash(this.options.parameters));

        parameters.merge(this._parametersMerge($H(
                {
                    start: 0,
                    limit: this.options.maxDownloadRows
                })
         ));

        return parameters;
    },


    _makeDownLoader: function(){

         if(!this.options.downloader) return ;

	try {

        var current_date=this._dateAsFileName();
        var csv_settings_string = this.cookies.get("Micex.CSVSettings");

	var csv_settings = $H();

	if (csv_settings_string)
	    csv_settings = csv_settings_string.toQueryParams();

        $(this.options.downloader).getElementsBySelector('a').each(function(a){

	    if (a.name != '')
	    {
        	var helper   =this.options.downloadUrl+'/micex_'+this.options.issParameters.trade_engine+'_'+this.options.issParameters.market+'_'+current_date+'.'+a.name;

        	var parameters = this._downloadParameters();
        	parameters['lang'] = LC_LANG;
        	parameters.merge(csv_settings);

        	a.href=helper+'?'+parameters.toQueryString();
    	    }
        }.bind(this));
        }
        catch(e) {alert(e);}
    },

    onClickHeader: function(e){

        this.suspend();
        this.lock();

        Event.stop(e);

        this.last_response_time = {};

        var element=Event.element(e);
        var na=element.readAttribute('name');

        this.table_body=undefined;

        var current_order_field=element.id.split($(this.table).id+'-field-order-by-')[1];

        if (current_order_field!=this.sort_order_field){
            this.sort_order_counter=0;
            this.sort_order_desc='desc';
            this.sort_order_field=current_order_field;
        }
        /*if(this.sort_order_counter==2){
            if(this.sort_order_field==this.options.sortOrderDesc)
                this.sort_order_desc=this.sort_order_desc==this.options.sortOrderDesc?undefined:this.options.sortOrderDesc;
            else
                this.sort_order_desc=this.options.sortOrderDesc;
            this.sort_order_field=this.options.sortOrderField;
            this.sort_order_counter=0;
        }*/
        else{
            this.sort_order_counter++;
            this.sort_order_field=current_order_field;
            this.sort_order_desc=(this.sort_order_desc=='desc'?undefined:'desc');
        }

        this._makeTabelHeader();

        if((this.options.onOrder || Prototype.emptyFunction).bind(this)())
            this._loadAjaxData();
    },

    _getIdByRowIndex: function(){
        if(this.table_body){
            var selected_row=undefined;
            $(this.table_body).getElementsBySelector('tr').each(function(e,index){
                if(this.selectedRowIndex==index){
                    var element_id=e.readAttribute('key')
                    selected_row=this._idToSelectedRow(element_id);
                    return;
                }
            }.bind(this));
            return selected_row;
        }
        return undefined;
    },

    _reselectRow: function(old_selected_row, new_selected_row){
        if(this.table_body && (new_selected_row!=old_selected_row)){
            this._resetSelectedRow(new_selected_row);
            (this.options.beforeSelect || Prototype.emptyFunction).bind(this)();
            (this.options.onSelect || Prototype.emptyFunction).bind(this)();
            (this.options.afterSelect || Prototype.emptyFunction).bind(this)();
        }
    },

    selectFirstRow: function(){
        this.selectedRowIndex=0;
        var old_selected_row=this._selectedRowID();
        this.selected_row=this._getIdByRowIndex();
        var new_selected_row=this._selectedRowID();
        this._reselectRow(old_selected_row,new_selected_row);
    },

    selectRow: function(boardid,secid,tradedate){
        var old_selected_row=this._selectedRowID();
        this.selected_row=$H({boardid: boardid, secid:secid, tradedate:tradedate, trade_engine: this.options.issParameters.trade_engine, market: this.options.issParameters.market});
        var new_selected_row=this._selectedRowID();
        this._reselectRow(old_selected_row,new_selected_row);
    },

    _idToSelectedRow: function(element_id, title){
        var selected_=new String(element_id).split(':');

        return $H({boardid: selected_[0], secid: selected_[1], tradedate: (selected_[2]=='undefined'?undefined:selected_[2]), trade_engine: this.options.issParameters.trade_engine, market: this.options.issParameters.market, title: title});
    },

    _resetSelectedRow: function(element_id, dontit){
        if(!this.table_body) return;
        $(this.table_body).getElementsBySelector('tr').each(function(tr){
            if(this._rowID(element_id)==$(tr).readAttribute('key') && !dontit){
                var title=$(tr).readAttribute('name');
                if(tr.hasClassName(this.options.selectedRow)){
                    if(!this.options.unselectable){
                        this.selected_row=undefined;
                        this.selectedRowIndex=undefined;
                        tr.removeClassName(this.options.selectedRow);
                    }
                }
                else{
                    this.selected_row=this._idToSelectedRow(element_id,title);
                    this.selectedRowIndex=undefined;
                    if(!dontit)
                        tr.addClassName(this.options.selectedRow);
                }
            }
            else{
                tr.removeClassName(this.options.selectedRow);
            }

        }.bind(this));
    },

    onClick: function(e) {
        try{
            Event.stop(e);
            var element=Event.element(e);
            var na=element.readAttribute('name');

            if(na=='load_info' || na=='load_info_cell'){

                ($(this.options).beforeSelect || Prototype.emptyFunction).bind(this)();

                var selectedRow = (na=='load_info_cell'?element.up():element.up().up());
                var element = (na=='load_info_cell'?element.down():element);

                this.selected_link=element;

                var onclick_result=undefined;

                if(na=='load_info' && this._selectedRowID()==element.id){
                    onclick_result=($(this.options).onClick || Prototype.emptyFunction).bind(this)();
                }

                if(onclick_result==undefined || onclick_result==true){
                    this._resetSelectedRow(element.id);
                }

                ($(this.options).onSelect || Prototype.emptyFunction).bind(this)();

                ($(this.options).afterSelect || Prototype.emptyFunction).bind(this)();
            }
        }catch(e){alert('mxtable onClick: '+e);}
    },

    onClickNavigator: function(e){
        Event.stop(e);

        this.last_response_time.data=0;

        var new_page=new Number(Event.element(e).readAttribute('name')).valueOf();

        if(this.current_page==new_page || new_page==0 ||  new_page>this.pages ) return false;
        this.suspend();
        this.lock();
        if(this._remakeNavigator(new_page)){
            this.table_body=undefined;
            if((this.options.onPage || Prototype.emptyFunction).bind(this)())
                this._loadAjaxData();
        }
        else{
            this.resume();
            this.unlock();
        }
    }
};

/**
*
* @updated: 2008-09-15
* @version: 0.9.6
*
*/

Common={};
Common.ElementGroup = Class.create();
Object.extend(Common.ElementGroup.prototype, Finder.Element.prototype);
Object.extend(Common.ElementGroup.prototype, {


    initialize: function(controls) {
        this.controls=controls;
        this.childElements = $A();

        this.controls.each (

            function(item) {
                if ( (item.updateOnChange == undefined) || (item.updateOnChange == true))
                    item.control.childElements.push(this);
            }
            .bind(this)
        );
    },

	show: function() {},
	hide: function() {},

	getControls: function() {
		var result=$H();

		this.controls.each(

			function (result,item) {
				result[item.id] = item.control;
			}
			.bind(this, result)

		);

		return result;
	},

	getValue: function() {

		var result=$H();

		this.controls.each(

			function (result,item) {
				result[item.id] = item.control.getValue();
			}
			.bind(this, result)

		);

		return result;
	}

});

Common.VisibleChangingElement = Class.create();
Object.extend(Common.VisibleChangingElement.prototype, Finder.Element.prototype);
Object.extend(Common.VisibleChangingElement.prototype, {

	activate_in: function() {
		Finder.Element.prototype.activate_in.apply(this, arguments);
		this.hide();
	},

	update_in: function() {
		Finder.Element.prototype.update_in.apply(this, arguments);
		(this.parentElement.getValue() != "")?this.show():this.hide();
	}

});

//----------------------------------------------------------------------------------------


MxChart.Helper.IndicatorInstance = Class.create()
MxChart.Helper.IndicatorInstance.prototype = {

	initialize: function (definition, controller) {
		this.controller = controller;
    	this.definition = definition;
    	this.params = new Array();
    	this.color = controller.colorList.shift();
  	},

  	remove: function () {

    	this.controller.list = this.controller.list.without(this);
    	this.data.dd.remove();
    	this.data.dt.remove();
    	this.controller.selector.hide();
    	this.controller.selector.show();
    	this.controller.colorList.push(this.color);
  	},

  	getDataBlock:  function () {

    	var data = Class.create();
    	this.data = data;

	    var dt = Element.extend (document.createElement("dt"));
	    dt.innerHTML = "&nbsp;";
	    dt.addClassName("null");
	    data.dt = dt;

	    var dd = Element.extend (document.createElement("dd"));
	    data.dd = dd;

	    var a = Element.extend(document.createElement("a"));
	    a.href="#";
	    a.addClassName("deleleIcon");
	    dd.appendChild(a);

	    Event.observe (a, "click", function (e) {
	       Event.stop(e);
	       this.remove();
	    }.bind(this));

    	var select = Element.extend(document.createElement("select"));

    	var selectorCounter = Class.create();
    	selectorCounter.counter=0;

    	//select.options[select.options.length] = new Option("Удалить",0);
    	this.controller.avaible.each(
                                 function (currentCode,selector, item) {

                                 	var newOption = new Option(item.name.strip(), item.id.strip());

                                 	if (item.id.strip() == currentCode) selector.selected=selector.counter;
                                 	selector.counter++;

                                 	this.options[select.options.length] = newOption;

                                 }.bind(select,this.definition.id.strip(), selectorCounter)
                                )

    	select.selectedIndex = selectorCounter.selected;

    	select.instance = this;
    	Event.observe (select, "change",

	    	function(e) {
                        Event.stop(e);
      			if (this.getValue() == "0") this.instance.remove();
        		else this.instance.controller.replaceItem(this.instance, this.getValue());
      		}.bind(select)
    	);
    	dd.appendChild(select);

    	var img = Element.extend(document.createElement("img"));
    	var params = $H();
    	params['id'] = this.definition.id.strip();
    	params['ts'] = ""+new Date();
    	//img.src = "/marketdata/analysis/indicator_icon?"+params.toQueryString();
    	img.src = "/images/"+this.definition.ta_icon;
    	img.width=40;
    	img.height=18;
    	Event.observe (img, "load", function(e) {
    	   img.show();
    	   img.setStyle({backgroundColor: '#'+this.color['1']})
    	}.bind (this, img));
    	dd.appendChild(img);

	    this.definition.params.each(
                                function(dd, item) {
                                	var span = Element.extend(document.createElement("span"));
                                	dd.appendChild(span);

                                  	span.appendChild (document.createTextNode(item.title));
                                	span.appendChild (document.createTextNode(": "));

                                    var arr = item.value.evalJSON();
                                    var input;
                               	    if ($A(arr).length>0) {
                                	    input = $(Builder.node("select"));
                                	    input.addClassName("parameter");
                                	    arr.each( function (item) {
                                	       var newOption = new Option (item.title, item.id);
                                	       input.options[input.options.length] = newOption;
                                	    });
                                	}
                                	else {
                                	    input = Element.extend(document.createElement("input"));
                                	    input.size=3;
                                        input.maxlength=3;
                                	    if (item.value)
                                	           input.value = (item.value.strip());
                                	}
                                 	span.appendChild(input);

                                  	if (item.title.strip() == "")
                                  		span.hide();

                                  	var paramObject = new Object();
                                  	paramObject.code=item.id.strip();
                                  	paramObject.object=input;
                                  	this.params[this.params.length] = paramObject;

                                }.bind(this,dd)
                               );

    		return data;
	}
};

//-----------------------------------------------------

MxChart.Interface.IndicatorsListController = Class.create();
Object.extend(MxChart.Interface.IndicatorsListController.prototype, Finder.Element.prototype);
Object.extend(MxChart.Interface.IndicatorsListController.prototype, {

    colorList: [
        {1: '00C424', 2: '007315'},
        {1: 'E11D00', 2: '991100'},
        {1: 'AFB800', 2: '676C00'},
        {1: 'AF0FDE', 2: '670990'},
        {1: '00C4A7', 2: '007362'},
        {1: '592DE6', 2: '200099'},
        {1: 'DE0F83', 2: '90094D'},
        {1: 'DCC500', 2: '8A7400'},
        {1: 'E16F00', 2: '994100'}
    ],

    coloredIndicators: [
	"stochastic",
	"macd"
    ],

    initialize: function(container, container_stop, selector) {
    	//container.hide();
    	this.buildControl(container, container_stop, selector);
    	this.hide();
    	this.childElements=$A();
    },

    show: function() {
    	this.container.show();
    },

    hide: function() {
    	this.container.hide();
    },

    cleanup: function(){},

    buildSelector: function() {
//    	new Ajax.Request("/marketdata/analysis/indicator_list", {
	var params = {};
	if (LC_LANG)
	    params["lang"] = LC_LANG;
    	new Ajax.Request("/cs_indicator_list", {
    		method: "get",
    		parameters: params,
    		onSuccess: function (transport) {


				var result = transport.responseText.evalJSON();
				this.avaible = result;

				this.selector.options[0] = new Option ((LC_LANG=='ru')?"Добавить":"Append",0);

				result = $A(result).sortBy (function (item) {return item.name});

				result.each (function (item) {
					this.selector.options[this.selector.options.length] = new Option(item.name.strip(), item.id.strip());
				}.bind(this));

    		}.bind(this)
    	});
    },

    buildControl: function (container, container_stop, selector) {
      this.avaible = $A();
      this.container = container;
      this.container_stop = container_stop;
      this.selector = selector;
      this.list = Element.extend(new Array());

      this.buildSelector();

      selector.controller = this;
      Event.observe (selector, "change",

     	 function(e) {
	        Event.stop(e);
      		if (this.getValue() == 0) return;

      		var newDef = this.controller.avaible.find (
                              function (item) { return item.id.strip() == this;}.bind(this.getValue())
                            );


      		var newInst = new MxChart.Helper.IndicatorInstance(newDef, this.controller);

      		var data = newInst.getDataBlock();

      		this.controller.container.insertBefore (data.dt, this.controller.container_stop);
      		this.controller.container.insertBefore (data.dd, this.controller.container_stop);

      		this.controller.list[this.controller.list.length] = newInst;
      		this.controller.selector.selectedIndex=0;
      		this.controller.selector.hide();
      		if (this.controller.list.length < 9)
      			this.controller.selector.show();

    	}.bind(selector)
      );

    },

    replaceItem: function(what, newCode) {

      var newDef = this.avaible.find (
                              function (item) { return item.id.strip() == this;}.bind(newCode)
                            );


      this.colorList.push(what.color);
      var newInst = new MxChart.Helper.IndicatorInstance(newDef, this);
      this.list[this.list.indexOf(what)] = newInst;


      var newData = newInst.getDataBlock();
      this.container.insertBefore(newData.dt, what.data.dt);
      this.container.insertBefore(newData.dd, what.data.dt);
      what.data.dt.remove();
      what.data.dd.remove();
    },

    getValue: function() {
    	return this.list;
    }
});

//-----------------------------------------------------

MxChart.Transport.ISS = Class.create();
Object.extend (MxChart.Transport.ISS.prototype, Finder.Element.prototype);
Object.extend (MxChart.Transport.ISS.prototype, Finder.AjaxElement.prototype);
Object.extend (MxChart.Transport.ISS.prototype, {

	onLoadCandleBordersError: function() {},
	onLoadCandleBordersSuccess: function() {},

	initialize: function () {
		Finder.AjaxElement.prototype.initialize.apply(this, arguments);
		this.secid="MICEXINDEXCF";
		this.boardid="EQBR";
		this.trade_engine="stock";
		this.market="shares";
		this.childElements=[];
		this.title="";
	},

	loadCandleBorders: function() {

		var params = {};
		var url = "";

		if (this.board_group_id)
		{
		    params = {
			"secid": this.secid,
			board_group_id: this.board_group_id
		    };
		    url = "/issrpc/marketdata/chart/candle_borders/result.json";
		}
		else
		{
		    params = {
			"secid": this.secid,
			"boardid": this.boardid
		    };
		    url = "/issrpc/marketdata/chart/candle_borders_by_boardid/result.json";
		}

		new Ajax.Request (url, {
			method: "get",
			parameters: params,
			onSuccess: function (transport){
				var obj = transport.responseText.evalJSON();
				this.candlesBorders = $H();
				obj.each (

					function (item) {
						if ($H(item).size()) {
							this.candlesBorders[item.period] =
								{"begin": item.first_candle, "end": item.last_candle};
						}
					}
					.bind (this)
				);
				if (this.candlesBorders.size() >0 ) {

					this.onLoadCandleBordersSuccess();

					if (this.onLoadCandleBordersComplete)
						this.onLoadCandleBordersComplete();
				}
				else
					this.onLoadCandleBordersError();

			}
			.bind (this)
		});
	},

	updateEndBorders: function(chain) {

    	    var params = {};
	    var url = "";

	    if (this.board_group_id)
	    {
	        params = {
		    "secid": this.secid,
		    board_group_id: this.board_group_id
		};
		url = "/issrpc/marketdata/chart/candle_borders/result.json";
	    }
	    else
	    {
	        params = {
	    	    "secid": this.secid,
		    "boardid": this.boardid
		};
		url = "/issrpc/marketdata/chart/candle_borders_by_boardid/result.json";
	    }


	   new Ajax.Request (url, {
			method: "get",
			parameters: params,
			onSuccess: function (chain, transport){
				var obj = transport.responseText.evalJSON();
				this.candlesBorders = $H();
				obj.each (

					function (item) {
						if ($H(item).size()) {
							this.candlesBorders[item.period] =
								{"begin": item.first_candle, "end": item.last_candle};
						}
					}
					.bind (this)
				);

				if (this.candlesBorders.size() >0 ){
					if (chain) chain();
				}
				else
					this.onLoadCandleBordersError();
			}
			.bind (this, chain)
		});
	},

	allIntervals: [
		{id: "1", title: (LC_LANG=='ru'?"минута":"minute")},
		{id: "10", title: (LC_LANG=='ru'?"10 минут":"10 minutes")},
		{id: "60", title: (LC_LANG=='ru'?"час":"hour")},
		{id: "24", title: (LC_LANG=='ru'?"день":"day")},
		{id: "7", title: (LC_LANG=='ru'?"неделя":"week")},
		{id: "31", title: (LC_LANG=='ru'?"месяц":"month")},
		{id: "4", title: (LC_LANG=='ru'?"квартал":"quoter")}
	],

	allPeriods: $A([
		{period_id: "-1h", period_title: (LC_LANG=='ru'?"час":"hour"), interval_id: "1", interval_title: "минута"},
		{period_id: "-1d", period_title: (LC_LANG=='ru'?"день":"day"), interval_id: "10", interval_title: "10 минут"},
		{period_id: "-7d", period_title: (LC_LANG=='ru'?"неделя":"week"), interval_id: "60", interval_title: "час"},
		{period_id: "-1M", period_title: (LC_LANG=='ru'?"месяц":"month"), interval_id: "24", interval_title: "день"},
		{period_id: "-3M", period_title: (LC_LANG=='ru'?"квартал":"quarter"), interval_id: "24", interval_title: "день"},
		{period_id: "-1y", period_title: (LC_LANG=='ru'?"год":"year"), interval_id: "7", interval_title: "неделя"}
	]),

	getPeriods: function(enableAll) {
		result = $A();

		this.allPeriods.each (
			function(item) {
				this[this.length] = {"id": item.period_id, "title": item.period_title};
			}
			.bind (result)
		);

		if (enableAll)
			result[result.length] = {"id": "all", "title": "Весь период"};

		return result;
	},

	timeSpanToInterval: function(timespan) {
		if (timespan<=2*60*60*1000) return 1;
		if (timespan<=2*24*60*60*1000) return 10;
		if (timespan<=14*24*60*60*1000) return 60;
		if (timespan<=5*31*24*60*60*1000) return 24;
		if (timespan<=3*365*24*60*60*1000) return 7;
                if (timespan<=3*365*24*60*60*1000) return 24;
		return 31;
	},

	verifyInterval: function (beginDate, endDate, interval) {
		var intervals = [1,10,60,24,7,31];
                //var intervals = [1,10,60,24,31];
		var cb= this.candlesBorders[interval];

		if (!cb) return interval;

		if (cb.begin>beginDate) {
			newInterval = intervals[intervals.indexOf(interval)+1];
			if (newInterval)
				return this.verifyIntervals(beginDate, endDate, newInterval);
		}
		else
			return interval;
	},

	getAvaiblePeriods: function(endDate, enableAll) {
		if (endDate>this.getLastTime())
			endDate = this.getLastTime();

		 var result = $A();

		 this.getPeriods(false).each (

		 	function (result, endDate, item) {
		 		var timetest = new Date(endDate);
		 		if (this.getTimeLine(endDate, item.id) != undefined)
		 			result.push (item);
		 	}
		 	.bind (this, result, endDate)

		 );

		 if (enableAll)
			result[result.length] = {"id": "all", "title": (LC_LANG=='ru'?"весь период":"all avaible")};

		 return result;
	},

	periodToInterval: function (period) {

		if (period == "all") {
			var beginDate = this.getFirstTime();
			var endDate   = this.getLastTime();
			var span      = endDate - beginDate;

			var opts={};
			opts.interval  = {id: this.allPeriods[0].interval_id, title: this.allPeriods[0].interval_title};
			this.allPeriods.each (

				function (span, item) {
					var testDate1 = new Date();
					var testDate2 = new Date(testDate1);
					testDate2.addTimeSpanString(item.period_id);
					var testSpan = testDate2 - testDate1;

					if (testSpan<span)
						this.interval = {id: item.interval_id, title: item.interval_title};
				}
				.bind (opts, span)

			);

			return opts.interval;
		}
		else {

			var item = this.allPeriods.find (
				function (period, item) {
					return item.period_id == period;
				}
				.bind (this, period)
			);

			if (item) return {id: item.interval_id, title: item.interval_title};
		}
	},

	getPeriodByInterval: function(interval) {

		var result = $A();

		this.allPeriods.findAll(

			function (interval, item) {
				return item.interval_id == interval;
			}
			.bind (this, interval)

		).each (

			function (result, item) {
				if (this.getAvaiblePeriods(new Date()).pluck ("id").indexOf(item.period_id)>=0)
					result[result.length] = {id: item.period_id, title: item.period_title};
			}
			.bind (this, result)

		);

		if (interval == 31 || interval == 4)
		  result[result.length] = {"id": "all", "title": (LC_LANG=='ru'?"весь период":"all avaible")};

		return result;
	},

	getAllPeriodInterval: function () {

		var allTimeLine = this.getTimeLine (undefined, "all");
		var opts = {"interval": "7"};
                //var opts = {"interval": "24"};

		this.getPeriods(false).reverse().each (
			function (opts, item) {

				var currentTimeLine = this.getTimeLine(allTimeLine[1], item.id);
				if (currentTimeLine == undefined)
					opts.interval = this.periodToInterval (item.id).id;
			}
			.bind (this,opts)
		);
		return opts.interval;

	},

	getTimeLine: function (endDate, period) {
		if (this.candlesBorders==undefined) return [new Date(), new Date()];
		if (period != "all") {
			if (this.candlesBorders[this.periodToInterval (period).id] == undefined) {
				return;
			}
			var dataEndDate = new Date();
			dataEndDate.fromDbString(this.candlesBorders[this.periodToInterval (period).id].end);
			if (endDate>dataEndDate) endDate = dataEndDate;

			var beginDate = new Date(endDate);
			beginDate.addTimeSpanString(period);
			var beginDateComparator = new Date();

			beginDateComparator.fromDbString(this.candlesBorders[this.periodToInterval (period).id].begin);
			if (beginDate<beginDateComparator && period!="-1h") {
				beginDate = beginDateComparator
				//return;
			}
			return [beginDate, endDate];
		}
		else {
			var intervals = [1,10,60,24,7,31,4];
                        //var intervals = [1,10,60,24,31,4];
			var minDate=null;
			var maxDate=null;

			for (var i=0; i<intervals.length; i++) {
				var candle = this.candlesBorders[intervals[i]];

				if (!candle) continue;

				var _beginDate = new Date();
				_beginDate.fromDbString(candle.begin);
				var _endDate = new Date();
				_endDate.fromDbString(candle.end);

				if (minDate==null || minDate>_beginDate)
					minDate = _beginDate;
				if (maxDate==null)
					maxDate = _endDate;

			}

			return [minDate, maxDate];
		}
	},

	getFirstTime: function() {
		return this.getTimeLine(undefined, "all")[0];
	},

	getLastTime: function () {
		return this.getTimeLine(undefined, "all")[1];
	},


	getValue: function() {
		try {
			return {
				secid: this.secid,
				lastTime: this.getLastTime(),
				firstTime: this.getFirstTime()
			};
		}
		catch (e) {};
	},

	lock: function(){},
	unlock: function() {},
	show: function() {},
	hide: function() {},


	update_in: function() {
		var conf = this.parentElement.getValue();
		if ( (!conf["secid"] || !conf["boardid"]) && !this.uData) return;

		if (this.uData) {
			this.secid = this.uData["secid"];
			this.boardid = this.uData["boardid"];
			this.market = this.uData["market"];
			this.trade_engine = this.uData["trade_engine"];
			this.title = this.uData["title"];
			this.loadCandleBorders();
		}
		else {
			this.secid=conf["secid"];
			/*this.boardid =
				this.parentElement.controls[1].control.data [
					this.parentElement.controls[1].control.data.pluck("id").indexOf(conf["boardid"])
				].name;
			*/
			this.board_group_id =
				this.parentElement.controls[1].control.data [
					this.parentElement.controls[1].control.data.pluck("id").indexOf(conf["boardid"])
				].id;


			this.loadMarket();
		}
	},

	loadMarket: function () {
		new Ajax.Request ("/marketdata/find/market", {
			method: "get",
			parameters: {"board_group_id": this.board_group_id},
			onSuccess: function (transport) {

				var result = transport.responseText.evalJSON();
				this.market = result.market.name;
				this.trade_engine = result.trade_engine.name;
				this.loadCandleBorders();
			}
			.bind (this),

			onFailure: function (transport) {
				if (this.onLoadMarketFailure)
					onLoadMarketFailure();
			}.bind (this)
		});
	},

        onLoadCandleBordersComplete: function () {
		this.initialized = true;
		Finder.Element.prototype.update_in.apply(this, arguments);
	},

	getTitle: function () {
		if (this.uData==undefined )
			return this.parentElement.controls[0].control.data.name?this.parentElement.controls[0].control.data.name:this.parentElement.controls[0].control.data.shortname;
		else
			return this.title;
	}

});

MxChart.Transport.CS = Class.create();
Object.extend (MxChart.Transport.CS.prototype, Finder.Element.prototype);
Object.extend (MxChart.Transport.CS.prototype, {

	onNoData: function() {},
	onBefore: function(){},
	onChartLoadComplete: function(){},
	onBeforeQuery: function(){},
	pricePrecision: 4,

    chartLines: [],

	valueTable: [
      	{"key": "0_line", values: [ {"id": 0, "title": (LC_LANG=='ru'?"Цена":"Price")}]},
    	{"key": "0_candle",values: [ {"id": 3, "title": (LC_LANG=='ru'?"Последнее":"Close")},{"id": 2, "title": (LC_LANG=='ru'?"Открытие":"Open")},{"id": 0, "title": (LC_LANG=='ru'?"Максимум":"Max")},{"id": 1, "title": (LC_LANG=='ru'?"Минимум":"Min")}]},
    	{"key": "0_stockbar",values: [ {"id": 3, "title": (LC_LANG=='ru'?"Последнее":"Close")},{"id": 2, "title": (LC_LANG=='ru'?"Открытие":"Open")},{"id": 0, "title": (LC_LANG=='ru'?"Максимум":"Max")},{"id": 1, "title": (LC_LANG=='ru'?"Минимум":"Min")}]},
    	{"key": "1_bar", values: [ {"id": 0, "title": (LC_LANG=='ru'?"Объем":"Volume")}]}
        ],

	lock: function(){},
	unlock: function() {},
	show: function() {},
	hide: function() {},

	initialize: function(controls) {

		this.childElements = $A();
		this.controls=controls;
	},

	reset: function () {
		this.setControls();
		this.graph.hasData=false;
		this.info_headers.immediateDescendants().invoke("remove");
        this.info_data.immediateDescendants().invoke("remove");
        this.chartLines.invoke("remove");
        this.chartLines = [];
		this.values=null;
		this.info=null;
		this.hInfo=$H();
	},

	_img_onload: function (e) {
        Event.stop(e);
		if (this.graph.hasData) {
			this.values=undefined;
			this.graph.hasData = false;
			this.values_failure = false;
			this.loadValues();
			if (this.chartShield) this.chartShield.hide();
			this.onChartLoadComplete();
		}
	},

	_img_onkeydown: function(e) {

	   var direction = 0;

	   if (e.keyCode == 39)
	       direction = 1; //Go right!
	   if (e.keyCode == 37)
	       direction = -1; //Go left!

	   if (e.keyCode == 36) {
	       this.currentPosition = 0;
	       this.paintLine (this.info[this.currentPosition]);
	   }

	   if (e.keyCode == 35) {

	       this.currentPosition = this.info.length-1;
	       this.paintLine (this.info[this.currentPosition]);

	   }

	   if (direction != 0) {
	       Event.stop(e);

	       this.processMovement(direction, this.currentInfo);
	   }
	},

	_img_onclick: function (e) {

        Event.stop(e);
        this.moveActive = !this.moveActive;

        var oma = this.moveActive;
        this.moveActive = true;
        this._img_onmousemove_binded(e);
        this.moveActive=oma;

        if (this.movementControlElement)
            this.movementControlElement.focus();

	},

	processMovement: function(direction, currentInfo) {
	   var pCnt = this.xCoords.length;

	   if (direction>0 && this.currentPosition >= pCnt-1) return;
	   if (direction<0 && this.currentPosition <= 0) return;

	   //var idx = this.xCoords.indexOf(currentInfo.x);
	   this.currentPosition+=direction;

	   var info = this.info[this.currentPosition];

	   this.paintLine(info);

	},

	_img_onmousemove: function (e) {

        if (!this.moveActive) return;

        Event.stop(e);
		if ((!this.posInd) || (this.posInd.length==0)) return
			if (!this.info) return;

			var newPos = $H();
			var xPos=0

			if (e.offsetX)
				xPos = e.offsetX
			else {

                if (!this.graph.posLeft)
                    this.graph.posLeft = Position.cumulativeOffset(this.graph)[0];

				xPos = (e.clientX - this.graph.posLeft);
			}

			var pCnt = this.xCoords.length;
			var xc0=this.xCoords[0];
			var xc1=xc0;
			var xc2=xc1;
			var xcl=this.xCoords[pCnt-1];
			var i=0;

			while (xPos>this.xCoords[i] && i<this.xCoords.length) {

            	i++;
            	xc1=xc2;
            	xc2=this.xCoords[i];

            }

            if (xPos<xc0)
            	xPos = xc0;
            else if (xPos>xcl)
            	xPos = xcl;
            else
            	xPos = (xc2-xPos)>(xPos-xc1)?xc1:xc2;

			if (xPos == xc2)
			   this.currentPosition = i;
			else
			   this.currentPosition = i - 1;

			info = this.hInfo[xPos];

			//$('chart-console').innerHTML = xPos;

			this.paintLine (info);
	},

	setControls: function () {


		if (!this.parentElement) return;
		var conf = this.parentElement.getControls();

		this.issProvider      = conf.issProvider;
		this.intervalSel      = conf.intervalSel;
		this.periodSel        = conf.periodSel
		this.endDate          = conf.endDateSel;
		this.lineType         = conf.linetypeSel;
		this.tickerComparator = conf.ticker2;
		this.comparatorBoard  = conf.board2
		this.indicatorsList   = conf.indicators;
		this.graph            = this.controls.graph;
		this.info_headers     = this.controls.info_headers;
		this.info_data        = this.controls.info_data;
		this.titleControl     = this.controls.title;
		this.chartShield      = this.controls.chartShield;

		this.controlsSetup=true;

		if (!this.pEvent) {
			Event.observe(this.graph, "load", this._img_onload.bind (this));
			this.pEvent = true;
		}


		this.moveActive = true;

		this._img_onmousemove_binded = this._img_onmousemove.bind (this);
		this._img_onclick_binded = this._img_onclick.bind (this);
		this._img_onkeydown_binded = this._img_onkeydown.bind (this);

		Event.observe (this.graph,"mousemove", this._img_onmousemove_binded);
		Event.observe (this.graph,"click", this._img_onclick_binded);
		Event.observe (this.graph,"keydown", this._img_onkeydown_binded);

	},

	updateTitle: function() {
		if (this.titleControl)
		    this.titleControl.update(this.issProvider.getTitle());
	},

	updateGraph: function () {

            if (!this.controlsSetup)
                    this.setControls();

            this.updateTitle();
            var tm_helper = '/issrpc/marketdata/chart/timeline/result.json';

            var boardid=this.issProvider.boardid;
            var secid=this.issProvider.secid;
            var candle_interval=this.intervalSel.getValue();

            var endDate = Finder.Date.stringDBToDate (this.endDate.getValue());
            endDate.setMaxTime();

            if (endDate>=this.issProvider.getLastTime()) {
                this.issProvider.updateEndBorders(this.doRequest.bind(this));
            }
            else
                this.doRequest();

    },

    loadMarket2: function (board_group_id,query) {
            if(!this.markets_cache) this.markets_cache={};
            if(!this.markets_cache["/marketdata/find/market:"+board_group_id]){
                new Ajax.Request ("/marketdata/find/market", {
                        method: "get",
                        parameters: {"board_group_id": board_group_id},
                        onSuccess: function (transport) {
                                var result = transport.responseText.evalJSON();
                                this.markets_cache["/marketdata/find/market:"+board_group_id]=result;

                                query['market2'] = result.market.name;
                                query['trade_engine2'] = result.trade_engine.name;

                                this._draw(query);

                        }
                        .bind (this)
                });
            }
            else{
                result=this.markets_cache["/marketdata/find/market:"+board_group_id];
                query['market2'] = result.market.name;
                query['trade_engine2'] = result.trade_engine.name;
                this._draw(query);
            }
    },


    doRequest: function() {

            var tm_helper = '/issrpc/marketdata/chart/timeline/result.json';

//            var board_group_id=this.issProvider.board_group_id;
            var secid=this.issProvider.secid;
            var candle_interval=this.intervalSel.getValue();

            var endDate = Finder.Date.stringDBToDate (this.endDate.getValue());
            endDate.setMaxTime();

            var timeline_arr = this.issProvider.getTimeLine(endDate, this.periodSel.getValue());
            var timeline = timeline_arr[0].toCSString() + " - " + timeline_arr[1].toCSString();

            var lt=this.lineType.getValue();
            this.linetypeValue = lt;
            var template = this.template?this.template:"micextest";
            if (lt=="line") {
                    this.interval = this.issProvider.timeSpanToInterval(timeline_arr[1]-timeline_arr[0]);
                    this.intervalSel.controlElement.options[0] = new Option(
                            this.issProvider.allIntervals[this.issProvider.allIntervals.pluck("id").indexOf(this.interval)].title,
                            this.interval);
            }
            else
                    this.interval = intervalSel.getValue();
            this.interval = this.issProvider.verifyInterval(timeline_arr[0],timeline_arr[1],this.interval);


            var query = $H();
            query["secid"]          = secid;
            query["template"]       = template;
            query["trade_engine"]   = this.issProvider.trade_engine;
            query["market"]         = this.issProvider.market;
            query["linetype"]       = lt;
            if (this.issProvider.board_group_id)
        	query["board_group_id"] = this.issProvider.board_group_id;
    	    else
	    	query["boardid"] = this.issProvider.boardid;
            query["rnd"]            = (new Date()).getTime();
            query["interval"]       = this.interval;
            query["timeline"]       = timeline;
            query["period"]         = this.periodSel.getValue();

            if (this.tickerComparator && this.tickerComparator.getValue()!="") {

                    var board2id = this.comparatorBoard.data [
                                    this.comparatorBoard.data.pluck("id").indexOf (this.comparatorBoard.getValue())
                                  ].name;

                    var board_group_id2 =this.comparatorBoard.data [
                                    this.comparatorBoard.data.pluck("id").indexOf (this.comparatorBoard.getValue())
                                  ].board_group_id;

                    query["secid2"] = this.tickerComparator.getValue();
                    query["boardid2"] = board2id;


                    this.loadMarket2(board_group_id2,query);

            }
            else
                this._draw(query);

	},

        _draw: function(query){
            if (this.indicatorsList)
                    for (var i=0;i<this.indicatorsList.list.length;i++) {
                            query["ind"+(i+1)] = this.indicatorsList.list[i].definition.id.strip();
                            query["ind"+(i+1)+'_color1'] = this.indicatorsList.list[i].color['1'];
			    try {
                            if (this.indicatorsList.coloredIndicators.indexOf(this.indicatorsList.list[i].definition.id.strip()) != -1 )
                        	query["ind"+(i+1)+'_color2'] = this.indicatorsList.list[i].color['2'];

			    }catch(e) {alert(e);}
                            for (var j=0; j<this.indicatorsList.list[i].definition.params.length;j++) {
                                    query["ind"+(i+1)+"_"+j+"_c"] = this.indicatorsList.list[i].params[j].code.strip();
                                    query["ind"+(i+1)+"_"+j+"_v"] = this.indicatorsList.list[i].params[j].object.getValue();
                            }
                    }

                    if (this.chartShield) this.chartShield.show();

                    this.graph.hasData=true;
            this.onBeforeQuery(query);
            if (LC_LANG)
        	query["lang"] = LC_LANG;
            //this.graph.src="/marketdata/analysis/chart_data?" + query.toQueryString();
            //this.graph.src="/marketdata/analysis/chart_preview?" + query.toQueryString();
            this.graph.src="/cs_compat?" + query.toQueryString();
            this.last_query = query;
            this.graph.show();
            if(!this.graphOnloadListener && this.controls.onLoad)
                Event.observe($(this.graph),'load', (this.graphOnloadListener=function(e){
                    this.controls.onLoad();
                }.bind(this)));
        },

	prepareInfo: function() {


    	if (this.values[3].length == 0) {
    		this.onNoData();
    		return;
    	}

        this.chartLines.invoke("remove");
        this.chartLines = [];
		this.info=null;
		this.hInfo=$H();

    	if (this.previsionLineType != this.linetypeValue) {
    	   	this.previsionLineType = this.linetypeValue;

    	   this.info_headers.immediateDescendants().invoke("remove");
           this.info_data.immediateDescendants().invoke("remove");

    	   for (var i=0; i<this.values[3].length; i++) {
        		var key = i+"_"+this.values[3][i].type;

                var fD = this.valueTable.find(function(item) {return item.key==this}.bind(key));
                var cells=[];
    		    if (fD) cells = fD.values;
    		    cells.each (function(item) {
                    var th = Element.extend (document.createElement("th"));
                    this.info_headers.appendChild(th);
                    th.update("<nobr>"+item.title+"</nobr>");
                }.bind (this)
                );
            };

            var newStyle = $H();
            newStyle['width'] = (80.0/(this.info_headers.immediateDescendants().length+2))+"%";
            this.info_headers.immediateDescendants().invoke("setStyle", newStyle);

            var th = Element.extend (document.createElement("th"));
            this.info_headers.appendChild(th);
            th.update((LC_LANG=='ru')?"<nobr>Дата/Время</nobr>":"<nobr>Date/Time</nobr>");

            var th = Element.extend (document.createElement("th"));
            this.info_headers.appendChild(th);
            th.update((LC_LANG=='ru')?"<nobr>Шаг</nobr>":"<nobr>Step</nobr>");
        }

    	this.posInd=$A();
    	this.values[2].each( function(item) {
    		var ind = {};
    		ind.top = item[1];
    		ind.bottom = item[3];
    		this.posInd[this.posInd.length] = ind;
    	}.bind(this));

    	var itemsPerPoint=0;

    	switch (this.values[3][0].type) {
    		case "line": {itemsPerPoint=4; break;}
    		case "stockbar":
    		case "candle": {itemsPerPoint=7; break;}
    	}

    	var pointCount = this.values[3][0].data.length/itemsPerPoint;
    	this.info=[];

    	for (var i=0;i<pointCount;i++) {

    		var item={};
    		item.x = this.values[3][0].data[(i+1)*itemsPerPoint-3];
    		item.ts = this.values[3][0].data[(i+1)*itemsPerPoint-2];
    		item.ts_end = this.values[3][0].data[(i+1)*itemsPerPoint-1];
    		item.data=[];
    		if (item.x>this.values[2][0][2]) {pointCount--; continue;};
    		this.info[this.info.length] = item;

    		this.hInfo[item.x] = item;
    	};

    	this.values[3].each (function(item) {

    		var itemsPerPoint=0;
    	   	switch (item.type) {
    			case "line": {itemsPerPoint=4; break;}
    			case "bar": {itemsPerPoint=4; break;}
    			case "stockbar":
    			case "candle": {itemsPerPoint=7; break;}
    		}
    		var pointCount = this.info.length;

    		for (var i=0;i<pointCount;i++) {
    			var data=[];
    			for (var j=0;j<itemsPerPoint-3;j++)
    				data[data.length] = item.data[i*itemsPerPoint+j];
    			this.info[i].data[this.info[i].data.length] = data;
    		}

    	}.bind(this));

        this.posInd.each (function(item) {
            var div = Builder.node("span");
            $(this.graph.up()).appendChild(div);

            $(div).setStyle({
                position: 'absolute',
                margin: 0,
                padding:0,
                height: (item.bottom-item.top)+'px',
                'border-left': '1px solid #6f6f6f',
                top: item.top+'px',
                display: 'none'
            });
            this.chartLines[this.chartLines.length] = $(div);

        }.bind (this));

        this.xCoords = this.info.pluck("x");
        this.paintLine();
        this.info_headers.up().up().show();

        if (this.info && this.info[0]) {
			var firstDate = new Date(this.info[0].ts*1000);
			var year = firstDate.getYear();
			if (year < 1900) year += 1900;

			if ((year <= 1997) && (this.onDenominationWarning))
				this.onDenominationWarning();
		}
    },

	loadValues: function() {

		if (this.values != undefined) return;

		new Ajax.Request("/cs_compat.json", {
			parameters: this.last_query,
			method: "get",
			onSuccess: function(transport) {
				try {
					this.graph.hasData = false;
					this.values = transport.responseText.evalJSON();
                    			this.prepareInfo();
				}
				catch (e) {
				    if (!this.values_failure)
				    {
					this.values_failure = true;
					this.loadValues();
				    }
				}
			}.bind (this)
		});
	},



	paintLine: function (info) {
		if (!info) info = this.info[this.info.length-1];

		var xPos = info.x;
		var newPos = xPos + "px";

		var lCnt = this.chartLines.length;

		for (var i=0; i< lCnt; i++){
        	$(this.chartLines[i]).setStyle({left:newPos});
        	$(this.chartLines[i]).show();
        }

        if (this.infoWriterExecutor)
        	this.infoWriterExecutor.stop();

        this.infoWriterExecutor = new PeriodicalExecuter (
        	function (pe) {
        		pe.stop();
        		this.infoWriterExecutor=undefined;
        		this.writeInfo(pe.info);

        	}
        	.bind (this),
        	0.1
        )
        this.infoWriterExecutor.info = info;
        this.currentInfo = info;
	},

	intervalToTimeSpan: function (interval) {

	   switch (interval) {
	       case "1":  return "1m";
	       case "10": return "10m";
	       case "60": return "1h";
	       case "24": return "1d";
	       case "7":  return "7d";
	       case "31": return "1M";
	       case "4":  return "3M";
	       default: return "";
	   }

	},

	writeInfo: function (info) {

		if (!info) info = this.info[this.info.length-1];
		if (!this.values || !this.values[3]) return;
		var xPos = info.x;

		this.currentInfo = info;

		var isFirst=(this.info_data.immediateDescendants().length>0)?false:true;
		var tCells = this.info_data.immediateDescendants();
		tCells.current=0;

		for (var i=0; i<this.values[3].length; i++) {
    		var key = i+"_"+this.values[3][i].type;

    		var fD = this.valueTable.find(function(item) {return item.key==this}.bind(key));
	    	var cells=[];
        	if (fD) cells = fD.values;
    		var cellCnt = cells.length;
    		var cInfo = info.data[i];

    		for (var j=0; j<cellCnt; j++) {
    			var tCell = tCells[tCells.current];

    			if (tCell == undefined) {
    				tCell = Element.extend (document.createElement("td"));
    				tCells[cells.current] = tCell;
    				this.info_data.appendChild(tCell);
    			}

    			var value = new Number(cInfo[cells[j].id]);
    			if (value>1e12)
    				tCell.innerHTML = "<nobr>"+(value/1e12).toSiteString(this.pricePrecision)+((LC_LANG=='ru')?" трлн":" trl"+"</nobr>");
    			else if (value>1e9)
    				tCell.innerHTML = "<nobr>"+(value/1e9).toSiteString(this.pricePrecision)+((LC_LANG=='ru')?" млрд":" bln"+"</nobr>");
    			else if (value>1e6)
    				tCell.innerHTML = "<nobr>"+(value/1e6).toSiteString(this.pricePrecision)+((LC_LANG=='ru')?" млн":" mln"+"</nobr>");
    			else
    				tCell.innerHTML = "<nobr>"+value.toSiteString(this.pricePrecision)+"</nobr>";
    			tCells.current++;
    		}
	   };

    	if (isFirst) {
    		var td = Element.extend (document.createElement("td"));
    		this.info_data.appendChild(td);
    		tCells[tCells.current] = td;

    		var td = Element.extend (document.createElement("td"));
    		this.info_data.appendChild(td);
    		tCells[tCells.current+1] = td;

    		this.info_data.immediateDescendants()[0].setStyle({"border-left": "0"});
    	}

    	var dateString =
    		(this.interval==24 || this.interval==7 || this.interval==31 || this.interval==4)?
    		(new Date(info.ts_end*1000)).toSiteDateString({year: true}):
    		(
    		 (this.interval==1)?
    		 (new Date(info.ts_end*1000+1000)).toSiteString({"year": true, "hours": true,"minutes": true,"seconds":true}):
    		 (new Date(info.ts_end*1000+1000)).toSiteString({"year": true, "hours": true,"minutes": true,"seconds":false})
    		);

    	tCells[tCells.current].innerHTML = "<nobr>"+dateString+"</nobr>";

    	var intervalString = this.issProvider.allIntervals[this.issProvider.allIntervals.pluck("id").indexOf(this.interval)].title;
    	tCells[tCells.current+1].innerHTML = "<nobr>"+intervalString+"</nobr>";


	}

});

MxChart.Interface.BeginDateElement = Class.create();
Object.extend (MxChart.Interface.BeginDateElement.prototype, Finder.DateElement.prototype);
Object.extend (MxChart.Interface.BeginDateElement.prototype, {

	update_in: function() {
		var conf = this.parentElement.getValue();
		//this.show();
		if (conf["issProvider"]) {
			this.disable();
			if (conf["period"] != "all") {
				var newDate = Finder.Date.stringDBToDate(conf["enddate"]);
				newDate.setMaxTime();
				newDate.addTimeSpanString(conf["period"]);
				this.setValue (newDate.toSiteDateString());
				Finder.DateElement.prototype.update_in.apply(this, arguments);
			}
			else {
				this.setValue(conf["issProvider"].firstTime.toSiteDateString());
			}
			//this.show();
			this.controlElement.disable();
		}
		else {
			Finder.DateElement.prototype.update_in.apply(this, arguments);
			//this.hide();
		}
		this.show();
	},

	activate_in: function() {
		Finder.DateElement.prototype.activate_in.apply(this, arguments);
		this.show();
	}

});

MxChart.Interface.EndDateElement = Class.create();
Object.extend(MxChart.Interface.EndDateElement.prototype, Finder.AjaxElement.prototype);
Object.extend(MxChart.Interface.EndDateElement.prototype, Finder.DateElement.prototype);
Object.extend(MxChart.Interface.EndDateElement.prototype, {

	enabledFlag: true,

	initialize: function () {
		Finder.Element.prototype.initialize.apply(this, arguments);
		Finder.AjaxElement.prototype.initialize.apply(this, arguments);
		Finder.DateElement.prototype.initialize.apply(this, arguments);
		this.childElements=$A();
	},

	setControlState: function() {
		var conf = this.parentElement.getValue();
		(conf["issProvider"])?this.show():this.hide();
		(conf["linetype"]=="line")?this.enable():this.disable();
		//if (periodSel.getValue()=="all") {
			//alert (conf["issProvider"].lastTime.toSiteString());
			//this.setValue (conf["issProvider"].lastTime.toSiteString({year: true}));
		//}

		if (!this.manualSelected && conf["issProvider"]) {
		    //alert (conf["issProvider"].lastTime.toSiteString({year: true}));
		    this.setValue (conf["issProvider"].lastTime.toSiteString({year: true}));
		}
	},

	activate_in: function() {
		Finder.DateElement.prototype.activate_in.apply(this, arguments);
		this.setControlState();
	},

	update_in: function() {
		Finder.DateElement.prototype.update_in.apply(this, arguments);
		this.setControlState();
	},

	enable: function() {
		this.enabledFlag = true;
		if (this.enabledFlag && !this.lockOnAll)
			Finder.DateElement.prototype.enable.apply(this, arguments);
	},

	disable: function() {
		this.enabledFlag = false;
		Finder.DateElement.prototype.disable.apply(this, arguments);
	},

	allLock: function() {
		this.lockOnAll = true;
		Finder.DateElement.prototype.disable.apply(this, arguments);
	},

	allRelease: function() {
		this.lockOnAll = false;
		if (this.enabledFlag && !this.lockOnAll)
			Finder.DateElement.prototype.enable.apply(this, arguments);
	},

	onChange: function (e) {
		this.manualSelected = true;
		Finder.DateElement.prototype.onChange.apply(this, arguments);
	}

});

MxChart.Interface.IntervalSelector = Class.create();
Object.extend (MxChart.Interface.IntervalSelector.prototype, Finder.SelectElement.prototype);
Object.extend (MxChart.Interface.IntervalSelector.prototype, {

	updateData: function () {

		if (this.parentElement.getValue()["linetype"] == "line")
			this.data=[];
		else{
			this.show();

			if (!this.parentElement.controls[0].control.initialized) return;

			var newData = $A();
			newData = this.parentElement.controls[0].control.allIntervals.findAll(

			    function (item) {
			        return this.parentElement.controls[0].control.getPeriodByInterval(item.id).length>0;
			    }
			    .bind(this)

			);
			this.data = newData;

		}
	},

	update_in: function () {
		this.updateData();

		Finder.SelectElement.prototype.update_in.apply(this, arguments);

		if (this.defaultId) {
			/*idx = this.data.indexOf(
				this.data.find (
					function (item) {
						return item.id == this.defaultId
					}.bind (this)));
			if (idx>=0)
				this.controlElement.selectedIndex = idx;*/

			this.setValue(this.defaultId);

			this.defaultId = undefined;
			Finder.SelectElement.prototype.update_after.apply(this, arguments);
		}

		(this.parentElement.getValue()["linetype"] == "line")?this.disable():this.enable();
	},

	activate_in: function () {
		this.updateData();
		Finder.SelectElement.prototype.activate_in.apply(this, arguments);
		(this.parentElement.getValue()["linetype"] == "line")?this.disable():this.enable();
	},

	disable: function() {
		this.controlElement.disable();
	},

	enable: function() {
		this.controlElement.enable();
	}

});

MxChart.Interface.PeriodSelector = Class.create();
Object.extend (MxChart.Interface.PeriodSelector.prototype, Finder.SelectElement.prototype);
Object.extend (MxChart.Interface.PeriodSelector.prototype, {

	initialize: function() {
		Finder.SelectElement.prototype.initialize.apply(this, arguments);
		Event.observe (this.controlElement, "change", this.clearValue.bind(this));
	},

	updateData: function () {
		if (this.parentElement.getValue()["linetype"] == "line")  {
			var endDate = Finder.Date.stringDBToDate(this.parentElement.getValue()["enddate"]);
			this.data = this.parentElement.controls[0].control.getAvaiblePeriods(endDate, true);

			var lastDate = this.parentElement.controls[0].control.getLastTime();
			if (
				(endDate.getDate() != lastDate.getDate()) ||
				(endDate.getMonth() != lastDate.getMonth()) ||
				(endDate.getYear() != lastDate.getYear())
				) {

				var tempDb = this.data;
				this.data=$A();
				tempDb.each (
					function (item) {
						if (item.id != "-1h")
							this.data.push(item);
					}.bind (this)
				);

			}
		}
		else
			this.data = this.parentElement.controls[0].control.getPeriodByInterval(this.parentElement.getValue()["interval"]);
	},

	update_in: function () {
		this.updateData();
		endDateSel.setControlState();
		Finder.SelectElement.prototype.update_in.apply(this, arguments);
	},

	activate_in: function () {

		this.updateData();
		Finder.SelectElement.prototype.activate_in.apply(this, arguments);
	},

	clearValue: function() {
		if (this.parentElement.getValue()["linetype"] == "line")
			if (this.parentElement.getControls()["interval"].controlElement.options.length>0)
				this.parentElement.getControls()["interval"].controlElement.options[0].remove();
	},

	setValue: function(value) {
		Finder.SelectElement.prototype.setValue.apply(this, arguments);
		if (this.getValue() == "all") {

			this.parentElement.getControls()["enddate"].setValue(Finder.Date.dateToString(this.parentElement.getControls()["issProvider"].getLastTime()));
			this.parentElement.getControls()["enddate"].allLock();

		}
		else
			this.parentElement.getControls()["enddate"].allRelease();


	}

});

MxChart.Interface.AjaxSelectElement = Class.create();
Object.extend(MxChart.Interface.AjaxSelectElement.prototype, Finder.SelectElement.prototype);
Object.extend(MxChart.Interface.AjaxSelectElement.prototype, Finder.AjaxElement.prototype);
Object.extend(MxChart.Interface.AjaxSelectElement.prototype, {
    initialize: function() {
        Finder.SelectElement.prototype.initialize.apply(this, arguments);
        Finder.AjaxElement.prototype.initialize.apply(this, arguments);
        this.onSuccess = this.onSuccess.bind(this);
        this.onFailure = this.onFailure.bind(this);
        this.hideIndicator();
    },

    activate_in: function() {
        if ($A(this.data).size()) Finder.SelectElement.prototype.activate_in.apply(this, arguments);
        else this.update_in();
    },

    update_in: function() {
        this.clear();
        this.load();
    },

    load: function() {
        if (this.parentElement.is_control_element && !this.parentElement.getValue()) return this.delegate(true);

        this.showIndicator();

        new Ajax.Request(this.options.url, {
            method: "get",
            parameters: this.parentElement.is_control_element ? this.parentElement.getParameters() : {},
            onSuccess: this.onSuccess,
            onFailure: this.onFailure
        });
    },

    onSuccess: function(transport) {
        this.hideIndicator();
        this.data = [];
        try {this.data = transport.responseText.evalJSON();} catch(e) {}
        if (!$A(this.data).size()) this.onNoData();
        this.delegate(!$A(this.data).size())
    },

    onNoData: function () {
    	alert ("NoDataFound");
    },

    onFailure: function(transport) {
        this.hideIndicator();
        alert (transport.responseText);
        alert('failure');
        this.delegate();
        this.lock();
    },

    delegate: function() {
        switch(this.transition) {
            case 'activate':
                Finder.SelectElement.prototype.activate_in.apply(this, arguments);
                break;
            case 'update':
                Finder.SelectElement.prototype.update_in.apply(this, arguments);
                break;
            default:
                alert('РќРµРёР·РІРµСЃС‚РЅРѕРµ СЃРѕСЃС‚РѕСЏРЅРёРµ РѕР±РЅРѕРІР»РµРЅРёСЏ "' + this.transition + '"!');
                throw 'РќРµРёР·РІРµСЃС‚РЅРѕРµ СЃРѕСЃС‚РѕСЏРЅРёРµ РѕР±РЅРѕРІР»РµРЅРёСЏ "' + this.transition + '"!';
        }
    }
});