var application = {
    //corner:{
    //    init: function(parent)
    //    {
    //        if ($.browser.msie && $.browser.version < 9)
    //            return;
    //        
    //        $('.corner').each(function(){
    //            $(this).corner();
    //        });
    //        $('.corner-3').each(function(){
    //            $(this).corner("3px");
    //        });
    //        $('.corner-5').each(function(){
    //            $(this).corner("5px");
    //        });
    //        $('.corner-10').each(function(){
    //            $(this).corner("10px");
    //        });
    //        $('.corner-top').each(function(){
    //            $(this).corner("top 25px");
    //        });
    //        $('.corner-all').each(function(){
    //            $(this).corner("left 5px").corner("right bevel 15px");
    //        });
    //        
    //        $('.corner-input').each(function(){
    //            $(this).corner("5px");
    //        });
    //    }
    //},
    aclick:
    {
        m:{
            '.open': '.otziv-add'
        },
        bg: null,
        init: function()
        {
            var self = this;
            this.font(self);
            this.open(self);
            this.exit(self);
        },
        font: function(self)
        {
            self.bg = $('<div class="opacity-body"></div>').appendTo("body");
        },
        exit: function(self)
        {
            $('.close').each(function(){
                $(this).click(function(){
                    self.bg.hide();
                    $(this).parent().parent().hide();
                    return false;
                });
            });
        },
        open: function(self)
        {
            $.each(this.m, function(key, value){
                $(key).click(function (){
                    var top = (document.documentElement && document.documentElement.scrollTop) || (document.body && document.body.scrollTop);
                    $(value).css('top', top+150);
                    self.bg.show();
                    $(value).show().appendTo("body");
                    return false;
                });
            })
        }
    },
    gallery: {
        options: {
            btnEnableClass: 'gallery-button-enable',
            step: 160,
            speed: 500,
            slidesPerStep: 4,
            slidesOnView: 1,
            current: 0,
            count: 0,
            timer: null,
            slideShow: false,
            slideShowSpeed: 4000
        },
        uri: {
            slider: '.slide-min',
            count: '.slide-min > div:first-child a',
            btnLeft: '.nav-left',
            btnRight: '.nav-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);
            /*
            self.node.slideRight.hover(function(){
                $(this).css('opacity', 0.6)
            },function(){
                $(this).css('opacity', 1)
            });
            self.node.slideLeft.hover(function(){
                $(this).css('opacity', 0.6)
            },function(){
                $(this).css('opacity', 1)
            });
            */
            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;
        }
    },
    searchForm: function()
    {
        var form  = $('.form-search');
        var image = $('.font-main img');
        var list  = $('.form-search select');
        var speed = 200;
        list.change(function(){
            form.attr('action', $(this).val());
            image.fadeOut(speed, function(){
                image.attr('src', list.find(':selected').attr('rel')).fadeIn(speed);
            });
        });
        form.submit(function(){
            if (!$(this).attr('action')){
                alert('Пожалуйста, выберите маршрут.');
                return false;
            }
        });
    },
    fastContacts: function()
    {
        var data = $('.contacts-list-content > .contacts-text');
        var list  = $('.contacts-list select');
        var speed = 200;
        list.change(function(){
            var id = $(this).val();
            data.filter(':not(.con-pos-'+id+')').fadeOut(speed, function(){
                data.filter('.con-pos-'+id).fadeIn(speed);
            });
        });
    },
    toggleMap: function()
    {
        $('.img-map').each(function(){
            var map_img = $(this).children('div');//.css('visibility', 'visible');
            $(this).find('.toggle-map_img').click(function(){
                map_img.toggleClass('showBlock');
                //map_img.css('visibility', 'visible').fadeToggle(250);
            });
        });
    },
    arendaForm: 
    {
        o: {
            list: '.arenda-foto input',
            selected: [],
            choose: '.choose-font',
            chooseClass: 'choosed',
            chooseTpl: '<div class="choose-add" id="ch_%id%"><a class="icon icon-delete" href="javascript:void(0)"></a><span>%name%</span></div>',
            emptyChooseId: '#choose-empty',
            emptyChooseTpl: '<div id="choose-empty">Выберите автобусы</div>'
        },
        init: function()
        {
            var self = this;
            self.o.list = $(self.o.list);
            self.o.choose = $(self.o.choose);
            
            if (!(self.o.list.length && self.o.choose.length))
                return;
            
            self.o.list.change(function(){
                var img = $(this).parent().prev();
                if ($(this).attr('checked'))
                    self.add(self, $(this).attr('id'), img);
                else
                    self.remove(self, $(this).attr('id'), img);
            });
        },
        add: function(self, id, img)
        {
            $(self.o.emptyChooseId).remove();
            img.addClass(self.o.chooseClass);
            
            var newNode = $(self.o.chooseTpl.replace('%name%', $('#'+id).attr('rel')).replace('%id%', id));
            newNode.find('a').click(function(){ self.remove(self, id, img)});
            newNode.appendTo(self.o.choose);
        },
        remove: function(self, id, img)
        {
            img.removeClass(self.o.chooseClass);
            $('#'+id).removeAttr('checked');
            $('#ch_'+id).remove();
            if (!self.o.choose.children().length)
                self.o.choose.append(self.o.emptyChooseTpl);
        },
        clear: function() {
            var self = this;
            self._clear(self);
        },
        _clear: function(self)
        {
            self.o.choose.empty().append(self.o.emptyChooseTpl);
        }
    },
    miniGallery: function() {
        $('.mini-gal').each(function(){
            var list = $(this).find('.gal-list > a');
            var img = $(this).find('.gal-big > img');
            list.first().addClass('active');
            list.click(function(){
                list.filter('.active').removeClass('active');
                $(this).addClass('active');
                img.attr('src',$(this).attr('href'));
                return false;
            });
        });
    },
    formValidate: function()
    {
        $('form').submit(function(){
            var hasError = false;
            var form = $(this);
            
            beforeSend(form);
            
            $('#message').hide();
            $('#message2').hide();
            $('#error').css('display', 'none');
            form.find('.error-empty-field').removeClass('error-empty-field');
            form.find('.error-field-message').removeClass('error-field-message');
            form.find('.required input, .required select, .required textarea').each(function(){
                if ($.trim($(this).val()) == ''){
                    $(this).addClass('error-empty-field');
                    hasError = true;
                }
            });
            
            if (form.is('#order-bus') && !$('.arenda-foto input:checked').length){
                $('#choose-empty').addClass('error-empty-field');
                hasError = true;
            }
            if (hasError){
                //alert('Вы заполнили форму не полностью');
                $('#message2').html('<span>Вы заполнили форму не полностью</span>').show();
                return false;
            }
            return true;
        });
        
        beforeSend = function(form) {
            if (!form.is('#order-bus'))
                return;
            var arr = [];
            $('.arenda-foto input:checked').each(function(){ arr.push($(this).attr('rel')) });
            $('#bus_list').val(arr.join(', '));
        }
    },
    formShow:
    {
        forms: ['#zakaz_bileta', '#order-bus'],
        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(form); break;
                    }
                    formsVals.clear();
                    application.arendaForm.clear();
                }
            }); 
        },
        //beforeSend: function()
        sendmailSuccess: function(form) {
            $('#message').slideDown();
            form.get(0).reset();
            
        },
        forgetSuccess: function(data) {
            $('#forget-form > form').slideUp();
            $('#forget-message').slideDown();
        },
        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');
            });
        }
    },
    datepicker: function()
    {
        var item = $('#f-data_otpravleniya');
        if (!item.length)
            return;
        item.datepicker({ dateFormat: 'dd.mm.yy', minDate: new Date(), maxDate: "+1M" });
    }
}
$(document).ready(function(){
    (function() {
        //this.corner.init();
        this.aclick.init();
        this.gallery.init();
        this.formValidate();
        this.searchForm();
        this.fastContacts();
        this.toggleMap();
        this.arendaForm.init();
        this.miniGallery();
        this.formShow.init();
        this.datepicker();
    }).call(application);
    formsVals.init();
    $('input[placeholder], textarea[placeholder]').placeholder();
});

$.fn.preload = function() {
    this.each(function(){
        $('<img/>')[0].src = this;
    });
}

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