window.addEvent('domready', function(){
	var slide_count = 5;
	var old_slide = null, new_slide = null;
	var duration_ = 300;
	var active_show = true;
	var screen = $("screen");
	var heap = $("heap");
	var arrow = $('arrow-inner');
	var last_slide_switched = true;
	
        if (screen && heap && arrow){
            arrow.set('morph', {duration: duration_, transition: 'sine'})
            
            function get_slidenum(menuelem){
                    return Number(menuelem.get('id').split('-')[1])
            }
            function setprops(el){
                    el.set('morph', {duration: duration_/2, transition: 'sine'})
                    el.setProperty('number', get_slidenum(el))
            }
            $$('.slide').each(setprops);
            $$('.slide_list li').each(setprops);
            
            
            function get_slide(number){return $('slide-' + number)}
            function get_menu (number){return $('slidemenu-' + number)}
            function morphin(number){get_menu(number).morph({'color': '#ffffff'});}
            function morphout(number){get_menu(number).morph({'color': '#000000'})}
            
            function show_slide(number){
                    if (new_slide)
                            var oldnum = new_slide.getProperty('number')
                    else
                            var oldnum = old_slide.getProperty('number')
                    if (oldnum == number) return null; // Если слайд не сменился
                    
                    if (old_slide && new_slide){
                            // Если нажимают на меню во время перестроения картинки
                            // сразу показывается нужная картинка без эффектов
                            old_slide.inject(heap);
                            new_slide.inject(heap);
                            morphin(number);
                            old_slide = get_slide(number).setStyles({
                                    'height': '400px',
                                    'opacity': 1
                            }).inject(screen, 'top');
    
                            new_slide = null;
                    } else {
                            new_slide = get_slide(number);
                            
                            old_slide.morph({'opacity': 0});
                            morphout(oldnum);
                            (function(){
                                    new_slide.setStyles({
                                    'opacity': 0,
                                    'overflow': 'hidden'
                                    }).inject(screen, 'top').morph({'opacity': 1});
                                    morphin(number);
                            }).delay(duration_/2);
    
                            var ns = new_slide, os = old_slide;
                            //old_slide.morph({'height': 0});
                            arrow.morph({'margin-top': 55 * (number-1)});
                            (function(){
                                    // После окончания анимации - подчищаем хвосты
                                    if (ns == new_slide && os == old_slide){
                                            // Если перекрытий анимации не было
                                            old_slide.inject(heap);
                                            old_slide = new_slide;
                                            new_slide = null;
                                    } else if (ns != old_slide){
                                            // Слайд сменился
                                            morphout(number);
                                    }
                                    if (!new_slide){
                                            // Анимация не в процессе
                                            var new_num = old_slide.getProperty('number');
                                    } else {
                                            // Анимация в процессе
                                            var new_num = new_slide.getProperty('number');
                                    }
                                    arrow.setStyle('margin-top', 55 * (new_num-1));
                            }).delay(duration_)
                    }
            }
            function next_slide(){
                    show_slide(old_slide.getProperty('number') % 5 + 1)
            }
            function slideshow(){
                    if (active_show){
                            //отключил слайд-шоу
                            //next_slide();
                            //slideshow.delay(15000);
                            last_slide_switched = true;
                    } else {
                            last_slide_switched = false;
                    }
            }
            
            old_slide = get_slide(1).inject(screen);
            morphin(1);
    
            slideshow.delay(15000);
            
            $$('#slide_list li').addEvent('click', function(){
                    if (active_show){
                            active_show = false;
                            (function(){
                                    active_show = true;
                                    slideshow();
                            }).delay(30000);
                    }
                    show_slide(get_slidenum(this))
                    last_slide_switched = true;
            })
        }

	var popup = new Popup({'top': 100});
	function close_form(){
		popup.hide();
		// Останавливаем показ слайдов
		active_show = true;
		//Если переключение слайда успело отработать вхолостую
		if (!last_slide_switched) slideshow.delay(15000);
	}
	
	function draw_form(response){
		if (response.success){
			close_form();
		} else {
			active_show = false;
			popup.container.set('html', response.html);
                        popup.show();
			var form = popup.container.getElement('form');
			form.addEvent('submit', function(event){
				event.stop();
				var dict = {};
				$A(form.elements).each(function(e){dict[e.name] = e.value})
				new Request.JSON({
					url: feedback_url,
					onComplete: draw_form
				}).post(dict)
			})
			new Element('a').addEvent('click', function(event){
				close_form();
				event.stop();
			}).set('html', '[x]').set('href', '#').inject(popup.container, 'top').setStyle('float', 'right');
			popup.centrize($('main')).scroll_to();
		}
	}
	$$('.want').addEvent('click', function(event){
		new Request.JSON({
			url: feedback_url,
			onComplete: draw_form
		}).get({});
		event.stop();
	})
})


/***
 * Каркас для создания всплывающих окошек...
 * Взято из sample_project/media/js/popups.js, изменять и улучшать там!
 */

var Popup = new Class({
    initialize: function(args){
        this.hidden = true;
        var inject_into = (args.inject_into ? args.inject_into : $(document.body));
        if(args.create_element){
            this.create_element = args.create_element;
        }
        
        this.create_element().inject(inject_into);
        
        if(args.top){ this.element.setStyle('top', args.top + 'px') }
    },
    create_element: function(){
        this.element = new Element('div').addClass('popup').setStyles({
            'display': 'none',
            'position': 'absolute'
        });
        new Element('div').addClass('popup_top').inject(this.element);
        this.container = new Element('div').addClass('popup_middle').inject(this.element);
        new Element('div').addClass('popup_bottom').inject(this.element);
        return this.element;
    },
    hide: function(){
        this.hidden = true;
        this.element.setStyle('display', 'none');
        return this;
    },
    show: function(){
        this.hidden = false;
        this.element.setStyle('display', '');
        return this;
    },
    destroy: function(){
        this.element.destroy()
        return this;
    },
    centrize: function(rel){
        if (!rel) rel = $(document.body);
        coord = rel.getCoordinates();
        coord1 = this.element.getCoordinates();
        this.element.setStyles({
                'left': (coord.left + (coord.width - coord1.width) / 2) + 'px'
        });
        return this;
    },
    scroll_to: function(){
        var top = this.element.getCoordinates().top;
        if (window.getScroll().y > top)
            window.scrollTo(0, top-50);
        return this;
    }
    
});
