Cufon.replace('#mainmenu li, .title, .ui-accord-head, .font-subst', {hover: true});

Object.extend(String.prototype, {
	ensureEndsWith: function(str) {
		return this.endsWith(str) ? this : this + str;
	},
	px: function() {
		return this.ensureEndsWith('px');
	},
	em: function(){
		return this.ensureEndsWith('em');
	},
	plural: function(titles) {
	    return parseInt(titles).plural(titles);
	}
});

Object.extend(Number.prototype, {
	px: function() {
		return this.toString().px();
	},
	em: function(){
		return this.toString().em();
	},
    plural: function(titles) {
        var cases = [2,0,1,1,1,2];
        return titles[ (this % 100 > 4 && this % 100 < 20) ? 2 : cases[[this % 10, 5].min()] ];
    }
});

UI = {};
UI.ProgrammSlider = Class.create(Control.Slider, {
	cellWidth: 87,
	initialize: function($super, track, options){
		var nullHandle = new Element('div');
		$super(nullHandle, track, options);
		this.options = Object.extend(this.options, options);
	},
	_setTrackWidth: function(value){}
});

UI.Tooltip = Class.create({

	container: {},
	triggers: [],
	closeTriggers: [],
	options: {},
	initialize: function(options){

		this.options = Object.extend({
			triggers: [],
			close: {
				className: '',
				event: 'mouseout'
			},
			triggerEvent: Prototype.emptyFunction,
			triggerOffset: Prototype.emptyFunction,
			nodeSelect: Prototype.emptyFunction
		}, options);

		this.container = new Element('div', {
			className: 'ui-popup-fixed',
			style: 'display: none'
		});

		this.triggers = this.options.triggers;
		this.closeTriggers = this.options.closeTriggers;

		this.triggers.each(function(t){
			t.observe('mouseover', function(event){

				var offset = t.cumulativeOffset();
				var content = this.options.nodeSelect(t);
				
	            this.container.setStyle({
	                position: 'absolute',
					top : (offset.top - 20).px(),
					left : (offset.left - 44).px()
				});
				this.updateContainer(content).show();

			}.bind(this));

		}.bind(this));

        document.body.appendChild(this.container);
	},

	updateContainer: function(node){
		this.container.update();
		this.container.insert(node);

		this.container.select(this.options.close.className).each(function(item){
			item.observe(this.options.close.event, function(event){
				this.hide();
			}.bind(this));
		}.bind(this));
		return this;
	},

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

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


UI.Slider = Class.create(Control.Slider, {
	minWidth: 80,
	maxWidth: 973,
	minHeight: 80,
	maxHeight: 307,
	area: {},

	initialize: function($super, handle, track, options){
		$super(handle, track, options);
		this.options = Object.extend(this.options, options);

		if(this.options.area){

			this.area = $(this.options.area);

			if(this.options.onItemOver){
				this.options.onItemOver(this);
			}

			if(this.options.onItemClick){
				this.options.onItemClick(this);
			}

			var count = this.area.select(this.options.elements).size();
			this.range = $R(0, count - 1);
			this.values = $R(0, count - 1);
			this.minimum = 0;
			this.maximum = count - 1;

			if(count > this.options.min){
				if(this.options.axis != 'vertical'){
					var size = this.maxWidth - (this.minWidth * count);
					this.setHandleWidth(size);
				}else{
					//если нечего скроллировать, то нужно прибить слайдер
					if(this.maxHeight > this.getAreaHeight()) {
						this.hide();
						if(this.options.container){
							var container = $(this.options.container);
							var d = this.area.select('.slider-height')[0].getDimensions();
							container.addClassName('slider-v-noslide');
							container.setStyle({width: d.width.px(), height: d.height.px()});
						}
					}else{
						var size = this.maxHeight * this.maxHeight / Math.min(1000, this.getAreaHeight());
						this.setHandleHeight(size);
					}
				}
			}else{
				this.hide();
				if(this.options.container){
					var container = $(this.options.container);
					var d = this.area.select('.slider-height')[0].getDimensions();
					container.addClassName('slider-v-noslide');
					container.setStyle({width: d.width.px(), height: d.height.px()});
				}
			}
			//this.scroll();
		}
	},

	getAreaWidth: function(){
		return this.area.select('.slider-width')[0].getDimensions().width;
	},

	getAreaHeight: function(){
		return this.area.select('.slider-height')[0].getDimensions().height;
	},

	scroll: function(){
		function wheel(event){
			var delta = this.value;
			if (!event) /* For IE. */
				event = window.event;

			if (!event) /* For IE. */
				event = window.event;
			if (event.wheelDelta) { /* IE/Opera. */
				delta -= Math.round(event.wheelDelta /  (this.maximum * this.maximum)) * 0.05;
				/** In Opera 9, delta differs in sign as compared to IE. */
				if (window.opera)
					delta = -delta;
			} else if (event.detail) {
				/** Mozilla case. */
				/** In Mozilla, sign of delta is different than in IE.
				* Also, delta is multiple of 3.
				*/
				delta += event.detail * 0.05;
			}
			if (delta)
				this.setValue(delta);
			/** Prevent default actions caused by mouse wheel.
			* That might be ugly, but we handle scrolls somehow
			* anyway, so don't bother here..
			*/
			if (event.preventDefault)
				event.preventDefault();
			event.returnValue = false;
		}
		Event.observe(this.area, 'mousewheel', wheel.bind(this));
		Event.observe(this.area, 'DOMMouseScroll', wheel.bind(this));
	},

	_setHandleWidth: function(value){
		this.handleLength = value;
		var handle = this.handles[0];
		handle.setStyle({width: value + 'px'});
		handle.select('.handle-center')[0].setStyle({'width': (value - 20).px()});
	},

	setHandleWidth: function(value){
		if(value <= this.minWidth){
			this._setHandleWidth(this.minWidth);
			return this;
		}
		if(value >= this.maxWidth){
			this._setHandleWidth(this.maxWidth);
			return this;
		}
		this._setHandleWidth(value);
		return this;
	},

	_setHandleHeight: function(value){
		this.handleLength = value;
		var handle = this.handles[0];
		handle.setStyle({height: value + 'px'});
		handle.select('.handle-center')[0].setStyle({'height': (value - 20).px()});
	},

	setHandleHeight: function(value){
		this._setHandleHeight(value);
		return this;
	},

	hide: function(){
		$(this.track).hide();
		return this;
	},

	show: function(){
		$(this.track).show();
		return this;
	}
});

UI.Accordition = Class.create({
    initialize: function(args){
		this.options = Object.extend({
			triggerSelector: '.ui-accord-head a',
			visibleSelector: '.ui-accord-body',
			parentSelector: '.ui-accord-container',
			animation: true,
			ajax: false,
			expand: true
		}, args);

		this.options.animation = true;
        if (Prototype.Browser.Opera) this.options.animation = false; // No opera in my internets!!1

		$$(this.options.triggerSelector).each(function(item, index){
			item.observe('click', function(e){
				if(!this.options.parentSelector){
					var parent = $(item.ancestors()[1]);
				}else{
					var parent = $(item.up(this.options.parentSelector));
				}
				var img = parent.select(this.options.imagesSelector)[0];
				var faq = parent.select(this.options.visibleSelector)[0];
				if(Element.visible(faq)){
					this.hideVisible(faq, img);
				}else{
					this.showVisible(faq, img);
				}
			}.bind(this));
		}.bind(this));
	},

	hideVisible: function(element, image){
		if(this.options.animation){
			new Effect.SlideUp(element, {duration: 0.5});
		}else{
			element.hide();
		}
		return this;
	},

	expandAll: function(){
		$$(this.options.visibleSelector).each(function(visible){
			if(Element.visible(visible)){
				if(this.options.animation){
					new Effect.SlideUp(visible, {duration: 0.5});
				}else{
					visible.hide();
				}
			}
		}.bind(this));
    },

    showVisible: function(element, image){
		if(this.options.expand){
			this.expandAll();
		}
		if(this.options.animation){
			new Effect.SlideDown($(element), {duration: 0.5});
		}else{
			element.show();
		}
		$$(this.options.parentSelector).invoke('removeClassName', 'active');
		element.up(this.options.parentSelector).addClassName('active');
		return this;
	}
});

Programm = {}
Programm.Element = Class.create({

	initialize: function(){

	},

	build: function(json){
/*
<table border="0" cellspacing="0" cellpadding="0" class="tele-grid programm show-grid-#DAY_NUM#" width="100%">
	<tbody>
		<tr class="#IF# whbscnbu #/IF#">
			<td class="t-time">
				<span class="icon icon-6"></span>
				<span>13:00</span>
			</td>
			<td class="t-name">
				<a href="#PROJECT_URL#">#WATCHED ELEMENT#</a>
			</td>
			<td class="t-type">#GENRE#</td>
		</tr>

		<tr class="t-announce" style="display: none;">
			<td colspan="3">
				<img src="#SRC#" width="#WIDTH#" height="#HEIGHT#" alt="" />
				#ANOUNCE TEXT#
			</td>
		</tr>
	</tbody>
</table>
*/
	}

});

News = {}
News.List = Class.create({
	from: 0,
	cleared: false,
	params: {},
	list: {},
	options: {},
	container: {},
	template: new Template('\
        <div class="column span-3">\
            <img src="#{image}" height="130" width="175" alt="#{name}" />\
        </div>\
        <div class="column span-13 last">\
            <h4 class="margin-5"><a class="color-1" href="#{url}">#{name}</a></h4>\
            <div class="color-3 italic margin-6">#{date}</div>\
            <div class="color-4">#{teaser}</div>\
        </div>'
	),

	initialize: function(options){
		this.options = Object.extend({
			container: 'news_list_list',
			limit: 6,
			url: '',
			moreLabel: 'Ещё новости'
		}, options);

		this.more = new Element('a', {
							href: '#from' + this.from,
							className: 'italic color-6 dotted-1',
							onclick: 'return false;'
						}).observe('click', function(event){
							this.get();
							//e.cancelBubble is supported by IE - this will kill the bubbling process.
							event.cancelBubble = true;
							event.returnValue = false;

							//e.stopPropagation works only in Firefox.
							if (event.stopPropagation) {
								event.stopPropagation();
								event.preventDefault();
							}

							return false;
						}.bind(this)).update(this.options.moreLabel);

		this.container = $(this.options.container);
		this.list = new Element('div');
		this.container.appendChild(this.list);
		this.container.appendChild(this.more);
		this.container.appendChild( new Element('span').update('&nbsp;&rarr;') );
	},

	get: function(parameters){

		this.params = Object.extend({
			from: this.from,
			limit: this.options.limit,
			id: this.params.id ? this.params.id : null
		}, parameters);

		new Ajax.Request(this.options.url, {
			contentType: 'application/json',
			method: 'get',
			onComplete: function(transport){
				json = transport.responseJSON;
				this.build(json.data);
				this.more.href = "#from=" + this.from + (this.params.id ? ("&id=" + this.params.id) : "");

				this.from += json.count;
				if(json.count < this.options.limit){
                    // $(this.more.up('div.boxy')).hide();
                    this.more.hide();
				}
			}.bind(this),
			parameters: this.params
		});
	},

	createNode: function(node){
	    var elt = new Element('div',{className: 'container margin-8'});
	    elt.innerHTML = this.template.evaluate(node);
	    return elt;
	},

	clear: function(force){
		return this;
	},

	build: function(json){
	    var self = this;
	    json.map(this.createNode.bind(this)).each(function(elt){
	        self.list.insert(elt);
	    });
	}
});

Blogs = {}
Blogs.List = Class.create({
	from: 0,
	cleared: false,
	params: {},
	list: {},
	options: {},
	container: {},
	tag: null,
    // template: new Template('\
    //  <!--div class="column span-3"></div-->\
    //         <div class="column span-13 last">\
    //             <h4 class="margin-5"><a class="color-1" href="#{url}">#{name}</a></h4>\
    //             <div class="color-3 italic margin-6">#{date}</div>\
    //             <div class="color-4 margin-5">#{body}</div>\
    //             <div class="color-3 icomment padding-2 margin-4">\
    //                 <a href="#{url}" title="Всего комментариев" class="color-6">#{comments}</a>\
    //                 <a href="#{url}" title="Всего просмотров" class="color-6 iviews padding-2">#{views}</a>\
    //             </div>\
    //             <div><a href="#{url}" class="italic color-6">Читать дальше</a>&nbsp;&rarr;</div>\
    //         </div>'
    // ),
    template: new Template('\
        <div class="span-6">\
            <div class="column span-14 last">\
                <img src="#{avatar}" width="160" alt="#{name}" />\
                <div class="color-3 margin-3a">\
                    <a href="#{url}" title="Всего комментариев" class="padding-2 icomment color-6">#{comments}</a>\
                    <a href="#{url}" title="Всего просмотров" class="padding-2 iviews color-6">#{views}</a>\
                </div>\
            </div>\
            <div class="column span-12 last">\
                <h4 class="margin-5"><span class="color-2">#{blog}</span>: <a class="color-1" href="#{url}">#{name}</a></h4>\
                <div class="color-3 italic margin-6">#{date}</div>\
                <div class="color-2 margin-5">#{body}</div>\
                <div><a href="#{url}" class="italic color-6">Читать дальше</a>&nbsp;&rarr;</div>\
            </div>\
        </div>\
    '),

	initialize: function(options){
		this.options = Object.extend({
			container: 'blogs_list_list',
			limit: 5,
			url: '',
			moreLabel: 'Ещё 5 последних постов'
		}, options);

		this.more = new Element('div', {className: 'padding-5 left'}).insert(
		        new Element('a', {
					href: '#from' + this.from,
					className: 'italic color-6 dotted-1',
					onclick: 'return false;'
				}).observe('click', function(event){
					this.get();
					//e.cancelBubble is supported by IE - this will kill the bubbling process.
					event.cancelBubble = true;
					event.returnValue = false;
					//e.stopPropagation works only in Firefox.
					if (event.stopPropagation) {
						event.stopPropagation();
						event.preventDefault();
					}
					return false;
				}.bind(this)).update(this.options.moreLabel + '<span>&nbsp;&rarr;</span>'));

		this.container = $(this.options.container);
		this.list = new Element('div');
		this.container.appendChild(this.list);
		this.container.appendChild(this.more);
		//this.container.appendChild( new Element('span').update('&nbsp;&rarr;') );
	},

    setTag: function(tag) {
        this.tag = tag;
        return this;
    },
        
    clearTag: function() {
        this.tag = null;
        return this;
    },

	get: function(parameters){

		this.params = Object.extend({
			from: this.from,
			limit: this.options.limit,
			id: this.params.id ? this.params.id : null,
			tag: this.tag 
		}, parameters);

		new Ajax.Request(this.options.url, {
			contentType: 'application/json',
			method: 'get',
			onComplete: function(transport){
				json = transport.responseJSON;
				this.build(json.data);
				this.more.href = "#from=" + this.from + (this.params.id ? ("&id=" + this.params.id) : "");

				this.from += json.count;
				if(json.count < this.options.limit){
                    // $(this.more.up('div.boxy')).hide();
                    this.more.hide();
				}
			}.bind(this),
			parameters: this.params
		});
	},

	createNode: function(node){
	    var elt = new Element('div',{className: 'span-6 margin-8'});
	    elt.innerHTML = this.template.evaluate(node);
	    return elt;
	},

	clear: function(force){
	    this.list.childElements().invoke('remove');
	    this.from = 0;
		return this;
	},

	build: function(json){
	    var self = this;
	    json.map(this.createNode.bind(this)).each(function(elt){
	        self.list.insert(elt);
	    });
	}
});


Video = {}
Video.List = Class.create({
	from: 0,
	cleared: false,
	params: {},
	options: {},
	container: {},
	requestSent: false,
	settingsPanel: null,
	settingsList: null,
	sort: '-_sort',
	type: 0,
	nodeTemplate: new Template('\
            <div class="video-block">\
                <a href="#{url}" title="#{name}"><img src="#{video_image_banner}" alt="#{name}" /></a>\
                <a class="play-button" title="#{name}" href="#{url}"></a>\
            </div>\
            <h4 class="color-2 margin-3 margin-5"><a href="#{url}" class="color-1">#{name}</a></h4>\
            <div class="color-3 italic margin-4">#{views}</div>\
            <div class="color-3 icomment padding-2"><a class="color-6" href="#{url}">#{comments}</a></div>'),

	initialize: function(options){
		this.options = Object.extend({
			container: 'video_list',
			limit: 6,
			url: '',
			moreLabel: '',
			sort: [],
			moreLabel: '',
			projectId: null,
			filters: [],
			settingsPanel: null
		}, options);
		
		this.more = new Element('span', { className : 'boxy' }).insert(
		    new Element('a', {
				href: '#',
				className: 'italic color-6 dotted-1',
				onclick: 'return false;'
			}).observe('click', function(event){
				this.get();

				//e.cancelBubble is supported by IE - this will kill the bubbling process.
				event.cancelBubble = true;
				event.returnValue = false;

				//e.stopPropagation works only in Firefox.
				if (event.stopPropagation) {
					event.stopPropagation();
					event.preventDefault();
				}

				return false;
			}.bind(this)).update(this.options.moreLabel + '<span>&nbsp;&rarr;</span>'));

        this.list = new Element('div', {});
        this.container = $(this.options.container);
        this.container.appendChild(this.list);
        this.container.appendChild(this.more);

        if (this.options.settingsPanel) {
            this.settingsPanel = $($$(this.options.settingsPanel)[0]);
            this.createOptions();
        }

        // this.container.appendChild( new Element('span').update('&nbsp;&rarr;') );
	},
	createOptions: function() {
	    this.settingsList = new Element('ul', {className: 'filters'});
	    this.settingsPanel.insert(this.settingsList);
	    if (this.options.sort) {
	        this.createSettings('Сортировка: ', 'sort', this.options.sort, this.changeSort);
            if (this.options.filters) this.settingsList.insert(new Element('li', {className: 'separator'}));
	    }
        if (this.options.filters) this.createSettings('Фильтр: ', 'filter', this.options.filters, this.changeFilter);
	},
	createSettings: function(title, className, settings, callback) {
	    var name = new Element('li', {className: 'first'}).update(title);
	    this.settingsList.insert(name);
	    settings.each(function(opts){
	        var opt = new Element('a', {href: '#'}).update(opts.label)
	        this.settingsList.insert(new Element('li', {className: className}).insert(opt));
	        opt.observe('click', callback.bind(this, opts[className], className));
	    }.bind(this));
	},
    setUrl: function(url) {
        this.options['url'] = url;
        return this;
    },
    setProjectId: function(id) {
        this.options['projectId'] = id;
        return this;
    },
    changeSort: function(sort, className, evt) {
        this.sort = sort;
        evt.stop();
        this.settingsList.select('li.' + className).invoke('removeClassName', 'active');
        $(evt.target).up('li').addClassName('active');
        this.clear().get();
    },
    changeFilter: function(sort, className, evt) {
        this.type = sort;
        evt.stop();
        this.settingsList.select('li.' + className).invoke('removeClassName', 'active');
        $(evt.target).up('li').addClassName('active');
        this.clear().get();
    },
	get: function(parameters){
		this.params = Object.extend({
			from: this.from,
			sort: this.sort, //(this.options.sort.size() > 0 ) ? (this.options.sort.first().sort) : false,
			limit: this.options.limit,
			type: this.type,
			id: this.options.projectId
		}, parameters);

		if (!this.requestSent) {
		    this.requestSent = true; // prevent really FAST sequence of clicks (hitting Enter, for example)
    		new Ajax.Request(this.options.url, {
    			contentType: 'application/json',
    			method: 'get',
    			onComplete: function(transport){
    			    this.requestSent = false;
    				json = transport.responseJSON;
    				this.build(json.data);
    				this.from += json.count;
    				if(json.count < this.options.limit || json.total <= this.from){
    					this.more.hide();
    				}
    			}.bind(this),
    			parameters: this.params
    		});
        }
	},

	createNode: function(node, index){
	    var el = new Element('div', {className: 'column span-1 height-1 border-2'});
	    el.innerHTML = this.nodeTemplate.evaluate(node);
	    return el;
	},

	clear: function(force){
		this.h = 0;
		this.from = 0;
        this.list.childElements().invoke('remove');
		return this;
	},

	build: function(json){
    	var self = this;
	    json.map(this.createNode.bind(this)).inGroupsOf(2).each(function(group){
	        var elt = new Element('div', {className: 'container margin-4'});
	        group.each(function(v){if (v) elt.insert(v);});
	        self.list.insert(elt);
	    });
	}
});


var AnchorNav = Class.create({
    initialize : function(options) {
        Object.extend(this, options);
        this.run();
        if (window.location.hash) {
            var elem = $($$('a[href=' + window.location.hash+ ']').first());
            if (elem) this.processLink(elem);
        }
    },
    run : function() {
        $$(this.selector).filter(function(v){ return !$(v).readAttribute('href').startsWith('#'); }).invoke('stopObserving', 'click').each(this.anchor).invoke('observe', 'click', this.observer.bind(this));
    	//if (Cufon) Cufon.refresh('h1.key-color, h2.key-color, h3.key-color, h4.key-color, h5.key-color, h6.key-color, a.menu-url, li.menu-fruit-element a');
    },
    anchor : function(elem) {
        elem.writeAttribute('href', '#' + elem.readAttribute('href'));
    },
    loadTarget : function(type, data) {
        var type = type.split(':');
        var target = (type[1] ? $(type[1]) : $(this.target));
        switch (type[0]) {
            case 'replace' : target.innerHTML = data.responseText; break;
            case 'append'  : target.innerHTML += data.responseText; break;
        }
        this.run();
    },
    processLink : function(target) {
        var link = target.readAttribute('href').split('#')[1];
        this.showactive(target);
        var type = target.readAttribute('rel') || 'replace';
        if (link){
            new Ajax.Request(link, {
                parameters: {
                    is_ajax: 1
                },
                evalJS : false,
                onSuccess : this.loadTarget.bind(this, type)
            });
        }
        return false;
    },
    observer : function(e) {
        var target = $(e.target);
        this.processLink(target);
    },
    showactive : function(target)
    {
    	$$(this.selector).each(function(elem) { elem.removeClassName('nodecoration').removeClassName('color-6').addClassName('dashed-1 color-1') });
    	target.addClassName('nodecoration color-6').removeClassName('dashed-1 color-1');
    }
});

var CProgrammPopups = Class.create({
    popup: null,
    initialize: function() {
        $('insertajax').observe('mouseover', this.mouseOver.bind(this));
        //$$('table.programm td.t-name a').invoke('observe', 'mouseover', this.mouseOver.bind(this));
        this.popup = new Element('div');
        this.popup.setStyle({background: '#f2f2f2'});
        this.popup.observe('mouseover', this.popupOver.bind(this));
        this.popup.hide();
        document.body.appendChild(this.popup);
    },
    lookupTarget: function(node) {
        return $($(node).up('tr.pop'));
    },
    renderTable: function(target, html) {
        var table = '<div class="popup-tele">\
            <table class="teleprogramm">\
                <tbody>\
                    <tr>' + target.innerHTML + '</tr>\
                </tbody>\
            </table>\
            <div style="padding: 0 1px; text-align: left;">' + html + '</div>\
        </div>';
        return table;
    },
    positionPopup: function(position) {
        var widths = ['22px', Prototype.Browser.IE ? '50px' : '53px','427px', '0px'],
            offset = Prototype.Browser.IE ? 13 : 11;
        this.popup.setStyle({
            position: 'absolute',
            top: (position.top - 2).px(),
            left: (position.left - offset).px()
        });

        this.popup.select('tr:first-child td').each(function(v,k){
            // console.log(v,k);
            $(v).setStyle({
                width: widths[k],
                border: 'none'
            });
        });
    },
    mouseOver: function(e) {
        var target = this.lookupTarget(e.target),
            html = $(target.down('div.shitty_announce')).innerHTML;
        e.stop();
        this.popup.innerHTML = this.renderTable(target, html);
        this.positionPopup(target.cumulativeOffset());
        this.popup.show();
    },
    popupOver: function(e) {
        var target = $(e.target);
        if (target.nodeName != 'TR' && target.up('tr') === undefined) this.popup.hide();
        e.stop();
        return true;
    }
});

var PrivateMessagePopup = Class.create({
	endpoint: '/system/php/profile/private_message_endpoint.php',
	to: null,
	link: null,
	popup: null,
	subject: null,
	message: null,
	sendButton: null,
	cancelButton: null,
	initialize: function(elem, to){
		this.link = elem;
		this.to = to;
		this.sendButton = new Element('a', {href: '#', className: 'send-button'}).update('Отправить');
		this.cancelButton = new Element('a', {href: '#', className: 'color-3 padding-2'}).update('Отменить');
		this.createPopupWindow();
		this.initObservers();
	},
	initObservers: function() {
		this.link.observe('click', this.showPopup.bind(this));
		this.cancelButton.observe('click', this.hidePopup.bind(this));
		this.sendButton.observe('click', this.sendMessage.bind(this));
	},
	sendMessage: function(evt) {
		evt.stop();
		var self = this;
		var invalidInputs = [this.subject, this.message].filter(function(s){return s.value.length == 0;});
		if (invalidInputs.length == 0) { 
			new Ajax.Request(this.endpoint, {
				parameters: {
					to: this.to,
					subject: this.subject.value,
					message: this.message.value
				},
				onSuccess: function(data) {
					if (data && data.responseJSON && data.responseJSON['status']) {
						self.popup.hide();
					} else {
						alert('Произошла ошибка при отсылке личного сообщения...');
					}
				}
			});
		} else {
        	invalidInputs.each(function(elem){
        		new Effect.Highlight(elem, {
                	startcolor: '#ee6666',
                    endcolor: '#ffffff',
                    duration: 0.3
                })
            });
		}
		return false;
	},
	decorate: function(name, element) {
		var label = new Element('label', {'for': element.id}).update(name),
			wrapper = new Element('div').insert(label).insert(element);
		return wrapper;
	},
	createPopupWindow: function() {
		this.popup = new Element('div', {className: 'private-message-popup'});
		this.popup.insert(
			new Element('h3', {className: 'color-1'}).update('Написать сообщение')
		);
		this.popup.hide();
		document.body.appendChild(this.popup);
		var linkPosition = this.link.cumulativeOffset();
		this.popup.setStyle({
			position: 'absolute',
			top: linkPosition.top.px(),
			left: (linkPosition.left - 60).px()
		});	
		this.subject = new Element('input', {id: 'subject-' + Math.random(5000), type: 'text'});
		this.message = new Element('textarea', {id: 'message-' + Math.random(5000)});
		this.popup.insert(this.decorate('Тема', this.subject));
		this.popup.insert(this.decorate('Текст', this.message));
		this.popup.insert(new Element('div', {className:'control'}).insert(this.sendButton).insert(this.cancelButton));
	},
	showPopup: function(evt) {
		evt.stop();
		this.popup.show();
		return false;
	},
	hidePopup: function(evt) {
		evt.stop();
		this.popup.hide();
		return false;
	}
});

var loadDynamic = function(url) {
    var head = $$('head')[0];
    if (head) {
        var script = new Element('script', { type : 'text/javascript', src : url });
        head.appendChild(script);
    }
}
window.onload = function(){

	/*
	$('mainmenu').select('li').each(function(item, index){
		var sub = item.select('.menu-sub');
		if(sub[0]){
			sub = sub[0];
			item.observe('mouseover', function(event){
                stillOver = true;
                item.addClassName('active');
                sub.show();
			});
            if (Prototype.Browser.IE) {
    			var stillOver = false;
    			item.observe('mouseout', function(event){
                    stillOver = false;
                    setTimeout(function(){
                        if (!stillOver) {
                            item.removeClassName('active');
                            sub.hide();
                        }
                    }, 200);
    			});
    	    } else item.observe('mouseout', function(event){
                item.removeClassName('active');
                sub.hide();
    	    })
		}
	});
	*/
	
	/* if( $('login-popup') )
	{
		var showEnter = function(evt)
						{					
						  	var pop = $('login-popup');
						  	if(pop.style.display != 'block')
						  		pop.setStyle({display: 'block'});
						};
						
		var hideEnter = function(evt)
					    {					
						  	var pop = $('login-popup');
						  	if(pop.style.display == 'block')
					  			pop.setStyle({display: 'none'});
					    };
					    
		$('login-popupenter').observe('mouseover', showEnter);								 
		$('login-popup').observe('mouseout',hideEnter).observe('mouseover',showEnter);
		$('login-cancel').observe('click', hideEnter);
	}*/
	
	if($('slider-handle') && $('slider-track')){
		var slider = new UI.Slider('slider-handle', 'slider-track', {
			area: 'slider_area',
			elements: 'li',
			min: 4,
			onItemOver: function(slider){
				slider.area.select('a').each(function(item){
					item.observe('mouseover', function(event){
						item.addClassName('hover');
					}).observe('mouseout', function(event){
						item.removeClassName('hover');
					});
				});
			},
			onSlide: function(v){
				slider.area.scrollLeft = Math.round(v / slider.maximum * (slider.area.scrollWidth - slider.area.offsetWidth));
			},
			onChange: function(v){
				slider.area.scrollLeft = Math.round(v / slider.maximum * (slider.area.scrollWidth - slider.area.offsetWidth));
			}
		});
	}

	if ($('programm-list')) new CProgrammPopups();

    var loginForm = $('login-form');
    if (loginForm) {
        $(loginForm.down('input[type=submit]')).observe('click', function(evt){
            evt.stop();
            loginForm.request({
                onComplete: function(data){
                    if (data && data.responseJSON && data.responseJSON['status']) window.location.reload(true);
                    else loginForm.select('input[type!=submit]').each(function(elem){
                        new Effect.Highlight(elem, {
                            startcolor: '#ee6666',
                            endcolor: '#ffffff',
                            duration: 0.3
                        });
                    });
                }
            });
            return false;
        });
    }

	new AnchorNav({
	    selector: 'a.anchornav',
        target: 'insertajax'
	});

    if ($('program_search')) {
        loadDynamic('/js/program_search.js?random=' + 1000*Math.random(100000));
    }

/*
	konami.code = function(){
		$('header').addClassName('carpet-rise');
	}
	konami.load();

    Ajax.Responders.register({ onComplete : function(){
        Cufon.refresh('h1.key-color, h2.key-color, h3.key-color, h4.key-color, h5.key-color, h6.key-color, a.menu-url, li.menu-fruit-element a, button.ui-button span');
    }});
*/
    if ($('remove-account-link')) $('remove-account-link').observe('click',function(evt){
        if (!confirm('Вы уверены, что хотите удалить учетную запись?')) {evt.stop();return false;}
    });
}

