$_CONTEXT_PATH = '';

Prototype.Browser.IE6 = Prototype.Browser.IE && parseInt(navigator.userAgent.substring(navigator.userAgent.indexOf("MSIE")+5)) == 6;

if (typeof tinyMCE == 'object') {

	var defaultTinyMCE = {
	
		mode : "specific_textareas",
		editor_selector:	"rich_editor",
		theme : "advanced",
		skin:	"o2k7",
		skin_variant : "silver",
		language : "ru",
		
		height: "300",
		width:	"100%",
		
		plugins : "safari,emotions,media,contextmenu,paste,noneditable,pagebreak,xhtmlxtras,fullscreen",
		
		theme_advanced_buttons1 : "undo,redo,|,bold,italic,underline,strikethrough,|,bullist,numlist,|,justifyleft,justifycenter,justifyright,|,outdent,indent,|,forecolor,backcolor,|,link,unlink,image,|charmap,emotions,hr,|,fullscreen,code",
		theme_advanced_buttons2 : "",
		theme_advanced_buttons3 : "",
		theme_advanced_toolbar_location : "top",
		theme_advanced_toolbar_align : "left",
		
		pagebreak_separator :"<cut>",
	    theme_advanced_statusbar_location : "bottom",
	    theme_advanced_resizing : true,
	    theme_advanced_resize_horizontal : 0,
	    theme_advanced_resizing_use_cookie : 0,
	    theme_advanced_path : false,
	    object_resizing : true,
	    fix_nesting : true,
		relative_urls : false,
		valid_elements : "*[*]",
		cleanup : true,
		verify_html : true,
		cleanup_on_startup : true,
		
		strict_loading_mode: tinymce.isWebKit,
		
		content_css : $_CONTEXT_PATH + "styles/fclm3/theme/live_styles/default.css"
	
	}, enhancedTinyMCE = {};
	
	for (var i in defaultTinyMCE) {
	
		enhancedTinyMCE[i] = defaultTinyMCE[i];
	
	}
	
	enhancedTinyMCE.editor_selector = "rich_editor_enh";
	
	enhancedTinyMCE.theme_advanced_buttons1 = "undo,redo,|,bold,italic,underline,strikethrough,|,bullist,numlist,|,justifyleft,justifycenter,justifyright,|,outdent,indent,|,forecolor,backcolor,|,link,unlink,image,|charmap,emotions,hr,|,media,pagebreak,|,fullscreen,code"

	tinyMCE.init(enhancedTinyMCE);
	
	tinyMCE.init(defaultTinyMCE);

}

var SimpleFormValidator = Class.create({

	initialize:	function(options) {
	
		if (!(this._element = $(options['element'])) || $(options['element']).hasClassName('validator_initiated')) return false;
		
		$(options['element']).addClassName('validator_initiated')
		
		this._onSubmit = this._submit.bindAsEventListener(this);
		
		this._onCancel = this._cancel.bindAsEventListener(this);
		
		this._cancelBtn = this._element.down('.cancel');
		
		this._submitBtn = this._element.down('.submit');
		
		if (this._submitBtn) {
		
			this._submitBtn.value = $_LOCALE['action_save'];
			
			this._submitBtn.innerHTML = $_LOCALE['action_save'];
			
		}
		
		this._submitBtn.observe('click', this._onSubmit);
		
		this._cancelBtn.observe('click', this._onCancel);
		
		if (!(this._alert = this._element.down('.error_alert'))) {
		
			this._alert = new Element('span', {'class': 'error_alert'});
			
			if (this._submitBtn.up('.btn')) {
			
				this._submitBtn.up('.btn').insert({ before: this._alert.hide() });
			
			} else {
			
				this._submitBtn.insert({ before: this._alert.hide() });
			
			}			
		
		}
		
		return this;
	
	},
	
	_destroy:	function() {
	
		this._submitBtn.stopObserving('click', this._onSubmit);
		
		this._cancelBtn.stopObserving('click', this._onCancel);
		
		this._element.remove();
	
	},
	
	_submit:	function(event) {
	
		this._required = this._element.select('.required input', '.required textarea');
		
		this._required.each(function(field) {
		
			field.value = field.value.gsub(/<p>([\s\t\n\r]|&nbsp;)+<\/p>/,'');
		
		});
		
		event.stop();
		
		var numErrors = 0;
		
		this._alert.update();
		
		var emptyFields = this._required.findAll(function(field) {
		
			var relField = $(field.readAttribute('rel'));
			
			if (relField) {
			
				if (!field.value && !!relField.value) {
				
					return true;
				
				}
			
			} else {
			
				return field.value.blank();
			
			}
		
		});
		
		if (emptyFields.length) {
			
			numErrors++;
		
			emptyFields.each(function(field) {
			
				if (field.readAttribute('value_holder')) {
				
					new Effect.Highlight($(field.readAttribute('value_holder')), { startcolor: '#ff9999', restorecolor: '#ffffff', duration: 3 });
				
				} else {
				
					new Effect.Highlight(field, { startcolor: '#ff9999', restorecolor: '#ffffff', duration: 3 });
				
				}
			
			});
			
			this._alert.insert($_LOCALE['error_empty_fields']).show();
		
		}
		
		this._element.getElements().find(function(field) {
		
			if ((field.tagName.toLowerCase() == 'input' || field.tagName.toLowerCase() == 'textarea') && field.value.length > 65000) {
			
				this._alert.insert($_LOCALE['error_length_fields']).show();
			
				new Effect.Highlight(field, { startcolor: '#ff9999', restorecolor: '#ffffff', duration: 3 });
				
				numErrors++;
				
				return true;
				
			} else {
			
				return false;
			
			}
		
		},this);
		
		if (!numErrors) {
			
			if (this._submitBtn && this._submitBtn.value == $_LOCALE['action_save']) {
			
				this._submitBtn.disabled = true;
				
				this._submitBtn.value = $_LOCALE['action_wait'];
				
				this._submitBtn.innerHTML = $_LOCALE['action_wait'];
				
				this._element.select('.notags').each(function(field) {
						
					field.value = field.value.stripTags();
				
				});
				
				if (this.didSubmit) this.didSubmit();
				
				this._element.submit();
			
			}
		
		} else {
		
			if (this._submitBtn) {
			
				this._submitBtn.disabled = false;
				
				this._submitBtn.value = $_LOCALE['action_save'];
				
				this._submitBtn.innerHTML = $_LOCALE['action_save'];
			
			}
			
			Element.hide.delay(5,this._alert);
		
		}
		
	},
	
	_cancel:	function(event) {
	
		if (this._submitBtn) {
		
			this._submitBtn.disabled = false;
		
			this._submitBtn.value = $_LOCALE['action_save'];
			
			this._submitBtn.innerHTML = $_LOCALE['action_save'];
			
		}
	
		document.back();
	
	}

});

var CreateWhatever = Class.create(SimpleFormValidator, {
	
	_submit:	function($super,event) {
	
		event.stop();
	
		if (this._element.down('.rich_editor') || this._element.down('.rich_editor_enh')) {
		
			var editor = tinyMCE.get(this._element.down('textarea').id);
		
			editor.save();
		
		}
		
		this._element.getElements().each(function(field) {
		
			if (field.tagName.toLowerCase() == 'input' && field.readAttribute('type') != 'hidden' && field.readAttribute('type') != 'file' ||
			
				field.tagName.toLowerCase() == 'textarea') {
				
				field.value = field.value.stripScripts();
				
			}
		
		});
		
		$super(event);
		
	},
	
	_cancel:	function() {
	
		if (tinyMCE.activeEditor) {
		
			tinyMCE.activeEditor.setContent('');
		
		}
		
		this._element.reset();

		if (this._submitBtn) {
		
			this._submitBtn.value = $_LOCALE['action_save'];
			
			this._submitBtn.innerHTML = $_LOCALE['action_save'];
			
		}
	
	}

});

var ToggleView = Class.create({

	initialize:	function(options) {
	
		if (!(this._element = $(options['element'])) || ($(options['element']).hasClassName('toggeler_initiated'))) return false
		
		$(options['element']).addClassName('toggeler_initiated');
		
		this._onShow = this._show.bindAsEventListener(this);
	
		this._onToggle = this._toggle.bindAsEventListener(this);
		
		this._onKeyPress = this._keypress.bindAsEventListener(this);
		
		if (!this._element.hasClassName('nontoggle')) {
		
			this._element.select('.toggeler button').invoke('observe', 'click', this._onToggle);
			
			this._element.select('.cancel').invoke('observe', 'click', this._onToggle);
		
		} else {
		
			this._element.addClassName('is_active');
			
			this._element.select('.close').invoke('hide');
		}
		
		document.observe('toggle_view:show',this._onShow);
		
		return this;
	
	},
	
	toggled:	function() {
	
		return this._element.hasClassName('is_active');
	
	},
	
	_show:		function(event) {
	
		if (!this.toggled()) {
		
			this._toggle(event);
		
		}
	
	},
	
	_toggle:	function(event) {
	
		if (this.toggled()) {
		
			this._element.removeClassName('is_active').down('.toggeled').hide();
			
			this._element.down('.toggeler button').observe('click',this._onToggle).blur();
			
			this._element.down('.toggeler .close').stopObserving('click',this._onToggle);
			
			document.stopObserving('keyup',this._onKeyPress);
		
		} else {
		
			Element.show(this._element.addClassName('is_active').down('.toggeled'));
			
			this._element.down('.toggeler .close').observe('click',this._onToggle).blur();
			
			this._element.down('.toggeler button').stopObserving('click',this._onToggle);
			
			document.observe('keyup',this._onKeyPress);
		
		}	
		
		if (event) {
		
			event.stop();
		
		}
	
	},
	
	_keypress:	function(event) {
	
		var keycode = event.keyCode ? event.keyCode : event.which ? event.which : event.charCode;
		
		if (keycode == 27) {
		
			this._toggle(event)
		
		} else {
		
			return true;
		
		}
		
		event.stop();
	
	}

});

var DateSelect = Class.create({

	initialize: function(options) {
	
		if (!(this._element = $(options['element']))) return false;
		
		this._calendar = Calendar.setup({
		
			dateField:		this._element.down('input'),
			
			triggerElement:	this._element,
			
			selectHandler:	this._select.bind(this),
			
			selectablePeriod:	'past'
		
		});
		
		return this;
	
	},
	
	_select: function(obj) {
	
		var month = obj.date.getMonth() + 1;
		
		document.location = this._element.readAttribute('title') + '/' +
		
					obj.date.getFullYear() + '-' +
	
					(month < 10 ? '0' + month : month) + '-' +
	
					(obj.date.getDate() < 10 ? '0' + obj.date.getDate() : obj.date.getDate());
	
	}

});

var TabView = Class.create({

	initialize:	function(options) {
	
		if (!(this._element = $(options['element']))) return false;
		
		this._selected = null;
		
		this._thumbs = this._element.down('.tabview_thumbs').childElements();
		
		this._bodies = this._element.down('.tabview_bodies').childElements().invoke('hide');
		
		this._thumbs.each(function(thumb,index) {
		
			thumb.index = index;
			
			if (thumb.hasClassName('selected')) {
			
				this._selected = thumb;
			
			}
		
		});
		
		this._onToggle = this._toggle.bindAsEventListener(this);
		
		this._thumbs.invoke('observe','click',this._onToggle);
		
		if (this._selected) {
		
			this._select(this._selected);
		
		} else {
		
			this._select(this._thumbs[0]);		
		
		}
		
		return this;
	
	},
	
	_toggle:	function(event) {
	
		if (this._selected == event.findElement('li')) return;
	
		this._deselect(this._selected);
		
		this._select(event.findElement('li'));
	
	},
	
	_select:	function(obj) {
	
		this._selected = obj;
		
		if (!this._selected.hasClassName('selected')) {
		
			this._selected.addClassName('selected');
		
		}
		
		this._bodies[this._selected.index].show();
	
	},
	
	_deselect:	function(obj) {
	
		this._selected.removeClassName('selected');
		
		this._bodies[this._selected.index].hide();
	
	}

});

var FullScreenView = Class.create({

	initialize:		function(options) {
	
		this._delegate = options['delegate'] || null;
	
		this._element = new Element('div', {'class': 'fullscreen_view'}).hide()
		
			.insert(new Element('div', {'class': 'fullscreen_dimmer'}))
			
			.insert(new Element('div', {'class': 'fullscreen_viewer'})
				
				    .insert(new Element('div',{'class': 'fullscreen_title'}))
				
		    		.insert(new Element('img', {'src': '', 'class': 'fullscreen_image', 'title': 'Следующее'}))
		    		
		    		.insert(new Element('div',{'class': 'fullscreen_tags'}))
		
		    		.insert(new Element('a', {'href': '#', 'class': 'prev', 'title': $_LOCALE['title_prev_photo']}).update($_LOCALE['link_prev_photo']))
			
		    		.insert(new Element('a', {'href': '#', 'class': 'next', 'title': $_LOCALE['title_next_photo']}).update($_LOCALE['link_next_photo']))
		    		
		    		.insert(new Element('span', {'class': 'current_photo'}))
			
		    		.insert(new Element('a', {'href': '#', 'class': 'close', 'title': $_LOCALE['title_close']}))
			
			);
			
		$(document.body).insert(this._element);
		
		this._onClick = this._click.bindAsEventListener(this);
		
		this._onKeyPress = this._keypress.bindAsEventListener(this);
		
		this._element.observe('click',this._onClick);
	
	},
	
	destroy:	function() {
	
		this._element.remove();
	
	},
	
	update:		function(params) {
	
		this._element.down('.fullscreen_title').update();
		
		this._element.down('.fullscreen_tags').update();
	
		var img = new Element('img', {'src': params.src});
		
		var tries = 0;
		
		var template = new Template($_LOCALE['current_photo']);
		
		$(document.body).insert(img.hide());
		
		var updateImage = function() {
		
			this._element.down('.fullscreen_image').src = img.src;
			
			if (!!params.title) {
			
				this._element.down('.fullscreen_title').update(params.title).show();
			
			} else {
			
				this._element.down('.fullscreen_title').hide();
			
			}
			
			if (!!params.tags) {
			
				this._element.down('.fullscreen_tags').update(params.tags).show();
			
			} else {
			
				this._element.down('.fullscreen_tags').hide();
			
			}
			
			this._element.down('.current_photo').update(template.evaluate({current: params.current, total: params.total}));
			
			delete img;
			
			var size = img.getDimensions();
			
			var ratio = size.width / size.height;
			
			var viewport = document.viewport.getDimensions();
			
			var e_height = 100 + (!!params.title ? 15 : 0) + (!!params.tags ? 15 : 0);
			
			if (size.height > viewport.height - e_height) {
			
				size.height = viewport.height - e_height;
				
				size.width = size.height * ratio;
			
			}
			
			if (size.width > viewport.width - 40) {
			
				size.width = viewport.width - 40;
				
				size.height = size.width / ratio;
			
			}
			
			this._element.down('.fullscreen_image').setStyle({
			
				width:	size.width + 'px',
				
				height:	size.height + 'px'
			
			});
			
			this._element.down('.fullscreen_viewer').setStyle({
				
				top:	Prototype.Browser.IE6
				
					?	(15 + document.viewport.getHeight() / 2 - (size.height + e_height) / 2) + document.documentElement.scrollTop + 'px'
					
					:	(15 + document.viewport.getHeight() / 2 - (size.height + e_height) / 2) + 'px',
				
				left:	(document.viewport.getWidth() / 2 - (size.width + 40) / 2) + 'px',
				
				width:	size.width + 'px',
				
				height:	size.height + e_height - 80 + 'px'
				
			});
			
			this._show();
		
		}.bind(this);
		
		new PeriodicalExecuter(function(pe) {
			
			if (img.getWidth() > 100 || tries > 40) {
				
				pe.stop();
				
				updateImage();
			
			}
			
			tries++;
		
		}.bind(this), 0.3);
	
	},
	
	_show:		function() {
	
		if (!this._element.visible()) {
		
			this._element.redraw();
		
			new Effect.Appear(this._element, {duration: 0.25});
			
			document.observe('keyup',this._onKeyPress);
		
		}
	
	},
	
	_hide:		function() {
	
		this._element.redraw();
	
		new Effect.Fade(this._element, {duration: 0.25});
		
		document.stopObserving('keyup',this._onKeyPress);
	
	},
	
	_click:		function(event) {
		
		var element = event.element();
		
		if (element.hasClassName('prev')) {
		
			this._previous();
		
		} else if (element.hasClassName('next') || element.hasClassName('fullscreen_image')) {
		
			this._next();
		
		} else if (!event.findElement('.fullscreen_viewer') || element.hasClassName('close')) {
		
			this._hide();
		
		}
		
		event.stop();
	
	},
	
	_keypress:	function(event) {
	
		var keyCode = Event.keyCode(event);
		
		if (keyCode == 27) {
		
			this._hide();
		
		} else if (keyCode == Event.KEY_RIGHT) {
		
			this._next();
			
			event.preventDefault();
		
		} else if (keyCode == Event.KEY_LEFT) {
		
			this._previous();
			
			event.preventDefault();
		
		}
	
	},
	
	_next:		function() {
	
		if (this._delegate && this._delegate.didSelectNext) {
		
			this._delegate.didSelectNext();
		
		}
	
	},
	
	_previous:	function() {
	
		if (this._delegate && this._delegate.didSelectPrevious) {
		
			this._delegate.didSelectPrevious();
		
		}
	
	}

});

$_MAX_THUMBS = 7;

var PhotoView = Class.create({
	
	initialize:	function(options) {
	
		if (!(this._element = $(options['element']))) return;
		
		if (!(this._thumbs = this._element.down('.thumbs'))) return;
		
		this._thumbs.makePositioned().down('ul').makePositioned();
		
		this._fullscreen = new FullScreenView({
		
			delegate:	this
		
		});
		
		this._fullsize = this._element.down('.fullsize img');
		
		this._desc = this._element.down('.desc');
		
		this._event_tags = this._element.down('.event_tags');
		
		this._selected = this._thumbs.down('.selected') ? this._thumbs.down('.selected') : this._thumbs.down().childElements().first();
		
		this._thumbWidth = this._selected.getWidth();
		
		this._maxWidth = this._element.down('.thumbs').getWidth();
		
		this._totalThumbs = this._thumbs.down().childElements().length;
		
		this._totalWidth = this._thumbWidth * this._totalThumbs;
		
		if (this._totalThumbs > $_MAX_THUMBS) {
		
			this._element.down('.thumbs').insert({
			
				before: new Element('a',{'href': 'javascript:void(0)', 'class': 'scroll_left'}).observe('click', this._scroll.bind(this,+$_MAX_THUMBS)),
				
				after: new Element('a',{'href': 'javascript:void(0)', 'class': 'scroll_right'}).observe('click', this._scroll.bind(this,-$_MAX_THUMBS))
					
			});
		
		}
		
		this._thumbs.observe('click', function(event) {
		
			this._select(event.findElement('li'));
			
		}.bind(this));
		
		this._fullsize.observe('click', this._showFullScreen.bind(this));
		
		this._select(this._selected);
		
		this._update();
		
		return this;
	
	},
	
	_select:	function(obj) {
	
		this._selected.removeClassName('selected');
		
		this._selected = obj.addClassName('selected');
		
		this._fullsize.src = this._selected.down('img').title.split(',')[0];
		
		var tags = this._selected.down('img').alt.split(';');
		
		this._desc.update(tags[0]);
		
		this._event_tags.update(createEventTagList(tags[1]));
			
	},
	
	_scroll:	function(offset) {
	
		var	willScroll = true;
		
		var scrollOffset = Math.ceil(this._thumbs.down().positionedOffset().left / this._thumbWidth) * this._thumbWidth + offset * this._thumbWidth;
		
		if (this._thumbs.down().positionedOffset().left >= 0 && offset > 0 ) {
		
			willScroll = false;
		
		}
		
		if (this._thumbs.down().positionedOffset().left <= - this._totalWidth + this._maxWidth && offset < 0) {
			
			willScroll = false;
		
		}
	
		if (willScroll) {
		
			if (scrollOffset > 0) {
			
				scrollOffset = 0;
			
			} else if (scrollOffset < -this._totalWidth + this._maxWidth) {
			
				scrollOffset = - this._totalWidth + this._maxWidth;
			
			}

			new Effect.Morph(this._thumbs.down(),{
			
				style: {
				
					left: scrollOffset + 'px'
					
				},
				
				duration:	0.5,
				
				afterFinish:	this._update.bind(this)
			
			});
		
		}
	
	},
	
	_update:	function() {
	
		var offset = - this._thumbs.down().positionedOffset().left;
	
		var hidden = {
		
			left: Math.ceil(offset / this._thumbWidth),
			
			right: Math.ceil((this._totalWidth - this._maxWidth - offset) / this._thumbWidth)
			
		};
		
		if (this._totalThumbs > 7) {
		
			this._element.down('.scroll_right').update(hidden.right);
			
			this._element.down('.scroll_left').update(hidden.left);
			
			if (hidden.right == 0) {
				
				this._element.down('.scroll_right').addClassName('disabled');
			
			} else {
			
				this._element.down('.scroll_right').removeClassName('disabled');
			
			}
			
			if (hidden.left == 0) {
				
				this._element.down('.scroll_left').addClassName('disabled');
			
			} else {
			
				this._element.down('.scroll_left').removeClassName('disabled');
			
			}
		
		}
	
	},
	
	_showFullScreen:	function() {
	
		var selected = this._selected.down('img');
		
		this._fullscreen.update({
		
			src: 	selected.title.split(',')[1],
				
			title:	selected.alt.split(';')[0],
				
			tags:	createEventTagList(selected.alt.split(';')[1]),
			
			current:this._thumbs.select('li').indexOf(this._thumbs.down('.selected')) + 1,
			
			total:	this._totalThumbs
		
		});
	
	},
	
	didSelectPrevious:	function() {
				
		this._scroll(+1);
		
		if (this._selected.previous()) this._select(this._selected.previous());
		
		this._showFullScreen();
	
	},
	
	didSelectNext:	function() {
				
		this._scroll(-1);
		
		if (this._selected.next()) this._select(this._selected.next());
		
		this._showFullScreen();
	
	}
		
});

function createEventTagList(src) {
	
	if(!!src) {
	
		var tags_arr = src.split(',');
		
		if (tags_arr.length == 1) {
		
			return 'действующее лицо: ' + '<strong>' + tags_arr[0] + '</strong>';
			
		} else {
			
			return 'действующие лица: ' + tags_arr.inject('',function(str,tag,index) {
			
				return str + (index ? ', ' : '') + '<strong>' + tag + '</strong>';
			
			});
			
		}
		
	} else {
	
		return src;
		
	}
	
}

var VideoView = Class.create({

	initialize:	function(options) {
	
		if (!(this._element = $(options['element']))) return;
		
		this._url = this._element.href;
		
		this._player = $f(this._element.identify(), {
		
			src:	$_CONTEXT_PATH + 'resources/swf/loco/flowplayer.commercial-3.1.2.swf',
			
		    key: '#@e664011b9c6d62a761b', // product key from your account 
		
			wmode: 'opaque'
			
		}, {
		
		    key: '#@e664011b9c6d62a761b',
		    
		    clip: {
		    
			    url:			this._url,
			    
			    autoPlay:		true,
		    
			    autoBuffering:	true,
		        
		        scaling:		'fit',
		        
		        accelerated:	false
		        
		    },
		    
		    logo: {
		    
		        url: $_CONTEXT_PATH + 'resources/css/loco/themes/content/video_watermark.png',
		        
		        fullscreenOnly: false,
		        
		        zIndex:	1,
		        
		        bottom:	'35px',
		        
		        right:	'7px'
		        
		    },
		    
		    plugins: {
		        
				controls: {
					tooltips: {		
						buttons:	true,
						fullscreen:	'Во весь экран',
						play:		'Играть',
						pause:		'Пауза',
						mute:		'Выключить звук'
					},
					sliderColor: '#ffffff',
					volumeSliderColor: '#000000',
					sliderGradient: 'none',
					durationColor: '#ffffff',
					timeColor: '#ffffff',
					progressGradient: 'medium',
					buttonOverColor: '#990000',
					tooltipTextColor: '#ffffff',
					borderRadius: '0',
					timeBgColor: '#555555',
					tooltipColor: '#5F747C',
					backgroundColor: '#bb0000',
					volumeSliderGradient: 'none',
					backgroundGradient: 'low',
					buttonColor: '#550000',
					bufferGradient: 'none',
					progressColor: '#550000',
					bufferColor: '#3B9937',
					height: 25,
					opacity: 1.0,
					bottom: 0
				}
		        
		    },
		    
			play: {
			
		        label:		null,
		        
		        replayLabel: "Нажмите для повтора"
		        
		    }

		});
		
		return this;
	
	}

});

var activeAudioPlayer = null;

var AudioView = Class.create({

	initialize:	function(options) {
	
		if (!(this._element = $(options['element']))) return;
		
		this._url = this._element.down('.holder') ? this._element.down('.holder').href : '';
		
		this._onPlay = this._initPlayer.bindAsEventListener(this);
		
		this._control = this._element.down('.init');
		
		this._time = this._element.down('.time');
		
		this._element.down('.desc').setStyle({
		
			top:	this._element.down('.desc').getHeight() > 15 ? '0px' : '8px'
		
		});
		
		if (this._control) {
		
			this._control.observe('click',this._onPlay);
			
		}
		
		return this;
	
	},
	
	destroy:		function() {
	
		if (this._control) {
		
			this._control.stopObserving('click');
			
		}
	
	},
	
	_initPlayer:	function(event) {
	
		event.stop();
	
		if (!!activeAudioPlayer) {
		
			activeAudioPlayer.unloadPlayer();
		
		}
		
		activeAudioPlayer = this;
	
		this._control.stopObserving('click',this._onPlay);
		
		this._control.className = 'play';
		
		var timeInSeconds = this._time.readAttribute('length').split(':').reverse().inject(0,function(seconds,order,index) {
		
			return seconds + parseInt(order)*Math.pow(60,index);
		
		});
		
		new Effect.Parallel([

			new Effect.Appear(this._element.down('.track'), {sync: true}),
			
			new Effect.Morph(this._element.down('.desc'), {style:{
			
				top:		this._element.down('.desc').getHeight() > 15 ? '-7px' : '0px'
			
			}, sync: true})
		
			], {
			
				duration: 0.25,
				
				afterFinish:	function() {
				
					this._element.down('.holder').setStyle({
					
						visibility:	Prototype.Browser.IE ? 'visible' : 'hidden'
					
					});
					
					this._player = $f(this._element.down('.holder').identify(), {
						
						src:	$_CONTEXT_PATH + 'styles/fclm3/template/live_js/lib/swf/loco/flowplayer.commercial-3.1.2.swf',
						
					    key: '#@e664011b9c6d62a761b' // product key from your account
						
					}, {
					
					    key: '#@e664011b9c6d62a761b',
					    
					    clip: {
					    
						    url: 			this._url,
						    
						    autoPlay:		true,
					    
						    autoBuffering:	true,
						    
						    duration:		timeInSeconds
					        
					    },
					    
					    canvas: {
					    
					        backgroundColor:'#ffffff'
					        
					    },
					    
					    plugins: {
					    
							controls: null,
							
					        audio: {
					        
					            url: $_CONTEXT_PATH + 'styles/fclm3/template/live_js/lib/swf/loco/flowplayer.audio-3.1.0.swf'
					            
					        }
					        
					    }
			
					}).controls(this._element.down('.controls').identify(), {
					
						duration:	timeInSeconds
					
					});
			
				}.bind(this)
		
			}
		
		);
	
	},
	
	unloadPlayer:		function() {
	
		this._player.stop();
	
		this._player.unload();
		
		this._control.observe('click',this._onPlay);
		
		this._control.onclick = function() {};
		
		this._time.update(this._time.readAttribute('length'));
		
		new Effect.Parallel([

			new Effect.Fade(this._element.down('.track'), {sync: true}),
			
			new Effect.Morph(this._element.down('.desc'), {style:{
			
				top:		this._element.down('.desc').getHeight() > 15 ? '0px' : '8px'
			
			}, sync: true})
		
			], {
		
				duration: 0.25,
				
				afterFinish:	function() {
				
					this._control.className = 'init';
				
				}.bind(this)
			
		});
	
	}

});

var EnhancedFile = function(options) {

	if (!(this.element = $(options['element']))) return false;
	
	this.allowed = options['allowed'] || '';
	
	this.delegate = options['delegate'] || null;
	
	this.element.wrap(new Element('div', {'class': 'eh_file'}))
	
		.insert(new Element('input', {'type': 'text', 'class': 'eh_filename'}))
		
		.insert(new Element('span', {'class': 'btn eh_button'})
		
			.insert(new Element('button', {'class': 'browse', 'title': $_LOCALE['title_browse']}).update($_LOCALE['action_browse']))
			
		);
	
	this._onSelect = this.select.bindAsEventListener(this);
	
	this.element.value = '';
	
	this.element.addClassName('eh_holder').setOpacity(0).observe('change',this._onSelect);
	
	this.element.setAttribute('value_holder',this.element.next('.eh_filename').identify())
	
	return this;

};

EnhancedFile.prototype = {

	select:	function(event) {
	
		if (!(this.test(this.element.value))) {
		
			alert(($_LOCALE['error_invalid_file']).replace('$1',this.allowed.join(', ')));
			
			this.element.value = '';
			
			return false;
		
		}
		
		if (this.duplicate(this.element.value)) {
		
			alert(($_LOCALE['error_duplicate_file']).replace('$1',this.element.value));
			
			this.element.value = '';
			
			return false;
		
		}
		
		if (this.delegate && this.delegate.didFileSelected) {
		
			this.delegate.didFileSelected(this.element.value);
		
		}
	
		this.element.next('.eh_filename').value = this.element.value;
	
	},
	
	test:	function (file) {
	
		function fileFromPath(file){
		
			return file.replace(/.*(\/|\\)/, "");
			
		}
		
		function getExt(file){
		
			return (/[.]/.exec(file)) ? /[^.]+$/.exec(file.toLowerCase()) : '';
			
		}
		
		var ext = getExt(fileFromPath(file));
		
    	var allowed = new RegExp('^(' + this.allowed.join('|') + ')$','i');
		
        if (ext && allowed.test(ext)) {
        
            return true;
        
        } else {
        
	        return false;
        
        }

	},
	
	duplicate:	function(file) {
	
		if (this.delegate && this.delegate.find) {
		
			return this.delegate.find(file);
		
		} else{
		
			return true;
		
		}
	
	},
	
	destroy:	function() {
	
		this.element.stopObserving('change',this._onSelect).setOpacity(1);
		
		this.element.up(1).insert({ top: this.element });
		
		this.element.next().remove();
		
		return this;
	
	}

}

var ProgressView = Class.create({

	initialize:	function(options) {
	
		if (!(this.element = $(options['element']))) return false;
		
		this.speed = options['speed'] || 'high';
		
		this.text = options['text'] || '';
		
		this.delegate = options['delegate'] || null;
		
		this.isEstimating = !!options['estimate'];
		
		this.element.insert(this.isEstimating
		
			? new Element('div', {'class': 'progress_estimation'})
			
			: ''
		
		).insert(
		
			new Element('div', {'class': 'progress_description'}).update(this.text)
		
		).insert(new Element('div', {'class': 'progress_line'})
		
			.insert(
				
				new Element('div', {'class': 'stripes'})
				
			)
		
		).hide();
		
		return this;
	
	},
	
	destroy:	function() {
	
		this.hide();
		
		this.element.remove();
		
		return this;
	
	},
	
	show:	function() {
	
		if (!this.element) return false;
		
		this.element.show();
		
		var stripes = this.element.down('.stripes');
		
		var estimates = this.element.down('.progress_estimation');
	
		var x = 0;
		
		var freq = 1;
		
		stripes.setStyle({
		
			width:	this.isEstimating ? '0' : '100%'
		
		});
		
		this.pe_stripes = new PeriodicalExecuter(function() {
		
			stripes.setStyle({
			
				backgroundPosition:	x++ + 'px 0px'
			
			});

		}, this.speed == 'high' ? 0.025 : 0.05);
		
		if (this.isEstimating && this.delegate && this.delegate.getProgressValue) {
		
			var values = [], time = 0;
			
			estimates.update($_LOCALE['progress_estimation']);
		
			this.pe_estimate = new PeriodicalExecuter(function() {
			
				values.push(this.delegate.getProgressValue());
				
				stripes.setStyle({
				
					width:	values.last() + '%'
				
				});
				
				if (values.length >= 5) {
				
					derivative = (values.last() - values.shift()) * freq / 5;
					
					time = parseInt((100 - values.last()) / derivative);
					
					estimates.update(this.echoTime(time));
				
				}
			
			}.bind(this), 1 / freq);
		
		}
	
	},
	
	hide:	function() {
	
		if (!this.element) return false;
	
		if (this.pe_stripes) {
		
			this.pe_stripes.stop();
			
		}
		
		if (this.pe_estimate) {
		
			this.pe_estimate.stop();
			
		}
		
		this.element.hide();
	
	},
	
	echoTime:	function(time) {
	
		var str = $_LOCALE['progress_left'];
		
		if (time < 2) {
		
			str = $_LOCALE['progress_1_second'];
		
		} else if (time < 5) {
		
			str += time + $_LOCALE['progress_low_seconds'];
		
		} else if (time < 6) {
		
			str += time + $_LOCALE['progress_high_seconds'];
		
		} else if (time < 11) {
		
			str += $_LOCALE['progress_less_than'] + '10' + $_LOCALE['progress_high_seconds'];
		
		} else if (time < 60) {
		
			str += $_LOCALE['progress_less_than'] + $_LOCALE['progress_low_minutes'];
		
		} else if (time < 120) {
		
			str += $_LOCALE['progress_less_than'] + '2' + $_LOCALE['progress_high_minutes'];
		
		} else if (time < 300) {
		
			str += $_LOCALE['progress_less_than'] + '5' + $_LOCALE['progress_high_minutes'];
		
		} else if (time < 600) {
		
			str += $_LOCALE['progress_less_than'] + '10' + $_LOCALE['progress_high_minutes'];
		
		} else if (time < 1200) {
		
			str += $_LOCALE['progress_less_than'] + '20' + $_LOCALE['progress_high_minutes'];
		
		} else if (time < 3600) {
		
			str += $_LOCALE['progress_less_than'] + $_LOCALE['progress_low_hours'];
		
		}
		
		return str;
	
	}

});

var FileSelector = function(options) {
	
	if (!(this.element = $(options['element']))) return false;
	
	this.allowed = options['allowed'] || '';
	
	this.defaultUploaded = options['upload'] || 3;
	
	this.loaders = [];
	
	this.rows = [];

	this.element.down('tbody').select('tr').each(function(row) {
	
		this.rows.push(row);
		
		this.loaders.push(this.row2obj(row));
	
	}, this);
	
	this._onClick = this.click.bindAsEventListener(this);
	
	this.element.observe('click', this._onClick);
	
	return this;

}

FileSelector.prototype = {

	_button:	'<span class="btn"><button type="button" class="remove" title="' + $_LOCALE['title_upload_remove'] + '">' + $_LOCALE['action_remove'] + '</button></span>',

	_template:	'<td class="filename required"><input type="file" name="photofile[]" value="" class="holder" title="' + $_LOCALE['title_upload_select'] + '" /></td><td class="filedesc required"><input type="text" name="description" value="" maxlength="150" class="text notags" /></td><td align="right"><span class="btn"><button type="button" class="remove" title="' + $_LOCALE['title_upload_remove'] + '">' + $_LOCALE['action_remove'] + '</button></span></td>',

	click:	function(event) {
	
		var element = event.element();
		
		if (element.hasClassName('remove')) {
		
			var row = element.up('tr').remove();
			
			this.rows = this.rows.without(row);
			
			this.loaders = this.loaders.reject(function(loader) {
			
				return loader.element == row.down('input[type="file"]') ? loader.destroy() : false;
			
			});
			
			if (this.rows.length == 1) {
			
				$(this.rows[0].cells[2]).update();
			
			}
			
			this.show();
		
		} else if (element.hasClassName('append') && !element.hasClassName('disabled')) {
		
			if (this.rows.length == 1) {
			
				$(this.rows[0].cells[2]).update(this._button);
			
			}
			
			for(var row = {}, i = 0; i < this.defaultUploaded; i++) {
			
				row = new Element('tr', {'valign': 'top'}).insert(this._template);
			
				this.rows.push(row);
			
				this.element.down('tbody').insert(row);
				
				this.loaders.push(this.row2obj(row));
			
			}
		
		} else if (element.hasClassName('infohelp')) {
		
			new Info({link: element, info: element.down('p').innerHTML});
		
		}
	
	},
	
	row2obj:	function(row) {
	
		var file = row.down('input[type="file"]');
	
		var desc = row.down('input[type="text"]');
		
		file.setAttribute('rel',desc.identify());
		
		desc.setAttribute('rel',file.identify());
	
		return new EnhancedFile({
					
			element:	file,
			
			delegate:	this,
			
			allowed:	this.allowed
			
		});
	
	},
	
	show:	function() {
	
		if (this.element.down('tfoot .count')) {
		
			this.element.down('tfoot .count').update(
			
				this.loaders.findAll(function(loader) {
				
					return loader.element.value
					
				}).length
				
			);
		
		}
	
	},
	
	didFileSelected:	function(file) {

		this.show();
	
	},
	
	find:	function(fileName) {
	
		return this.loaders.findAll(function(loader) {
		
			return loader.element.value == fileName;
		
		}).size() > 1;
	
	}

};

var FileUploader = Class.create(SimpleFormValidator, {

	initialize:		function ($super,options) {
	
		if (!($super(options))) return false;
		
		this.url = this._element.action;
		
		var selector = this._element.down('.file_selector');
	
		this.fileSelector = new FileSelector({
		
			element:	selector,
			
			upload:		1, /*selector.hasClassName('photo') ? 3 : 1*/
			
			allowed:	selector.hasClassName('video') 
			
							? ['avi','divx','avi','xvid','wmv','mp4','mpeg4','mpeg2','mpeg1','flv','3gp','3gpp','mkv','mov','mxf','f4v','m2v','mpg']
							
							: selector.hasClassName('photo')
							
								? ['jpg','gif','png']
								
								: ['mp3', 'wav', 'aiff', 'ogm', 'flac', 'wma']
		
		});
		

		this.progressView = new ProgressView({
		
			element:	this._element.down('.progress_indicator'),
			
			estimate:	true,
			
			delegate:	this
			
		});

		
		return this;
	
	},
	
	didSubmit:	function() {
	
		this.element.down('.append').addClassName('disabled');
		
 		this.file_key = Math.floor(Math.random()*10000000); //php_only */
 			
		this.checkProgress = new PeriodicalExecuter(function(pe) {
			
			new Ajax.Request(/*this.url*/'/b2c/backend/uploadprogress', {
			
				parameters:	{
				
					key:	this.file_key //php_only
				
				},
				
				evalJSON:	true,
				
				onSuccess:	function (transport) {
				
					this.progressStatus = transport.responseJSON.value;
				
				}.bind(this)
			
			});
		
		}.bind(this), 1);
		
		this.progressView.show();
		
		this._element.action = this._element.action + '?key='+this.file_key;
	
	},
	
	_cancel:	function($super,event) {
	
		this.element.down('.append').removeClassName('disabled');
	
		if (this.checkProgress) {
		
			this.checkProgress.stop();
			
			this.checkProgress = null;
		
		}
	
 		this.progressView.hide();
	
		this._element.reset();
		
		if (this._submitBtn) {
		
			this._submitBtn.value = $_LOCALE['action_save'];
			
			this._submitBtn.innerHTML = $_LOCALE['action_save'];
			
		}
	
	},
	
	getProgressValue:	function() {
	
 		return this.progressStatus ? this.progressStatus : 0; 
	
	}

});

var insertContent = function(content,level) {
	
	var editor = tinyMCE.activeEditor;
	
	if (editor.id == 'new_message') {
	
		document.fire('toggle_view:show');
		
		if ($('new_message_form')) {
		
			Element.scrollTo('new_message_form');
		
		} else {
		
			window.scrollTo(0,0);
		
		}
	
	} else {
	
		Element.scrollTo(editor.id + '_form');
	
	}
	
	editor.focus(false);
	
	if (level == 'block') {

		if (Prototype.Browser.Opera) {
		
			var node = editor.selection.getNode();
			
			if (node.innerHTML.replace(/^<br.*>$/i,'').empty()) {
			
				Element.insert(node, {before: content + '<br mce_bogus="1"/>'});
				
				Element.remove(node);
			
			} else {
			
				Element.insert(node, {after: content + '<br mce_bogus="1"/>'});
			
			}
		
		} else {
		
			editor.selection.setContent('' + content);
		
		}
	
	} else {
		
		editor.selection.setContent(content);
	
	}

}

var citeMessage = function(event) {

	event.stop();
	
	var id = event.findElement('a').id.replace('cite_','');
	
	insertContent(
	
		'<div class="cite">' +

			'<div class="cited">' +
			
				'<a href="' + $('link_' + id).href + '" class="perm_link">' +
				
					'Цитата: (' + $('sender_' + id).innerHTML + ' @ ' + $('date_' + id).innerHTML + ')</a>' +
					
			'</div>' +
			
			'<div>' + $('message_' + id).innerHTML + '</div>' +
			
		'</div> ',
	
	'block');
	
}

var linkMessage = function(event) {

	event.stop();
	
	var id = event.findElement('a').id.replace('link_','');
	
	insertContent(
	
		' <p><a href="' + event.findElement('a').href + '" title="' + $('message_' + id).innerHTML.stripTags().substring(0,300) + '…" class="perm_link"> ' +
			
			 '&gt;&gt;&nbsp;' + $('sender_' + id).innerHTML + ' @ ' + $('date_' + id).innerHTML +
		
		' </a></p> ',
	
	'block');

}

var linkSender = function(event) {

	event.stop();

	var id = event.findElement('a').id.replace('link_','');
				
	insertContent(
	
		' <a href="' + event.findElement('a').href + '" title="' + $('sender_' + id).innerHTML + '" class="perm_link"> ' +
					
			$('sender_' + id).innerHTML +
		
		' </a> ',
	
	'inline');

}

var activeEditors = []

var InlineEditor = Class.create(CreateWhatever, {

	initialize:	function($super,options) {
	
		this._editedItem = $(options['editedItem']);
		
		this.id = this._editedItem.identify();
		
		if (activeEditors.indexOf(this.id) < 0) {
		
			activeEditors.push(this.id);
		
		} else {
		
			return false;
		
		}
		
		this._element = new Element('form', {'action': options['url'], 'method': 'post', 'class': 'edit_whatever inline_editor'}).hide();
		
		this._submitButton = new Element('span', {'class': 'btn'})
			
			.insert(new Element('button', {'type': 'submit', 'class': 'submit'}).update($_LOCALE['action_save']));
			
		this._cancelButton = new Element('span', {'class': 'btn'})
			
			.insert(new Element('button', {'type': 'button', 'class': 'cancel'}).update($_LOCALE['action_cancel']));
		
		this._text = new Element('textarea', {'name': 'message', 'class': 'rich_editor', 'rows': '6', 'cols': '160', 'title': $_LOCALE['title_message']});
		
		this._text.value = this._editedItem.innerHTML;

		this._editedItem.insert({before: 
		
			this._element
			
				.insert(new Element('fieldset', {'class': 'required'})
				
					.insert(this._text)
				
				)
				
				.insert(new Element('fieldset', {'class': 'form_actions'})
				
					.insert(this._submitButton)
					
					.insert(this._cancelButton)
				
				)
		
		});
		
		tinyMCE.execCommand('mceAddControl', false, this._text.identify());
		
		this._element.id = this._text.identify() + '_form';
		
		$super({element: this._element});
		
		new Effect.BlindDown(this._element, { duration: 0.35 });
		
		return this;
	
	},
	
	_cancel:	function(event) {
	
		if (this._submitBtn) {
		
			this._submitBtn.value = $_LOCALE['action_save'];
			
			this._submitBtn.innerHTML = $_LOCALE['action_save'];
			
		}
		
		this._destroy();
	
	},
	
	_destroy:	function($super) {
	
		new Effect.BlindUp(this._element,{duration: 0.35, afterFinish: function() {
		
			tinyMCE.execCommand("mceRemoveControl", true, this._text.id);
			
			activeEditors = activeEditors.reject(function(id) {
			
				return this.id == id
			
			}, this);
			
			$super();
		
		}.bind(this)});
	
	}
});

var FilteredSearchForm = Class.create({

	initialize:		function(options) {
	
		if (!(this._element = $(options['element']))) return false;
		
		this._field = this._element.down('#search');
		
		this._selector = this._element.down('#search_filter').hide();
		
		this._filters = $A(this._selector.options);
		
		this._selectedHolder = new Element('span', {'class': 'selected'}).update(this._filters[this._selector.selectedIndex].text);
		
		this._selectorHolder = new Element('ul', {'class': 'selector'}).hide();
		
		this._filters.each(function(filter, index) {
		
			this._selectorHolder.insert(
			
				new Element('li', {'class': 'item', 'index': index})
				
					.insert(new Element('a', {'href': 'javascript:void(0)'}).update(filter.text))
			
			)
		
		}, this);
		
		this._selectorHolder.insert(
		
			new Element('li', {'class': 'bottom'}).insert(
			
				new Element('img', {'src': $_CONTEXT_PATH + 'styles/fclm3/theme/live_styles/themes/services/selector_bottom.png',
				
					'style':	Prototype.Browser.IE6 ? 'behavior: url("' + $_CONTEXT_PATH + 'styles/fclm3/theme/live_styles/iepngfix.htc")' : ''
				
				})
			
			)
		
		);
		
		this._field.wrap(new Element('div', {'class': 'filters_holder'})).insert(this._selectedHolder).insert(this._selectorHolder);
		
		this._onClick = this._click.bindAsEventListener(this);
		
		this._onKeyPress = this._keypress.bindAsEventListener(this);
		
		this._element.down('.filters_holder').observe('click', this._onClick);
		
		return this;
	
	},
	
	_click:		function(event) {
	
		var element = event.element();
		
		if (element.up().hasClassName('item')) {
		
			this._select(event,element.up());
		
		} else if (element != this._field || this._selectorHolder.visible()) {
		
			this._toggle(event);
		
		}
		
	},
	
	_toggle:	function(event) {
	
		this._selectorHolder.toggle();
		
		this._element.down('.filters_holder').redraw();
		
		if (this._selectorHolder.visible()) {
		
			document.observe('click', this._onClick);
			
			document.observe('keyup', this._onKeyPress);
		
		} else {
		
			document.stopObserving('click', this._onClick);
			
			document.stopObserving('keyup', this._onKeyPress);
		
		}
		
		event.stop();
	
	},
	
	_select:	function(event,item) {
	
		this._selector.selectedIndex = item.readAttribute('index');
		
		this._selectedHolder.update(item.down('a').innerHTML);
		
		this._toggle(event);
	
	},
	
	_keypress:	function(event) {
	
		if (Event.keyCode(event) == 27) {
		
			this._toggle(event);
		
		}
	
	}

});

var ListFilter = Class.create({

	initialize:	function (options) {
		
		if (!(this.element = $(options['element']))) return false;
		
		this.filters = this.element.select('.filter');
		
		this.preffix = this.element.id;
		
		if (this.deselected = getCookie('fclm_' + this.preffix + '_filter')) {
			
			this.deselected = this.deselected.split(',');
		
		} else {
		
			this.deselected = [];
		
		}
		
		var filter_type;
		
		this.filters.each(function(filter) {
		
			filter_type = filter.id.replace('_filter','');
		
			if (this.deselected.indexOf(filter_type) < 0) {
			
				filter.checked = true;
			
			} else {
			
				filter.checked = false;
				
				$$('.' + filter_type).invoke('hide');
			
			}
		
		}, this);
		
		this._onClick = this.toggle.bindAsEventListener(this);
		
		this.element.observe('click', this._onClick);
		
		return this;
	
	},
	
	toggle:		function (event) {
	
		var element = event.element()
	
		if (element.hasClassName('filter')) {
		
			if (element.checked) {
			
				filter_type = element.id.replace('_filter','');
				
				$$('.' + filter_type).invoke('show');
			
			} else {
			
				filter_type = element.id.replace('_filter','');
				
				$$('.' + filter_type).invoke('hide');
			
			}
			
			setCookie('fclm_' + this.preffix + '_filter',
			
				this.filters.map(function(filter) {
				
					return filter.checked ? '' : filter.id.replace('_filter','');
				
				}, this).join(',')
			
			);
		
		}
	
	}

});

var EncoderStatusUpdater = Class.create({

	templates:	{
	
		video_success:	'<div style="background-image: url(#{background});" class="videoview" href="#{url}"><img src="' + $_CONTEXT_PATH + 'resources/css/loco/themes/content/play.png" class="png" alt="#{title}"/></div><a href="#{url}#p" title="" class="desc">#{title} (#{length})</a><a href="#{remove_link}" title="Удалить" class="remove"><img src="' + $_CONTEXT_PATH + 'resources/css/loco/themes/content/closebox.png" alt="[x]"/></a><a href="#{url}#comments" title="" class="item_comments"><img alt="Комментарии" src="' + $_CONTEXT_PATH + 'resources/css/loco/themes/content/comments_icon.gif"/><span>0</span></a>',
		
		audio_success:	'<div class="actions"><a href="#{rename_link}" title="Редактировать название" class="btn_link edit rename"><img src="' + $_CONTEXT_PATH + 'resources/css/loco/themes/content/edit.gif" alt="" /> Переименовать</a><a href="#{remove_link}" title="Удалить" class="btn_link remove"><img src="' + $_CONTEXT_PATH + 'resources/css/loco/themes/content/delete.gif" alt="Удалить" /> Удалить</a></div><a href="#{url}" class="holder"></a><div class="controls"><div class="init"></div><p class="desc">#{title} (<span class="time" title="Длительность" length="#{length}">#{length}</span>)</p><div class="track" style="display: none"><div class="buffer"></div><div class="progress"></div><div class="playhead"></div></div><a class="mute">mute</a></div>',
		
		audio_failure:	'<div class="actions"><a href="#{remove_link}" title="Удалить" class="btn_link remove"><img src="' + $_CONTEXT_PATH + 'resources/css/loco/themes/content/delete.gif" alt="Удалить" /> Удалить</a></div><div class="controls"><div class="audio_error"></div><p class="desc">#{title} (Ошибка кодирования)</p></div>',
		
		video_failure:	'<div style="background: #333" class="videocoding"><img src="' + $_CONTEXT_PATH + 'resources/css/loco/themes/content/encoding_failed.png" class="encoding"/><a title="Удалить" class="remove" href="#{remove_link}"><img src="' + $_CONTEXT_PATH + 'resources/css/loco/themes/content/closebox.png"/></a></div>'
				
	},

	initialize:	function (options) {
	
		if (!(this.element = $(options['element']))) return false;
		
		this.updater = new Ajax.PeriodicalUpdater('', this.element.readAttribute('href'), {
		
			frequency:	30,
			
			evalJSON:	true,
			
			onSuccess:	function(transport) {

				var obj = transport.responseJSON;
				
				if (obj.status == 'done') {
				
					this.updater.stop();
					
					this.element.removeClassName('encoding');
					
					switch (obj.type) {
					
						case 'audio':
						
							this.element.update(new Template(this.templates.audio_success).evaluate(obj));
							
							new AudioView({element: this.element});
							
							break;
							
						case 'video':
						
							this.element.update(new Template(this.templates.video_success).evaluate(obj));
							
							new VideoView({element: this.element.down('.videoview')});
							
							break;
					
					}
				
				} else if (obj.status == 'error') {
				
					this.updater.stop();
					
					this.element.removeClassName('encoding');
					
					switch (obj.type) {
					
						case 'audio':
						
							this.element.update(new Template(this.templates.audio_failure).evaluate(obj));
							
							new AudioView({element: this.element});
							
							break;
							
						case 'video':
						
							this.element.update(new Template(this.templates.video_failure).evaluate(obj));
							
							break;
					
					}
				
				}
			
			}.bind(this)
		
		});
		
		return this;
	
	}

});

