var application = {
    menu: function() {
        var pause = 150;
        $('.mm-item').each(function(){
            var link = $(this);
            var subMenu = link.children('div').hide();
            var timer = null;
            link.hover(
                function(){
                    clearTimeout(timer);
                    timer = setTimeout(function(){subMenu.fadeIn(150);}, pause);
                },
                function(){
                    clearTimeout(timer);
                    timer = setTimeout(function(){subMenu.fadeOut(150);}, pause);
                }
            );
        });
    },
    
    content_change: function()
    {
        var parDiv = $('.news_about-company');
        $('.links a').each(function(){
            var self=$(this);
            $(this).click(function(){
                var pos = $(this).attr('href');
                parDiv.find('.active').removeClass('active');
                parDiv.find('.news_about-company_content .news').hide();
                self.addClass('active');
                parDiv.find(pos).show();
                return false;
            });
        });
    },
    print: function()
    {
        $('.print').click(function(){
            addClass('print_clear');
        });
    },
    opisanie_gallery_object: function()
    {
        var parDiv = $('.why-shinglas');
        var list = $('.znachki li a');
        list.mouseenter(function(){
            parDiv.find('.act').removeClass('act');
            parDiv.find('.text').hide();
            parDiv.find($(this).attr('href')).show();
            $(this).addClass('act');
            
            return false;
        });
        list.first().mouseenter();
    },
    collection_chinglas: function()
    {
        var list    = $('.center .collections > .collect');
        var img     = $('.center .big_img_content > div');
        var banner  = $('.center .sidebar_right > .look_collection > div');
        var content = $('.center .classic-content > div');
        
        if (!(list.length && img.length && banner.length))
            return;
        
        list.click(function(){
            var rel = $(this).attr('rel');
            setActive(rel, list);
            setActive(rel, img);
            setActive(rel, banner);
            setActive(rel, content);
        });
        list.first().click();
        
        function setActive(target, list)
        {
            list.removeClass('active');
            list.filter('[rel="'+target+'"]').addClass('active');
        }
    },
    collectionPhoto: function()
    {
        $(".form-link").fancybox({
            'scrolling'		: 'no',
            'titleShow'		: false,
            'onClosed'		: function() {}
        });
    },
    ajaxCollections: {
        init: function() {
            var self = this;
            var conteiner = $('#collections');
            if (!conteiner.length)
                return;
            
            self.bindLinks(self, conteiner);
        },
        bindLinks: function(self, conteiner)
        {
            conteiner.find('a[rel!="js-link"]').click(function(){
                $.get('/ajax' + $(this).attr('href'), function(data){
                    conteiner.html(data);
                    self.bindLinks(self, conteiner);
                    application.gallery.init();
                    application.collectionPhoto();
                });
                return false;
            });
            conteiner.find('.gallery .slide-img').fancybox();
        }
    },
    ajaxGallery: {
        action: null,
        loadObject: false,
        
        init: function() {
            var form = $('#gallery-form');
            var content = $('#gallery-content');
            var self = this;
            
            if (!form.length || !content.length)
                return;
            
            self.action = '/ajax' + form.attr('action');
            
            form.ajaxForm({
                url: self.action,
                success: function(data) { 
                    self.success(self, data);
                }
            });
            self.object(self, $('#gallery-content'), true);
            self.fancy();
        },
        success: function(self, data)
        {
            var content = $('#gallery-content');
            content.html(data);
            self.pagination(self, content);
            self.object(self, content);
            self.loadObject = false;
        },
        pagination: function(self, conteiner)
        {
            conteiner.find('.numpage a').click(function(){
                $.get(self.action + $(this).attr('href'), function(data){ self.success(self, data) });
                return false;
            })
        },
        object: function(self, conteiner, contentLoaded){
            var list = conteiner.find('.gallery .img-tabs');
            var item = $('#gallery-item');
            if (contentLoaded)
                self.navigator(self);
            else
                item.empty();
            
            list.children('a').click(function(){
                var link = $(this);
                $.get('/ajax' + link.attr('href'), function(data){
                    list.removeClass('active');
                    link.parent().addClass('active');
                    item.html(data);
                    self.fancy();
                    self.navigator(self);
                });
                return false;
            });
            
            if (self.loadObject)
                list.filter(':'+self.loadObject).children('a').click();
        },
        navigator: function(self)
        {
            var numpage = $('.numpage li');
            var current = $('.gallery .img-tabs.active');
            var prev = $('#gallery-prev');
            var next = $('#gallery-next');
            var prevEl = current.prev();
            var nextEl = current.next();
            if (nextEl.is('hr')) nextEl = nextEl.next();
            if (prevEl.is('hr')) prevEl = prevEl.prev();
            
            bind(self, prevEl, prev, numpage, 'prev');
            bind(self, nextEl, next, numpage, 'next');
            
            function bind(self, target, button, numpage, type) {
                if (target.length)
                    button.click(function(){ target.children('a').click()});
                
                else if (numpage.filter('.'+type).length)
                    button.click(function(){
                        self.loadObject = (type == 'next') ? 'first' : 'last';
                        numpage.filter('.'+type).children('a').click();
                    });
                
                else
                    button.addClass('disabled').click(function(){ return false;});
            }
        },
        fancy: function()
        {
            $('#gallery-item').find('.images a').fancybox();
            
        }
    },
    faq: function()
    {
        $('.question_resullt').each(function(){
            var text = $(this).children('.answer_question').hide();
            $(this).find('h2 > a').click(function(){
                $(this).toggleClass('active');
                text.slideToggle();
                return false;
            });
        });
    },
    units: function()
    {
        $('.units h3').each(function(){
            var target = $(this).next('div').hide();
            $(this).children('a').click(function(){
                $(this).toggleClass('active');
                target.slideToggle();
                return false;
            });
        });
    },
    gallery: {
        options: {
            btnEnableClass: 'gallery-button-enable',
            step: 160,
            speed: 500,
            slidesPerStep: 1,
            slidesOnView: 1,
            current: 0,
            count: 0,
            timer: null,
            slideShow: false,
            slideShowSpeed: 4000
        },
        uri: {
            slider: '.slide-promo',
            count: '.slide-promo a',
            btnLeft: '.slide-left',
            btnRight: '.slide-right'
        },
        node: {
            slider: null,
            slideLeft: null,
            slideRight: null
        },
        init: function()
        {
            var self = this;
            
            self.node.slider = $(self.uri.slider);
            
            if (!self.node.slider.length)
                return;
            
            self.options.step = $(self.uri.count).filter(':first').outerWidth(true);
            self.options.slidesOnView = Math.round(self.node.slider.parent().width() / self.options.step);
            
            self.options.count = $(self.uri.count).length;
            self.node.slideLeft = $(self.uri.btnLeft);
            self.node.slideRight = $(self.uri.btnRight);
            
            if ((self.options.count-self.options.slidesOnView) > self.options.current)
                self.node.slideRight.addClass(self.options.btnEnableClass);
            
            self.node.slideRight.click(function(){
                clearInterval(self.options.timer);
                self.slideRight(self);
                return false;
            });
            
            self.node.slideLeft.click(function(){
                clearInterval(self.options.timer);
                self.slideLeft(self);
                return false;
            });
            
            if (self.options.slideShow)
                self.slideShow(self);
        },
        slideLeft: function(self)
        {
            if (self.options.current <= 0)
                return false;
            
            if ((self.options.current - self.options.slidesPerStep) >= 0)
                self.options.current -= self.options.slidesPerStep;
            else
                self.options.current = 0;
            
            self.node.slider.stop();
            self.node.slider.animate({'left':  (self.options.current*self.options.step*-1) + 'px'}, self.options.speed);
            
            if (!self.node.slideRight.hasClass(self.options.btnEnableClass))
                self.node.slideRight.addClass(self.options.btnEnableClass);
            
            if (self.options.current <= 0)
                self.node.slideLeft.removeClass(self.options.btnEnableClass);
            
            return true;
        },
        slideRight: function(self)
        {
            
            if (self.options.current >= (self.options.count - self.options.slidesOnView))
                return false;
            
            if ((self.options.current + self.options.slidesPerStep) <= (self.options.count - (self.options.slidesOnView + self.options.slidesPerStep - 1))){
                self.options.current += self.options.slidesPerStep;
            }
            else
                self.options.current = self.options.count - self.options.slidesOnView;
            
            self.node.slider.stop();
            self.node.slider.animate({'left':  (self.options.current*self.options.step*-1) + 'px'}, self.options.speed);
            
            if (!self.node.slideLeft.hasClass(self.options.btnEnableClass))
                self.node.slideLeft.addClass(self.options.btnEnableClass);
            
            if (self.options.current >= (self.options.count-self.options.slidesOnView))
                self.node.slideRight.removeClass(self.options.btnEnableClass);
            
            return true;
        },
        slideShow: function(self)
        {
            self.options.timer = setInterval(function() {
                if (!self.slideRight(self)) {
                    self.options.current = self.options.slidesPerStep;
                    self.slideLeft(self);
                }
            }, self.options.slideShowSpeed);
        },
        goTo: function(self, btn, pos)
        {
            self.node.slider.stop();
            self.node.slider.animate( { left: (self.options.step * pos * -1) + "px" }, self.options.speed );
            return true;
        }
    },
    formValidate: {
        init:function()
        {
            var self = this;
            $('form').submit(function(){
                var hasError = false;
                self.clear($(this));
                $(this).find('.required input:text, .required select, .required textarea').each(function(){
                    if (!$(this).is(':disabled') && $.trim($(this).val()) == ''){
                        $(this).addClass('error-empty-field');
                        if ($(this).is('select')) $(this).prev().addClass('error-empty-field');
                        hasError = true;
                    }
                });
                $(this).find('.required input:checkbox').each(function(){
                    if (!$(this).is(':checked')){
                        $(this).prev().addClass('error-empty-field');
                        hasError = true;
                    }
                });
                if (hasError){
                    alert('Вы заполнили форму не полностью');
                    return false;
                }
                return true;
            });
        },
        clear: function(node)
        {
            node.find('.error-empty-field').removeClass('error-empty-field');
            node.find('.error-field').removeClass('error-field');
            node.find('.error-field-message').remove();
        }
    },
    cuSel: function()
    {
        $('select').each(function(i){
            var select = $(this).css({opacity: 0, zIndex: 5, 'position': 'relative'});
            var id = 'select'+i;
            var newsel = $('<div class="select"><div><span><span id="%id%">%val%</span></span></div></div>'.replace('%id%', id).replace('%val%', select.children(':selected').text())).width(select.width());
            select.before(newsel);
            var sel = $('#'+id);
            select.change(function(){
                var selOption = select.children(':selected');
                sel.text(selOption.text());
                
                sel.removeClass('placeholder').parent().parent().removeClass('disabled');
                if (!selOption.val())
                    sel.addClass('placeholder');
                if (!select.children().length)
                    sel.parent().parent().addClass('disabled').parent().removeClass('error-empty-field');
                
            }).change();
        });
    },
    filterRelations: function()
    {
        var series = $('#f-series');
        var collection = $('#f-collection');
        var color = $('#f-color');
        
        if (!(series.length && collection.length && color.length))
            return;
        
        var list = {collection: makeList(collection.find('option')), color: makeList(color.find('option'))};
        
        bindEvent(list, series, color, collection);
        bindEvent(list, collection, color);
        
        function bindEvent(list, target, color, collection)
        {
            target.change(function(){
                var val = $(this).val() || 'all';
                if (collection){
                    collection.removeAttr('disabled').empty().append((list.collection[val] || []).join('')).change();
                    if (!collection.children().length) collection.attr('disabled', 'disabled');
                }
                color.removeAttr('disabled').empty().append((list.color[val] || []).join('')).change();
                if (!color.children().length) color.attr('disabled', 'disabled');
            });
        }
        function makeList(options)
        {
            list = {};
            var first = '<option value="">'+options.first().text()+'</option>';
            options.each(function(){
                var item = $(this);
                var rel = (item.attr('rel') || '').split(' ');
                if (rel[0]){
                    if (!list[rel[0]]) list[rel[0]] = [first];
                    list[rel[0]].push('<option value="'+item.val()+'">'+item.text()+'</option>');
                }
                if (rel[1]){
                    if (!list[rel[1]]) list[rel[1]] = [first];
                    list[rel[1]].push('<option value="'+item.val()+'">'+item.text()+'</option>');
                }
                if (!list['all']) list['all'] = [];
                list['all'].push('<option value="'+item.val()+'">'+item.text()+'</option>');
            });
            return list;
        }
    },
    formShow:
    {
        forms: ['#guarantee'],
        init: function()
        {
            var self = this;
            for (i in self.forms)
                self.ajaxForm($(self.forms[i]));
            
        },
        ajaxForm: function(form)
        {
            var self = this;
            form.attr('action', '/udata/webforms/c_send/');
            var preloader = form.find('.ajax-preloader');
            form.ajaxForm({
                beforeSubmit: function(){ preloader.fadeIn(); },
                success: function(responseText)
                {
                    preloader.fadeOut();
                    var data = $(responseText);
                    
                    if (data.find('success').text() == 0){
                        self.showErrors(data, form);
                        return;
                    }
                    
                    switch (data.find('udata').attr('method')) {
                        case 'c_send': self.sendmailSuccess(data, form); break;
                    }
                    formsVals.clear();
                }
            }); 
        },
        //beforeSend: function()
        sendmailSuccess: function(data, form) {
            if (data.find('message').length)
                $('#message').append('<p>Вы можете загрузить свой сертификат по <a href="'+data.find('message').text()+'" target="_blank" id="guarantee-pdf">данной ссылке</a></p>')
            
            form.find('.success').slideDown();
            form.find('fieldset').slideUp();
            form.get(0).reset();
        },
        showErrors: function(data, form)
        {
            $('#message2').empty().show();
            data.find('item').each(function(){
                $('<span>', {text: $(this).text(), 'class':'error-field-message'}).appendTo('#message2');//insertBefore(form.find($(this).attr('field')).addClass('error-field'));
                $($(this).attr('field')).addClass('error-empty-field');
            });
        }
    },
    fancyLinks: function()
    {
        $('.fancy-flash').each(function(){
            var item = $(this);
            var size = item.attr('target').split('*');
            
            item.fancybox({
                type: 'iframe',
                width: parseInt(size[0]) || 'auto',
                height: parseInt(size[1]) || 'auto'
            });
        });
        
        $('.fancy-popup').click(function(){
            $.fancybox({
                'padding'		: 0,
                'autoScale'		: false,
                'transitionIn'	: 'none',
                'transitionOut'	: 'none',
                'title'			: this.title,
                'width'		    : 630,
                'height'		: 495,
                'href'			: this.href.replace(new RegExp("watch\\?v=", "i"), 'v/'),
                'type'			: 'swf',
                'swf'			: {
                    'wmode'		: 'transparent',
                    'allowfullscreen'	: 'true'
                }
            });
            return false;
        });
        $('.fancy-image').fancybox();
    },
    placeholder: function()
    {
        $('input[placeholder], textarea[placeholder]').placeholder();
    },
    selectSite: function()
    {
        $('.select_sites').change(function(){
            if ($(this).val())
                window.location = $(this).val();
        });
    }
}
$(document).ready(function(){
    (function() {
        this.cuSel();
        this.menu();
        this.collectionPhoto();
        this.collection_chinglas();
        this.content_change();
        this.ajaxGallery.init();
        this.ajaxCollections.init();
        this.print();
        this.opisanie_gallery_object();
        this.faq();
        this.gallery.init();
        this.formValidate.init();
        this.filterRelations();
        this.formShow.init();
        this.fancyLinks();
        this.placeholder();
        this.selectSite();
        this.units();
    }).call(application);
    formsVals.init();
});

function showForm() {
    $(document).ready(function(){
        $(".form-link").click();
    });
}

formsVals = {
    init: function()
    {
        var self = this;
        this._save(self);
        this._load(self);
        this._clear(self);
    },
    clear: function() {  this._clear(this) },
    _save: function(self) {
        $('form').submit(function(i){
            var list = '';
            $(this).find('input:text, input:hidden, select, textarea').each(function(){
                if ((key = $(this).attr('id'))) {
                    self.cookie(key, $(this).val());
                    list += '|' + key;
                }
            });
            if (list != '')
                self.cookie('form_vals', list.substring(1));
            return true;
        });
    },
    _load: function(self) {
        if (!(fVals = self.cookie('form_vals')))
            return;
        for (i in (list = fVals.split('|'))) {
            $('#'+list[i]).val(self.cookie(list[i]));
        }
        
    },
    _clear: function(self) {
        if (!(fVals = self.cookie('form_vals')))
            return;
        self.cookie('form_vals', null);
        for (i in (list = fVals.split('|'))) 
           self.cookie(list[i], null);
    },
    /**
    * jQuery Cookie plugin
    *
    * Copyright (c) 2010 Klaus Hartl (stilbuero.de)
    * Dual licensed under the MIT and GPL licenses:
    * http://www.opensource.org/licenses/mit-license.php
    * http://www.gnu.org/licenses/gpl.html
    *
    */
    cookie: function (key, value, options) {
        if (arguments.length > 1 && String(value) !== "[object Object]") {
            options = jQuery.extend({}, options);
    
            if (value === null || value === undefined) {
                options.expires = -1;
            }
    
            if (typeof options.expires === 'number') {
                var days = options.expires, t = options.expires = new Date();
                t.setDate(t.getDate() + days);
            }
    
            value = String(value);
    
            return (document.cookie = [
                encodeURIComponent(key), '=',
                options.raw ? value : encodeURIComponent(value),
                options.expires ? '; expires=' + options.expires.toUTCString() : '', // use expires attribute, max-age is not supported by IE
                options.path ? '; path=' + options.path : '',
                options.domain ? '; domain=' + options.domain : '',
                options.secure ? '; secure' : ''
            ].join(''));
        }
    
        // key and possibly options given, get cookie...
        options = value || {};
        var result, decode = options.raw ? function (s) { return s; } : decodeURIComponent;
        return (result = new RegExp('(?:^|; )' + encodeURIComponent(key) + '=([^;]*)').exec(document.cookie)) ? decode(result[1]) : null;
    }
}
