var sprevs = false;
var gprev = false;
$(document).ready(function(){

    // Шрифты
    Cufon.replace("h1");
    //Cufon.replace("div.center-column .text h2");
    Cufon.replace("form button");
    Cufon.replace(".xenia");
    //Cufon.replace("div#slider div p.text em");
    //Cufon.replace("div#slider_small em");

    // слайдер на морде
    if ($('#slider')) {
    
        $('#slider div').hover(
          function () {
            clearInterval(sldr);
            $('#slider .active').removeClass('active').prev('div').removeClass('noborder');
            $(this).addClass('active').prev('div').addClass('noborder');
          },
          function () {
            sldr = setInterval(sliderRotate, 10000);
          }
        );
        
        var sldr = setInterval(sliderRotate, 10000);

    }
    
    if ($('#slider_small')) {
    
        $('#slider_small div').hover(
          function () {
            $('#slider_small .active').removeClass('active').prev('div').removeClass('noborder');
            $(this).addClass('active').prev('div').addClass('noborder');
          }
        );

    }
    
    $('.actions #last a').click(function() {
        if ($("#slider_small").is(":hidden")) {

            $('#slider').slideUp('medium', function() {
                $('#slider_small').slideDown();
            });
            
            document.cookie = "csldr=1";
            
            $('.actions #last a').text('Развернуть');
            
        } else {
       
            $('#slider_small').slideUp('medium', function() {
                $('#slider').slideDown();
            });  
            
            document.cookie = "csldr=0;expires=0";
            
            $('.actions #last a').text('Свернуть');  
        
        }
        
        return false;
    });
    
    
    // галерея на морде
    $("div.main-column .photo ul li").hover(function() {
        $(this).children('a').show();
    },function() {
        $(this).children('a').hide();
    }).children('a').hide();;
    
    $("#carusel li a").hover(function() {
        if (gprev) gprev.hide();
        var p = $(this).position();
        var id = $(this).attr('rel');
        gprev = $('#desc_'+id);
        var l = p.left-720;
        gprev.show().css('left',l);
        
    });
    
    $(".photo .data").hover(false,function() {
        if (gprev) gprev.hide();
        gprev = false;
        return false;
    });
        
    $('#info-gfx-panel a').click(function() {
        if ($('#info-gfx').height() >= $('#info-gfx img').height()) {
            $('#info-gfx').animate( { height: '80px' });
            $('#info-gfx-panel a').css('background-image',"url('/images/info-gfx-right.png')").text('Развернуть'); 
        } else {
            $('#info-gfx').animate( { height: ($('#info-gfx img').height()+20) + 'px' });
            $('#info-gfx-panel a').css('background-image',"url('/images/info-gfx-right2.png')").text('Свернуть');
        }
        return false;
    });
    
    $('#info-gfx img').click(function() {
        if ($('#info-gfx').height() >= $('#info-gfx img').height()) {
            window.open($(this).attr('alt'));
        } else {
            $('#info-gfx').animate( { height: ($('#info-gfx img').height()+20) + 'px' });
            $('#info-gfx-panel a').css('background-image',"url('/images/info-gfx-right2.png')").text('Свернуть');
        }
        return false;
    });
    
    // регистрация/авторизация
    /*
    $('.login').click(function(){
        $('#login_form').css({'left':$(this).offset().left+50,'top':$(this).offset().top-80}).toggle();
        return false;
    });
    */
       
    fix_input("textarea#comment", 'Ваш комментарий');
    fix_input("textarea#question", 'Ваш вопрос');
    fix_input("#query", 'Поиск по сайту');
    
    $('.reply').click(function(){
        $("textarea#comment").focus().val($('#c'+$(this).attr('id')).html()+': ');
    });
    
    $('a.delete').click(function(){
        var a = $(this).attr('id').split('_');
        if (confirm('Удалить комментарий?')) {
          $.ajax({
              url : '/action/delete?id='+a[1],
              success: function () {                                
                   $("#com_"+a[1]).remove();
              }
          });
        }
        return false;
    });
    
    $('a.delete_q').click(function(){
        var a = $(this).attr('id').split('_');
        if (confirm('Удалить вопрос?')) {
          $.ajax({
              url : '/action/delete_q?id='+a[1],
              success: function () {                                
                   $("#com_"+a[1]).remove();
              }
          });
        }
        return false;
    });
    
    $('.reply_q').click(function(){
        var a = $(this).attr('id').split('_');
        $("form").hide();
        $("#f_"+a[1]).show();
        return false;
    });
    
    $('#login_form a').click(function(){
        $("#login_form p.error").html('<img src="/images/ajax-small.gif" />');
        $.ajax({
            type: 'POST',
            url : '/action/login',
            dataType : 'json',
            data: $("#login_form").serializeArray(),
            success: function (data) {                                
                if (!data.success) {
                     $("#login_form p.error").html(data.message);
                } else {
                    location.reload();
                }
            }
        });
        return false;
    });
    
    //Твиддичь
    $('.twidich .item a').hover(function(){
        $(this).next('div').show();
    }, function(){
        $(this).next('div').hide();
    });
    
    //Свежий выпуск
    $('.issue').hover(function(){
        $(this).css('z-index', 200);
    }, function(){
        $(this).css('z-index', 100);
    });
    
    // Галереи
    
    if ($(".gallery #preview").length) {
        gallery_preview = $(".gallery .preview");
        $("#counter span").eq(1).html(gallery_preview.length);
        gallery_preview.hide();
        $(gallery_preview[0]).show();
        
        $("#preview #next, #zoompanel .right").click(function(){
            var o = $(".gallery .preview:visible").css({'z-index':1});
            var n = o.next('.preview');
            if (n.length) e = $(n[0]); else e = $(gallery_preview[0]);
            
            if ($("#zoompanel").is(':visible')) {
                $("#zoompanel .loading").show();
                $("#picture").attr('src',e.children("a").attr('rel'));
            } 
            
            e.css({left:"-720px",'z-index':2}).show().animate({left:"0px"}, function() {
                o.hide();
                $("#counter span").eq(0).html(1+$(".gallery .preview").index($(".gallery .preview:visible")));
            });
        });
        
        $("#preview #prev, #zoompanel .left").click(function(){
            var o = $(".gallery .preview:visible").css({'z-index':1});
            var n = o.prev('.preview');
            if (n.length) e = $(n[0]); else e = $(gallery_preview[gallery_preview.length-1]);
            
            if ($("#zoompanel").is(':visible')) {
                $("#zoompanel .loading").show();
                $("#picture").attr('src',e.children("a").attr('rel'));
            } 
            
            e.css({left:"720px",'z-index':2}).show().animate({left:"0px"}, function() {
                o.hide();
                $("#counter span").eq(0).html(1+$(".gallery .preview").index($(".gallery .preview:visible")));
            });
        });
                       
        $("#preview #zoom, .gallery .preview a img").click(function(){  
            zoompanel_loading();  
            $("#picture").attr('src',$(".gallery .preview:visible a").attr('rel'));
        });
        
        $("#preview #desktop").click(function(){        
            $("#preview .desktop").toggle();
        });
    }

    $("#zoompanel .close").click(function(){
        $("#zoompanel").hide();
    });
    
    $("#picture").load(function(){
        //alert($("#zoompanel").width());
        $("#zoompanel .loading").hide();
        $("#zoompanel table").css({'height':$('body').height(),'margin-top': $(document).scrollTop()});
        $("#zoompanel").css({'height':$(document).height()}).show();
        $("#zoompanel .picture").css({'width':$("#picture").width(),'height':$("#picture").height()});
        $("#picture").show();
    });
    
    //Развернуть картинку
    $('.pictures a.expand').click(function(){
        //var act = $(this).nextAll('.actual');
        //act.css({'z-index':1000}).animate({width:act.children('img').width(), height:act.children('img').height()+17});
        zoompanel_loading();
        $("#picture").attr('src',$(this).attr('rel'));
        $('.pictures .active').removeClass('active');
        $(this).parent('.image').addClass('active');
        return false;
    });
    
    if ($('.pictures .image').length == 1) 
        $("#zoompanel .right, #zoompanel .left").hide();
    
    if ($('.pictures .image').length > 1) {
        $("#zoompanel .right").click(function(){
            var n = $('.pictures .active').next('.image');
            if (n.length) e = $(n[0]); else e = $($('.pictures .image')[0]);
            $('.pictures .active').removeClass('active');
            e.addClass('active');
            $("#zoompanel .loading").show();
            $("#picture").attr('src',e.children("a").attr('rel'));
        });
        
        $("#zoompanel .left").click(function(){
            var n = $('.pictures .active').prev('.image');
            if (n.length) e = $(n[0]); else e = $($('.pictures .image')[$('.pictures .image').length-1]);
            $('.pictures .active').removeClass('active');
            e.addClass('active');
            $("#zoompanel .loading").show();
            $("#picture").attr('src',e.children("a").attr('rel'));
        });
    }
    
    /*
    $('.pictures a.collapse, .pictures .actual img').click(function(){
        var act = $(this).parent('.actual');
        act.animate({width:116, height:116}, false, false, function(){act.css({'z-index':-1});} );
        return false;
    });
    */
    
    // Форма входа
    fix_input('#entry_email', 'Ваш e-mail');
    fix_input('#entry_openid', 'OpenID URL');
    $('#entry_password_fake').focus(function () {
        $(this).hide();
        $('#entry_password').show().focus();
    });
    $('#entry_password').blur(function () {
        if ($(this).val() == '') {
            $(this).hide();
            $('#entry_password_fake').show();
        }
    });
    
    // Регистрация
    $('form#register').submit(function () {
        $('p.error').html('');
        var error = '';
        if (!isEmail($('#entry_email').val())) error = 'Введите свой настоящий e-mail.<br />';
        if (!$('#name').val() || !$('#password').val() || !$('#password2').val())
            error += 'Заполните все обязательные поля.<br />';
        if ($('#password').val() != $('#password2').val())
            error += 'Введенные пароли не совпадают.<br />';
        if (error) {
            $('p.error').html(error);
            return false;
        }
    });
    
    //Твиддич
    $('#twidich_more a').click(get_twiddich);
    
    $('div.articles span.blockquote').wrapInner('<div></div>').css('display','inline-block').hover(
        function() {
            $(this).children('div').show();
        },
        function() {
            $(this).children('div').hide();
        }
    );
    
    $("div.articles tr:even, div.table tr:even").addClass('g');
    
    $("div.articles .cut").click(function() {
        $(this).toggleClass('cut-active');
    });
});


function get_twiddich() {
        $('#twidich_more').html('<img src="/images/ajax-small.gif" />');   
        $.ajax({
            url : '?start='+$(this).attr('rel'),
            success: function (data) {                                
                $('#twidich_more').replaceWith(data);
                $('#twidich_more a').click(get_twiddich);
            }
        });
        return false;
}

var gallery_preview;

function isEmail(email) {
    var reg = /[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?/;
    return email.match(reg); 
}

function fix_input(elm, text) {
    $(elm).focus(function () {
        if ($(this).val() == text) $(this).val('');
    }).blur(function () {
        if ($(this).val() == '') $(this).val(text);
    });
}

function zoompanel_loading() {
    $("#picture").hide();
    $("#zoompanel .picture").css({'width':'300px','height':'300px'});
    $("#zoompanel .loading").show();
    $("#zoompanel table").css({'height':$('body').height(),'margin-top': $(document).scrollTop()});
    $("#zoompanel").css({'height':$(document).height()}).show();
}

function sliderRotate() {
    //alert('!');
    var c = $('#slider .active');
    var n;
    if (c.hasClass('last')) 
        n = $('#slider .first');
        else n = c.next('div');
    n.addClass('active').prev('div').addClass('noborder');
    c.removeClass('active').prev('div').removeClass('noborder');
}
