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": "s1_line", values: [ {"id": 0, "title": (LC_LANG=='ru'?"Цена":"Price")}]},
    	{"key": "s1_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": "s1_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": "s2_bar", values: [ {"id": 0, "title": (LC_LANG=='ru'?"Объем":"Volume")}]},
        {"key": "yields.s1_line", values: [ {"id": 0, "title": (LC_LANG=='ru'?"Доходность":"Yield")}]},        
        ],

	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.interval == "24") || 
		 (this.interval == "7") || 
		 (this.interval == "31") || 
		 (this.interval == "4"))
	    {
                if (this.yields)
	           query["yields"] = 1;
	    }
		
            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.interval != this.previousInterval) ) {
    	   
    	   this.previsionLineType = this.linetypeValue;
    	   this.previousInterval  = this.interval;

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

    	   for (var i=0; i<this.values[3].length; i++) {
        	var key = this.values[3][i].id+"_"+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;
    		var pointIdx=0;

    		for (var i=0;i<pointCount;i++) {
    		    var data=[];
    		    var ts=item.data[(pointIdx+1)*itemsPerPoint-2]
    			
    		    if (ts<=this.info[i].ts)
    		    {
    			for (var j=0;j<itemsPerPoint-3;j++)
    			    data[data.length] = item.data[pointIdx*itemsPerPoint+j];
    			pointIdx++;
    		    }
    		    else
    		    {
    		    	for (var j=0;j<itemsPerPoint-3;j++)
    			    data[data.length] = "0";
    		    }

    		    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 = this.values[3][i].id+"_"+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 dt = new Date();
    	var dateString = "";
    	if ( (this.interval==24) || (this.interval==7) || (this.interval==31) || (this.interval==4))
    	{
    	    dt.setTime(info.ts_end*1000+3600*4000);
    	    dateString = dt.getUTCDate().toPaddedString(2) + "." + (dt.getUTCMonth()+1).toPaddedString(2) + "." + dt.getUTCFullYear();
    	}
    	else
    	{
    	    dt.setTime(info.ts_end*1000+1000+3600*4000);
    	    if (this.interval==1)
    		dateString = dt.getUTCDate().toPaddedString(2) + "." + (dt.getUTCMonth()+1).toPaddedString(2) + "." + dt.getUTCFullYear() + " " + dt.getUTCHours().toPaddedString(2) + ":" + dt.getUTCMinutes().toPaddedString(2) + ":" + dt.getUTCSeconds().toPaddedString(2);
    	    else
    		dateString = dt.getUTCDate().toPaddedString(2) + "." + (dt.getUTCMonth()+1).toPaddedString(2) + "." + dt.getUTCFullYear() + " " + dt.getUTCHours().toPaddedString(2) + ":" + dt.getUTCMinutes().toPaddedString(2);
    	    
    	}

    	/*var dateString =
    		(this.interval==24 || this.interval==7 || this.interval==31 || this.interval==4)?
    		    dt.toSiteDateString({year: true}):
    		(
    		 (this.interval==1)?
    		 dt.toSiteString({"year": true, "hours": true,"minutes": true,"seconds":true}):
    		 dt.toSiteString({"year": true, "hours": true,"minutes": true,"seconds":false})
    		);/

/*    	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 + '"!';
        }
    }
});
