$(function(){
    //+++menu slider on Big Page
    var activeMenuItem;


    $("#menuUnitBigCont .menuUnitBig").live({
        'mouseenter': function(event) {
            $("#menuUnitBigAct").stop(true);
            var add = ($(".activeItem").is('#mUB1')) ? 3 : 0;
            add = 0;

            var diff = $(this).position().left + add - $("#menuUnitBigAct").position().left,
                    duration = Math.abs(diff * 400 / 568);

            $("#menuUnitBigAct").zIndex(1).delay(200).animate({
                        left: $(this).position().left + add + "px"
                    }, duration, "linear", function() {
                        $(this).zIndex(1);
                    });
            $(".activeItem").removeClass("menuUnitBigHover2");
            $(this).addClass('menuUnitBigHover');
        },
        'mouseleave': function(event) {
            $("#menuUnitBigAct").stop(true);

            var add = ($(".activeItem").is('#mUB1')) ? 3 : 0;
            add = 0;

            var diff = $(".activeItem").position().left + add - $("#menuUnitBigAct").position().left,
                    duration = Math.abs(diff * 400 / 568);

            $("#menuUnitBigAct").zIndex(1).animate({
                        left: $(".activeItem").position().left + add + "px"
                    }, duration, "linear", function() {
                        $(this).zIndex(1);
                    });
            $(this).removeClass('menuUnitBigHover');
            $(".activeItem").addClass("menuUnitBigHover2");
        },
        'click' : function(){
            $(".menuUnitBig").removeClass('menuUnitBigHover2 activeItem');
            $(this).addClass('menuUnitBigHover2 activeItem');
            
            $(this).addClass($(this).attr('id') + '_active')
            $('.menuUnitBig').not(this).removeClass('mUB1_active mUB2_active mUB3_active mUB4_active mUB5_active');
        }
    });
    //---menu slider on Big Page

    ///+++menu slider on Small Page
    $("#menuUnitSmallCont .menuUnitSmall").live({
        'mouseenter': function(event) {
            $("#menuUnitSmallAct").stop(true);

            var diff = $(this).position().left + 3 - $("#menuUnitSmallAct").position().left,
                    duration = Math.abs(diff * 400 / 568);

            $("#menuUnitSmallAct").delay(200).animate({
                left: $(this).position().left + 3 + "px"
            }, duration, "linear");
            $(this).addClass('menuUnitSmallHover');
            $(".activeItem").removeClass("menuUnitSmallHover2");
        },
        'mouseleave' : function() {
            $("#menuUnitSmallAct").stop(true);

            var diff = $(".activeItem").position().left + 3 - $("#menuUnitSmallAct").position().left,
                    duration = Math.abs(diff * 400 / 568);

            $("#menuUnitSmallAct").animate({
                left: $(".activeItem").position().left + 3 + "px"
            }, duration, "linear");
            $(this).removeClass('menuUnitSmallHover');
            $(".activeItem").addClass("menuUnitSmallHover2");
        },
        'click' : function(){
            $(".menuUnitSmall").removeClass('menuUnitSmallHover2 activeItem');
            $(this).addClass('menuUnitSmallHover2 activeItem');
        }
    });
    ///---menu slider on Small Page

    //+++ Main MmSlider
    function animateBigmmSlider() {
        var color = "white",
                height = $("#sliderBig").height(),
                interval = height / $(".block").length;

        $(".block").each(function(i, block) {
            $(block)
                    .css({"top" : -height * i , "height": height, "background-color" : color })
                    .animate({ "height" : "0px", "top" : height - interval *i + "px" }, 900);
        });
    }

    var mmSliderIsAnimated = false;
    function mmSlider() {
        if (mmSliderIsAnimated) return;
        mmSliderIsAnimated = true;
        var $next = $(".sliderUnitsBig:visible").next(".sliderUnitsBig");
        if ($next.length === 0) {
            $next = $(".sliderUnitsBig:first");
        }

        animateBigmmSlider();

        $(".sliderUnitsBig:visible").hide();

        $next.show();

        var $img = $next.find('img[name|="bigpic"]');
        if ($img.is('[data-src]')) {
            // если картинка 118. вставить перед ней ссылку на видео
            //if ($img.is('[data-src$="118.jpg"]')) { insertLinkToVideoBefore($img); }
            $img.attr('src', $img.attr('data-src')).removeAttr('data-src').removeClass('placeholder');
        }

        setTimeout(function () {
            mmSliderIsAnimated = false;
            /*if ($img.is('.placeholder')) {
             $img.show();
             }*/
        }, 1000);
    }

    $("#sliderBig").live({
        click: function(){
            mmSlider();
        }
    });

    //mm small slider
    function animateSmallmmSlider() {
        var color = "white",
                height = $("#sliderSmall").height(),
                interval = height / $(".block").length;

        $(".block").each(function(i, block) {
            $(block)
                    .css({"top" : -height * i , "height": height, "background-color" : color })
                    .animate({ "height" : "0px", "top" : height - interval *i + "px" }, 900);
        });
    }

    var mmSlider2IsAnimated = 0;
    function mmSlider2() {
        if (mmSlider2IsAnimated !== 0) return;
        mmSlider2IsAnimated = 2;
        var $next = $(".sliderUnitsSmall:visible").next(".sliderUnitsSmall");
        if ($next.length === 0) {
            $next = $(".sliderUnitsSmall:first");
        }

        animateSmallmmSlider();

        $(".sliderUnitsSmall:visible").hide();

        $next.show();

        var $img = $next.find('img');
        if ($img.is('.placeholder')) {
            // если картинка 119. вставить перед ней ссылку на видео
            //if ($img.is('[data-src$="119.jpg"]')) { insertLinkToVideoBefore($img); }
            $img.attr('src', $img.attr('data-src')).removeAttr('data-src').removeClass('placeholder');
        }

        setTimeout(function () {
            mmSlider2IsAnimated = 0;
            /*if ($img.is('.placeholder')) {
             $img.show();
             }*/
        }, 1000);
    }

    $("#sliderSmall").live({
        click: function(){
            mmSlider2();
        }
    });
    //--- Main MmSlider

    //+++Accordion
    $('span', '#left_navs_for_accordeon2').live('click', function() {
       
        // индекс кружка
    	var index = $('span', '#left_navs_for_accordeon2').removeClass('active').index(this);
    	// позиция для анимации слайда
        var top = index * -333;
        // картинка на слайде
        var img = $('.slides_wrapper_for_accorderon2 img', '#left_slides_block').eq(index);
        
        // если картинка не показана - показать
        if (img.data('src')) {
        	img.attr('src', img.data('src'));
        	img.data('src', false);
        }
        
        $(this).addClass('active');
        
        // передвинуть слайд
        $('.slides_wrapper_for_accorderon2', '#left_slides_block').stop(true).animate({ top: top + "px"});
    });

    
    $('span', '#right_navs_for_accordeon2').live('click', function() {
    	// индекс кружка
    	var index = $('span', '#right_navs_for_accordeon2').removeClass('active').index(this);
    	// позиция для анимации слайда
        var top = index * -333;
        // картинка на слайде
        var img = $('.slides_wrapper_for_accorderon2 img', '#right_slides_block').eq(index);
        
        // если картинка не показана - показать
        if (img.data('src')) {
        	img.attr('src', img.data('src'));
        	img.data('src', false);
        }
        $(this).addClass('active');
        
        // передвинуть слайд
        $('.slides_wrapper_for_accorderon2', '#right_slides_block').stop(true).animate({ top: top + "px"});
    });


    $('.arrow_bottom').live('click', function() {
        var spans = $(this).siblings('.active'), next = spans.next('span');
        if (next.length) {
            next.click();
        } else {
            $(this).siblings('span:first').click();
        }
    });

    $('.arrow_top').live('click', function() {
        var spans = $(this).siblings('.active'), prev = spans.prev('span');
        if (prev.length) {
            prev.click();
        } else {
            $(this).siblings('span:last').click();
        }
    });
    /*$.fn.mmAccordion = function (part, unit) {
     $(this).live('mouseenter', function(event) {
     $(this).siblings()
     .stop(true)
     .animate({ height:"24.6%" }, 250);

     $(this)
     .stop(true)
     .animate({ height:"50%" }, 250);
     });
     };

     $("#accordeonBigPartLeft .accordeonUnitBig").mmAccordion(".accordeonBigPart", ".accordeonUnitBig");
     $("#accordeonBigPartRight .accordeonUnitBig").mmAccordion(".accordeonBigPart", ".accordeonUnitBig");*/

    /*$("#accordeonTopSmall").live('click', function () {
     var ac = $('#accordeonSmall');
     if (ac.is(':animated')) return;
     if (ac.height() === 0) {
     ac.animate({ height : "212px", top : "0px" });
     } else {
     ac.animate({ height : "0px", top : "-4px" })
     }
     });

     $("#accordeonSmallPartLeft .accordeonUnitSmall").mmAccordion(".accordeonSmallPart", ".accordeonSmallBig");
     $("#accordeonSmallPartRight .accordeonUnitSmall").mmAccordion(".accordeonSmallPart", ".accordeonSmallBig");*/
    //---Accordion

    //+++ mmSquare Slider
    function MMSquare() {}

    MMSquare.prototype = {
        start: function (leftFirst) {
            if (leftFirst === true) {
                this._toLeft();
            } else {
                this._toRight(this._toLeft);
            }
        },
        _toRight: function (cb) {
            var that = this;
            $("#movingSquare").animate({ "left" : "348px" }, function () {
                        cb.call(that);
                    });
        },
        _toLeft: function () {
            this._togglePhrase();
            var $next = $(".dynamicPhrase:visible").next();
            if($next.length === 0) {
                $next = $(".dynamicPhrase:first");
            }
            $("#movingSquare").animate({ "left" : "0px" }, 1000);
        },
        _togglePhrase: function () {
            var phrases = $('.dynamicPhrase:hidden'),
                    random = parseInt(Math.random() * phrases.length);

            $('.dynamicPhrase:visible').hide();
            phrases.eq(random).show();
        }
    }

    var mmSquare = new MMSquare();
    $("#movingSquare").live({
        click: function(){
            if(!$(this).is(':animated')) {
                mmSquare.start();
            }
        }
    });

    //--- mmSquare Slider

    /*++++++ ANIMATION ++++++*/
    //plugin hitherAndThither
    $.fn.hitherAndThither = function(options) {
        var that = $(this), timer, target;
        that.live({
            'mouseenter': function (event) {
                var target = $(event.currentTarget);
                options.animation.call(target);
                timer = setInterval(function() {
                    options.animation.call(target);
                }, options.interval);
            },
            'mouseleave': function (event) {
                clearInterval(timer);
            }
        });
    };

    // first Arrow
    $("#strelkaHover").hitherAndThither({
        animation : function() {
            $("#newNumberTextBig")
                    .animate({
                        "backgroundPosition" : "+=17px"
                    }, 700)
                    .animate({
                        "backgroundPosition" : "-=17px"
                    }, 1000);
        },
        interval : 1710
    });

    $("#strelkaHoverSmall ").hitherAndThither({
        animation : function() {
            $("#newNumberTextSmall")
                .animate({backgroundPosition: '-431px -1083px'}, 700) 
                .animate({backgroundPosition: '-446px -1083px'}, 1000);           
        },
        interval: 1710
    });

    $(".accUPReadMoreBig").live({
        mouseover: function(){
            $(this).css({
                color:"#e64315",
                cursor:"pointer"
            });
        },
        mouseout: function(){
            $(this).css('color','#A7A9AC');
        }
    });

    /* Обложка нового номера на БОЛЬШОЙ странице */
    function NewNumberCoverBig() {
        var newNumberClickTimeout = null;
        var firstExpand = true;
        $("#numberDateIm").live({
            dblclick: function () {
                clearTimeout(newNumberClickTimeout);
                if ($(this).data("maximized")) {
                    document.location.href = "http://21mm.ru/?mag=74#001";
                }
            },
            click: function () {
                if ($(this).width() > 342) {
                    collapse();
                } else {
                    if (firstExpand) {
                        loadHDCover();
                    }
                    expand();
                }
            }
        });

        var loadHDCover = function () {
            $("#numberDateIm").attr('src', '/media/images/newNumberCoverHD.jpg');
            firstExpand = false;
        };

        var expand = function () {
            var maxHeight = $(window).height() - $("#blanckpalce").height(),
                    height = (maxHeight < 766) ? maxHeight : 766,
                    top = 342 - height,
                    cover = $("#numberDateIm");

            //прокрутить страницу, чтобы обложка нового номера упиралась в верхний край экрана
           // var targetTop = $(window).scrollTop()  + $(".main").offset().top - $("#numberDateIm").offset().top - top;
			var targetTop = $("#numberDateIm").offset().top - $("#blanckpalce").height() + top;

			$('html,body').animate({ scrollTop: targetTop });
            //$('html,body').animate({ top:targetTop });

            cover.animate({
				"height" : height + "px",
				"margin-top"   : top + "px"
			}, 250, function () {
				cover.data("maximized", true);
			});

            cover.attr('rel', 'Уменьшить');
        };

        var collapse = function () {
            var cover = $("#numberDateIm");
            newNumberClickTimeout = setTimeout(function () {
                $("#numberDateIm").animate({
                            "height" : "342px",
                            "margin-top" : "0px"
                        }, 250, function () {
                            cover.data("maximized", false);
                        });
                $("#numberDateIm").attr('rel', 'Увеличить');
            }, 200);
        };
    }

    function NewNumberCoverSmall() {
        var firstExpand = true;
        $("#newNumberCoverSmall").live({

            click: function () {
                if ($(this).width() >= 400) {
                    collapse();
                } else {
                    if (firstExpand) {
                        loadHDCover();
                    }
                    expand();
                }
            },
            dblclick:function(){
                var href= $(this).data("href");
                document.location = href;
                 collapse();
            }
        });

        var expand = function() {
            $("#newNumberCoverSmall")
                    .animate({
                        "left" : "179px",
                        "width" : "423px",
                        "top" : "-309px",
                        "height" : "522px"
                    }, 250)
                    .attr('rel', 'Уменьшить');
        };

        var loadHDCover = function () {
            $("#newNumberCoverSmall").attr('src', '/media/images/newNumberCoverHD.jpg');
            firstExpand = false;
        };

        var collapse = function () {
            $("#newNumberCoverSmall")
                    .animate({
                        "left" : "1px",
                        "width" : "169px",
                        "top" : "0px",
                        "height" : "205px"
                    }, 250)
                    .attr('rel', 'Увеличить');
        };
    };


    //small page menu
    var showActiveSmallMenuItemTimeout = null;
    $.fn.showSmallMenuItem = function () {
        $('.mPBBLSmall').removeClass("gradient_back_small");
        this
                .stop(true).animate({ marginLeft:'2px'})
                .prev().addClass("gradient_back_small");
    }

    $.fn.hideSmallMenuItem = function () {
        this.stop(true).animate({marginLeft:'-150px'});
    }

    $('.mPBBLSmall, .mPBBRSmall').live({
        mouseenter: function(){
            var target = $(this), panel = (target.is('.mPBBRSmall')) ? target : target.next();
            clearTimeout(showActiveSmallMenuItemTimeout);
            panel.showSmallMenuItem();
            if (!panel.is('.buy_it_small')) {
                $('.buy_it_small').hideSmallMenuItem();
            }
        },
        mouseleave: function() {
            var target = $(this), panel = (target.is('.mPBBRSmall')) ? target : target.next();
            panel.hideSmallMenuItem();
            showActiveSmallMenuItemTimeout = setTimeout(function () {
                $('.buy_it_small').showSmallMenuItem();
            }, 200);
        }
    });


//big page menu
    var showActiveItemTimeout = null;
    $.fn.showBig = function () {
        $('.mPBBLBig').removeClass("gradient_back_big");
        this
                .stop(true).animate({ marginLeft:'12px'})
                .parent().siblings('.mPBBLBig').addClass("gradient_back_big");
    }

    $.fn.hideBig = function () {
        this.stop(true).animate({marginLeft:'-137px'});
    }

    $('.mPBBLBig, .mPBBRBig').live({
        mouseenter: function(){
            var target = $(this), panel = (target.is('.mPBBRBig')) ? target : target.next().children('.mPBBRBig');
            clearTimeout(showActiveItemTimeout);
            panel.showBig();
            if (!panel.is('.buy_it_big')) {
                $('.buy_it_big').hideBig();
            }
        },
        mouseleave: function() {
            var target = $(this), panel = (target.is('.mPBBRBig')) ? target : target.next().children('.mPBBRBig');
            panel.hideBig();
            showActiveItemTimeout = setTimeout(function () {
                $('.buy_it_big').showBig();
            }, 200);
        }
    });



    /* +++ иницаилизация частей +++ */
    var newNumberCoverBig = new NewNumberCoverBig();
    var newNumberCoverSmall = new NewNumberCoverSmall();
    /* --- иницаилизация частей --- */

//для ff 3.6
    var ua = $.browser;
    if ( ua.mozilla && ua.version.slice(0,3) == "1.9" ) {
        $('.accordeonUnitPartBig').css({'width':'210px'});
        //alert(1);
    }

    $('#left_slides_block .slides_wrapper_for_accorderon2').css({'top':'2663px'});

    function Account (isLogin, id) {
        var that = this;
        this.isLogin = isLogin;
		this.id = (isLogin) ? id : null;
        this.cache = {};
        
        // callback если вход или регистрация были выполнены
        this.postLoginCallback = $.noop;
        
        // callback если окно входа было закрыто и вход не был выполнен
        this._cancelLoginCallback = $.noop;
        this._module = $('#m-account');

		$('#close_cabinet, #close_user_profile').live('click', function() {
			 $('#alertOverlay, #cabinet-container, #user-profile').hide();
		});
		
		$("#alertOverlay, #cross").live("click", function(e) {
	        if($(e.target).is("#alertOverlay") || $(e.target).is("#cross")) {
	            $("#alertOverlay").fadeToggle();
	            $('#user-cabinet, #user-profile').hide();
	            that._cancelLoginCallback();
	            that._cancelLoginCallback = $.noop;
	            that.postLoginCallback = $.noop;
	        }
	        e.stopPropagation();
	    });
		
		// клик на кнопку открытия профайла пользователя
		$('#openUserProfile').live('click', function() {
			$('#user-cabinet').hide();
			$('#user-profile').load('/ajax/user_info').show();
		});
		
        $('#enterLabel').click(function() {
            //    триггер onopencabinet
            that._module.trigger('onopencabinet');
            
            that.showCabinet();  
        });
        
        $('.left_main_bottom_menu_exit').click(function () {
//          триггер onopencabinet
            if (that.isLogin) { 
                that._logout();
            } else {
                that._module.trigger('onopencabinet');               
                that.showCabinet(true);  
            }
           
            
        });
        
        $('.left_main_bottom_menu_name').click(function() {
            if (that.isLogin) {
                that._module.trigger('onopencabinet');               
                that.showCabinet(true);  
            }
        });
        
        // top - show cabinet for toppages
        this.showCabinet = function(top) {
            if (that.isLogin) {
                // залогинились - показать кабинет
                if (that.cache['cabinet']) {
                    $('#alertOverlay, #cabinet-container').show();
                } else {
                    if ($('#user-cabinet').is(':empty')) {
                        $.ajax({
                            dataType: 'html',
                            url: '/ajax/cabinet/',
                            type: 'post',
                            success: function(data) {
                                $('#user-cabinet').html(data).show();
                                
                                // установить по верхней панели 
                                $('#cabinet-container').css({'top' : '45px', 'left' : $('.topPanel').offset().left + 7});
                                
                                if (top) {
                                  
                                    $('#cabinet-container').css('top', $(window).height() - 594 + 'px');
                                }
                                
    
                                $('#cabinet-form').validate({
                                    ignore: ".ignore",
                                    submitHandler: function(form) {
                                        /*$.ajax({
                                            type: 'post',
                                            url: '/ajax/mmregedit/',
                                            data: $.extend($('#cabinet-form').serializeObject(), { file_avatar: $('#select_avatar').val() }),
                                            success: function() {
                                                Service.message("Cохранено.");
                                                //$('#alertOverlay, #cabinet-container').hide();
                                            }
                                        });*/
                                        $(form).ajaxSubmit({
                                            success: function(data) {
                                                if (data === '0') {
                                                    Service.message("Размер файла не может превышать 100 килобайт");
                                                } else {
                                                    Service.message("Cохранено.");
                                                    
                                                    // refresh image
                                                    var cab = $('.cabinet-avatar').get(0);
                                                    var src = cab.src.split('?')[0];
                                                    src += '?anti_cache=' + +new Date();
                                                    cab.src = src;
                                                    //$('#alertOverlay, #cabinet-container').hide();
                                                }
                                            }
                                        });
                                    }
                                });
                                
                                
                                
                                // клик по кноппе пригласть друга
                                $('#submit_friend').click(function() {
                                    var email = $('#friends_email').val();
                                    if (email.length != 0) {
                                        if(isValidEmail(email)) {
                                            $('#friends_email').siblings('.error').text('');
                                            $.ajax({
                                                type: 'post',
                                                url: '/ajax/invite_friend/',
                                                data: { email: email },
                                                success: function() {
                                                    Service.message("Приглашение отправлено");
                                                    //Popup.show({ html: 'Приглашение отправлено'});
                                                    $('#friends_email').val('');
                                                }
                                            });
                                        } else {
                                            $('#friends_email').siblings('.error').text('E-mail должен быть корректным');
                                        }
                                    } else {
                                        $('#friends_email').siblings('.error').text('Введите e-mail');
                                    }
                                    
                                    
                                });
                                
                                $('#alertOverlay, #cabinet-container').show();
                                /*
                                if (data.add_info){
                                    data.add_info = eval ('(' + data.add_info + ')');
                                }
                                that.cache['cabinet'] = true;
                                // заполнить форму данными с сервера
                                $('#cabinet-form :text').each(function() {
                                    if (data.add_info[this.name]) {
                                        this.value = data.add_info[this.name];
                                    } else {
                                        this.value = "";
                                    }
                                });
                                
                                if (data.subscribed == 1) {
                                    $('#unsubscribe').show();
                                } else {
                                    $('#subscribe').show();
                                }
                                */                                           
                            }
                        });
                    } else {
                        $('#user-cabinet').show();
                        // установить по верхней панели 
                        $('#cabinet-container').css({'top' : '45px', 'left' : $('.topPanel').offset().left + 7});
                        $('#alertOverlay, #cabinet-container').show();
                        
                        
                    }
                }
            } else {
                // не залогинились - показать вход
                $('#alertOverlay, #enter').show();
                
                if (top) {
                    //var top = $(window).height() - 594;

                    //$('#enter').css('top', top + 'px');
                    $('#enter').css('top', $(window).height() - 378 + 'px');
                    
                }
            }
        }

        this.logoutSuccess = function() {
			that.id = null;
            that.isLogin = false;
			
            isLogin = false;
            that.cache['cabinet'] = false;

            $('#enterLabel')
                    .removeClass('enter-label-text')
                    .text("");
            
            $('.left_main_bottom_menu_name').text('');
            $('.left_main_bottom_menu_exit em').text("Bойти");

            $('#enter-message').text('');
            $('#alertOverlay, #cabinet-container').hide();
            $('.QapTcha').QapTchaLock();
			
			// установить цвет фона по-умолчанию
			$('body').css('background-color', $('body').data('default-color'));
			
			// триггер logout
			that._module.trigger('onlogout');
        }

        this.noAuthLogin = function(_userid, callback) {
            $.post('/ajax/mmlogin_noauth/', {userid:_userid}, function(data) {
                if (data != 1) that.loginSuccess($('#enter-login-form'), data);
                        
                 callback();
            });
        }

        // on success login
        this.loginSuccess = function(form, data) {
			var name = data.email;
			that.id = data.id;
            that.isLogin = true;
            isLogin = true;
            $("#alertOverlay").unbind('click').fadeOut();
            $("#enter").fadeOut();
            $(form).clearForm();
            $('#enterLabel')
                    .addClass('enter-label-text')
                //.text(name);
                    .text(name.match(/[^@]+/)[0]);
            
            $('.left_main_bottom_menu_name').text(name.match(/[^@]+/)[0]);
            $('.left_main_bottom_menu_exit em').text("выход");

            $('#enter-message').text('');
            that.postLoginCallback();
            that.postLoginCallback = $.noop;
            that._cancelLoginCallback = $.noop;
			
			// если у пользователя был выбран цвет
			if  (data.add_info && data.add_info.color) {
				// установить цвет фона
				$('body').css('background-color', '#' + data.add_info.color);
			}
			
			// триггер login
			that._module.trigger('onlogin');
        }
        
        this.bind = function(eventType, handler) {
            $.fn.bind.apply(this._module, arguments);
        }

        $('#logoutLabel').live('click', function(){
            that._logout();
        });
        
        this._logout = function() {
            $.ajax({
                url: '/ajax/exit/',
                type: 'post',
                success: that.logoutSuccess
            });
        }


        $('.enter-action-title').click(function() {
            $(this).next('div').slideDown();
            $('.enter-action-title').not(this).next('div').slideUp();
        });



        

        $('#enter-login-form').validate({
            submitHandler: function(form) {
                $(form).ajaxSubmit({
					dataType: 'json',
                    success: function(data) {
                        if (data == 1) {
                            Service.message('Неверный логин / пароль');
                        } else if (data == 2) {

                        } else {
                            that.loginSuccess(form, data);
                        }
                    }
                });
            },
            rules: {
                password: 'required',
                login: { required: true }
            },
            messages: {
                password: 'Введите пароль',
                login: { required: 'Введите e-mail' }
            },
            focusCleanup: true,
            focusInvalid: false
        });

        $('#enter-backup-form').validate({
            submitHandler: function(form) {
                $(form).ajaxSubmit({
                    success: function(data) {
                        if (data == 1) {
                            Service.message('Письмо с паролем выслано вам на почту.');
                        } else if (data == -1) {
                            Service.message('Неверный e-mail');
                        }
                    }
                });
            },
            rules: {
                email: { required: true, email: true }
            },
            messages: {
                email: { required: 'Введите e-mail', email: "e-mail должен быть корректным"}
            },
            focusCleanup: true,
            focusInvalid: false
        });

        $('#enter-registration-form').validate({
            submitHandler: function(form) {
                $(form).ajaxSubmit({
					dataType: 'json',
                    success: function(data) {

                        if (data.error == 2) {
							$('.QapTcha').QapTchaLock();
							alert('Извините произошла ошибка. Попробуйте ещё раз.');
                        } else if (data == 0) {
                            alert('Введённый вами e-mail уже используется.');
                            $('.QapTcha').QapTchaLock();
                        } else { 
                            that.loginSuccess(form, data);
                            Popup.show({
                                html: 'Благодарим Вас за интерес к сообществу 21mm.ru!<br>На ваш адрес отправлено письмо для завершения регистрации.',
                                css: {
                                    width: '501px', top: '48px'
                                }
                            });
                        }

                    }
                });
            },
            rules: {
                login: 'required',
                password: 'required',
                email: { required: true, email: true },
                repassword: { required: true, equalTo: '#regpassword' }
            },
            messages: {
                login: 'Введите login',
                password: 'Введите пароль',
                email: { required: 'Введите e-mail', email: 'E-mail должен быть корректным' },
                repassword: { required: 'Введите пароль ещё раз', equalTo: 'Пароли не совпадают'}
            },
            focusCleanup: true,
            focusInvalid: false
        });

        this.showLogin = function(message, poctCb, cancelCb) {
            this.postLoginCallback = poctCb || $.noop;
            this._cancelLoginCallback = cancelCb || $.noop;
            $('#alertOverlay, #enter').show();
            $('#enter-message').text(message);
            this._module.trigger('onopencabinet');
        }

        

        $('.QapTcha').QapTcha({
            disabledSubmit:true,
            autoRevert:true,
            txtUnlock: "Разблокировано.",
            txtLock: "Оживите форму, передвинув слайдер к замку"
        });

        $('#unsubscribe').click(function() {
            if (Service.confirm("Вы действительно хотите перестать получать рассылку?")) {
                $.ajax({
                    url: '/ajax/subscribe/',
                    type: 'post',
                    data: { subscribed: 0 },
                    success: function() {
                        $('.cabinet-subscribe').toggle();

                        Service.message("Вы успешно отписались от рассылки");
                    }
                });
            }
        });

        $('#subscribe').click(function() {
            if (Service.confirm("Вы действительно хотите получать рассылку?")) {
                $.ajax({
                    url: '/ajax/subscribe/',
                    type: 'post',
                    data: { subscribed: 1 },
                    success: function() {
                        $('.cabinet-subscribe').toggle();
                        Service.message("Вы успешно подписались на рассылку");
                    }
                });
            }
        });
		
		
    }

    account = new Account(isLogin, user_id);

    

    
	
	function createPopup() {
        var popup = {},
                overlay = $('.new_pop_overlay'),
                window = $('.new_pop_window'),
                html = $('.new_pop_window_html');

        overlay.click(function(e) {
            if ($(e.target).is('.new_pop_overlay')) popup.close();
        });

        popup.settings = {
            buttons: {
                'ok': function() {
                    popup.close();
                }
            },
            html: "",
            css: {
                width: '300px',
                top: '48px',
				left: '200px'
            }

        }

        popup.close = function() {
            overlay.hide();
            window.hide();
			html.html('');
        }

        function setContent() {
            html.html(popup.settings.html);
        }

        function showWindow() {
            window.css(popup.settings.css);
            window.show();
        }

        popup.show = function(options) {
            popup.settings = $.extend(popup.settings, options);
            setContent();
            overlay.show();
            showWindow();
        }

        return popup;
    }
	
	// TODO Popup in module
	Popup = createPopup();
	
    Video = (function() {
        var video = { subjectid: null };
        $('#video-button-send').live({
            'click': function() {
                video.postComment();
            }
        });

        video.postComment = function() {
            var comment = $('#video-textarea-comment');
            if (comment.val().length == 0 || comment.val() == "Оставьте комментарий") return;
            if (account.isLogin) {
                $.ajax({
                    url: '/ajax/post_comment/',
                    type: 'post',
                    data: {
                        text: comment.val(),
                        subjectid: video.subjectid
                    },
                    success: function() {
                        $('#video-message-gray').after('<div class="video-comment video-comment-just">' + comment.val() + '<br><b>' + 'Вы' + '  </b>' + '1 сек. назад' + '</div>');
                        comment.val("");
                    }
                });
            } else {
                $('#video-message-gray').text('Необходимо выполнить вход или зарегистрироваться');
            }

        }

        video.show = function(id, href) {
            this.subjectid = id;
			var data = (href === undefined) ? { id: id } : { id: id, href: href }; 
            $.ajax({
                url: '/ajax/get_video/',
                type: 'post',
                //data: { href: href, title: title, id: id },
                data: data,
                success: function(data) {
                    $.fancybox(data, {
                        onClosed: function() {
                            coreNotice('video closed');
                        }
                    });
                    
                    $('.video-textarea-comment').focus(function(){
                        if ($(this).val() == 'Оставьте комментарий'){
                            $(this).val('');
                        }
                    });

                    $('.video-textarea-comment').blur(function(){
                        if ($(this).val() == ''){
                            $(this).val('Оставьте комментарий');
                        }
                    });

                }
            });
        }

        // TODO deprecated
        video.showIfLogin = function(href, title, id) {
            var that = this;
            if (account.isLogin) {
                this.show(href, title, id);
            } else {
                account.showLogin("Видеоинтервью доступно только для зарегистрированных пользователей", function() { that.show(href, title, id); });
                $('#alertOverlay').show();
            }
        }

        return video;
    })();



    var Service = {};
    Service.message = function(msg) {
        alert(msg);
    }
    Service.confirm = function(msg) {
        return confirm(msg);
    }


    var burnThumbl = null;
    var hideCloud = function(img, cloud) {
        return setTimeout(function() {
            img.attr('src', img.data('addinactive'));
            cloud.hide();
        }, 300);
    }
    $('.question_thumbl').live({
        mouseenter: function() {
            clearTimeout(burnThumbl);
            $(this)
                    .attr('src', $(this).data('add'));
            
            var cloud = $(this).parent().siblings('.user-cloud');
            if (cloud.data('show')) cloud.show();
            /*
             .parent().parent().parent()
             .find('.user-text')
             .html($(this).data('phrase'))
             .show();
             */
        },
        mouseleave: function() {
            burnThumbl = hideCloud($(this), $(this).parent().siblings('.user-cloud'));
        },
        
        click: function() {
            
        }
    });

    $('.user-cloud').live({
        mouseenter: function() {
            clearTimeout(burnThumbl);
        },
        mouseleave: function() {
            burnThumbl = hideCloud($(this).siblings('.user-pic').find('.question_thumbl'), $(this));
        },
        click: function(event) {
            event.stopPropagation();
        }

    });

	// TODO deprecated
    $('.video-link').live('click', function(event) {
        Video.show($(this).data('video-id'));
        return false;
    });
	
	// панель статей. когда она свёрнута - развернуть по клику
	$('#icons_panel').click(function(event) {
		if ($(this).hasClass('small_panel')) {
			$(this).removeClass('small_panel');
		} else if ( $(event.target).is('#inner_block_hide')) {
			$(this).addClass('small_panel');
		}
	});
	
	// прокрутка кабинета
	$('#cabinet-container').live('mousewheel', function(event, delta) {
		var t = $(this).offset().top;
		$(this).offset({ top: t + delta * 10});
		return false;
	});
	
	// перетаскивание кабинета
	$('#cabinet-container').draggable({ handle: '#remove_place' });
	
	// 
	$('.h2_right_content_list').live('click', function() {
		Popup.show({
			html: '<textarea id="m-pages-content-feedback-text" style="width: 400px; height: 100px;margin-bottom: 4px; margin-left: -3px;"></textarea>' + 
			'<button id="m-pages-content-feedback-button">Оставить отзыв</button>',
			css: {
				width: '418px', 
				top: ($(window).height() - 171) / 2 + 'px', 
				left: ($(window).width() - 418) / 2 + 'px'
			}
		});
		
		$('#m-pages-content-feedback-button').click(function() {
			var text = $('#m-pages-content-feedback-text').val();
			if (account.isLogin) {
				if (text.length) $.ajax({
					type: 'post',
					url: '/ajax/sergey/', 
					data: { text: text }, 
					success: function(data) {
						if (data == 0) {
							alert('Отзывы могут отправлять только зарегистрированные пользователи');
						} else {
							alert('Ваш отзыв принят');
						}
						Popup.close();
					}
				});
			} else {
				alert('Отзывы могут отправлять только зарегистрированные пользователи');
			}
		});
	});
});
