//change preloader
var lastWait = [];
/* non-xhr loadings */
BX.showWait = function (node, msg) {
    node = BX(node) || document.body || document.documentElement;
    msg = msg || BX.message('JS_CORE_LOADING');

    var container_id = node.id || Math.random();

    var obMsg = node.bxmsg = document.body.appendChild(BX.create('DIV', {
        props: {
            id: 'wait_' + container_id,
            className: 'bx-core-waitwindow'
        },
        text: msg
    }));

    setTimeout(BX.delegate(_adjustWait, node), 10);

    $('#win8_wrapper').show();
    lastWait[lastWait.length] = obMsg;
    return obMsg;
};

BX.closeWait = function (node, obMsg) {
    $('#win8_wrapper').hide();
    if (node && !obMsg)
        obMsg = node.bxmsg;
    if (node && !obMsg && BX.hasClass(node, 'bx-core-waitwindow'))
        obMsg = node;
    if (node && !obMsg)
        obMsg = BX('wait_' + node.id);
    if (!obMsg)
        obMsg = lastWait.pop();

    if (obMsg && obMsg.parentNode) {
        for (var i = 0, len = lastWait.length; i < len; i++) {
            if (obMsg == lastWait[i]) {
                lastWait = BX.util.deleteFromArray(lastWait, i);
                break;
            }
        }

        obMsg.parentNode.removeChild(obMsg);
        if (node)
            node.bxmsg = null;
        BX.cleanNode(obMsg, true);
    }
};

function _adjustWait() {
    if (!this.bxmsg)
        return;

    var arContainerPos = BX.pos(this),
        div_top = arContainerPos.top;

    if (div_top < BX.GetDocElement().scrollTop)
        div_top = BX.GetDocElement().scrollTop + 5;

    this.bxmsg.style.top = (div_top + 5) + 'px';

    if (this == BX.GetDocElement()) {
        this.bxmsg.style.right = '5px';
    }
    else {
        this.bxmsg.style.left = (arContainerPos.right - this.bxmsg.offsetWidth - 5) + 'px';
    }
}

//end preloader

$(document).ready(function () {
    var tmp = getUrlVars();
    //alert(tmp['order_by']);
    if (typeof tmp['order_by'] !== 'undefined') {
        var top = $("#filter").offset().top; //#anchor - анкор к которому прокручиваем
        var height = document.body.clientHeight;
        $('html,body').animate({scrollTop: top});
    }
});

$('#search_input').keyup(function () {
    $('#search_result').html('');
    if ($(this).val().length > 2) {
        $.ajax({
            type: "POST",
            url: "/ajax/ajax_search_result.php",
            data: {q: $(this).val()},
            dataType: "json",
            success: function (json) {
                $('#search_result').html('');
                $.each(json, function (index, element) {
                    if (element.NOT_FOUND) {
                        $('#search_result').append('<div class="search_dropdown__item clearfix">' +
                            '<span>' + element.NOT_FOUND + '</span>' +
                            '</div>');
                    } else {
                        $('#search_result').append('<div class="search_dropdown__item clearfix">' +
                            '<div class="search_dropdown__pic">' +
                            '<img src="' + element.PICTURE + '" alt="">' +
                            '</div>' +
                            '<div class="search_dropdown__text"><a href="' + element.URL + '">' + element.TITLE + '</a></div>' +
                            '</a></div>');
                    }
                });
            }
        });
    }
});

//Header menu search
if ($('#search_input').length) {
    $('#search_input').on('keyup', function () {
        var searchInpVal = $(this).val();
        if (searchInpVal != '') {
            $('.search_dropdown').addClass('active');
        } else {
            $('.search_dropdown').removeClass('active');
        }
    })
}

function getUrlVars() {
    var vars = [], hash;
    var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
    for (var i = 0; i < hashes.length; i++) {
        hash = hashes[i].split('=');
        vars[hash[0]] = hash[1];
    }
    return vars;
}

$('body').on("change", "#page_count", function () {
    var url_parameters = getUrlVars();

    url_parameters['page_count'] = $(this).val();

    var result = "?";
    for (var i in url_parameters) {
        if (url_parameters.hasOwnProperty(i)) {
            result += i + "=" + url_parameters[i] + "&";
        }
    }

    result = result.slice(0, -1);

    var url = location.protocol + '//' + location.host + location.pathname + result;

    window.location.href = url;
});

$('body').on("click", "div ._filters_view a", function () {
    $.ajax({
        type: "POST",
        url: location.href,
        data: {template_name: this.id},
        dataType: "html",
        beforeSend: function () {
            $('#win8_wrapper').show();
        },
        success: function (resp) {
            $('#catalog').html($(resp).find('#catalog').html());

            $(".b_product").magnificPopup({
                delegate: 'a._product_img',
                type: 'image',
                closeOnContentClick: false,
                closeBtnInside: false,
                mainClass: 'mfp-with-zoom mfp-img-mobile',
                image: {
                    verticalFit: true
                },
                zoom: {
                    enabled: true,
                    duration: 300,
                    opener: function opener(element) {
                        return element.find('img');
                    }
                }
            });
        },
        complete: function (jqXHR, textStatus) {
            $('#win8_wrapper').hide();
        }
    });
});

$(document).on('click', '#catalog_4_filter_set_btn', function (e) {
    var url = $('#link_to_set_filter').attr('href');
    var params = {};
    $('div ._filter_types input:checkbox').each(function () {
        if (this.checked) {
            params[this.name] = 'on';
        }
    });

    var str = jQuery.param(params);
    window.location.href = url + '?' + str;

    e.preventDefault();
});

function reloadCaptcha() {
    $.ajax({
        type: "POST",
        url: '/ajax/ajax_reload_captcha.php',
        dataType: "json",
        beforeSend: function () {
            $('#reload_captcha_icon').hide();
            $('#floatingBarsG').show();
        },
        success: function (data) {
            $('#captchaImg').attr('src', '/bitrix/tools/captcha.php?captcha_sid=' + data);
            $('#captchaSid').val(data);
        },
        complete: function (jqXHR, textStatus) {
            $('#floatingBarsG').hide();
            $('#reload_captcha_icon').show();
        }
    });
    return false;
}

function reloadCaptchaVacancies(template_folder, id) {
    $.ajax({
        type: "POST",
        url: template_folder + '/reload_captcha.php',
        dataType: "json",
        beforeSend: function () {
            $('#reload_captcha_icon_' + id).hide();
            $('#floatingBarsG_' + id).show();
        },
        success: function (data) {
            $('#captchaImg_' + id).attr('src', '/bitrix/tools/captcha.php?captcha_sid=' + data);
            $('#captchaSid_' + id).val(data);
        },
        complete: function (jqXHR, textStatus) {
            $('#floatingBarsG_' + id).hide();
            $('#reload_captcha_icon_' + id).show();
        }
    });
    return false;
}

$(document).on("click", "._product_buy", function (e) {
    var id = $(this).data("id");
    var product_picture = $(this).closest('div.b_product').find('a._product_img').attr('href'),
        product_name = $(this).closest('div.b_product').find('a._product_name').text();

    $('#popup_product_img').attr("src", product_picture);
    $('#popup_product_img').attr("alt", product_name);

    var item_quantity = $(this).closest('form').find('input._spinner_input ').val();

    if (!item_quantity) {
        item_quantity = $(this).closest('form').find('input.number_input').val();
    }

    if (!item_quantity) {
        item_quantity = 1;
    }

    $.ajax({
        type: "POST",
        url: '/ajax/ajax_add_to_basket.php',
        data: {id: id, item_quantity: item_quantity},
        dataType: "html",
        beforeSend: function () {
            $('#win8_wrapper').show();
        },
        success: function (data) {
            reloadBasketLine();
            $.magnificPopup.open({
                items: {
                    src: '#in_basket_popup'
                },
                type: 'inline'
            });
        },
        complete: function (jqXHR, textStatus) {
            $('#win8_wrapper').hide();
        }
    });
    e.preventDefault();
});

$(document).on("click", "#clear_all_basket", function () {
    $.ajax({
        type: "POST",
        url: '/ajax/ajax_delete_all_basket.php',
        dataType: "html",
        beforeSend: function () {
            $('#win8_wrapper').show();
        },
        success: function (data) {
            location.reload();
        },
        complete: function (jqXHR, textStatus) {
            $('#win8_wrapper').hide();
        }
    });
});

$(document).on('change', '.b_basket .b_spinner ._spinner_input', function () {
    var id = $(this).attr("id").replace('QUANTITY_INPUT_', ''),
        quantity = $(this).val();
    if ($(this).val() == 0 || !$(this).val()) {
        $(this).val(1);
        quantity = 1;
    }
    if ($(this).attr('max').length > 0){
        var max = $(this).attr('max');
        if (parseInt(quantity) > parseInt(max)){
            quantity = max;
            $(this).val(quantity);
        }
    }

    updateQuantity(id, quantity);
    var price_for_one = parseFloat($(this).closest('._tr').find('div.-price input[type=hidden]').val());
    var price_currency_arr = $(this).closest('._tr').find('div.-price').text().split(" "),
        price_currency = price_currency_arr[price_currency_arr.length - 1],
        total = price_for_one * quantity;

    total = total.toFixed(2);

    $(this).closest('._tr').find('div.-total').text(total.toString().replace(/(\d)(?=(\d{3})+(?!\d))/g, '$1 ') + ' ' + price_currency);
});

$(document).on('mousedown', '.b_basket .b_spinner .ui-spinner-up', function () {
    var id = $(this).closest('._tr').find('input._spinner_input').attr("id").replace('QUANTITY_INPUT_', ''),
        quantity = $(this).closest('._tr').find('input._spinner_input').val();
    updateQuantity(id, quantity);
    var price_for_one = parseFloat($(this).closest('._tr').find('div.-price input[type=hidden]').val());
    var price_currency_arr = $(this).closest('._tr').find('div.-price').text().split(" "),
        price_currency = price_currency_arr[price_currency_arr.length - 1],
        total = price_for_one * quantity;

    total = total.toFixed(2);

    $(this).closest('._tr').find('div.-total').text(total.toString().replace(/(\d)(?=(\d{3})+(?!\d))/g, '$1 ') + ' ' + price_currency);
});

$(document).on('mousedown', '.b_basket .b_spinner .ui-spinner-down', function () {
    var id = $(this).closest('._tr').find('input._spinner_input').attr("id").replace('QUANTITY_INPUT_', ''),
        quantity = $(this).closest('._tr').find('input._spinner_input').val();
    updateQuantity(id, quantity);
    var price_for_one = parseFloat($(this).closest('._tr').find('div.-price input[type=hidden]').val());
    var price_currency_arr = $(this).closest('._tr').find('div.-price').text().split(" "),
        price_currency = price_currency_arr[price_currency_arr.length - 1],
        total = price_for_one * quantity;

    total = total.toFixed(2);

    $(this).closest('._tr').find('div.-total').text(total.toString().replace(/(\d)(?=(\d{3})+(?!\d))/g, '$1 ') + ' ' + price_currency);

});

function sumFormat(n) {
    n += "";
    n = new Array(4 - n.length % 3).join("U") + n;
    return n.replace(/([0-9U]{3})/g, "$1 ").replace(/U/g, "");
}

function updateQuantity(id, quantity) {
    $.ajax({
        type: "POST",
        url: '/ajax/ajax_basket_update_quantity.php',
        dataType: "html",
        data: {id: id, quantity: quantity},
        // beforeSend: function () {
        //     $('#win8_wrapper').show();
        // },
        success: function (data) {
            console.log(data);
            reloadBasketLine();
        },
        // complete: function (jqXHR, textStatus) {
        //     $('#win8_wrapper').hide();
        // }
    });
}

function reloadBasketLine() {
    $.ajax({
        type: 'post',
        url: '/ajax/ajax_load_basket_line.php',
        data: 'basket_ajax=Y',
        success: function (htmlContent) {
            if (typeof(htmlContent) == "string" && htmlContent.length > 0) {
                $('#header_small_basket').html(htmlContent);
            }
            window.arParams = {};
            total();
        }
    });
}

function total() {
    var quantity, price_for_one, price_currency_arr, price_currency, total_tr, total = 0;
    $('#basket_items_list div._tr').each(function () {
        quantity = $(this).find('input._spinner_input').val();
        price_for_one = parseFloat($(this).find('div.-price input[type=hidden]').val());
        price_currency_arr = $(this).find('div.-price').text().split(" ");
        price_currency = price_currency_arr[price_currency_arr.length - 1];
        total_tr = price_for_one * quantity;
        total += total_tr;
    });

    total = total.toFixed(2);

    $('#basket_total_price').text(total.toString().replace(/(\d)(?=(\d{3})+(?!\d))/g, '$1 ') + ' ' + price_currency);
}

$('#auth_log_out').click(function (e) {
    e.preventDefault();
    $(this).closest("form").submit();
});

$('#auth_log_out_from_personal').click(function (e) {
    e.preventDefault();
    $(this).closest("form").submit();
});

$(document).on('click', '#current_order_btn', function () {
    $('#current_order_btn_ajax').trigger('click');
});

$(document).on('click', '#history_order_btn', function () {
    $('#history_order_btn_ajax').trigger('click');
});

$(document).on('click', 'a[id^=order_item_detail_]', function (e) {
    var id = $(this).attr('id').replace('order_item_detail_', '');
    $.ajax({
        type: "POST",
        url: '/ajax/ajax_order_detail.php',
        dataType: "html",
        data: {ID: id},
        beforeSend: function () {
            $('#win8_wrapper').show();
        },
        success: function (data) {
            $('#order_item_content').html(data);
            $.magnificPopup.open({
                items: {
                    src: '#order_item_content'
                },
                type: 'inline'
            });

        },
        complete: function (jqXHR, textStatus) {
            $('#win8_wrapper').hide();
        }
    });
    e.preventDefault();
});


$(document).on('click', '#add_order_btn', function () {
    $('#add_order_submit_btn').trigger('click');
});

$(document).on('change', '#subscribe_chckbx', function () {
    if (this.checked) {
        $('#UF_IS_SUBSCRIBE').val(1);
    } else {
        $('#UF_IS_SUBSCRIBE').val(0);
    }
});

$(document).on('change', '.b_order_details #terms', function () {
    if (this.checked) {
        $('#add_order_btn').removeAttr('disabled');
        $(this).next('label._label').removeClass('error');
    } else {
        $('#add_order_btn').attr('disabled', 'disabled');
        $(this).next('label._label').addClass('error');
    }
});

$(function () {
    $("input:file").change(function () {
        var fileName = $(this).val().replace("C:\\fakepath\\", "");
        $("#user_filename_" + $(this).data('id')).text(fileName);
    });
});


function getParameterByName(name, url) {
    if (!url) url = window.location.href;
    name = name.replace(/[\[\]]/g, "\\$&");
    var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
        results = regex.exec(url);
    if (!results) return null;
    if (!results[2]) return '';
    return decodeURIComponent(results[2].replace(/\+/g, " "));
}

$(document).ready(function () {
    var login = getParameterByName('login');
    if (login == "yes") {
        $('#enter_popup_btn').trigger("click");
    }

    var forgot = getParameterByName('forgot_password');
    if (forgot == "yes") {
        $('#forgot_popup_btn').trigger("click");
    }
});


$(document).on('click', '#add_order_by_xls', function (event) {
    event.preventDefault();  // Полная остановка происходящего

    // Создадим данные формы и добавим в них данные файлов из files

    var captcha_word = $('input[name=captcha_word]').val(),
        captcha_sid = $('input[name=captcha_sid]').val(),
        user_id = $('#user_id').val();

    var file_data = $('#xls_order_file').prop('files')[0];

    if (!file_data) {
        $('#xls_order_file').addClass('error');
        $('#order_xls_errors').text('Необходимо добавить файл!');
        $('#order_xls_errors').show();
        return;
    } else {
        $('#xls_order_file').removeClass('error');
        $('#order_xls_errors').hide();
    }

    if (!captcha_word) {
        $('input[name=captcha_word]').addClass('error');
        $('#order_xls_errors').text('Введите код с картинки!');
        $('#order_xls_errors').show();
        $('input[name=captcha_word]').focus();
        return;
    } else {
        $('input[name=captcha_word]').removeClass('error');
        $('#order_xls_errors').hide();
    }


    var data = new FormData();

    data.append('file', file_data);
    data.append('captcha_word', captcha_word);
    data.append('captcha_sid', captcha_sid);
    data.append('user_id', user_id);


    // Отправляем запрос
    $.ajax({
        url: '/ajax/ajax_create_order_xls.php',
        type: 'POST',
        data: data,
        cache: false,
        dataType: 'html',
        processData: false, // Не обрабатываем файлы (Don't process the files)
        contentType: false, // Так jQuery скажет серверу что это строковой запрос
        beforeSend: function () {
            $('#win8_wrapper').show();
        },
        success: function (respond, textStatus, jqXHR) {
            reloadCaptcha();
            $('input[name=captcha_word]').val('');
            $('input[name=captcha_word]').focus();
            // Если все ОК
            if (typeof respond.error === 'undefined') {
                var resp = JSON.parse(respond);
                if (resp['ERROR']) {
                    $('#order_xls_errors').html(resp['ERROR']);
                    $('#order_xls_errors').show();
                } else {
                    $('#order_xls_errors').hide();
                    $('#not_available').html(resp['not_available']);
                    $.magnificPopup.open({
                        items: {
                            src: '#success_order_xls'
                        },
                        type: 'inline'
                    });
                    reloadBasketLine();
                }
            }
            else {
                console.log('ОШИБКИ ОТВЕТА сервера: ' + respond.error);
            }
        },
        error: function (jqXHR, textStatus, errorThrown) {
            console.log('ОШИБКИ AJAX запроса: ' + textStatus);
        },
        complete: function (jqXHR, textStatus) {
            $('#win8_wrapper').hide();
        }
    });

});


function downloadOrderXls(id) {
    $.ajax({
        type: "POST",
        url: '/ajax/ajax_order_xls.php',
        dataType: "html",
        data: {ID: id},
        beforeSend: function () {
            $('#win8_wrapper').show();
        },
        success: function (data) {
            var resp;
            if (resp = JSON.parse(data)) {
                window.location.href = resp['SRC'];
            }
        },
        complete: function (jqXHR, textStatus) {
            $('#win8_wrapper').hide();
        }
    });
}

function downloadPriceList(id, for_order) {
    if (!for_order) {
        for_order = 0;
    } else {
        for_order = 1;
    }

    $.ajax({
        type: "POST",
        url: '/ajax/ajax_create_price_list.php',
        dataType: "html",
        data: {ID: id, for_order: for_order},
        beforeSend: function () {
            $('#win8_wrapper').show();
        },
        success: function (data) {
            console.log(data);
            var resp;
            if (resp = JSON.parse(data)) {
                // window.location.href = resp['SRC'];
                window.open(resp['SRC']);
            }
        },
        complete: function (jqXHR, textStatus) {
            $('#win8_wrapper').hide();
        }
    });
}

// ловим событие отправки формы
$('#enter_popup form').submit(function (e) {

    $.ajax({
        type: "POST",
        url: '/ajax/ajax_auth.php',
        dataType: "html",
        data: $(this).serialize(),
        success: function (data) {
            var resp = parseInt(data);
            if (resp === 1) {
                window.location.reload();
            } else {
                $('#auth_errors').html(data);
            }
        }
    });

    e.preventDefault();
});


if ($('nav.b_main_side_nav').length > 0){
    var pathname = window.location.pathname;
    var hrefname = '';

    $('nav.b_main_side_nav a').each(function () {
        hrefname = $(this).attr('href').toString();
        if (hrefname === pathname.toString()){
            $(this).closest('._nav_sub_sub_item').addClass('-opened');
            $(this).closest('._nav_sub_item').addClass('-opened');
            $(this).closest('._nav_item').addClass('-opened');
        }
    });
}

$(document).on('submit', '#profileForm', function (e) {
    $('#profileForm input').each(function () {
        if ($(this).hasClass('require_input') && $(this).val().length <= 0){
            var input_name = this.name,
                input_id = this.id;
            $(this).addClass('error');
            $(this).after('<label id="' + input_name + '-error" class="error" for="'+input_id+'">Это поле необходимо заполнить.</label>');
            e.preventDefault();
            e.stopPropagation();
            $('#win8_wrapper').hide();
            $('div[id^=wait_comp_]').hide();
        } else {
            $(this).removeClass('error');
            $(this).next('label.error').remove();
        }
    });
});

$(document).on('submit', '#profileFormPass', function (e) {
    $('#profileFormPass input').each(function () {
        if ($(this).hasClass('require_input') && $(this).val().length <= 0){
            var input_name = this.name,
                input_id = this.id;
            $(this).addClass('error');
            $(this).after('<label id="' + input_name + '-error" class="error" for="'+input_id+'">Это поле необходимо заполнить.</label>');
            e.preventDefault();
            e.stopPropagation();
            $('#win8_wrapper').hide();
            $('div[id^=wait_comp_]').hide();
        } else {
            $(this).removeClass('error');
            $(this).next('label.error').remove();
        }
    });
});

$(document).on('click', 'a.open-my-video', function (e) {
   var $this = $(this),
       src = $this.attr('data-src'),
       extension = $this.attr('data-extension');

    $('#video_popup').html('<video id="my-video" class="video-js" controls autoplay preload="auto" width="640" height="264" data-setup=\'{}\'>'+
        '<source id="video_source" src="'+src+'" type="video/'+extension+'">'+
        '<p class="vjs-no-js">'+
        'To view this video please enable JavaScript, and consider upgrading to a web browser that'+
    '<a href="http://videojs.com/html5-video-support/" target="_blank">supports HTML5 video</a>'+
    '</p>'+
    '</video><a href="'+src+'" target="_blank" class="_title" download="">Скачать видео</a> ');

    $.magnificPopup.open({
        items: {
            src: '#video_popup'
        },
        type: 'inline'
    });


    e.preventDefault();
});

$(document).on('submit', '#subscribe_main_form', function (e) {
    var email = $(this).find('input[name=SENDER_SUBSCRIBE_EMAIL]').val(),
        $this = $(this);

    $.ajax({
        type: "POST",
        url: '/ajax/ajax_check_subscribe.php',
        dataType: "html",
        async: false,
        data: {EMAIL: email},
        success: function (data) {
            console.log(data);
            var resp = JSON.parse(data);
            if (resp.ERROR) {
                $.magnificPopup.open({
                    items: {
                        src: '#thx_subscribed_popup_error'
                    },
                    type: 'inline'
                });
                $this.find('._submit').removeAttr('disabled');
                e.preventDefault();
            }
        },
        complete: function (jqXHR, textStatus) {
            $('#win8_wrapper').hide();
        }
    });

    // e.preventDefault();
})