

/* Mega menu */

$(document).ready(function(){
	$('.popup_menu').hover(
        function(){
            $(this).children('div').css("display", "block");
        },
        function(){
            $(this).children('div').css("display", "none");
        }
    );

    $('.popup_menu').hover(
        function(){
            $(this).children('ul').css("display", "block");
        },
        function(){
            $(this).children('ul').css("display", "none");
        }
    );

});


$(document).ready(function(){
    $('.mega_menu_col ul li:has(ul)').hover(
        function(){
            $(this).children('ul').show();
        },
        function(){
            $(this).children('ul').hide();
        }
    )
});

// Занрузка формы отправки заказа

function addCart(id, value) {
    $.getJSON(
		'/catalog/?ajaxAddCart=' + id + '&value=' + value,
		{},
		function (data)
		{
            
		}
	);
}




/**
 *  Функция isValidEmail принимает один или 2 аргумента:
 *  email - электронный адрес для проверки;
 *  strict - необязательный логический параметр (true/false), который определяет строгую проверку при которой пробелы до и после адреса считаются ошибкой
 *  В качестве результата функция возвращает либо true, либо false
*/

function isValidEmail (email, strict)
{
    if ( !strict ) email = email.replace(/^\s+|\s+$/g, '');
    return (/^([a-z0-9_\-]+\.)*[a-z0-9_\-]+@([a-z0-9][a-z0-9\-]*[a-z0-9]\.)+[a-z]{2,4}$/i).test(email);
}






/**
 * Проверка формы
 */
function checkForm(check, email) {

    var errors = 0;

    for (i=0; i<check.length; i++)
        if ($('#' + check[i]).val() == '' || $('#' + check[i]).val() == 0)
        {
            if ($('#' + check[i]).attr('type') == 'text')
                $('#' + check[i] + '_text').children('span').css('color', '#cc0000').html('Необходимо заполнить поле');
            else
                $('#' + check[i] + '_text').children('span').css('color', '#cc0000').html('Необходимо выбрать значение');

            errors++;
        }
        else
            $('#' + check[i] + '_text').children('span').css('color', '#cc0000').html('');

    // Проверка email
    if (!isValidEmail($('#' + email).val()))
    {
        $('#' + email + '_text').children('span').css('color', '#cc0000').html('Введите корректный E-mail');
        errors++;
    }


    if (errors == 0)
        return true;
    else
        return false;
}


/**
 *  Получение списка продуктов AJAX
 */
function showItems(id) {
    $.getJSON(
		'/catalog/?ajax_id=' + id,
		{},
		function (data)
		{
			$('#item').html('');
			
            for(i=0;i<data.length;i++)
                $('#item').append('<option value="' + data[i].item_id + '">' + data[i].item_name + '</option>');


            if (data.length == 0)
                $('#item').html('<option value="0">В данном каталоге нет товаров</option>');

		}
	);
    
}





/**
 * Раздвигающиеся блоки меню
 */
$(document).ready(function(){

    function hideMenu (menu, menu_class) {
        menu.children('ul').each(function() {
            if($(this).height() > 0)
            {
                // Закрываем все открытые элементы
                $(this).animate({
                    height: "0px"
                }, 1000);

                $(this).children('li').fadeOut(1000);
                $(this).parent().children('span').css("border-bottom", "1px dashed #005ca1");
                $(this).parent().attr("class", menu_class + " plus");
            }
        });
    }

    function loadCat(link) {
        $.getJSON(
            link + '?ajaxCatLoad=1',
            {},
            function (data)
            {
                var contaner = $('#sub');
                var crumbs = data.crumbs;
                var _html_crumbs = '';

                var cat = data.subcat;
                var _html_cat = '';

                var _html = '';

                // Собираем хлебные крошки

                _html_crumbs += '<div class="bread_crumbs">';
                    _html_crumbs += '<a href="/">Главная</a> / ';
                    for (i=0;i<crumbs.length;i++)
                        if (crumbs.length == (i+1))
                            _html_crumbs += crumbs[i].group_name;
                        else
                            if (crumbs[i].link == '/catalog/')
                                _html_crumbs += crumbs[i].group_name + ' / ';
                            else
                                _html_crumbs += '<a href="' + crumbs[i].link + '">' + crumbs[i].group_name + '</a> / ';
                _html_crumbs += '</div>';

                // Собираем список подкаталогов
                _html_cat += '<div class="catalog">';

                    for(i=0;i<cat.length;i++)
                    {
                        if ((i+1)%2==0)
                            var style = 'style="margin-left: 40px;"';
                        else
                            var style = '';

                        _html_cat += '<div class="cat_post" ' + style + '>';
                            _html_cat += '<div class="cat_post_img">';

                            if (cat[i].image != '')
                                _html_cat += '<img src="/show/' + cat[i].image + '?198" width="198" style="margin-top: -' + cat[i].imgsize.m + 'px" alt="">';

                            _html_cat += '</div>';
                            _html_cat += '<p><a href="' + cat[i].link + '">' + cat[i].group_name + '</a></p>';
                        _html_cat += '</div>';
                    }

                    _html_cat += '<div class="space" style="height: 20px;"></div>';
                _html_cat += '</div>';


                // скрываем контейнер
                contaner.fadeOut();

                // Очищаем контейнер
                contaner.html('');

                _html += _html_crumbs;
                _html += '<h1>' + data.h1 + '</h1>';
                _html += _html_cat;
                _html += data.text;


                setTimeout(function(){
                    contaner.html(_html);
                }, 500);

                // показываем контейнер
                setTimeout(function(){
                    contaner.fadeIn();
                }, 600);

            }
        );
    }

    var _list = $('#catalogue_list').children('div').children('ul').children('li');
    _list.children('span').bind('click', function() {
        // время выполнения действия
        var t = 1000;
        var tmp = 0;

        _list.children('a').css("color", "#005ca1");
        _list.children('span').css("color", "#005ca1");
        _list.children('ul').children('li').children('span').css("color", "#005ca1");
        _list.children('ul').children('li').children('ul').children('li').children('a').css("color", "#005ca1");

        // Закрываем все открытые блоки
        hideMenu(_list, 'menulist');

        // Закрываем все открытые внутренние блоки
        hideMenu(_list.children('ul').children('li'), 'submenulist');

        if ($(this).parent().children('ul').height() == 0)
        {
            var h = 0;

            $(this).parent().children('ul').children('li').each(function() {
                 h += $(this).height() + 6;
            });

            $(this).parent().children('ul').children('li').fadeIn(t);
            $(this).parent().children('ul').animate({
                height: h + "px"
            }, t);

            $(this).css("color", "#005ca1");
            $(this).css("border-bottom", "0");
            $(this).parent().attr("class", "menulist minus");


            loadCat($(this).children('div').html());

        }
    });
    
    _list.children('ul').children('li').children('span').bind('click', function() {
        var t = 1000;
        var h = 0;
        var tmp = 0;
        var ph = $(this).parent().parent().height();

        _list.children('ul').children('li').children('ul').each(function() {
                ph = ph - $(this).height();
        })

        _list.children('ul').children('li').children('a').css("color", "#005CA1");
        _list.children('ul').children('li').children('span').css("color", "#005CA1");
        _list.children('ul').children('li').children('ul').children('li').children('a').css("color", "#005CA1");

        hideMenu(_list.children('ul').children('li'), 'submenulist');

        // Закрываем все открытые элементы
        if ($(this).parent().parent().height() > ph)
            $(this).parent().parent().animate({
                height: ph + "px"
            }, 1000);

        if ($(this).parent().children('ul').height() == 0)
        {
            $(this).parent().children('ul').children('li').each(function() {
                 h += $(this).height() + 6;
            });

            // Открываем родительский блок
            if ($(this).parent().parent().height() <= (ph + h))
                $(this).parent().parent().animate({
                    height: (ph + h) + "px"
                }, t);

            // открываем блок
            $(this).parent().children('ul').children('li').fadeIn(t);
            $(this).parent().children('ul').animate({
                height: h + "px"
            }, t);

            $(this).css("color", "#005ca1");
            $(this).css("border-bottom", "0");
            $(this).parent().attr("class", "submenulist minus");

            loadCat($(this).children('div').html());
        }
    });

});


/**
 * Отображение страницы AJAX JSON
 */

function showPage(link) {
    $.getJSON(
		link + '?AjaxShowPage=1',
		{},
		function (data)
		{
            var _obj = $('#text_page_content');
            var _html = '';

            var head = data.h1 != '' ? data.h1 : data.name;

            _html += '<p class="order_form_head">' + head + '</p>';
            _html += data.text;

            _obj.html(_html);

            $('#text_page').fadeIn(1500);

		}
	);
}



/**
 * ОТображение карты
 */

function showFilialMap(src)
{
	
	
	
    if (src != '')
    {
        $('#img_place').html('<img src="' + src + '" />');
        setTimeout(function() {$('#filial_map').fadeIn(500);}, 500);
    }
    else
        return false;

}



