// Cufon.replace('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, .authbar a.key-color', {
//     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(this).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()] ];
    },
    fuzzy: function() {
        var diff = this / 1000, l = [60/*m*/,24/*h*/,30/*mnth*/,12/*yr*/], cnt = 0;
        return '';
        //return Math.ceil(this / (1000*60*60));
    }
});

Object.extend(Date, {
    fromMySQL: function(timestamp) {
        var regex = /^([0-9]{2,4})-([0-1][0-9])-([0-3][0-9]) (?:([0-2][0-9]):([0-5][0-9]):([0-5][0-9]))?$/;
        var parts = timestamp.replace(regex, "$1 $2 $3 $4 $5 $6").split(' ');
        return new Date(parts[0], parts[1] - 1, parts[2], parts[3], parts[4], parts[5]);
    }
});

Object.extend(Array.prototype, {
    takeWhile: function(iterator) {
        var l = this.length,
            result = [];
        for (var i = 0; i < l && iterator(this[i]); result.push(this[i]), i++);
        return result;
    },
    sum: function() {
        return this.inject(0, function(acc,n){ return acc + n; });
    }
});

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({
					top : ((offset.top) - 22).px(),
					left : ((offset.left) - (Prototype.Browser.IE ? 34 : 36)).px()
				});
				this.updateContainer(content).show();

                event.stop();
			}.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();
				event.stop();
			}.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: 56,
	maxHeight: 375,
	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{
					var size = this.maxHeight * this.maxHeight / Math.min(1000, this.getAreaHeight());
					//если нечего скроллировать, то нужно прибить слайдер
					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()});
						}
					}
					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){			
		Effect.toggle(element, 'slide', {duration: 0.5});
		return this;
	},

	expandAll: function(){
		$$(this.options.visibleSelector).each(function(visible){
			if(Element.visible(visible)){
				Effect.toggle(visible, 'slide', {duration: 0.5});
			}
		}.bind(this));
    },

    showVisible: function(element, image){
		if(this.options.expand){
			this.expandAll();
		}
		new Effect.SlideDown($(element), {duration: 0.5});
		$$(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: {},

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

		this.list = new Element('ul', {
							className: 'no-list news-list'
						});
		this.more = new Element('a', {
							href: '#from' + this.from,
							className: 'key-color-dashed',
							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);
	},

	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){
		return new Element('li', {
			className: 'news-block'
		}).insert(
			new Element('div', {
				className: 'left'
			}).insert(
			    new Element('a',{href: node.url}).insert(
    				new Element('img', {
    					width: 150, height: 100, alt: '', src: node.image
    				})
    			)
			)
		).insert(
			new Element('div', {
				className: 'right'
			}).insert(
				new Element('div', {
					className: 'news-date'
				}).update(node.date)
			).insert(
				new Element('a', {
					href: node.url,
					className: 'big key-color'
				}).update(node.name)
			).insert(
				new Element('p').insert(node.teaser)
			)
		).insert(new Element('div', {className: 'clearfix'}));
	},

	clear: function(force){
		if(force){
			this.cleared = false;
		}

		if(!this.cleared){
			this.from = 0;
			this.container.update();
			this.list.update();
			var divTop 		= new Element('div', {className: 'top'});
			var divBottom	= new Element('div', {className: 'bottom'});

			divTop.insert(this.list);
			divBottom.insert(
			    new Element('div', {
			            className : 'boxy'
			        }).insert(this.more)
			);
			this.container.insert(divTop);
			this.container.insert(divBottom);
			this.cleared = true;
		}
		return this;
	},

	build: function(json){
		json.each(function(news, index){
			this.list.insert(this.createNode(news));
		}.bind(this));
        this.container.select('li.clearfix').invoke('remove');
		this.list.insert(new Element('li', {className: 'clearfix'}).setStyle({height: '1px', margin: 0, padding: 0}).update(' '));
	}
});


Video = {}
Video.List = Class.create({
	from: 0,
	cleared: false,
	sorted: false,
	filtered: false,
	params: {},
	options: {},
	container: {},
	requestSent: false,
	sortCurrent: '-_sort',
	filterCurrent: 0,

	initialize: function(options){
		this.options = Object.extend({
			container: 'news_list_list',
			sortContainer: "video_sort",
			limit: 6,
			sort: [],
			url: '',
			moreLabel: '',
			project_id: null
		}, options);

		this.more = new Element('div', { className : 'boxy' }).insert(
		    new Element('a', {
				href: '#',
				className: 'key-color-dashed',
				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.list = new Element('div', {});
		this.container = $(this.options.container);
	},
    setUrl: function(url) {
        this.options['url'] = url;
        return this;
    },
    setType: function(type) {
        this.filterCurrent = type;
        return this;
    },
    setProjectId: function(id) {
        this.options['project_id'] = id;
        return this;
    },
	get: function(parameters){
		this.params = Object.extend({
			from: this.from,
			sort: this.sortCurrent,//(this.options.sort.size() > 0 ) ? (this.options.sort.first().sort) : false,
			limit: this.options.limit,
			type: this.filterCurrent,
			//id: this.params.id ? this.params.id : null
			id: this.options['project_id']
		}, parameters);

		if (!this.requestSent) {
		    this.requestSent = true; // prevent really FAST sequance 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();
    				} else this.more.show();
    			}.bind(this),
    			parameters: this.params
    		});
        }
	},

	createNode: function(node, index){
		return new Element('div', {
			className: (index % 2) ? 'column span-1 last' : 'column span-1'
		}).insert(
			new Element('div', {
				className: 'video'
			}).insert(
			    new Element('a', {
			        href : node.url,
			        title : node.name,
					className: 'video-url'
			    }).insert(
    				new Element('img', {
    					width: 315, height: 130, alt: node.alt_name, src: node.video_image_banner
    				})
    			).insert(
					new Element('img', {
						alt: '',
						src: '/img/video/video_icon.png',
						className: 'video-icon-315x130 pngfix',
						style: "behavior: url('/css/iepngfix/iepngfix.htc')"
					})
				)
			)
		).insert(
			new Element('a', {
				className: 'big key-color',
				href: node.url
			}).update(node.name)
		).insert(
			new Element('div', {
				className: 'info'
			}).update(node.desc)
		).insert(
			new Element('p', {
				className: 'stat'
			}).update(node.views + ' ' + node.views.plural(['просмотр','просмотра','просмотров']) + '<br/>').insert((node.comments > 0) ?
			    	new Element('a', {href: node.url, title: node.name, className: 'comments-count'}).update(node.comments + ' ' + node.comments.plural(['комментарий','комментария','комментариев']))
			    	: ''
			)
		);
	},

	clearSort: function(){
		if((this.options.sort.size() > 0) && !this.sorted){
			this.sort = [];
			this.options.sort.each(function(item, index){
				var html = new Element("a", {
							href: '#',
							className: 'dashed video-sort' + ((item.sort == this.sortCurrent) ? " key-color-back selected" : ""),
							onclick: 'return false;'
						}).observe("click", function(event){
                            this.sort.each(function(tag){tag.html.removeClassName("key-color-back selected");});
                            html.addClassName("key-color-back selected");
                            this.clear(true);
                            this.sortCurrent = item.sort;
                            this.get();
                            event.stop();
                            return false;
						}.bind(this)).update(item.label);
				this.sort.push({
					html: html,
					sort: item.sort
				});
			}.bind(this));

			$(this.options.sortContainer).update();
			$(this.options.sortContainer).insert(new Element('span').update('Сортировка: '));
			this.sort.each(function(s){
				$(this.options.sortContainer).insert(s.html);
			}.bind(this));
			this.sorted = true;
		}
		if ((this.options.filters.size() > 0) && !this.filtered) { 
		    this.filters = [];
		    this.options.filters.each(function(item, index){
		        var html = new Element('a', {
		            href: '#',
		            className: 'dashed video-sort' + ((item.type == this.filterCurrent) ? ' key-color-back selected' : ''),
		            onclick: 'return false;'
		        }).observe('click', function(event) {
                    this.filters.each(function(tag){tag.html.removeClassName("key-color-back selected");});
                    html.addClassName('key-color-back selected');
                    this.clear(true);
                    this.filterCurrent = item.type;
                    this.get();
                    event.stop();
                    return false;
		        }.bind(this)).update(item.label);		        
		        this.filters.push({
		            html: html,
		            type: item.type
		        });
		    }.bind(this));
		    
		    $(this.options.sortContainer).insert(new Element('span', {className: 'divider'}).update(' ')).insert(new Element('span').update('Фильтр: '));
		    this.filters.each(function(s){
		        $(this.options.sortContainer).insert(s.html);
		    }.bind(this));
		    this.filtered = true;		    
		}
		return this;
	},

	clear: function(force){
		if(force){
			this.cleared = false;
		}

		if(!this.cleared){
			this.h = 0;
			this.from = 0;
			this.container.update();
			this.list.update();
			this.divTop 	= new Element('div', {className: 'top'});
			this.divBottom	= new Element('div', {className: 'bottom'});
			this.container.insert(this.divTop);
			this.container.insert(this.divBottom);
			this.divTop.insert(this.list);
			this.divBottom.insert(this.more);
			this.clearSort();
			this.cleared = true;
		}
		return this;
	},

    reset: function() {
        // this.list.innerHTML = '';
        this.list.childElements().invoke('remove');
        return this;
    },

	build: function(json){
		json.each(function(o, index){
			var element = this.createNode(o, index);
			this.list.insert(element);
//			this.h += element.getDimensions().height / 2;
			if(index % 2){
				this.list.insert(new Element('div', {className: 'clearfix column-clear'}));
			}
		}.bind(this));
		this.list.insert(new Element('div', {className: 'clearfix column-clear'}));
		this.container.select('div.clearfix').each(function(v){
		   var elem = $(v),
		       next = elem.next();
		   if (next && $(next).hasClassName('clearfix')) elem.remove();
		});
	}
});


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];
        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);
    }
});

var CProgrammPopups = Class.create({
    popup: null,
    initialize: function() {
        $('programm_list').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({
            width: '680px'
        //,padding: '0 5px'
        });
        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 style="background:url(/img/ui/popup/white-popup-top.png) no-repeat top left; height: 16px;"></div>\
        <div style="background:url(/img/ui/popup/white-popup-bottom.png) no-repeat bottom left; padding: 0 20px 16px 20px;">\
            <table class="tele-grid programm" style="width: 655px;padding:0px;margin:0px;border:none;">\
                <tbody>\
                    <tr style="white-space: nowrap;">' + target.innerHTML + '</tr>\
                </tbody>\
            </table>\
            <div style="padding: 0 8px; text-align: left;">' + html + '</div>\
        </div>';
        return table;
    },
    positionPopup: function(position) {
        var widths = ['47px','417px','135px'],
            offset = Prototype.Browser.IE ? 26 : 13;
            offset = 20;
        this.popup.setStyle({
            position: 'absolute',
            top: (position.top - 16).px(),
            left: (position.left - offset).px()
        });

        this.popup.select('tr:first-child td').each(function(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 CProgrammRefresh = Class.create({
    programm: null,
    startTime: null,
    diffs: [],
    initialize: function() {
        this.startTime = this.now();
        this.programm = $($('submenu').down('ul'));
        this.diffs = this.programm.select('a').map(function(elem){return $(elem).readAttribute('rel') ? parseInt($(elem).readAttribute('rel')) : null; }).reject(this.is_null);
        setInterval(this.scrollProgramm.bind(this), 60*1000);
    },
    is_null: function(item) { return item === null; },
    now: function() {
        return Math.round((new Date()).getTime() / 1000);
    },
    scrollProgramm: function() {
        if (this.diffs.length == 0) window.location.reload(true);
        if (this.now() - this.startTime >= this.diffs[0]) {
            this.diffs[0] = null;
            this.diffs = this.diffs.reject(this.is_null);
            this.scrollItem();
        }
    },
    scrollItem: function() {
        var elem = $(this.programm.select('li')[1]);
        new Effect.Fade(elem, {
            afterFinish: function() { elem.remove(); }
        });
    }
});

var CPoll = Class.create({
    options: {},
    top: null,
    bottom: null,
    initialize: function(options) {
        this.options = options;
        if (this.options['element']) this.run();
    },
    run: function() {
        this.buildPollLayout();
    },
    buildPollLayout: function() {
        this.top = new Element('div', {className: 'top'}).insert(
            new Element('div', {className: 'left'}).insert(new Element('img', {src: 'http://css.ctc-tv.ru/cache/54e91b59da781f220ac66b732538411c.png', alt: 'Опрос'}))
        ).insert(
            new Element('div', {className: 'right'})
        ).insert(
            new Element('div', {className: 'clearfix'})
        );
        this.bottom = new Element('div', {className: 'bottom'}).insert(
            new Element('h4').update(this.options['question'])
        );
        if (this.options['voted']) this.voted(); else this.bottom.insert(this.buildPollForm());
        if (this.options['background']) this.bottom.setStyle({
            backgroundImage: 'url(' + this.options['background'] + ')',
            backgroundRepeat: 'no-repeat',
            backgroundPosition: 'top left',
            height: this.options['backgroundHeight'].px()
        });
        this.options['element'].appendChild(this.top);
        this.options['element'].appendChild(this.bottom);
    },
    buildPollForm: function() {
        var form = new Element('form'), poll_id = Math.round(Math.random(1,100)*100000000);
        this.options['answers'].each(function(item, index){
            var choice_id = ['poll', poll_id, index].join('_'),
                choice = new Element('input', {type:'radio', id: choice_id, name:'poll_' + poll_id});
            choice.observe('click', this.choiceClick.bind(this, item['id']));
            form.appendChild(
                new Element('div').insert(
                    new Element('div', {className: 'left l-10'}).insert(choice)
                ).insert(
                    new Element('div', {className: 'left l-85'}).insert(
                        new Element('label', {'for': choice_id}).update(item['title'])
                    )
                ).insert(new Element('div', {className: 'clearfix'}))
            );
        }.bind(this));
        return form;
    },
    choiceClick: function(id) {
        new Ajax.Request(this.options['url'], {
            method: 'post',
            parameters: {
                _resource: 'rating',
                document_id: this.options['document_id'],
                vote_id: id,
                kind: 3,
                type: this.options['type']
            },
            onComplete: this.voted.bind(this)
        });
    },
    voted: function() {
        this.bottom.innerHTML = '<div class="poll-result">Спасибо, ваш голос учтён</div>';
    },
    getResults: function() {
        new Ajax.Request(this.options['url'], {
            method: 'get',
            parameters: {
                _resource: 'rating',
                document_id: this.options['document_id'],
                kind: 3
            },
            onComplete: this.drawResults.bind(this)
        });
    },
    drawResults: function(data) {
        var container = new Element('div');
        if (data && data.responseJSON) {
            var sum = data.responseJSON.inject(0, function(acc,n){return acc + parseInt(n['rating']);});
            data.responseJSON.each(function(item,index){
                var share = Math.ceil( 100 * item['rating'] / sum );
                container.insert(new Element('div', {className: 'vote-share'}).update(item['text'] + '&nbsp;&mdash;&nbsp;' + share + '%'));
            });
        }
        this.bottom.innerHTML = '';
        this.bottom.insert(container);
    }
});

var CBannersManager = Class.create({
    video: {},
    container: null,
    rotator: null,
    shadow: null,
    rotationElements: [],
    currentRotationElement: 0,
    offset: {},
    mouseState: 0,
    watchingVideo: false,
	flashvars: {
	    plugins:"http://css.ctc-tv.ru/js/lib/JPlayer/sts_jwplayer_plugin.swf",
		controlbar:"over",
		skin:"http://css.ctc-tv.ru/js/lib/JPlayer/sts_jwplayer_skin.swf",
		abouttext:"СТС-плеер",
		aboutlink:"http://www.ctc-tv.ru",
		bufferlength:.1,
		overstretch:"true"
	},	
	params: {
	    wmode:"opaque",
		menu:"true",
		allowFullScreen:"true",
		allowScriptAccess:"always"
	},
	rotationUpdateInterval: 2200,
	watchInterval: 2200,
	animationDuration: 0.5,
    initialize: function(container, rotator) {
        this.container = $(container);
        this.rotator = $(rotator);
        this.offset = this.rotator.cumulativeOffset();
        this.shadow = new Element('div', {
            style:'width:990px;height:360px;opacity:0.8;background:#333;position:absolute;top:'+this.offset.top+'px;left:'+this.offset.left+'px;padding:20px;z-index:9998;display:none;'
        });
        document.body.appendChild(this.shadow);
    },
    setVideo: function(video) {
        this.video = video;
        return this;
    },
    run: function() {
        this.initRotation();
        this.video.each(function(item,index){
            var bannerElement = $('promo_banner_' + item['id']);
            this.drawSticker(bannerElement, item).observe('click', this.embedSWF.bind(this, item));
        }.bind(this));
    },
    drawSticker: function(elem, item) {
        var sticker = new Element('div', {className:'video-sticker'}),
            parent = $(elem.parentNode);
        sticker.insert(new Element('img', {src: item['banner'], alt: item['name']}))
               .insert(new Element('img', {src: 'http://css.ctc-tv.ru/img/video/video_icon.png', className:'video-icon-315x130 pngfix',alt:''}))
               .insert(new Element('h4').update(item['name']));
        parent.appendChild(sticker);
        return sticker;
    },
    changeMouseState: function(state) {
        this.mouseState = state;
    },
    initRotation: function() {
        this.rotationElements = this.rotator.select('li');
        if (this.rotationElements.length > 1) {
            this.rotator.observe('mouseover', this.changeMouseState.bind(this, 1)).observe('mouseout', this.changeMouseState.bind(this, 0));
            setTimeout(this.rotateBanner.bind(this), this.watchInterval + this.rotationUpdateInterval);
        }
    },
    rotateBanner: function() {
        var rotatorUL = this.rotator.down('ul');
        if (this.mouseState || this.watchingVideo) return setTimeout(this.rotateBanner.bind(this), this.rotationUpdateInterval);
        if (this.currentRotationElement < this.rotationElements.length - 1) {
            $(this.rotationElements[this.currentRotationElement+1]).show();
            new Effect.Tween(rotatorUL, -990*this.currentRotationElement, -990*(this.currentRotationElement+1), {
                duration: this.animationDuration,
                // transition: Fx.Transitions.Cubic.easeInOut,
                afterFinish: function() {this.currentRotationElement++; setTimeout(this.rotateBanner.bind(this), this.watchInterval + this.rotationUpdateInterval);}.bind(this)
            }, function(p){rotatorUL.setStyle({left:p.px()});});
        } else {
            var fakeEl = new Element('li');
            rotatorUL.setStyle({width:(rotatorUL.getWidth()+990).px()});
            fakeEl.insert(this.rotationElements[0].childElements()[0].clone().writeAttribute('id', false));
            rotatorUL.appendChild(fakeEl);
            new Effect.Tween(rotatorUL, -990*this.currentRotationElement, -990*(this.currentRotationElement+1), {
                duration: this.animationDuration,
                // transition: Fx.Transitions.Cubic.easeInOut,
                afterFinish: function() {
                    this.currentRotationElement = 0; rotatorUL.setStyle({left:'0px',width:(rotatorUL.getWidth()-990).px()}); fakeEl.remove(); setTimeout(this.rotateBanner.bind(this), 300+this.rotationUpdateInterval);
                }.bind(this)
            }, function(p){rotatorUL.setStyle({left:p.px()});});
        }
    },
    embedSWF: function(item, event) {
        event.stop();
        this.watchingVideo = true;
        var replaceId = 'inner_' + this.container.readAttribute('id'),
            cutOff = Math.ceil( (990 - item['width']) / 2),
            closeButton = new Element('a', {href:'#'}).update('закрыть');
        this.container.insert(new Element('div', {id: replaceId}));
        this.flashvars['playlistfile'] = item['url'];
        swfobject.embedSWF('http://css.ctc-tv.ru/js/lib/JPlayer/player-licensed.swf', replaceId, item['width'], item['height'], "9.0.0", false, this.flashvars, this.params, {id:replaceId,name:replaceId});
        this.positionContainer();
        this.container.setStyle({height:'360px', width: (990 - cutOff).px(), paddingLeft: cutOff.px()});
        this.container.insert(new Element('div', {className:'promo_banner_link'}).insert(closeButton));
        this.container.show();
        this.shadow.show();
        closeButton.observe('click', function(evt){
            evt.stop();
            this.watchingVideo = false;
            this.container.childElements().invoke('remove');
            this.container.hide();
            this.shadow.hide();
        }.bind(this));
    },
    positionContainer: function() {
        this.container.setStyle({
            zIndex: 9999,
            position: 'absolute',
            top: this.offset.top.px(),
            left: this.offset.left.px(),
            padding: '20px',
            width: '990px'
        });
    }
});

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
var readyCallback = function(){

    var overLay = new Element('div');
    overLay.setStyle({
        background: 'url(/img/today2.png) no-repeat top left',
        width: '211px',
        height: '28px',
        position: 'absolute',
        zIndex: 4000,
        padding: '6px 10px',
        color: 'white',
        fontSize: '10px'
    });

    overLay.hide();


    var nowA = $($('submenu').select('li:first-child a')[0]),
        cumOff = nowA.cumulativeOffset();
    overLay.setStyle({
        top: (cumOff.top + 20).px(),
        left: cumOff.left.px()
    });
    var wdays = ['воскресенье','понедельник', 'вторник', 'среда', 'четверг', 'пятница', 'суббота'],
        months = ['января', 'февраля', 'марта', 'апреля', 'мая', 'июня', 'июля', 'августа', 'сентября', 'октября', 'ноября', 'декабря'];

    var twoDigits = function(num) {
        if (num >= 10) return num;
        else return '0' + num;
    }

    var updateTimer = function() {
        var date = new Date(),
            dateStr = ['Сегодня: ' + date.getDate() + ' ' + months[date.getMonth()], wdays[date.getDay()], twoDigits(date.getHours())+':'+twoDigits(date.getMinutes())].join(', ');
        overLay.update(dateStr);    
    }	
    updateTimer();
    document.body.appendChild(overLay);
    overLay.show();
    
	setInterval(updateTimer, 60*1000);
    
	$('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');
                overLay.hide();
                sub.show();
			});
            if (Prototype.Browser.IE) {
    			var stillOver = false;
    			item.observe('mouseout', function(event){
                    stillOver = false;
                    setTimeout(function(){
                        if (!stillOver) {
                            item.removeClassName('active');
                            overLay.show();
                            sub.hide();
                        }
                    }, 200);
    			});
    	    } else item.observe('mouseout', function(event){
                item.removeClassName('active');
                overLay.show();
                sub.hide();
    	    })
		}
	});

	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();
	new AnchorNav({
	    selector: 'a.anchornav',
        target: 'content'
	});

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

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

	// ховер меню для "вход"
	// start
    var loginLink = $('login-link');
    if (loginLink) 
    {
	    loginLink.observe('click', function(){
	        var ul = $(this.up('ul.no-list')).hide();
	        $(ul.next()).show();
	    });
	    
	    var stillHere     = false;
	    var showUserBar   = function() { stillHere = true;	$$('.menu-sub-enter')[0].show();  $$('.menu-login a')[1].addClassName('active');  }
	    var hideUserBar   = function() { $$('.menu-sub-enter')[0].hide(); $$('.menu-login a')[1].removeClassName('active'); }
	    var hideUserBarIE = function() { stillHere = false; setTimeout(function(){ if (!stillHere) hideUserBar(); }, 200); }
	    
	    loginLink.observe('mouseover', showUserBar);
	    $$('.menu-sub-enter')[0].observe('mouseover', showUserBar);				
	    if (Prototype.Browser.IE) 
		{
			loginLink.observe('mouseout', hideUserBarIE);
		    $$('.menu-sub-enter')[0].observe('mouseout', hideUserBarIE); 
	    }
	    else
	    {
	    	loginLink.observe('mouseout', hideUserBar);
	    	$$('.menu-sub-enter')[0].observe('mouseout', hideUserBar);
    	}
    	$$('.menu-sub-enter')[0].down('.dashed').observe('click', hideUserBar);
    }
    // end
    		
    // ховер меню для "здравствуйте, %username%"
    var userBar = $('user-bar2');
    if (userBar) 
    {
	    var stillHere     = false;
	    var showUserBar   = function() { stillHere = true; $$('.menu-sub-user')[0].show(); $('user_bar').addClassName('active');  }
	    var hideUserBar   = function() { $$('.menu-sub-user')[0].hide(); $('user_bar').removeClassName('active'); }
	    var hideUserBarIE = function() { stillHere = false; setTimeout(function(){ if (!stillHere) hideUserBar(); }, 200); }
	    
    	$('user_bar').observe('mouseover', showUserBar);
    	Prototype.Browser.IE ? $('user_bar').observe('mouseout', hideUserBarIE) : $('user_bar').observe('mouseout', hideUserBar);
	}
	// end ховер
	
    var loginForm = $('login-form');
    if (loginForm) {
        var formInputs = loginForm.select('input[type=text],input[type=password]');
        var sendAuthForm = function(evt) {
            evt.stop();
            loginForm.request({
                onComplete: function(data){
                    if (data && data.responseJSON && data.responseJSON['status']) window.location.reload(true);
                    else formInputs.each(function(elem){
                        new Effect.Highlight(elem, {
                            startcolor: '#ee6666',
                            endcolor: '#ffffff',
                            duration: 0.3
                        });
                    });
                }
            });
            return false;
        }
        $(loginForm.down('input[type=submit]')).observe('click', sendAuthForm);
        loginForm.observe('submit', sendAuthForm);
    }

    $$('input.place_holder').each(function(elem){
        var val = elem.value;
        $(elem).observe('blur', function(){
            if (elem.value == '') elem.value = val;
        }).observe('focus', function(){
            if (elem.value == val) elem.value = '';
        });
    });

    new CProgrammRefresh();
}
Event.observe(window, 'load', readyCallback);
