/**
 * Главная страница 
 */
$(function() {

    //*** Хедер ***
    // Меню
    $('#mainmenu .itemmenu').mouseenter(function() {
        if ( ! $(this).hasClass('nodropdown') && ! $(this).hasClass('active') && ! $(this).hasClass('active-section')) {
            $(this).addClass("hover");
        }
    }).mouseleave(function() {
        $(this).removeClass("hover");
		$(this).children('a').removeClass('show');
		$(this).find('.dropdown').css('display', 'none');
    });
	
	// при клике на меню товары, всплывает меню (раньше было при наведении)
	$('#mainmenu .itemmenu:first:not(.active-section):has(.dropdown) > a')
		.addClass('show-level-1')
		.attr('href', 'javaScript:void(0)')
		.css('text-decoration', 'none')
		.click(function() {
			var dd = $(this).parent().find('.dropdown');
			if ('block' == dd.css('display')) {
				dd.css('display', 'none');
				$(this).removeClass('show')
			} else {
				dd.css('display', 'block');
				$(this).addClass('show')
			}
		})
		.find('span')
			.css('position', 'relative')
			.css('margin-right', '10px')
			.addClass('show-level-1-text')
			.append($('<span/>').addClass('show-level-icon'));


    // Второй уровень меню
    $('#mainmenu .level-2, #mainGoodsList .level-2').hide();
    $('#mainmenu .show-level-2, #mainGoodsList .show-level-2').bind('click', function(){
        $(this).toggleClass('show');
        $( '.level-2', $(this).parent() ).toggle();
    });

    // Стиль при наведении на ссылки Домой и Почта
    $('#navigation li').mouseenter(function(){
        if ($("a", this).attr('href')) {
            // Если внутри ссылка
            $(this).addClass('hover');
        }
    }).mouseleave(function(){
        $(this).removeClass('hover');
    });

    $('#basket-button').expandButton();

    //*** Begin: Контент ***
    // Эмуляция перехода по якорю в блоке с overflow:hidden
    $('.pseudo-anchor').click(function(){
        var a = $(this).attr('href');
        goAnchor(a);
        return false;
    });
    var goAnchor = function (hash) {
        if (hash) {
            window.location.hash = hash;
            var elem = $('#_' + hash.replace("#", ""));
            if ($(elem).length) {
                $(document).scrollTop($(elem).offset().top);
            }
        }
    }
    goAnchor(window.location.hash);

    // Случайный выбор комментария
    $('#pageMainSubWrapper .refresh').click(function() {
        var visible = $("#pageMainSubWrapper .textCloud:visible");
        var indexVisible = $("#pageMainSubWrapper .textCloud").index( visible );
        var size = $("#pageMainSubWrapper .textCloud").size();
        var newIndex = Math.floor(Math.random() * size);
        while (newIndex == indexVisible) {
            newIndex = Math.floor(Math.random() * size);
        }
        $("#pageMainSubWrapper .textCloud:eq(" + newIndex + ")").show();
        $(visible).hide();
    });
    //*** End: Контент ***


    //*** Begin: Футер ***
    // Затирание вертикальной черты у последнего элемента
    $('#footer ul').each(function(){
        $(this).children('li:last').addClass('last');
    });
    $('#footer').append(
        $('<div/>').attr('id', 'liveinternet').html(
            $('<a/>')
                .attr('href', 'http://www.liveinternet.ru/stat/' + window.location.hostname + '/')
                .attr('target', '_blank')
                .html(
                    $('<img />')
                        .attr('src',    "http://counter.yadro.ru/hit?t14.4;r"+escape(document.referrer)+((typeof(screen)=="undefined")?"":";s"+screen.width+"*"+screen.height+"*"+(screen.colorDepth?screen.colorDepth:screen.pixelDepth))+";u"+escape(document.URL)+";"+Math.random())
                        .attr('alt',    '')
                        .attr('title',  'LiveInternet: показано число просмотров за 24 часа, посетителей за 24 часа и за сегодня')
                        .attr('width',  88)
                        .attr('height', 31)
                        .attr('border', 0)
                )
        )
    );
    //*** End: Футер ***

    $.fn.ratingText = function(options) {
        var marks = ['ужасно!', 'плохо', 'нормально', 'хорошо', 'отлично!'];
        var opt = options;
        this.each(function(){
            var rating = this;

            var options = $.extend({
                readOnly : true,
                callback : function(value, link){
                    setText();
                },
                focus : function (value, link) {
                    setText(value );
                },
                blur : function(value, link){
                    setText();
                }
            },
            opt);
            $('input', rating).rating(options);
            setText();

            function setText(rate){
                var rate = (rate) ? rate : $('input:checked', rating).val();
                if(marks[rate - 1] == undefined) {
                    $('.rating-text', rating).text('');
                }
                else {
                    $('.rating-text', rating).text(marks[rate - 1]);
                }
            }
        })
    }

    $('.rating').ratingText({readOnly : true});

    // FAQ: скрыть/показать ответ при клике на вопрос
    $(".toggle").click(function(){
        if (this.rel) {
        	$('#' + this.rel).toggle()
        }        
        $(this).toggleClass('close');
        return false;
    }).click();


     /**
     * Активирует кнопку, если заполнено хотя
     * бы одно обязательное поле. Цепляется к форме
     *
     * Параметры
     * options = {
     *         fields : array         // Обязательные поля
     *         submit : string     // Кнопка
     * }
     *
     */
    $.fn.activeSubmit = function(options) {
        var form = this;
        $(options.fields.join(', ')).bind('keyup', activeSubmit)
        function activeSubmit() {
            var complete = false;
            for (i in options.fields) {
                if ($(options.fields[i]).val()) {
                    complete = true;
                }
            }
            complete ? $(options.submit).expandButton('enable') : $(options.submit).expandButton('disable');
        }
        activeSubmit();
    }
});
