// ставим капчу (this - форма)
AUTO.setCaptcha = function(){
    that = this;
    $.get('/ajax/captcha/set/',
          {form_id: $('input[name=form_id]', that).val()},
            function(data) {
              $('input[name=form_create_time]', that).val(data);
              $('input:visible, textarea', that).first().focus();
          }
    );
}

$('#show_phone').show();
$('.noscript').hide();

$(function(){
    // показываем телефон по клику
    $('#show_phone').click(function(e){
        e.preventDefault();
        $that = $(this);
        $that.hide();
        $('#show_phone ~ .noscript').show();
        $.ajax({
            url: '/ajax/phone/get/',
            data: {instructor_id: $that.attr('instructor_id')},
            dataType: 'html',
            success: function(data) {
//                $that.replaceWith(data);
                _gaq.push(['_trackPageview', '/phone/get/'+$that.attr('instructor_id')]);
            }
        });
    });

    // отзыв
    $('.make_review_link').click(function(e){
        e.preventDefault();
        $that = $(this);
        // меняем текст "открыть форму" на "закрыть форму"
        $('.reviews_submit_form_label:hidden').show();
        $that.parent().hide();
        $('form#add_review').slideToggle('fast',
             function(){
                $(this).loadValidation({
                    formLoad: AUTO.setCaptcha,
                    beforeSend: function() {
                        $('.reviews_submit_form input[type=submit]').attr('disabled', true);
                    },
                    formSuccess: function(data){
                        $('.reviews_submit_form input[type=submit]').removeAttr('disabled');
                        $('.reviews_submit_form').after(unescape(data.review_html));
                        $('.make_review_link:visible').click();
                        $('.reviews_submit_form form')
                            //.find('input[name=form_create_time]').val(0).end()
                            .get(0).reset(); // очищаем форму
                    }
                });
            }
        );
    });

    $('#info_error_text').change(function() {
        if ($.trim($(this).val())) {
            $('#info_other_error').attr('checked', 'true');
        } else {
            $('#info_other_error').removeAttr('checked');
        }
    });

    // сообщение об ошибке
    $('.point_out_info_error_link').click(function(e){
        e.preventDefault();
        // Очищаем текст сообщения формы
        $('#info_error_form_message').text('');
        $that = $(this);
        // меняем текст "открыть форму" на "закрыть форму"
        $('.info_error_submit_form_label:hidden').show();
        $that.parent().hide();
        $('form#point_out_info_error').slideToggle('fast',
             function(){
                $(this).loadValidation({
                    formLoad: AUTO.setCaptcha,
                    beforeSend: function() {
                        $('#point_out_info_error input[type=submit]').attr('disabled', true);
                    },
                    formSuccess: function(data){
                        $('#point_out_info_error input[type=submit]').removeAttr('disabled');
                        $('.point_out_info_error_link:visible').click();
                        $('#point_out_info_error').get(0).reset();
                        $('#info_error_form_message').text(unescape(data.message))
                        .effect('highlight', {}, 3000);
                    }
                });
            }
        );
    });

    // ответ инструктора
    $('.make_response_link').click(function(e){
        e.preventDefault();
        // меняем текст "открыть форму" на "закрыть форму"
        $that = $(this).parent().siblings('.make_response_link_label').show().find('a');
        $(this).parent().hide().siblings('form').slideToggle('fast',
            function(){
                $(this).loadValidation({
                    formLoad: AUTO.setCaptcha,
                    formSuccess: function(data){
                        $('#review'+data.review_id).replaceWith(unescape(data.review_html));
                        $that.click();
                    }
                });
             }
         );
    });

    /**
     * Наводим мышь на звёздочку
     */
    $('.instructor_fav_from_profile').live('mouseover mouseout', function(event) {
        if (event.type == 'mouseover') {
            $(this).addClass('instructor_fav_on_hover');
          } else {
            $(this).removeClass('instructor_fav_on_hover');
          }
    });

    // избранное
    $('.instructor_fav_from_profile').click(function(e){

        var instructor_id = $(this).attr('instructor_id');

        // меняем картинку в инструкторолле
        if (top.document) {
            $('.instructor_fav[instructor_id='+instructor_id+']', top.document)
                .toggleClass('instructor_fav_on');
        }
        // меняем картинку в объявлении
        $(this).toggleClass('instructor_fav_on').removeClass('instructor_fav_on_hover');
        // добавляем в избранное (или удаляем)
        var action = $(this).hasClass('instructor_fav_on') ? 'add' : 'remove';

        // меняем title у звёздочки
        var newTitle = $(this).attr('other_title');
        $(this).attr('other_title', $(this).attr('title'));
        $(this).attr('title', newTitle);

        // убираем из избранного
        if ('remove' == action && parent.$.bbq.getState('favorite')) {
            var deleted = $('.instructor_fav[instructor_id='+instructor_id+']',top.document)
                            .closest('tr').children('td');
            if ($.browser.msie) {
                deleted.remove();
            } else {
                deleted.fadeOut(700, function(){
                    $(this).remove();
                });
            }
        }

        // асинхронно добавляем в избранное (либо удаляем)
        $.ajax({
            cache: false,
            url: '/ajax/favorite/'+action+'/'+instructor_id+'/',
            success: function(){
                if (parent.AUTO.favorite) {
                    parent.AUTO.favorite[action](instructor_id);
                }
            }
        });
    });
});