Mx.EmitentNews=Class.create();
Mx.EmitentNews.prototype = {
	initialize: function(options){
		this.setOptions(options);
		this.emitent_news_o = new Mx.EmitentNewsLine(this.options.element_news,this.options.element_info)
		if(options.onStart){
			options.onStart.bind(this)();
		}
	},

	setOptions: function(options){
		this.options = $H({
			wrap_element:	$('emtent-info-news-list'),
			news_parent:	$('emtent-info-news'),
			element_news:	$('emitent-news-display'),
			element_info:	$('emitent-info-display'),
			element_warn:	undefined,

			params: {},

			url:			'/markets/stock/emitents_info/list_news_json',
			data_absent_message: '&mdash;',

			template_news:	'<p><i class="dt">%date%</i><br/><a rel="%id%" class="emitentNewsLine" href="%href%">%title%</a> %stitle%</p>',
			template_news_also:	'<p><a style="font-size:11px;color:black;" rel="emitent_all_news" href="#" >Все новости эмитента</a></p>',

			news_limit:		3,
			unlimited:		false
		}).merge(options);
	},

	_display_news: function(json){
		if (!json || json.length <= 0 || !json[0]){
			this._show_no_data();
			return ;
		}
		var ret = '';
		for(var i=0, c=json.length; i<c && (i<this.options.news_limit || this.options.unlimited); i++){
			var nhref = '#'; var stitle = ''; var hid = json[i].id

			if (json[i].files.length > 0){
				var f = json[i].files[0]
				nhref = '/file/'+f.id+'/'+f.name;
				stitle = '<span class="file-info">' + f.icon_name + ' ' +f.size+'</span>';
				hid = '#';
			}

			ret += this.options.template_news.replace('%date%',json[i].published_at).replace('%title%',json[i].title).replace('%href%',nhref).replace('%stitle%',stitle).replace('%id%',hid);
		}

		if (json.length > this.options.news_limit && !this.options.unlimited){
			ret += this.options.template_news_also;
		}

		this.options.wrap_element.innerHTML = ret;
		this.options.news_parent.show();

		if (json.length > this.options.news_limit && !this.options.unlimited){
			this.onClickAllNewsListener = this.onClickAllNewsListener || this.onClickAllNews.bindAsEventListener(this);
			$$('a[rel="emitent_all_news"]').invoke('observe', 'click', this.onClickAllNewsListener);
		}

		this.onClickListener = this.onClickListener || this.onClick.bindAsEventListener(this);
		$$('a.emitentNewsLine:not([rel="#"])').invoke('observe', 'click', this.onClickListener);

		this._revertNormalDisplay();
	},

	_revertNormalDisplay: function(){
		this.options.element_news.hide();
		this.options.element_info.show();
		if (this.options.element_warn){ $(this.options.element_warn).hide(); }
	},

	_show_no_data: function(){
		if (this.options.element_warn){
			$(this.options.element_warn).show();
		}
		else{
			this.options.wrap_element.innerHTML = this.options.data_absent_message;
		}

		this.options.news_parent.hide();
		this.options.element_news.hide();
	},

	_get_data: function(){
		new Ajax.Request(this.options.url, {
			method: 'get',
			asynchronous: true,
			parameters: this.options.params,
			onComplete: function(transport,json){
				try{
					if(!json){json = transport.responseText.evalJSON(false);}
					if(!json) throw 'Errors evaluating json';
				}catch(e){/*alert('_get_data: '+e);*/}
				this._display_news(json);
			}.bind(this),
			onFailure: function(transport,json){this._show_no_data()}.bind(this)
		});
	},

	run: function(emitent_id){
		if (this.id && this.id != emitent_id){
			this.options.unlimited = false;
		}

		this.id = emitent_id;

		this.options.params.emitent_id	= this.id;
		this.options.params.unlimited	= this.options.unlimited

		this._stopObserve();
		this._get_data();
	},

	runWPage: function(page){
		if (!page){ page = 1; }
		try{
			this.options.params.start = this.options.params.limit*(page-1)
		}
		catch(e){this.options.params.start = 0;}
		this._stopObserve();
		this._get_data();
	},

	onClick: function(e){
		if (Event.element(e).getAttribute('href').match(/#$/)){
			Event.stop(e);
			this.emitent_news_o.run(Event.element(e).getAttribute('rel'));
		}
	},

	onClickAllNews: function(e){
		Event.stop(e);
		this.options.unlimited = true;
		this.run(this.id);
	},

	_stopObserve: function(){
		if (this.onClickListener)
			$$('a.emitentNewsLine:not([rel="#"])').invoke('stopObserving', 'click', this.onClickListener);
		if (this.onClickAllNewsListener)
			$$('a[rel="emitent_all_news"]').invoke('stopObserving', 'click', this.onClickAllNewsListener);
	}
}

Mx.EmitentNewsLine=Class.create();
Mx.EmitentNewsLine.prototype = {
	tmpl_return: '<p style="%style%"><a class="emitent-news-display-revert" href="#">Вернуться</a></p>',
	revertIds: 'a.emitent-news-display-revert',

	initialize: function(element_news,element_info){
		this.element_news = element_news;
		this.element_info = element_info;

		this.setOptions({})
	},

	setOptions: function(options){
		this.options = $H({
			url:	'/markets/stock/emitents_info/list_news_full_json'
		}).merge(options);
	},

	_showNewsLine: function(){
		new Ajax.Request(this.options.url, {
			method: 'get',
			asynchronous: true,
			parameters: {'id' : this.id},
			onComplete: function(transport,json){
				try{
					if(!json){json = transport.responseText.evalJSON(false);}
					if(!json) throw 'Errors evaluating json';
				}catch(e){alert('_showNewsLine: '+e);}
				this._displayNewsLine(json);
			}.bind(this),
			onFailure: function(transport,json){
				this._displayNewsLineNoData()
			}.bind(this)
		});
	},

	_displayNewsLine: function(json){
		this.element_news.innerHTML =
			this.tmpl_return.replace('%style%','text-align:right; margin-bottom:0')
			+ '<i>' + json['date'] + '</i>'
			+ '<h3 style="margin-right:100px;">'+json['title']+'</h3>'
			+ json.body.replace(/\n/g,'<br/>')
			+ this.tmpl_return.replace('%style%','')

		this._normalDisplay(1);
		this._startObserve();
	},

	onClickReturn: function(e){
		Event.stop(e);
		this._normalDisplay();
		this._stopObserve()
	},

	_displayNewsLineNoData: function(){alert('Ошибка при получении полного текста статьи.\nПопробуйте еще раз, или обратитесь к администрации сайта.');},

	_displayNewsLineElements: function(){

	},

	_normalDisplay: function(show){
		if (show && show == 1){
			this.element_news.show();
			this.element_info.hide();
		}
		else{
			this.element_news.hide();
			this.element_info.show();
		}
	},

	_startObserve: function(){
		this.onClickReturnListener = this.onClickReturnListener || this.onClickReturn.bindAsEventListener(this);
		$$(this.revertIds).invoke('observe','click',this.onClickReturnListener);
	},

	_stopObserve: function(){
		if(this.onClickReturnListener){
			$$(this.revertIds).invoke('stopObserving', 'click', this.onClickReturnListener);
		}
	},

	run: function(news_id){
		this.id = news_id;
		this._showNewsLine();
	}
}

