var application = {
    textShadow: {
        o: {
            black: {
                node: '.big-block-tab .h1, .big-block-tab h2, .big-block-tab .h2, .big-block-tab .h3, .big-block-tab .h4, .big-block-menu a',
                color: '#000'
            }
        },
        init: function()
        {
            var self = this;
            $.each(self.o, function(i,item){
                $(item.node).each(function(){
                    var conteiner = $(this);
                    var shadow = $('<span class="shadow">'+conteiner.html()+'</span>').width((conteiner.width())).css('color', item.color);
                    if (conteiner.css('position') != ('absolute' || 'relative'))
                        conteiner.css({position: 'relative', 'z-index': 1, overflow: 'hidden'});
                    shadow.appendTo(conteiner);
                });
            });
        }
    },
    blueLinkUnderliner: function() {
        $('.blue-link').each(function(){
            $(this).html('<span>'+$(this).text()+'</span>');
        });
    },
    formLabels: {
        labels: {
            name: {
                label: "Ваше имя",
                required: true
            },
            email: {
                label: "E-mail",
                required: true
            },
            phone: {
                label: "Телефон",
                required: false
            },
            cb_name: {
                label: "Ваше имя",
                required: true
            },
            cb_phone: {
                label: "Телефон",
                required: false
            }
            /*,
            message: "Текст сообщения"*/
        },
        init: function()
        {
            var self = this;
            $.each(self.labels, function(node, options){
                var nodeObj = $('#' + node);
                if (nodeObj.length){
                    nodeObj.focus(function(){
                        if (nodeObj.hasClass('pale-text'))
                            nodeObj.removeClass('pale-text').val('');
                    }).blur(function(){
                        if ($.trim(nodeObj.val()) == '')
                            nodeObj.addClass('pale-text').val(options.label);
                        else
                            nodeObj.removeClass('error');
                    });
                    
                    if ($.trim(nodeObj.val()) == '')
                        nodeObj.addClass('pale-text').val(options.label);
                    if (options.required)
                        nodeObj.addClass('required-field');
                }
            });
            
            $('form').submit(function(){
                var form = $(this);
                var emptyFields = form.find('.pale-text.required-field');
                if (emptyFields.length) {
                    emptyFields.addClass('error');
                    return false;
                }
                var email  = form.find('input[name="email"]');
                if (email.length && !email.hasClass('.pale-text') && $.trim(email.val()) != '')
                {
                    if (!(/^(?:[a-z0-9]+(?:[-_\.]?[a-z0-9]+)?@[a-z0-9]+(?:\.?[a-z0-9]+)?\.[a-z]{2,5})$/i.test(email.val()))){
                        alert('Вы ввели некорректный e-mail.');
                        email.addClass('error');
                        return false;
                    }
                }
                form.find('.pale-text').val('');
                return true;
            });
        }
    },
    fadeForms: {
        node: {
            main: null,
            window: null,
            processBar: null,
            message: null,
            form: null,
            formFields: {}
        },
        options: {
            mainHeight: 300,
            topInc: 100,
            formIsClose: true
        },
        init: function() {
            var self = this;
            
            $('div.fade-form').each(function(){
                var fadeForm = $(this);
                fadeForm.children('.background').css('opacity', 0.5);
            });
            
            self.node.main = $('#callback');
            if (!self.node.main.length)
                return;
            self.node.window = self.node.main.children('.window');
            self.node.message = self.node.window.children('.ajax-message');
            self.node.processBar = self.node.window.find('.process-bar');
            self.node.form = self.node.window.find('form');
            
            $('.call-me').click(function() {
                self.node.window.css('top', ((document.documentElement && document.documentElement.scrollTop) || (document.body && document.body.scrollTop) + self.options.topInc));
                self.node.main.show();
                return false;
            });
            self.node.window.children('.close-window').click(function(){
                self.resetForm(self);
                self.node.message.html('&nbsp;');
                self.node.main.hide();
            });
            
            self.node.form.unbind('submit');
            self.node.form.submit(function(){
                var postData = {};
                self.node.form.find('input, textarea').each(function(){
                    var inputNode = $(this);
                    postData[inputNode.attr('name')] = inputNode.hasClass('pale-text') ? '' : inputNode.val();
                });
                $.ajax({
                    url: '/send-mail/?format=json',
                    data: postData,
                    type: "post",
                    success: function(data) {
                        if (!data.response)
                            return;
                        self.setMessages(self, data.response);
                    }
                });
                return false;
            });
        },
        setMessages: function(self, response) {
            self.node.message.removeClass('ajax-error ajax-success');
            self.node.message.addClass((!response.error) ? 'ajax-success' : 'ajax-error');
            self.node.message.text(response.message);
            $.each(response.messages, function(node, errors){
                if (errors.length)
                    $('#'+node).addClass('error');
                
            });
            if (!response.error)
                self.resetForm(self);
        },
        resetForm: function(self)
        {
            self.node.form.find("input[type='text']").removeClass('error').val('').blur();
            self.node.form.find("textarea").removeClass('error').text('').blur();
        }
    },
    bigBlock: {
        o: {
            main: '.big-block-container',
            btnClose: '.big-block-button',
            tabs: '.big-block'
        },
        n: {
            main: null,
            btnClose: null
        },
        init: function()
        {
            var self = this;
            self.n.main = $(self.o.main);
            if (!self.n.main.length)
                return;
            
            self.n.btnClose = $(self.o.btnClose);
            
            $(self.o.btnClose).click(function(){
                self.toggleBlock(self, 500);
            });
            
            if (application.cookies.get('big-block') == 'hide')
                self.toggleBlock(self, 0);
            
            $(self.o.tabs).tabs({fx:{opacity:'toggle', duration: 200}});
        },
        toggleBlock: function(self, speed)
        {
            self.n.main.slideToggle(speed);
            if (self.n.btnClose.hasClass('big-block-button-close')){
                application.cookies.del('big-block');
                self.n.btnClose.removeClass('big-block-button-close').text('Скрыть');
            }else{
                application.cookies.set('big-block', 'hide', {path: '/'});
                self.n.btnClose.addClass('big-block-button-close').text('Показать');
            }
        }
    },
    portfolioSlider: {
        o: {
            navConteiner: '.portfolio-element-navigation',
            sliderConteiner: '.portfolio-element-img-slider',
            active: 'current',
            step: 610,
            timer: null
        },
        n: {
            nav: null,
            slider: null
        },
        init: function()
        {
            var self = this;
            
            self.n.slider = $(self.o.sliderConteiner);
            self.n.nav = $(self.o.navConteiner);
            if (!(self.n.slider.length && self.n.nav.length))
                return;
            
            self.n.nav.prepend('<ul>' + ('<li><a href="javascript:void(0)"></a></li>'.repeat(self.n.slider.children('img').length)) + '</ul>');
            
            self.n.nav.find('ul a').each(function(i){
                var btn = $(this);
                if (i == 0)
                    self.goTo(self, btn, i);
                
                btn.bind( "mouseenter" , function() {
                    clearInterval(self.o.timer);
                    self.goTo(self, btn, i);
                });
            });
            
            self.slideShow(self);
        },
        slideShow: function(self)
        {
            var len = self.n.nav.find('ul a').length;
            var i = 0;
            self.o.timer = setInterval(function(){
                self.goTo(self, self.n.nav.find('ul a:eq('+i+')'), i);
                i = ((i+1) == len) ? 0 : (i+1);
            }, 5000);
        },
        goTo: function(self, btn, pos)
        {
            self.n.slider.stop();
            self.n.slider.animate( { marginLeft: (self.o.step * pos * -1) + "px" }, 500 );
            
            self.n.nav.find('.'+self.o.active).removeClass(self.o.active);
            btn.addClass(self.o.active);
            return true;
        }
    },
    slider: {
        options: {
            btnEnableClassL: 'slide-enable-l',
            btnEnableClassR: 'slide-enable-r',
            step: 560,
            speed: 500,
            slidesPerStep: 5,
            current: 0,
            count: 0
        },
        uri: {
            slider: '.portfolio-list-slider',
            btnLeft: '.portfolio-arrow-l',
            btnRight: '.portfolio-arrow-r'
        },
        node: {
            slider: null,
            slideLeft: null,
            slideRight: null,
            preloader: null
        },
        init: function()
        {
            var self = this;
            
            self.node.slider = $(self.uri.slider);
            
            if (!self.node.slider.length)
                return;
            
            self.options.count = self.node.slider.children().length;
            self.node.slideLeft = $(self.uri.btnLeft);
            self.node.slideRight = $(self.uri.btnRight);
            
            if (self.options.count > self.options.current)
                self.node.slideRight.addClass(self.options.btnEnableClassR);
            
            self.node.slideRight.click(function(){
                self.slideRight(self);
                return false;
            });
            
            self.node.slideLeft.click(function(){
                self.slideLeft(self);
                return false;
            });
        },
        slideLeft: function(self)
        {
            if (self.options.current <= 0)
                return;
            
            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.btnEnableClassR))
                self.node.slideRight.addClass(self.options.btnEnableClassR);
            
            if (self.options.current <= 0)
                self.node.slideLeft.removeClass(self.options.btnEnableClassL);
        },
        slideRight: function(self)
        {
            if (self.options.current >= (self.options.count-self.options.slidesPerStep))
                return;
            
            if ((self.options.current + self.options.slidesPerStep) <= (self.options.count-self.options.slidesPerStep))
                self.options.current += self.options.slidesPerStep;
            else
                self.options.current = (self.options.count-self.options.slidesPerStep);
            
            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.btnEnableClassL))
                self.node.slideLeft.addClass(self.options.btnEnableClassL);
            
            if (self.options.current >= (self.options.count-self.options.slidesPerStep))
                self.node.slideRight.removeClass(self.options.btnEnableClassR);
        }
    },
    vacancy: function (){
        var vacancyBlock = $('.vacancy');
        if (!vacancyBlock.length)
            return;
        var hash = window.location.hash;
        
        vacancyBlock.children('.list-item').each(function(){
            var item = $(this);
            var info = item.children('.info');
            
            if (hash != ('#'+item.attr('id')))
                info.hide();
            
            $('<a>', {
                href: 'javascript:void(0)',
                text: 'Подробнее...',
                'class': 'more',
                click: function(){
                    info.slideToggle();
                    return false;
                }
            }).prependTo(item);
        });
    },
    cookies: {
        get: function(name) {
            var matches = document.cookie.match(new RegExp(
              "(?:^|; )" + name.replace(/([\.$?*|{}\(\)\[\]\\\/\+^])/g, '\\$1') + "=([^;]*)"
            ))
            return matches ? decodeURIComponent(matches[1]) : undefined;
        },
        set: function (name, value, props) {
            props = props || {}
            var exp = props.expires
            if (typeof exp == "number" && exp) {
                var d = new Date();
                d.setTime(d.getTime() + exp*1000);
                exp = props.expires = d;
            }
            if(exp && exp.toUTCString) { props.expires = exp.toUTCString() }
            value = encodeURIComponent(value)
            var updatedCookie = name + "=" + value
            for(var propName in props){
                updatedCookie += "; " + propName
                var propValue = props[propName]
                if(propValue !== true){ updatedCookie += "=" + propValue }
            }
            document.cookie = updatedCookie
        },
        del: function(name) {
            this.set(name, null, { expires: -1 , path: '/'})
        }
    },
    topLine: {
        node: {
            detail: null,
            activeText: null,
            textTpl: null,
            link: null
        },
        options: {
            aminateTime: 500,
            timeToHide: 1000,
            timeToShow: 300,
            timer: null,
            runingLineSpeed: 30000,
            hiddenPosition: -200,
            visiblePosition: 30,
            state: 0
        },
        init: function()
        {
            var self = this;
            
            self.node.detail = $('#top-line > .detail-wrap');
            self.node.link = $('#top-line .line > .running-line');
            self.node.activeText = self.node.link.children('.active').eq(0);
            self.node.textTpl = '<div>' + self.node.activeText.html() + '</div>';
            
            self.runLine(self);
            
            self.node.link.hover(
                function() {
                    clearTimeout(self.options.timer);
                    if (!self.options.state)
                        self.options.timer = setTimeout(function() { self.show(self); }, self.options.timeToShow);
                },
                function() {
                    clearTimeout(self.options.timer);
                    if (self.options.state)
                        self.options.timer = setTimeout(function() { self.hide(self); }, self.options.timeToHide);
                }
            ).click(function(){
                clearTimeout(self.options.timer);
                self.show(self);
                return false;
            });
            self.node.detail.children('div').hover(
                function() {
                    clearTimeout(self.options.timer);
                },
                function() {
                    clearTimeout(self.options.timer);
                    if (self.options.state)
                        self.options.timer = setTimeout(function() { self.hide(self); }, self.options.timeToHide);
                }
            );
        },
        hide: function(self)
        {
            if (!self.options.state)
                return;
            self.node.detail.animate({top: self.options.hiddenPosition}, self.options.aminateTime, 'swing', function() {self.node.detail.css('display', 'none'); self.options.state = 0});
            clearTimeout(self.options.timer);
        },
        show: function(self)
        {
            if (self.options.state)
                return;
            self.node.detail.css('display', 'block').animate({top: self.options.visiblePosition},self.options.aminateTime, 'swing', function() {self.options.state = 1});
            clearTimeout(self.options.timer);
        },
        runLine: function(self)
        {
            self.node.activeText.animate({width: 0}, self.options.runingLineSpeed, 'linear', function() {
                self.node.activeText.remove();
                self.node.link.append(self.node.textTpl);
                self.node.activeText = self.node.link.children('div').eq(0).addClass('active');
                self.runLine(self);
            });
        }
    }
}
function clone(o) {
    if(!o || 'object' !== typeof o)  {
        return o;
    }
    var c = 'function' === typeof o.pop ? [] : {};
    var p, v;
    for(p in o) {
        if(o.hasOwnProperty(p)) {
            v = o[p];
            if (v && 'object' === typeof v) {
                c[p] = clone(v);
            }
            else {
                c[p] = v;
            }
        }
    }
    return c;
}

$(document).ready(function(){
    (function() {
        //this.textShadow.init();
        this.blueLinkUnderliner();
        //this.bigBlock.init();
        this.portfolioSlider.init();
        //this.slider.init();
        //this.vacancy();
        this.fadeForms.init();
        //this.fadeForms.callMe.init();
        this.formLabels.init();
    }).call(application);
});

String.prototype.repeat = function(num)
{
    return new Array(num + 1).join(this);
}
