jQuery(document).ready(function(){

    var $ = jQuery;

    if (jQuery.browser.msie && jQuery.browser.version <= 8) {fadeInValue = 0;}
    else {fadeInValue = 200;};

    var FUCKING_IE = (($.browser.msie) && ($.browser.version < 9));

    var $dynamicBox = $('#dynamicBox');

    if ($dynamicBox.length) {

        dynamicBox($dynamicBox);
    }

    function dynamicBox($wrap) {
        var BACK_DELAY_TIMEOUT = 80,
            BACK_OPACITY_STEP = 0.15,
            BACK_SLIDE_DURATION = 500,
            BACK_SLIDE_TO = -500,
            IMAGE_FADE_DELAY = 200,
            IMAGE_FADE_DURATION = 1000,
            TEXT_FADE_DURATION = 300,
            CUR_SLIDE_DURATION = 350,
            SLIDESHOW_TIMEOUT = 10000;

        var curIndex = 0,
            isAnimation = false,
            _t = 0;
        var $nav = $('#dynamicBox-nav'),
            $navItems = $nav.find('div').click(_navClickHandler),
            $boxes = $('#dynamicBox-content .box');

        $boxes.find('img').each(function() {
            var img = new Image();
            img.src = this.src;
            if (FUCKING_IE) {
                this.style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + img.src + "',sizingMethod='crop')"
            }
        });

        var $navCur = $(document.createElement('ins'))
            .addClass('cur')
            .css({
                top : $navItems.eq(0).addClass('active').position().top
            })
            .appendTo($nav);

        var $p = $('#dynamicBox-podlozhka div'),
            pLength = $p.length;
        $p.hide().last().show();
        for (var i = 0; i < pLength; i++) {
            $p.eq(i).css({ opacity : (pLength - 1 + i) * BACK_OPACITY_STEP });
        }
        if (FUCKING_IE) {
            $p.find('ins').css({
                backgroundImage : 'none',
                filter :  "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='/design/images/dymamicBox/podlozhka_1.png',sizingMethod='crop')"
            });
        }

        function _goBack() {
            var $t = $(this),
                index = $p.index(this);
            $t
                .css({
                    zIndex : -index,
                    opacity : 1 - index * BACK_OPACITY_STEP
                })
                .animate({ left : 0 }, BACK_SLIDE_DURATION, 'swing');
        }

        function setActive(index) {
            if ((curIndex !== index) && (!isAnimation)) {
                function callback() {
                    $p.hide().first().show();
                    curIndex = index;
                    isAnimation = false;
                    setupTimeout();
                }
                dropTimeout();
                $navItems.removeClass('active');
                var $navItem = $navItems.eq(index);

                var $curBox = $boxes.eq(curIndex),
                    $curText = $curBox.find('.text'),
                    $curImg = $curBox.find('.img'),
                    $nextBox = $boxes.eq(index),
                    $nextImg = $nextBox.find('.img'),
                    $nextText = $nextBox.find('.text');

                if (FUCKING_IE) {
                    $curText.hide();
                } else {
                    $curText.fadeOut(TEXT_FADE_DURATION);
                }
                $p.show();
                for (var i = 0; i < pLength; i++) {
                    $p.eq(pLength - i - 1).css({ zIndex : 1, opacity : 1 - i * BACK_OPACITY_STEP }).delay(i * BACK_DELAY_TIMEOUT).animate({
                        left : BACK_SLIDE_TO
                    }, BACK_SLIDE_DURATION, 'swing', _goBack);
                }
                $curBox.css({ zIndex : 10 });
                $nextBox.css({zIndex : 15}).show();
                $nextImg.delay(IMAGE_FADE_DELAY).fadeIn(IMAGE_FADE_DURATION, function() { $curBox.hide(); $curImg.hide(); $curText.hide(); });
                if (FUCKING_IE) {
                    window.setTimeout(function() {
                        $nextText.show();
                        callback();
                    }, IMAGE_FADE_DURATION);
                } else {
                    $nextText.delay(IMAGE_FADE_DURATION).fadeIn(TEXT_FADE_DURATION, callback);
                }
                isAnimation = true;
                $navCur.animate({
                    top : $navItem.position().top
                }, CUR_SLIDE_DURATION, 'swing', function() {
                    $navItem.addClass('active');
                });
            }
        }

        function showNext() {
            var index = curIndex + 1;
            if (index > $boxes.length - 1) {
                index = 0;
            }
            setActive(index);
        }


        function setupTimeout() {
            _t = window.setTimeout(showNext, SLIDESHOW_TIMEOUT);
        }
        function dropTimeout() {
            if (_t) {
                window.clearTimeout(_t);
                _t = 0;
            }
        }

        function _navClickHandler() {
            var index = $navItems.index(this);
            setActive(index);
        }

        setupTimeout();
    }



    /* Колорбокс */
    if (jQuery('a.colorBox').length) {
        $("a.colorBox").colorbox();
    };


    /* Всплывающая форма */
    jQuery('[popupID]').click(
        function() {
            var thisID = jQuery(this).attr('popupID');
            var scrollTop = jQuery(document).scrollTop();
            var popupHeight = jQuery(thisID).height();
            var documentHeight = jQuery(window).height();

            if (popupHeight > documentHeight) {
                var indent = scrollTop + 5;
            } else {
                var indent = ((documentHeight - popupHeight) / 2) + scrollTop;
            }

            jQuery(thisID).hide().css({'top': indent}).fadeIn(fadeInValue);
            jQuery('#popup-bg').show();

            return false;
        }
    );

    // Закрыть
    jQuery('.popupBox-close').click( function() {hidePopup()} );
    jQuery(document).click( function(e){
        if (jQuery('DIV.popupBox:visible').length) {
            if (jQuery(e.target).filter('DIV.popupBox:visible').length != 1 && jQuery(e.target).parents().filter('DIV.popupBox:visible').length != 1 ) {
                hidePopup();
            };
        };
    });
    function hidePopup() {
        jQuery('DIV.popupBox-wrapper').hide();
        jQuery('#popup-bg').hide();
    };


    /* Ховер картинки на заголовок */
    jQuery('#catalogPage').find('.catalogBox .box-img A').hover(
        function() {
            jQuery(this).parents('.catalogBox').find('H2 A').addClass('hover');
        },
        function() {
            jQuery(this).parents('.catalogBox').find('H2 A').removeClass('hover');
        }
    );


    /* Исчезание рамки у картинок */
    jQuery('.imgBox A').hover(
        function() {
            jQuery(this).parent('.imgBox').addClass('imgBox-inHover');
        },
        function() {
            jQuery(this).parent('.imgBox').removeClass('imgBox-inHover');
        }
    );


    /* Переключение фотографий при наводе */
    var _$tovarBigImg = $('#tovar-bigPhoto');
    var _tovarBigImgTimeout = 0, _tovarOrigImg = true;
    jQuery('#tovar-podrobno .malenkie .imgBox').hover(
        function() {
            var $t = $(this);
            $t.addClass('active');
            _dropBigImgTimeout();
            _tovarBigImgTimeout = window.setTimeout(function() {
                _showTovarBigImg($t.find('a').attr('href'));
            }, 150);

        }, function() {
            var $t = $(this);
            $t.removeClass('active');
            _dropBigImgTimeout();
            _tovarBigImgTimeout = window.setTimeout(function() {
                _showTovarBigImg($('#baseImg').attr('src'));
            }, 150);
        }
    ).click(
        function() {return false;}
    );
    function _dropBigImgTimeout() {
        if (_tovarBigImgTimeout) {
            window.clearTimeout(_tovarBigImgTimeout);
            _tovarBigImgTimeout = 0;
        }
    }
    function _hideTovarBigImg() {
        _tovarOrigImg = true;
        _$tovarBigImg.find('div').fadeOut(400, function() { $(this).remove(); });
    }
    function _showTovarBigImg(src) {
        _tovarOrigImg = false;
        _hideTovarBigImg();
        $(document.createElement('div'))
            .hide()
            .css({ backgroundImage : 'url(' + src + ')' })
            .appendTo(_$tovarBigImg)
            .fadeIn(400, _origBigImageHide);
    }
    function _origBigImageHide() {
        if (!_tovarOrigImg) {
            _$tovarBigImg.find('img').hide();
        }
    }


    /* Подробнее - скрыть */
    jQuery('#catalogPage').find('.moreLink A').click(
        function() {
            var parents = jQuery(this).parents('.catalogBox-text');
            var $box = parents.find('.box'),
                box = $box.get(0);
            if (!box._origHeight) {
                box._origHeight = $box.height();
            }
            parents.find('.moreLink').find('A').toggle();

            if (!box._shown) {
                $box.css({ height : box._origHeight, overflow : 'hidden' });
                if (FUCKING_IE) {
                    $box.find('.hiddenText').show();
                } else {
                    $box.find('.hiddenText').fadeIn(300);
                }
                $box.animate({
                    height : box.scrollHeight
                }, 300, 'swing');
                box._shown = true;
            } else {
                box._shown = false;
                if (FUCKING_IE) {
                    $box.animate({
                        height : box._origHeight
                    }, 300, 'swing', function() {
                        $box.find('.hiddenText').hide();
                    });
                } else {
                    $box.find('.hiddenText').fadeOut(300);
                    $box.animate({
                        height : box._origHeight
                    }, 300, 'swing');
                }
            }
        }
    );


    /* Меню */
    jQuery('#navigation').find('.navigation-item').click(
        function() {
            var link = jQuery(this).find('A').attr('href');
            window.location.href = link;
            return false;
        }
    );

    var NAVIGATION_FADE_DURATION = 280;
    var $navigationCatalogContent = jQuery('#navigation-catalog-content');
    jQuery('#navigation-catalog').hover(
        function() {
            if (FUCKING_IE) {
                $navigationCatalogContent.show();
            } else {
                $navigationCatalogContent
                .stop()
                .css({
                    opacity : 0
                })
                .show()
                .animate({
                    opacity : 1
                }, NAVIGATION_FADE_DURATION, 'swing');

            }
        },
        function() {
            if (FUCKING_IE) {
                $navigationCatalogContent.hide();
            } else {
                $navigationCatalogContent.stop()
                .animate({
                    opacity : 0
                }, NAVIGATION_FADE_DURATION, 'swing', function() { $(this).hide(); });
            }
        }
    );


    /* Важный текст */
    jQuery('.embedText').each(
        function() {
            var height = jQuery(this).height();
            height += 36;
            jQuery(this).find('.embedText-border').css('height', height);
        }
    );


    /* Партнеры */
    $('.toggle-block a.toggle-link').click(function(e) {
        e.preventDefault();
        $(this).parents('.toggle-block').eq(0).find('.hidden-text').slideToggle(350);
        $(this).find('.toggle-text').toggleClass('toggle-text-show');
    });

    var $partnersMap = $('#partners-map');
    if ($partnersMap.length) {
        var partnersMapAnimate = false;
        var mapWidth = $partnersMap.width();
        var $line = $partnersMap.find('.line');
        var $cov = $partnersMap.find('.city .circ-v').css({ opacity : 0 }).show();
        if (($.browser.msie) && ($.browser.version < 9)) {
            $cov.each(function() {
                var $t = $(this);
                if ($t.css('backgroundImage').match(/url\(['"]?(.+?)['"]\)/)) {
                    var src = RegExp.$1;
                    var ins = document.createElement('ins');
                    ins.style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='"+src+"', sizingMethod='scale')";
                    $t.css('background', 'none').append(ins);
                }
            });
        }
        $partnersMap.find('.city').hover(function() {
            $(this).find('.circ-v').stop().animate({
                opacity : .33
            }, 250, 'swing');
        }, function() {
            var $t = $(this);
            if (!$t.hasClass('active')) {
                $t.find('.circ-v').stop().animate({
                    opacity : 0
                }, 150, 'swing');
            }
        }).click(function() {
            var $t = $(this);
            if ((partnersMapAnimate) || ($t.hasClass('active'))) return;
            var pos = $t.position(),
                width = mapWidth - pos.left;
            var $descr = $t.find('.descr').css({
                marginTop : -pos.top,
                width : width
            });
            function show() {
                $line.css({
                    left : pos.left,
                    top : pos.top
                }).show().animate({
                    height : 435 - pos.top,
                    width : 10
                }, 350, 'swing', function() {
                    var h = $descr.height();
                    $descr.css({ height : 0 }).show().animate({
                        height : h
                    }, 350, 'swing', function() {
                        if ($.browser.msie) {this.style.removeAttribute('filter');}
                        partnersMapAnimate = false;
                    });
                });
            }
            partnersMapAnimate = true;
            var $active = $partnersMap.find('.active');
            if ($active.length) {
                $active.removeClass('active').trigger('mouseout');
                $active.find('.descr').animate({
                    height : 0
                }, 250, 'swing', function() {
                    $(this).hide().css('height', 'auto');
                    $line.animate({
                        height: 0,
                        width : 0
                    }, 250, 'swing', function() {
                        $(this).hide();
                        show();
                    });
                });
            } else  {
                show();
            }
            $t.addClass('active');
        }).filter('.initial').trigger('click');
    }


    jQuery('.lClients').css('cursor', 'pointer').click(function(){
        window.location.href = '/clients/';
    });

    /* Таблицы */
    jQuery('.textBox').find('TABLE.stylized TBODY TR:odd').addClass('even');
    jQuery('.textBox').find('TABLE.stylized TR').find('TD:last, TH:last').css('border-right', 'none');

    var specialMarginTop = jQuery('#specialMarginTop').find('THEAD').height();
    jQuery('#specialMarginTop').css('marginTop', -(specialMarginTop)-36);


    /* Прокрутка логотипов клиентов */
    if (jQuery('#clientsSlider-inner').length) {
        jQuery('#clientsSlider-inner').jCarouselLite({
            circular: false,
            btnNext: "#clientsSlider-right",
            btnPrev: "#clientsSlider-left",
            visible: 1
        });
    };

    cuSel_init();


	$('.zLink').mouseover(function() {var obj = $(this).next().fadeIn('fast');});
	$('.zPic').mouseout(function() {var obj = $(this).fadeOut('fast');});
});


var filter_selected = {};
function filterPoTovaram (value, id) {
    var $filterContent = $('#filterContent');

    if (value == 'все') delete filter_selected[id];
    else filter_selected[id] = value;

    var find_el = $filterContent.find('tr').hide().find('td').removeClass('activeColumn');
    var i = 0;
    var number_current = id.charAt(id.length-1);

    for (p in filter_selected) {
        var number = p.charAt(p.length-1);
        find_el = find_el.parents('TR').find('TD:eq('+ number +'):containsNC("'+ filter_selected[p] +'")');
        if (number == number_current) find_el.addClass('activeColumn');
        i++;
    }
    find_el.parents('TR').show();

    cuSelRefresh({
        refreshEl: "select",
        visRows: 4
    });

};


$.extend($.expr[":"], {
    "containsNC": function(elem, i, match, array) {
        return (elem.textContent || elem.innerText || "").toLowerCase().indexOf((match[3] || "").toLowerCase()) >= 0;
    }
});


function _swapNode(node) {
    var nextSibling = this.nextSibling;
    var parentNode = this.parentNode;
    node.parentNode.replaceChild(this, node);
    parentNode.insertBefore(node, nextSibling);
}


var first_init = true;
function cuSel_init() {
    var catalogFilter_elements = jQuery('#catalogFilter').find('.formItem');
    var catalogFilter_elements_length = catalogFilter_elements.length;
    catalogFilter_elements.each( function() {
        jQuery(this).css('zIndex', catalogFilter_elements_length--);
    });


    if (first_init) {
        saveAllFilters();
        saveAllSearchFields();
    }

    /* Подсветка ячеек таблицы при наведении */
    jQuery('.tableHover').find('TBODY TR').hover(
        function() {
            var thisParents = jQuery(this).addClass('trHover').parents('.tableHover');

            var rassoyanieDoVerha_1 = thisParents.offset().top;
            var rassoyanieDoVerha_2 = jQuery(this).offset().top;
            var rassoyanieDoVerha = rassoyanieDoVerha_2 - rassoyanieDoVerha_1;

            var visota = jQuery(this).height();

            thisParents.find('.shadowBox').show().css({'top': rassoyanieDoVerha, 'height': visota});
        },
        function() {
            var thisParents = jQuery(this).removeClass('trHover').parents('.tableHover');
            thisParents.find('.shadowBox').hide();
        }
    ).click(
        function() {
            var link = jQuery(this).find('A:first').attr('href');
            window.location.href = link;
            return false;
        }
    );


    var $filterTable = $('#tableWithFilter');
    var filterTableColSortColumn = 0;
    if  ($filterTable.length) {
        var $filter = $('#filter');

        if ((!$.browser.msie) || ($.browser.version > 6)) {
            $filter.css('visibility', 'hidden');
            var $place = $('#specialSpace').addClass('tableHover').html('<table><thead>' + $filter.html() + '</thead></table>');
            $place.parent().css('zIndex', 5);
            var $th = $filter.find('th').addClass('hidden'), $nTh = $place.find('th');
            for (var i = 0; i < $th.length; i++) {
                $nTh.eq(i).width($th.eq(i).width());
            }
            $filter = $place.find('thead').eq(0);
            var $zPlace = $place.parent().parent().parent().css({ width: '100%', zIndex : 5, left : 0, top : 0 });
            if (first_init) {
                var $dummy = $(document.createElement('div'))
                    .css({
                        position : 'relative',
                        height : $zPlace.outerHeight()
                    })
                    .hide()
                    .insertBefore($zPlace);
            }
            var zTopPos = $zPlace.offset().top;
            $(window).scroll(function() {
                var scrollTop = document.body.scrollTop + document.documentElement.scrollTop;
                if (scrollTop >= zTopPos) {
                    $zPlace.css({
                        position : 'fixed'
                    });
                    $dummy.show();
                } else {
                    $zPlace.css('position', 'relative');
                    $dummy.hide();
                }
            });
        }


        var $filterContent = $('#filterContent');
        var $sortBtns = $filter.find('span.sort').click(function() {
            $sortBtns.removeClass('sort-active');
            $(this).addClass('sort-active');
            var idx = $sortBtns.index(this) + 2;
            var direction = 1;
            if (Math.abs(filterTableColSortColumn) === idx) {
                direction = - filterTableColSortColumn / Math.abs(filterTableColSortColumn);
            }
            var cnt = [];
            var $cells = $filterContent.find('tr td:nth-child(' + (idx) + ')');
            for (var i = 0; i < $cells.length; i++) {
                cnt.push($cells.eq(i).text());
            }
            for (var i = 0; i < cnt.length - 1; i++) {
                for (var j = i + 1; j < cnt.length; j++) {
                    var c1 = cnt[i], c2 = cnt[j];
                    if (c1 == parseFloat(c1)) {
                        c1 = parseFloat(c1);
                    }
                    if (c2 == parseFloat(c2)) {
                        c2 = parseFloat(c2);
                    }
                    if (((c1 > c2) && (direction == 1)) || ((c1 < c2) && (direction == -1))) {
                        var tmp  = cnt[i];
                        cnt[i] = cnt[j]; cnt[j] = tmp;
                        var $r = $filterContent.children('tr');
                        var o1 = $r.get(i), o2 = $r.get(j);
                        if (o1.swapNode) {
                            o1.swapNode(o2);
                        } else {
                            _swapNode.call(o1, o2);
                        }
                    }
                }
            }
            filterTableColSortColumn = idx * direction;
        })
    }


    /* Селекты */
    if (jQuery('SELECT').length) {
        cuSel({
            changedEl: "select",
            visRows: 10,
            scrollArrows: true
        });
    };

    first_init = false;
}

var allFilters = {};
function saveAllFilters() {
    var filters = getAllFilterFields();

    for (p in filters) {
        if (filters[p] == null) continue;
        allFilters[p] = {};
        for (var i = 0; i < filters[p].options.length; i++) {
            if (filters[p].options[i].value == '') continue;
            allFilters[p][filters[p].options[i].value] = filters[p].options[i].text;
        }
    }
}

function getAllFilterFields() {
    return {
	    type: document.getElementById('select-1'),
	    material: document.getElementById('select-2'),
//	    application_area: document.getElementById('select-3'),
	    weight_class: document.getElementById('select-4'),
//	    flow_area: document.getElementById('select-5'),
	    hydraulic_section: document.getElementById('select-5'),
	    /*capacity: document.getElementById('select-6'),*/
	    capacity_filter: document.getElementById('select-6'),
	    overall_dimensions: document.getElementById('select-7')
    };
}

var allSearchFields = {};
function saveAllSearchFields() {
    var filters = getAllSearchFilterFields();

    for (p in filters) {
        if (filters[p] == null) continue;
        allSearchFields[p] = {};
        for (var i = 0; i < filters[p].options.length; i++) {
            if (filters[p].options[i].value == '') continue;
            allSearchFields[p][filters[p].options[i].value] = filters[p].options[i].text;
        }
    }
}

function getAllSearchFilterFields() {
    return {
	    type: document.getElementById('select-1'),
	    material: document.getElementById('select-2'),
	    application_area: document.getElementById('select-3'),
	    weight_class: document.getElementById('select-4'),
	    hydraulic_section: document.getElementById('select-5'),
	    /*capacity: document.getElementById('select-6'),*/
	    capacity_filter: document.getElementById('select-6')
    };
}

function article_filter(str) {
    $('#filterContent').find('tr').hide().find('TD:eq(0):containsNC("Артикул № '+ str +'")').parents('TR').show();
}
