﻿/* browser detection */
var browser_info = new function(ie) {
    var d = document, w = window, qsel = !!d.querySelectorAll,
    csel = !!d.getElementsByClassName;
    this.ff = !!w.Iterator && !!d.addEventListener && /a/[-1] == 'a';
    this.ff2 = this.ff && (function x() { })[-6] == 'x';
    this.ff3 = csel && this.ff && (function x() { })[-5] == 'x';
    this.ff35 = qsel && this.ff;
    this.ie = (ie && '\v' == 'v');
    this.ie5 = this.ie && ie == 5;
    this.ie6 = this.ie && (ie == 6 || (d.compatMode && d.all && !!d.readyState));
    this.ie7 = this.ie && (ie == 7 && d.documentElement && typeof d.documentElement.style.maxHeight != "undefined");
    this.ie8 = this.ie && (ie == 8 && qsel);
    this.safari = /a/.__proto__ == '//';
    this.chrome = /source/.test((/a/.toString + ''));
    this.opera = (!ie && !!w.opera && w.opera.toString() === "[object Opera]");
} (0/*@cc_on + (@_jscript_version * 10 % 10)@*/);
/* / browser detection */

function stopEvent(e) { if (e.preventDefault) { e.preventDefault(); e.stopPropagation(); } else { e.returnValue = false; e.cancelBubble = true; } return false; }

// ie6 fix && ie7 cleartype fix
function clearFilters(elem) {
    if (typeof elem.style.filter != 'undefined' && elem.style.removeAttribute) {
        elem.style.removeAttribute('filter');
    };
};

// and once again, as a jquery plugin
; (function($) {
    $.fn.clearTypeFix = function() {
        return this.each(function() {
            if (browser_info.ie) {
                if (this.style.filter != 'undefined' && this.style.removeAttribute) {
                    this.style.removeAttribute('filter');
                };
            };
        });
    };
})(jQuery);

// popup utilities
var popup_height_percent = null;
function popupResize() {
    if (!popup_height_percent)
        return false;

    var $popup = $('.popup:visible').css({ height: 'auto' });
    var $over = $('.overflow', $popup).css({ height: 'auto' });
    
    var w_height  = $(window).height();
    var height    = Math.min($popup.height(), Math.floor(w_height * popup_height_percent / 100));
    var scrollTop = self.pageYOffset || document.documentElement.scrollTop || 0;

    $popup.css({
        top: scrollTop + Math.floor(w_height / 2),
        height: height,
        marginTop: 0 - Math.floor(height / 2)
    });


    if ($over.length) {
        var over_height = height -
                          50 - // .t
                          52 - // .b
                          42;  // h2
                            
        $over.height(over_height)
    }
    
    return true;
};

function popupShow($popup, height_percent) {
    if (typeof height_percent != 'undefined') {
        $popup = $popup.clone().appendTo('body').addClass('removable').show();
        popup_height_percent = height_percent;
        popupResize();
        $(window).bind('resize', popupResize);
    } else {
        $popup.show().parents('.block, .mediaWeather, .subheader').addClass('bigZindex');
    }

    if (typeof $.fn.bgiframe != 'undefined') {
        $popup.bgiframe();
    }
    $(document).bind('mousedown', popupBlur);
};

function popupGenerate(html, css) {
    popupHide();
    
    if (typeof css == 'undefined')
        css = {
            width: 400,
            left: '50%',
            top: '40%',
            marginLeft: -200
        };
    
    popupShow(
        $('<div class="popup removable"><a class="close" href="#" title="Закрыть">&nbsp;</a>' +
          '<table><tr><td class="lt">&nbsp;</td><td class="t">&nbsp;</td><td class="rt">&nbsp;</td></tr>' +
          '<tr><td class="l">&nbsp;</td><td class="c">' +
          html +
          '</td><td class="r">&nbsp;</td></tr>' +
          '<tr><td class="lb">&nbsp;</td><td class="b">&nbsp;</td><td class="rb">&nbsp;</td></tr></table>' +
          '</div>' ).appendTo('body').css(css)
    );

};

function popupHide() {
    $('.popup:visible').hide().parents('.bigZindex').removeClass('bigZindex');
    $('.popup.removable').remove();
    $('.bgiframe', '.popup').remove();
    $(document).unbind('mousedown', popupBlur);
    $(window).unbind('resize', popupResize);
    popup_height_percent = null;
    return false;
};

function popupBlur(e) {
    var trgt = e.target;
    var curElements = $('.popup:visible').find('*').andSelf().add('.ac_results').add('.ac_results *');
    if ($.inArray(trgt, curElements) < 0) {
        popupHide();
    };
};

// loading utilities
function blockLoading($block) {
    if ($block == null)
        return false;
    if (!$block.hasClass('block'))
        return false;
    if ($('div.loading', $block).length)
        return false;
    var css = {overflow: 'hidden'};
    if ($block.css('position') == 'static') {
        $block.data('position', 'static');
        css.position = 'relative'
    }
    if ($block.css('overflow') == 'visible') {
        $block.data('overflow', 'visible');
    }
    $block.css(css);
    $block.append('<div class="loading" />');
    if (typeof $.fn.bgiframe != 'undefined') {
        $('.loading', $block).bgiframe().height($block.height());
    }
}

function blockLoaded($block) {
    if ($block == null)
        return false;
    $('div.loading', $block).remove();
    if (typeof $block.data('position') != 'undefined') {
        $block.css({ position: $block.data('position') }).removeData('position');
    }
    if (typeof $block.data('overflow') != 'undefined') {
        $block.css({ overflow: $block.data('overflow') }).removeData('overflow');
    }
}

/* table.zebra */
function zebrify() {
    $('.zebra tr.even', '.pageContent').removeClass('even');
    $('.zebra', '.pageContent').each(function() {
        $(this).children('tr:even').addClass('even');
        $(this).children('tbody').children('tr:even').addClass('even');
    });
    $('.zebra table tr:even', '.pageContent').addClass('even');
    $('tr:not(:has(table))', '.pageContent .zebra').unbind().hover(function() {
        $(this).addClass('highlighted');
    }, function() {
        $(this).removeClass('highlighted');
    });
}
/* / table.zebra */

// document.ready
$(function () {


    $('a[rel=blank]').click(function () {
        window.open($(this).attr('href'));
        return false;
    });

    $('a[rel=fancy]').fancybox({
        centerOnScroll: false,
        hideOnContentClick: false,
        overlayOpacity: .9,
        padding: 0
    });

    /* .header search form */
    $('.searchTheSite input.searchQuery', '.header').focus(function () {
        $(this).removeClass('searchQueryEmpty');
    }).blur(function () {
        if ($(this).val() == '') {
            $(this).addClass('searchQueryEmpty');
        };
    });

    /* POPUPS */
    $('.close', '.popup').live('click', function () {
        popupHide();
        return false;
    });

    /* metros popup */
    $('a.trigger', '#metro_pan').live('click', function () {
        popupShow($(this).next('.popup'));
        return false;
    });

    /* .header .location popup */
    $('.choose-city, #cityChoiceAutoNope').click(function () {
        popupShow($(this).parents('.popunder').next('.popup'));
        return false;
    });
    $('#cityChoiceAutoYep').click(function () {
        $.cookie('cityApproved', 1, { path: '/', expires: 20 });
        $(this).parents('.popunder').removeClass('yellow');
    });
    var cityLi = {
        id: 0,
        name: ''
    };
    $('#cityChoice').autocomplete("/interfaces/autocomplete.asmx/getCities", {
        autoFill: true,
        mustMatch: true,
        //maxItemsToShow: 15,
        formatRequest: function (q) { return '{city: "' + q + '"}'; },
        formatData: function (data) {
            if (typeof data.d == 'string')
                return data.d;
            else
                return '';
        },
        formatLi: function (li, row) {
            li.innerHTML = row[0];
            li.selectValue = row[0];
            li.cityID = row[1];
            return li;
        },
        onItemSelect: function (li) {
            if (typeof li.cityID != 'undefined') {
                cityLi.id = li.cityID;
                cityLi.name = li.selectValue;
                if (cityLi.name) {
                    $('#cityChoiceOk').removeAttr('disabled');
                } else {
                    $('#cityChoiceOk, #cityChoiceReset').attr('disabled', 'disabled');
                }
            }
        }
    }).keyup(function () {
        if ($(this).val().replace(' ', '').length == 0)
            $('#cityChoiceOk').attr('disabled', 'disabled');
    });

    $('#cityChoice').val(topCityName);
    if ($('#cityChoice').val().length) {
        $('#cityChoiceOk, #cityChoiceReset').removeAttr('disabled');
    }

    $('#cityChoiceOk').click(function () {
        if (cityLi.id > 0) {
            $.cookie('topCityID', cityLi.id, { path: '/' });
            $('.choose-city', '.header .location').text(cityLi.name);
            $('#cityChoiceReset').removeAttr('disabled');
            $(this).attr('disabled', 'disabled');
            $(this).parents('.popup').prev('.popunder').removeClass('yellow');
            popupHide();
            window.location.reload();
        }
        else {
            setTimeout(function () {
                $('#cityChoice').val(topCityName);
            }, 300);
            popupHide();
        }
    });

    $('#cityChoiceCancel').click(function () {
        setTimeout(function () {
            $('#cityChoice').val(topCityName);
        }, 300);
        popupHide();
    });

    /* .mediaWeather popup */;
    $('.chooseWeatherCity').click(function () {
        popupShow($(this).nextAll('.choose-weather-popup'));
        return false;
    });
    $('a', 'ul.weatherCities').click(function () {
        if ($(this).hasClass('active')) {
            return false;
        };
        $('a.active', $(this).parents('ul')).removeClass('active');
        $(this).addClass('active');
        popupHide();
        return false;
    });
    $('.chooseWeatherCityRe').click(function () {
        popupShow($(this).parent().nextAll('.choose-weather-popup'));
        return false;
    });

    /* .choose-manager-popup */
    $('.choose-manager').click(function () {
        popupShow($(this).nextAll('.choose-manager-popup'), 80);
        return false;
    });
    $('a', '.choose-manager-popup ul').click(function () {
        $('a.choose-manager', '.info').text($(this).text());
        $('strong.phone', '.info').html($(this).nextAll('span.phone').html());
        popupHide();
        return false;
    });

    /* .manager-contacts-popup */
    $('.manager-contacts').click(function () {
        popupShow($(this).nextAll('.manager-contacts-popup'), 80);
        return false;
    });

    /* .searchResults popups */
    $('.searchResults a.popup').live('click', function () {
        popupGenerate(
            $(this).next('div.popup').html(),
            {
                left: $(this).offset().left - 50,
                top: $(this).offset().top - 50,
                width: 400
            }
        );
        return false;
    });
    /* / POPUPS */



    /* ie6 pngfix */
    if ($.ifixpng) {
        $.ifixpng('/i/blank.gif');
        $('img[src$=.png]').ifixpng();
    };

    /* .mainMenu .submenu */
    $('.mainMenu td.hassub').hover(function () {
        clearTimeout($(this).data('t_leave'));
        if ($(this).siblings().hasClass('hassub-hover')) {
            var $this = this;
            var timeoutMainEnter = setTimeout(function () {
                $($this).addClass('hassub-hover');
                $('.sub', $this).show(0);
            }, 500);
            $(this).data('t_enter', timeoutMainEnter);
        }
        else {
            $(this).addClass('hassub-hover');
            $('.sub', this).show(0);
        }
    }, function () {
        clearTimeout($(this).data('t_enter'));
        var $this = this;
        var timeoutMainLeave = setTimeout(function () {
            $($this).removeClass('hassub-hover');
            $('.sub', $this).hide(0);
        }, 500);
        $(this).data('t_leave', timeoutMainLeave);
    });

    $('.mainMenu a.menuItem').hover(function () {
        $(this).addClass('hover');
    }, function () {
        $(this).removeClass('hover');
    });

    var timeoutFirst;
    $('.mainMenu td.hassub-first').hover(function () {
        clearTimeout($(this).data('t_leave_first'));
        if ($(this).siblings().hasClass('hassub-first-hover')) {
            var $this = this;
            var timeoutFirstEnter = setTimeout(function () {
                $($this).addClass('hassub-first-hover');
            }, 500);
            $(this).data('t_enter_first', timeoutFirstEnter);
        }
        else {
            $(this).addClass('hassub-first-hover');
        }
    }, function () {
        clearTimeout($(this).data('t_enter_first'));
        var $this = this;
        var timeoutFirstLeave = setTimeout(function () {
            $($this).removeClass('hassub-first-hover');
        }, 500);
        $(this).data('t_leave_first', timeoutFirstLeave);
    });

    $('.submenu > li.has-submenu, .submenu ul li.has-submenu, .submenu ul ul li.has-submenu').hover(function () {
        clearTimeout($(this).data('t_leave'));
        if ($(this).siblings().hasClass('hover')) {
            var $this = this;
            var timeoutSubEnter = setTimeout(function () {
                showSubMenuOnHover($this);
            }, 600);
            $(this).data('t_enter', timeoutSubEnter);
        }
        else {
            showSubMenuOnHover(this);
        }
    }, function () {
        clearTimeout($(this).data('t_enter'));
        var $this = this;
        var timeoutSubLeave = setTimeout(function () {
            $($this).removeClass('hover');
        }, 600);
        $(this).data('t_leave', timeoutSubLeave);
    });

    function showSubMenuOnHover(thisVar) {
        $(thisVar).addClass('hover');
        var sumMenuColumns = $(thisVar).attr('subMenuColumns');
        if (sumMenuColumns > 1) {
            var e = $(thisVar).find('ul').eq(0);
            var w = $(e).outerWidth();
            if (!$(e).hasClass('withcolumns')) {
                $(e).addClass('withcolumns');
                var linkWidth = $(e).children().width();
                $(e).css('width', w * sumMenuColumns);
                $(e).children().width(linkWidth + 1);
                var length = $(e).children().length;
                var num = Math.ceil(length / sumMenuColumns);
                var lastInCol, lastInColNum = num - 1;
                for (var i = 1; i < sumMenuColumns; i = i + 1) {
                    lastInCol = $(e).children().eq(lastInColNum);
                    $(lastInCol).next().css('margin-top', -($(lastInCol).outerHeight()) * num);
                    $(lastInCol).nextAll().css('margin-left', w * i);
                    lastInColNum = lastInColNum + num;
                }
            }
        }
    }
    /* / .mainMenu .submenu */

    /* .submenu IE fixes */
    if ((browser_info.ie6 || browser_info.ie7) && !browser_info.ie8) {
        $('img.banner', '.header').css({
            zoom: 1
        });

        setTimeout(function () {
            $('body').append('<div class="submenu" style="float:left;width:auto;"/>');
            $('ul.submenu ul').each(function () {
                var $clone = $(this).clone().appendTo('div.submenu').css({
                    float: 'left',
                    width: 'auto'
                });
                var width = 0;
                $clone.children('li').css({ float: 'left' }).each(function () {
                    $('a', this).css({
                        float: 'left'
                    });
                    width = Math.max(width, $(this).width());
                });
                $clone.remove();
                $(this).css({ width: width + 'px' });
            });
            $('div.submenu').remove();
        }, 100);
    };

    if (typeof $.fn.bgiframe != 'undefined') {
        $('.mainMenu .sub').bgiframe();
        $('.submenu ul').bgiframe();

        $('.submenu li').hover(function () {
            $(this).addClass('hover');
            if ($(this).parent().hasClass('submenu')) {
                if (!$(this).hasClass('has-submenu')) {
                    return;
                };
                $('a', this).eq(0).addClass('top-level-active');
            } else {
                $('a', this).eq(0).addClass('sub-level-active');
            };
        }, function () {
            $(this).removeClass('hover');
            if ($(this).parent().hasClass('submenu')) {
                $('a', this).eq(0).removeClass('top-level-active');
            } else {
                $('a', this).eq(0).removeClass('sub-level-active');
            };
        });

        $('a span', '.allCountries').hover(function () {
            $(this).css('text-decoration', 'underline');
        }, function () {
            $(this).css('text-decoration', 'none');
        });
    };
    /* / .submenu IE fixes */



    zebrify();

    // accordeonTable
    $('.toggle h3', '.accordeonTable').click(function () {
        $(this).parents('tr').nextAll('tr').each(function () {
            if (!$(this).hasClass('collapsed'))
                return false;
            $(this).toggle();
        });
        return false;
    });

    // ooh html 4...
    $('img[align]').each(function () {
        var css = {};
        var fl = $(this).attr('align');
        if (fl == 'left')
            css = {
                float: 'left',
                margin: '0 10px 10px 0'
            };
        else if (fl == 'right')
            css = {
                float: 'right',
                margin: '0 0 10px 10px'
            };
        $(this).removeAttr('align').removeAttr('hspace').removeAttr('vspace').css(css);
    });
});


/* gal */
var gal_animated = false;
function gal($block, $paginator, $clicked, not_class) {
    if (gal_animated) {
        return false;
    };

    if (typeof not_class == 'string' && not_class.length) {
        var $imgs = $('img', $block).not(not_class);
    } else {
        var $imgs = $('img', $block);
    };
    var $active = $('.active', $paginator);
    var $a = $('a:not(.prev):not(.next)', $paginator);

    var current = $a.index($active);
    var next = $a.index($clicked);

    if ($clicked.hasClass('prev')) {
        next = current - 1;
        if (next < 0) {
            next = $imgs.length - 1;
        };
    } else if ($clicked.hasClass('next')) {
        next = current + 1;
        if (next >= $imgs.length) {
            next = 0;
        };
    };

    if (next < 0 || next >= $imgs.length) {
        return false;
    };

    gal_animated = true;

    $active.removeClass('active');
    $a.eq(next).addClass('active');

    $cur = $imgs.eq(current);
    $next = $imgs.eq(next);

    $cur.animate({
        opacity: 0
    }, 500);

    $next.animate({
        opacity: 1
    }, 500, function() {
        $cur.removeClass('active');
        $next.addClass('active');
        gal_animated = false;
    });
};
/* /gal */
