$(document).ready(function() {
    $('#page_content input[type=text], #page_content input[type=password]').each(function() {
        $(this).addClass('inp_txt');
    });
    
    $('#right_column #search_frm .inp_txt').attr('autocomplete', 'off');
    $(document).click(function() {
        $('#search_autocomplete_data').hide();
    });

    initTabs();
    
    $('#fader').click(requestCallbackHide);
    $('#fader').click(compareHide);

    /* Vendors logo vertical-align: top */
    $('.vendors_list .vendor .vendor_descr a img.logo').each(function() {
        var top = Math.round($(this.parentNode.parentNode).attr('offsetHeight') / 2) - Math.round($(this).attr('offsetHeight') / 2);

        if (top > 0) {
            $(this).css('top', top);
        }
    });
});

$(window).load(function() {
    initGallery();
    resizeFader();
    centrateCallback();
    centrateCompare();
});

$(window).scroll(function() {
    centrateCallback();
    centrateCompare();
});

/* ========================================================================== */

function sendGivenForm(id) {
    try {
        document.getElementById(id).submit();
    } catch (e) {}
}

/* ========================================================================== */

function hideInputLabel(inp, label) {
    if (inp && (typeof(inp) != 'undefined') && label && (typeof(label) != 'undefined')) {
        if (inp.value == label) {
            inp.value = '';
        }
    }
}

function showInputLabel(inp, label) {
    if (inp && (typeof(inp) != 'undefined') && label && (typeof(label) != 'undefined')) {
        if (inp.value == '') {
            inp.value = label;
        }
    }
}

/* ========================================================================== */

var galleryCanWork = false;

function initGallery() {
    galleryCanWork = true;

    var preloadedImg = $('.img_preload_holder img:first-child');
    if (/^preloaded_img_(\d+)$/i.test(preloadedImg.attr('id'))) {
        var id = RegExp.$1;
        changePhoto($('#cur_goods_img_holder img:first-child').attr('id'), id);
    }

    var page = $('.previews_list_inner');
    var holder = $('.previews_list');

    if ((page.length > 0) && (holder.length > 0) && (page.attr('offsetHeight') > holder.attr('offsetHeight'))) {
        $('.previews_down').removeClass('inactive');
    }
}

function changePhoto(imgId, id) {
    if (galleryCanWork) {
        var img = $('#' + imgId);
        var preloadedImg = $('#preloaded_img_' + id);

        if ((img.length > 0) && (preloadedImg.length > 0)) {
            img.fadeOut(250, function() {
                $('#cur_goods_img_holder').css('height', preloadedImg.attr('offsetHeight') + 'px');
                img.attr('src', preloadedImg.attr('src'));
                full = preloadedImg.attr('src').substr(35).split('&');
                img.parent().attr('href', full[0]);
                img.fadeIn(300);
            });
        }
    }
}

function changePage(elem, direction) {
    if (galleryCanWork && elem && (typeof(elem) != 'undefined') && direction && (typeof(direction) != 'undefined')) {
        var dx = 0;
        var page = $(elem.parentNode).find('.previews_list_inner');
        var holder = $(elem.parentNode).find('.previews_list');

        if ((page.length > 0) && (holder.length > 0)) {
            if (page.attr('offsetHeight') > holder.attr('offsetHeight')) {
                if (direction == 'up') {
                    dx = (Math.abs(page.attr('offsetTop')) > holder.attr('offsetHeight')) ? holder.attr('offsetHeight') : Math.abs(page.attr('offsetTop'));
                } else if (direction == 'down') {
                    dx = page.attr('offsetHeight') - Math.abs(page.attr('offsetTop')) - holder.attr('offsetHeight');
                    dx = (dx > holder.attr('offsetHeight')) ? -holder.attr('offsetHeight') : -dx;
                }

                if (dx != 0) {
                    page.animate({"top": page.attr('offsetTop') + dx + 'px'}, 750, function() {
                        if (page.attr('offsetTop') == 0) {
                            $(elem.parentNode).find('.previews_up').addClass('inactive');
                        } else {
                            $(elem.parentNode).find('.previews_up').removeClass('inactive');
                        }

                        if ((-1 * page.attr('offsetTop')) == (page.attr('offsetHeight') - holder.attr('offsetHeight'))) {
                            $(elem.parentNode).find('.previews_down').addClass('inactive');
                        } else {
                            $(elem.parentNode).find('.previews_down').removeClass('inactive');
                        }
                    });
                }
            }
        }
    }
}

/* ========================================================================== */

function initTabs () {
    var i = 0;

    $('.tabs_holder').each(function() {
        var holder = $(this);
        var j = 0;

        this.id = 'dTabs_holder_' + i;

        holder.find('h4').each(function() {
            this.id = 'dTabs_label_' + i + '_' + j;
            $(this).click(dTabSelect);
            j++;
        });

        j = 0;
        holder.find('.tab_content').each(function() {
            this.id = 'dTabs_content_' + i + '_' + j;
            j++;
        });

        $('#dTabs_label_' + i + '_0').addClass('active');
        $('#dTabs_content_' + i + '_0').addClass('active');
        i++;
    });
}

function dTabSelect() {
    try {
        if (/^dTabs_label_(\d+)_(\d+)$/i.test(this.id)) {
            var holderId = RegExp.$1;
            var tabId = RegExp.$2;

            $('#dTabs_holder_' + holderId).find('h4').removeClass('active');
            $('#dTabs_holder_' + holderId).find('.tab_content').removeClass('active');

            $(this).addClass('active');
            $('#dTabs_content_' + holderId + '_' + tabId).addClass('active');
        }
    } catch (e) {}
}

/* ========================================================================== */

function requestCallback() {
    $.ajax({
        "type": 'GET',
        "url": '/modules/feedback.php',
        "data": {"by_ajax": 1},
        "dataType": 'text',
        "success": requestCallbackShow
    });
}

function requestCallbackAct(frm) {
    if (frm && (typeof(frm) != 'undefined') && frm.fio && (typeof(frm.fio) != 'undefined') && frm.phone && (typeof(frm.phone) != 'undefined')) {
        var re = /\/shop\/goods\.(\d+)\//i;
        var data = {"by_ajax": 1, "feedback_frm": 1, "fio": frm.fio.value, "phone": frm.phone.value};

        if (re.test(location.href)) {
            data.goods_id = RegExp.$1;
        }

        $.ajax({
            "type": 'POST',
            "url": '/modules/feedback.proc.php',
            "data": data,
            "dataType": 'text',
            "success": requestCallbackSuccess
        });
    }
}

function requestCallbackSuccess(response) {
    if (response == 0) {
        $('#request_callback_holder .callback').html('Ваш заказ успешно отправлен. Наши менеджеры свяжутся с вами в ближайшее время.');
    } else {
        $('#request_callback_holder').html(response);
    }
}

function requestCallbackShow(response) {
    $('#fader').show();
    resizeFader();

    $('#request_callback_holder').html(response);
    $('#request_callback_holder').show();
    centrateCallback();
}

function requestCallbackHide() {
    $('#fader').hide();
    $('#request_callback_holder').hide();
}

function resizeFader() {
    var h = $('#main_wrapper').attr('offsetHeight');
    var fader = $('#fader');

    if ((fader.length > 0) && (h > fader.attr('offsetHeight'))) {
        fader.css('height', h + 'px');
    }
}

function centrateCallback() {
    var callback = $('#request_callback_holder');
    var top0 = document.documentElement.scrollTop;
    var offsetTop = top0 - 0; //Screen top
    offsetTop += Math.round(document.documentElement.offsetHeight / 2); //Screen center
    offsetTop -= Math.round(callback.attr('offsetHeight') / 2); //Middle

    callback.css('top', offsetTop + 'px');
}

/* ========================================================================== */

function dCartDel(id) {
    $('#' + id).val(0);
    $('#full_cart').submit();
}

function dCartFlush() {
    $('#full_cart .quantity input').val(0);
    $('#full_cart').submit();
}

function recountDelivery(price, limit) {
    price -= 0;
    limit -= 0;
    var orderPrice = $('#order_price');
    var totalPrice = $('#total_with_delivery .total_price');
    var re = /^(\d+)\sруб\.$/i;

    if (!isNaN(price) && !isNaN(limit) && (orderPrice.length > 0) && (totalPrice.length > 0) && re.test(orderPrice.html())) {
        var price0 = RegExp.$1 - 0;

        if (price0 < limit) {
            totalPrice.html(price0 + price + ' руб.');
        }
    }
}

/* ========================================================================== */

function changeSubcatsList(catSelect) {
    var subcatSelect = $('#subcat_id');
    var html = '<option value="0">Выберите подкатегорию</option>';
    var disabled = true;

    if (catSelect && (typeof(catSelect) != 'undefined') && (subcatSelect.length == 1)) {
        var catId = catSelect.value - 0;

        if (catId > 0) {
            if (subcatsList && (typeof(subcatsList) != 'undefined') && subcatsList[catId] && (typeof(subcatsList[catId]) != 'undefined') && (subcatsList[catId].length > 0)) {
                for (var i = 0; i < subcatsList[catId].length; i++) {
                    if (subcatsList[catId][i] && (typeof(subcatsList[catId][i]) != 'undefined') && (subcatsList[catId][i].id > 0)) {
                        html += '<option value="' + subcatsList[catId][i].id + '">' + subcatsList[catId][i].name + '</option>';
                        disabled = false;
                    }
                }
            }

            subcatSelect.html(html);
            subcatSelect.attr('disabled', disabled);
        } else {
            subcatSelect.html(html);
            subcatSelect.attr('disabled', disabled);
        }
    }
}

function showVendorsList() {
    $('#vendors_filter').show();
}

function hideVendorsList() {
    $('#vendors_filter').hide();
}

function selectAllVendors(elem, checked) {
    $('#vendors_filter').find('input[type=checkbox]').attr('checked', checked);
}

function countVendors() {
    var num = 0;

    $('#vendors_filter').find('input[type=checkbox]').each(function() {
        if (this.checked) {
            num++;
        }
    });

    $('#f_vendors_count').html(num);
}

$(document).ready(countVendors);

function openAdditFilters() {
    $('#additional_filters').show();
}

function closeAdditFilters() {
    $('#additional_filters').hide();
}

/* ========================================================================== */

function showHideCompareAside(elem) {
    var div = $('#compare_aside');

    if (div.length > 0) {
        if (div.css('display') == 'none') {
            div.show();
            $(elem).addClass('opened');
        } else {
            div.hide();
            $(elem).removeClass('opened');
        }
    }
}

function compareGoods(catId) {
    catId -= 0;

    if (catId > 0) {
        $('#fader').show();
        resizeFader();
        $('#compare_content').html('<div class="preloader"><!-- --></div>');

        $.ajax({
            "type": 'GET',
            "url": '/shop/compare/',
            "dataType": 'text',
            "data": {"cat_id": catId, "by_ajax": 1},
            "success": showComparedGoods
        });

        $('#compare_content').show();
        centrateCompare();
    }
}

function showComparedGoods(response) {
    $('#compare_content').find('.preloader').hide();
    $('#compare_content').html(response);
}

function centrateCompare() {
    var compare = $('#compare_content');
    var top0 = document.documentElement.scrollTop;
    var offsetTop = top0 - 0; //Screen top
    offsetTop += Math.round(document.documentElement.offsetHeight / 2); //Screen center
    offsetTop -= Math.round(compare.attr('offsetHeight') / 2); //Middle

    compare.css('top', offsetTop + 'px');
}

function compareHide() {
    $('#fader').hide();
    $('#compare_content').hide();
}
