(function ($) {
    // Sitemap handler
    $.fn.sitemap = function (config, callback) {
        // Show animation
        $('#ajax-process')
            .css({top: ($(window).height() - $('#ajax-process').height()) / 2
                  + $(window).scrollTop() + 'px',
                  left: ($(window).width() - $('#ajax-process').width()) / 2
                  + $(window).scrollLeft() + 'px'})
            .show();
        var placeholder = $(this);
        // Send request
        $.post(config.post_url,
               {'url' : config.url,
                'csrfmiddlewaretoken' : config.csrf},
               function (data) {
                   placeholder.after(data);
                   // Hide animation
                   $('#ajax-process').hide();
                   callback();
               });
        return $(this);
    };

    $(function () {

        var sitemap = false;
        var sitemap_loaded = false;
        var callback = false;
        var $items = $('#logo').children('div, a:not(.home)');
        var $colors = $('#logo a.home').children('img:not(.blue)');
        var color_index = 0;
        var color_time = 0;

        if ( $('table.hl-td').width() < 700 ){ 
            $('table.hl-td').addClass('small');
        }
        else { 
            $('table.hl-td').removeClass('small');
        }

        function randelem($objects) {
            var randItem = Math.floor(Math.random() * $items.length);
            if (randItem == indexes[0] || 
                randItem == indexes[1] || 
                randItem == indexes[2]){
                return randelem($objects);
            }
            else {
                return randItem;
            };
        };

        function logo_animate(){
            color_time = Math.floor(Math.random() * 3000);
            $colors.eq(color_index)
                .fadeTo(1000,1).delay(color_time+1000).fadeTo(1000,0);
            if (color_index < $colors.length){
                color_index=color_index+1;
            }
            else {
                color_index=0;
            }
            setTimeout(function () { logo_animate(); }, (color_time+2000));
        }
        logo_animate();

        var indexes = new Array();
        indexes[0] = randelem($items);
        indexes[1] = randelem($items);
        indexes[2] = randelem($items);
        $items.eq(indexes[0]).fadeTo(500,1);
        $items.eq(indexes[1]).fadeTo(500,1);

        function animate(){
            var $last = $items.eq(indexes[0]);
            var $next = $items.eq(indexes[2]);
            ($next).fadeTo(500,1);
            ($last).fadeTo(500,0);
            indexes[0] = indexes[1];
            indexes[1] = indexes[2];
            indexes[2] = randelem($items);

            if ( $('table.hl-td').width() < 700 ){ 
                $('table.hl-td').addClass('small');
            }
            else { 
                $('table.hl-td').removeClass('small');
            }

            setTimeout(function () { animate(); }, 1000);
        }
        setTimeout(function () { animate(); }, 1000);


        $('#contacts a').css('opacity', '0.6')
        $('.lang a:not(.selected)').each(function () {
            $(this).css('opacity', '0.25');
        });

        $('.lang a:not(.selected)').hover(
            function () {
                $(this).fadeTo(200, 1);
            },
            function () {
                $(this).fadeTo(100, 0.25);
            }
        );

        $('#menu ul li').hover(
            function () {
                $(this).addClass('hovered');
            },
            function () {
                $(this).removeClass('hovered');
            }
        );

        $('#controls input').focus(function() {
            if (this.value == this.defaultValue){  
                this.value = ''; 
            }  
            if(this.value != this.defaultValue){  
                this.select();  
            }  
        });  
        $('#controls input').blur(function() {  
            if (this.value == "" || this.value == this.defaultValue){  
                this.value = (this.defaultValue ? this.defaultValue : '');  
            }
        });
        $('#contacts p.link').click(function() {
            if (callback == false) {
                $('#overlay').fadeTo(500, 0.8);
                $('#callback').fadeTo(500, 1);
                $('#contacts .info').css('zIndex', 999);
                callback = true;
            }
            else {
                $('#overlay').hide();
                $('#callback').hide();
                $('#ajax-info').hide();
                callback = false;
            }
        });
        $('#overlay').click(function() {
            if (callback == true) {
                $('#overlay').hide();
                $('#callback').hide();
                $('#ajax-info').hide();
                callback = false;
            };
        });

        $('table[class!="nohl"][class!="hl-td"] td, table[class!="nohl"][class!="hl-td"] th').hover(
            function () {
                $(this).parent().addClass('hovered');
            },
            function () {
                $(this).parent().removeClass('hovered');
            }
        );

        $('table[class*="hl-td"] tr[class!="head"] td, table[class*="hl-td"] tr[class!="head"] th').hover(
            function () {
                var pos = $(this).parent().children().index($(this))+1;
                $(this).addClass('hovered');
                $(this).closest('tr[class!="head"]').prev().children('td:nth-child('+pos+')').addClass('hovered');
            },
            function () {
                var pos = $(this).parent().children().index($(this))+1;
                $(this).removeClass('hovered');
                $(this).closest('tr[class!="head"]').prev().children('td:nth-child('+pos+')').removeClass('hovered');
            }
        );

        $('table[class*="hl-td"] tr[class="head"] td, table[class*="hl-td"] tr[class="head"] th').hover(
            function () {
                var pos = $(this).parent().children().index($(this))+1;
                $(this).addClass('hovered');
                $(this).closest('tr').next().children('td:nth-child('+pos+')').addClass('hovered');
            },
            function () {
                var pos = $(this).parent().children().index($(this))+1;
                $(this).removeClass('hovered');
                $(this).closest('tr').next().children('td:nth-child('+pos+')').removeClass('hovered');
            }
        );

        $('#contacts a').hover(
            function () {
                $(this).fadeTo(100, 1);
            },
            function () {
                $(this).fadeTo(100, 0.6);
            }
        );

        var tooltip_active = false;
        var $current_tooltip = null;
        var $current_tooltip_window = null;

        $('a.tip').click(
            function () {
                if (tooltip_active == false ){
                    $current_tooltip = $(this);

                    tooltip_active = true;
                    tip = $current_tooltip.attr("title");

                    var link = $current_tooltip.attr("href");
                    if ( link != '#' && link != ' '){
                        link = '<a target="_blank" href="'+ $current_tooltip.attr("href") + '">Подробнее' + '</a>' ;
                    }
                    else {
                        link = ''; 
                    }
                    var offset = $current_tooltip.position();

                    if (offset.left > 400){
                        offset.left = 400;
                    }

                    $current_tooltip.after('<div class="arrow"></div><div class="tooltip"><p>' + tip + '</p>' + link + '</div>');
                    $('div.arrow').css({ left: ($current_tooltip.position().left+ $current_tooltip.width()/2) + 'px' });
                    $current_tooltip_window = $('div.tooltip');
                    $current_tooltip.attr('title', '');
                    
                    $('div.tooltip').css({left: offset.left + 'px'});

                    $('div.arrow').fadeTo(300, 1);
                    $('div.tooltip').fadeTo(300, 1);
                }
                else {
                    tooltip_active = false;
                    $current_tooltip_window.remove();
                    $('div.arrow').remove();
                    $current_tooltip.attr('title', tip);
                    if ($(this)[0] != $current_tooltip[0]){
                        $(this).trigger('click');
                    }
                };
                return false;
            }
        );

        var show_sitemap = function () {
            $('#sitemap').removeClass('initial');
            sitemap = true;
            var end = $('#footer').position().top;
            $('html, body').animate({scrollTop: end}, 800);
        };

        $('#sitemap span a').click(function() {
            if (sitemap == false) {
                if (!sitemap_loaded) {
                    // Load sitemap and show
                    $('#sitemap-placeholder').sitemap(
                        {
                            post_url: sitemap_post_url,
                            csrf: sitemap_csrf_token
                        },
                        show_sitemap // Show after load
                    );
                    sitemap_loaded = true;
                }
                else {
                    // Show sitemap
                    show_sitemap();
                }
                // Prevent default action
                return false;
            }
            else {
                $('#sitemap').addClass('initial');
                sitemap = false;
                return false;
            }
        });

        $('#sitemap a').hover(
            function () {
                $(this).css('cursor','pointer');
            },
            function () {
                $(this).css('cursor','auto');
            }
        );

        $('.fade-top, .fade-bottom').hover(
            function () {
                $(this).css('cursor','pointer');
                $(this).addClass('hover');
            },
            function () {
                $(this).css('cursor','auto');
                $(this).removeClass('hover');
            }
        );

        $("a.popup").colorbox({
	    speed: 500,
	    initialWidth: "100",
	    maxWidth: "1100",
	    initialHeight: "100",
	    opacity: 0.8,
	    preloading: true,
	    current: "",
	    previous: "",
	    next: "",
	    close: "",
	    open: false,
	    returnFocus: false,
	    loop: true,
	    slideshow: false,
	    overlayClose: true,		
	    escKey: true,
	    arrowKey: true
        });

        // Social networks share buttons
        // Check IE opacity
        var social_links = $('#social-share a');
        if (!$.support.opacity)
            social_links.css({'opacity' : 0.8});
        // Add hover handlers
        social_links.attr('target', '_blank').hover(
            function () { $(this).css({'opacity' : 1}); },
            function () { $(this).css({'opacity' : 0.8}); }
        );

        // Guestbook form toggling
        $('#toggle-guestbook-form').click(function () {
            $('#messages').slideToggle();
            return false;
        });



        $('#tariff-select').hover(
            function() {
                $(this).css('cursor','pointer');
            }, 
            function() {
                $(this).css('cursor','auto');
            }
        );

        $('#tariff-select span').click(
            function() {
                    $('#tariff-select ul').show();
            } 
        );

        $('#tariff-select li').hover(
            function() {
                $(this).addClass('hovered');
                $(this).children('div').show();
            }, 
            function() {
                $(this).removeClass('hovered');
                $(this).children('div').hide();
            }
        );

        $('#tariff-select ul li').click(
            function() {
                $('#tariff-select li').removeClass('selected');
                $(this).addClass('selected');
                $('#tariff-select span span').replaceWith('<span>'+ $(this).children('span').text() +'<span>');
                $('#tariff-select ul').hide();
                $('#consult_price').val($(this).children('span').text());
            }
        );

        // Upload file fields handling
        var inputs = $('input[id^="consult_upload_"]');
        if (!inputs.length)
            var inputs = $('input[id^="id_upload_"]');
        // Make list with jquery objects
        var fields = $.map(inputs.parent(), 
                           function (val, i) { return $(val); });
        var displayed = 0;
        var max = fields.length - 1;
        inputs.change(function () {
            if ($(this).val() && (displayed < max))
                fields[++displayed].show()
            return false;
        });

        // Top menu
        // Put hidden element before visibe. Bad css.
        $('div.sub:not(:visible)').insertBefore($('div.sub:visible'));
        $('a.top-menu-link').mouseover(function () {
            // Hide displayed item when another link is hovered
            $('div.sub.hovered:visible').hide();
            if ($(this).parents('li').hasClass('selected'))
                return;
            var id = $(this).attr('id').slice(4);
            $('div[id="sublevel-' + id + '"]').show();
        });
        // We can't use mouseleave on top-menu-link, sub div isn't link's child
        $('#menu').mouseleave(function () { 
            $('div.sub.hovered:visible').hide(); 
        });
        // Top menu third level
        $('.has-thirdlevel').mouseover(function () {
            $(this).parent().addClass('dd');
            $(this).next('div').show();
        });
        $('div.thirdlevel').mouseleave(function () { 
            $(this).parent().removeClass('dd');
            $(this).hide() 
        });
    });

})(jQuery);

