// основной скрипт

jQuery(function($){
    fixIE7();
    $('.target-blank').attr('target', '_blank');

    $('.widget-about').widget({closeOnTitleClick: true});
    $('.widget-contact').contactWidget();
    $('.recent-works .slides').frontSlider({backSlider: '#sliderContainer'});
    $('#sliderContainer').backSlider({frontSlider: '.recent-works .slides'});
    
});

(function ($) {
    
    $.Controller('BackgroundResizer', 
        {
            pluginName: 'bgResizer'
        }, 
        {
            init: function () {
                this.slideContainer = this.find('.slides');
                this.slides = this.slideContainer.find('.slide');
                this.startSlideCount = this.slides.length;
                this.window = $(window);
                this.doc = $(document);
                this.notChecked = true;
                this.loaded = false;
                
                var self = this;
                $('#sliderContainer img').each(function () {
                    var img = $(this);
                    img.attr('src', img.attr('src'));
                    img.bind('load', self.proxy(function (ev) {
                        this.resizeBG();
                    }));
                });
                //this.resizeBG();
                this.onLoadTimeout();      
            },
            
            onLoadTimeout: function () {
                if (!this.loaded) {
                    setTimeout(this.proxy(function () {
                        this.resizeBG();
                        this.onLoadTimeout();
                    }), 200);
                }
            },
            
            '{window} resize': function () {
                this.resizeBG();
            },
            '{window} load': function () {
                this.resizeBG();
                this.loaded = true;
            },
            '{document} ready': function () {
                this.resizeBG();
            },
            
            resizeBG: function () {
                var screenX = this.window.width(),
                    screenY = this.window.height(),
                    docX = this.doc.width(),
                    docY = this.doc.height();
                
                screenX = screenX < docX ? docX : screenX;
                screenY = screenY < docY ? docY : screenY;
                var ratio = screenX / screenY;
                
                var slideHeight = null,
                    slideHeightStart = parseInt(this.slides.eq(0).height(), 10);
                    
                this.slides = this.slideContainer.find('.slide');

                this.slides.each(function () {
                    var slide = $(this),
                        img = slide.find('img'),
                        imgX = img.width(),
                        imgY = img.height(),
                        imgRatio = imgX / imgY,
                        width, height, top, left,
                        align = slide.attr('data-align');
                        
                    if ($.inArray(align, ['bottom', 'top', 'center']) < 0) {
                        align = 'center';
                    }
                    
                    if (ratio >= imgRatio) {
                        width = screenX;
                        height = screenX / imgRatio;
                        switch (align) {
                            case 'center':
                                top = parseInt(-(height - screenY) / 2, 10);
                                break;
                                
                            case 'top':
                                top = 0;
                                break;
                                
                            case 'bottom':
                                top = -(height - screenY);
                                break;
                        }
                        left= 0;
                        
                    } else {
                        height = screenY;
                        width = screenY * imgRatio;
                        left = parseInt(-(width - screenX) / 2, 10);
                        top = 0;
                    }
                    
                    img.css({
                        top: top,
                        left: left,
                        width: parseInt(width, 10), 
                        height: parseInt(height, 10)
                    });
                    slide.css({
                        width: screenX,
                        height: screenY
                    });
                    slideHeight = screenY;
                });
                
                if (!this.notChecked) {
                    var containerSlidesNum = parseInt(this.slideContainer.height() / slideHeightStart, 10),
                        containerSlidesTopNum,
                        containerTop = 0;

                    if (parseInt(this.slideContainer.css('top'), 10) !== 0) {
                        containerSlidesTopNum = parseInt(parseInt(this.slideContainer.css('top'), 10) / slideHeightStart, 10);
                        containerTop = (containerSlidesTopNum * slideHeight) + 'px';
                    } 
                    
                    this.slideContainer.css({
                        height: (slideHeight * containerSlidesNum) + 'px',
                        top: containerTop
                    });
                    
                }
                this.notChecked = false;
                this.element.trigger('resized');
            }
        }
    );

    $.Controller('Widget', 
        {
            defaults: {
                closeOnTitleClick: false
            }
        },
        {
            init: function (el) {
                this.o = this.options;
                this.closeButton = this.find('.close-button');
                this.content = this.find('.widget-content');
                if (this.o.closeOnTitleClick) {
                    this.find('.title').css({'cursor': 'pointer'});
                }
            },
            '.close-button click': function (el, ev) {
                this.toggle();
            },
            '.title click': function () {
                if (this.o.closeOnTitleClick) {
                    this.toggle();
                }
            },
            toggle: function () {
                if (this.element.is('.closed')) {
                    this.open();
                } else {
                    this.close();
                }
            },
            open: function () {
                this.content.stop(false, true).fadeIn('fast');
                this.element.removeClass('closed');
            },
            close: function () {
                this.content.stop(false, true).fadeOut('fast');
                this.element.addClass('closed');
            }
        }
    );
    
    $.Controller('ContactForm', 
        {
            pluginName: 'contactForm',
            defaults: {
                validation: {
                    errorPlacement: function (error, element) {},
                    highlight: function (element, errorClass) {
                        $(element).closest('.row').addClass(errorClass);
                    },
                    unhighlight: function (element, errorClass) {
                        $(element).closest('.row').removeClass(errorClass);
                    }     
                }
            }
        },
        {
            init: function (el) {
                this.o = this.options;
                this.element.validate(this.o.validation);
            },
            
            'submit': function (el, ev) {
                ev.preventDefault();
                if (this.element.valid()) {
                    $.post('/', this.element.formParams(), this.proxy(this.successSubmit));
                }
            },
            
            '.submit click': function (el, ev) {
                ev.preventDefault();
                this.element.submit(); 
            },
            
            successSubmit: function (response) {
                if (response.status == 'success') {
                    location = '/thankyou/';
                } else {
                    $.each(response.errors, this.proxy(function (name, val) {
                        this.find('[name="Contact[' + name + ']"]').closest('.row').addClass('error');
                    }));
                }
            }
        }
    );
    
    Widget('ContactWidget',
        {
            pluginName: 'contactWidget',
            defaults: {
                closeOnTitleClick: true
            },
            listenTo: ['mousewheel']
        },
        {
            init: function (el) {
                this._super(el);
                this.find('form').contactForm();
            },
            'mousewheel': function (el, ev) {
               ev.stopPropagation();
            }
        }
    );
    
    $.Controller('FrontSlider',
        {
            pluginName: 'frontSlider',
            listenTo: ['mousewheel', 'scrolled']
        },
        {
            init: function () {
                // запускаем слайдер
                var oCarousel, 
                    self = this;
                this.element.jcarousel({
                    auto:0,
                    //wrap:'circular',
                    scroll:2,
                    easing: 'easeInOutCubic',
                    initCallback: function (carousel) {
                        self.carousel = carousel;
                    } 
                });
                //this.carousel = oCarousel;
                //console.log(oCarousel);
                this.selectedByBack = false;
                
                this.slides = this.find('.slide');
                this.slidesCount = this.slides.length;
                this.slides.each(function () {
                    var slide = $(this),
                        popup = slide.find('.popup'),
                        left = parseInt((slide.innerWidth() - popup.width()) / 2, 10);
                    popup.css({left: left + 'px'});
                    setTimeout(function () {
                        left = parseInt((slide.innerWidth() - popup.width()) / 2, 10);
                        popup.css({left: left + 'px'});
                    }, 1000);
                });
                
                this.backSlider = $(this.options.backSlider);
                this.backSlider.bind('scrolled.slider', this.proxy(function (ev, index, repeat) {
                    index = typeof index === 'undefined' ? 0 : index;
                    
                    var nIndex = this.normalizeIndex(index),    
                        fIndex = this.normalizeIndex(this.carousel.first),
                        lIndex = this.normalizeIndex(this.carousel.last),
                        scroll = true;
                    if (nIndex >= fIndex && nIndex <= lIndex) {
                        scroll = false;
                    }
                    this.setActive(index, scroll);

                }));
                
                // устанавливаем первый элемент
                this.setActive(1);
            },
            
            'mousewheel': function (el, ev, delta) {
                ev.preventDefault();
                ev.stopPropagation();
                this.carousel[delta > 0 ? 'prev' : 'next']();
            }, 
            
            setActive: function (index, scroll) {
                scroll = typeof scroll === 'undefined' ? true : !!scroll;
                var index2 = (index - 1) % this.slidesCount + 1;
                index2 = index2 <= 0 ? index2 + this.slidesCount : index2;
                
                this.find('.slide').removeClass('active');
                this.current = this.carousel.get(index2);
                this.current.addClass('active');
                if (scroll) {
                    this.carousel.scroll(index2);
                }

                this.element.trigger('selected', index2);
            },
            
            '.slide click': function (el, ev) {
                var index = parseInt($(el).attr('jcarouselindex'), 10);
                this.backSlider.controller && this.backSlider.controller() && (this.backSlider.controller().selectedByFront = true);
                this.setActive(index, false);
                $(el).addClass('active');
            },
            
            destroy: function () {
                this.backSlider.unbind('scrolled.slider');
            },
            
            normalizeIndex: function (index) {
                index = (index - 1) % this.slidesCount + 1;
                index = index <= 0 ? index + this.slidesCount : index;
                return index;
            }
        }
    );
    
    $.Controller('BackSlider',
        {
            pluginName: 'backSlider',
            listenTo: ['mousewheel', 'selected']
        },
        {
            init: function () {
                var self = this;
                var oCarousel;
                
                this.frontSlider = $(this.options.frontSlider);
                
                this.element.jcarousel({
                    auto:0,
                    //wrap:'circular',
                    easing: 'easeInOutCubic',
                    scroll:1,
                    vertical: true,
                    buttonNextHTML: null,
                    buttonPrevHTML: null,
                    animation: 1000,
                    initCallback: function (carousel) {
                        self.carousel = carousel;
                    },
                    itemVisibleInCallback: {
                        onBeforeAnimation: function(carousel, index, num) {
                            self.element.trigger('scrolled', num, true);    
                        }
                    }
                });
                //this.carousel = oCarousel;
                this.selectedByFront = false;
                
                // приделываем ресайзер
                this.element.bgResizer();
                
                this.frontSlider.bind('selected.slider', this.proxy(function (ev, index) {
                    this.carousel.list.stop(false, true);
                    // this.carousel.animating = false;
                    this.carousel.scroll(index);
                }));
            },
            
            '{document} resized': function () {
                this.carousel.reload();
            },
            
            '{document} mousewheel': function (el, ev, delta) {
                ev.preventDefault();
                ev.stopPropagation();
                this.carousel[delta > 0 ? 'prev' : 'next'](3);
            },
            
            destroy: function () {
                this.frontSlider.unbind('selected.slider');
            }
        }
    );

})(jQuery);


function fixIE7()
{   
    (function ($) {
        if ($.browser.msie && parseInt($.browser.version, 10) < 8) {
            $('.clients .client').each(function () {
                var client = $(this),
                    img = client.find('img'),
                    padding = parseInt((client.height() - img.height()) / 2 - 3, 10);

                img.css('padding-top', padding + 'px');
            });
        }
    })(jQuery);
}
