$(document).ready(function(){

    var waitForImage = function waitForImage( img, callback ) {
        if( typeof img === 'string' ) {
            var obj = new Image();
            obj.src = img;
            img = obj; // >_>
        }

        if( ! img.complete || ( typeof img.naturalWidth != "undefined" && img.naturalWidth == 0 ) ) {
            // Картинка недогружена, ждем дальше
            setTimeout( function () {waitForImage( img, callback );}, 100 );
        } else {
            // Картинка загружена, вызываем callback
            callback.apply( img );
        }
    }

	//empty links
	$('a[href=#]').click(function(){
		return false;
	});
    
    //navigation
    var nProc = 0;
    var i = 0;
    
    $('.animated a.current').find('div').animate({'opacity':0});
    $('.animated a').hover(function(){
        if( nProc == 0 ) {
            nProc = 1;
            $(this).children('div').animate({'opacity':1, 'border-radius':'5px'}, 400);
            $(this).children('div').children('span').animate({'top':0}, 100, function(){nProc = 0;});
            
        }
    }, function(){
        if( ! $(this).hasClass('current') ) {
            $(this).children('div').animate({'opacity':0, 'border-radius':'5px'}, 400);
            $(this).children('div').children('span').animate({'top':30});
        }
    });


    // предзагрузка изображений
    
    var preloadImages = $('.bg [data*="bg"]'),
        preloader = jQuery('.preloader');
        
        preloader.show();
    
    $('.bg [data*="bg"]').each(function(k,v){
        
        waitForImage($(this).attr('src'), function(){

		$(v).css({'visibility':'visible'});
                
                if( $(v).parent().index(0) == 1 ){
                    $(v).parent().find('[data*="bg"]:eq(0)').fadeIn(250);
                    preloader.fadeOut(250).hide();
                }
        });

        
    });
    

    //index bg rotation
    var i = 1;
    var interval;
	
	function start_interval () {
		interval = setInterval(function() {
			i++;
			
				$('.currHead').fadeOut(500).removeClass('currHead');
				$('[data="bg' + i + '"]').fadeIn(1200).addClass('currHead');
			
			if( i == 4 ) {
				i = 0;
			}
		}, 4000);
	}
	
	function end_interval () {
		clearInterval(interval);
	}
	
    

	start_interval();
	$(function() {
        $("#navigation li").hover(
          function () {
			var $this = this,
				liPrefix = 'n',
				imgPrefix = 'bg';
		    end_interval();

			
			$('.bg img').each(function (k, img) {
				var counter = k + 1,
					thisImg = $(img).attr('data');
				
				if ($($this).hasClass(liPrefix + counter) && thisImg === imgPrefix + counter) {
					$('.bg img').removeClass('currHead').hide();
					$(img).addClass('currHead').show();
					
				}
			});
          },
          function () {
		    start_interval();
          }
		);
    });
	
       
	
});
