(function() {
    $(document).bind('loadImages', initImageLoader);
    var imgs = {};
    var len = 0;
    var timeOut;
    
    function initImageLoader() {
        $(document).unbind('loadImages', initImageLoader);
        $('.wrapper').css({
	        position: 'absolute',
	        top: 111,
	        width: $('#footer').width(),
	        height: $('#footer').width()*.475
	    });
        
        timeOut = setTimeout(function() {
        	$('.loading-wheel').appendTo('body');
            $('.loading-wheel').show();
            var top = $('.wrapper').height() / 2 + $('#header').height();
            $('.loading-wheel').width($(window).width()).height($(window).height()).fadeTo("fast", .5);
            $('.loading-wheel img').css('top', top);
        }, 150);
        
        if($('#copy').length == 0) {
            return;
        }
        
        $(window).load(function() {
            $('<div />').appendTo('body').addClass('hiddenLoader');
            
            len = $('img').length;
            
            $('img').each(function() {
                var src = $(this).attr('src');
                if(imgs[src]) {
                    return;
                }
                imgs[src] = true;
                $('<img />').appendTo('.hiddenLoader').hide().load(imageLoadedHandler).error(imageLoadedHandler).attr('src', src);
            });
        });
    };
    
    function imageLoadedHandler(e) {
        var src = $(this).attr('src');
        delete(imgs[src]);
        if(Object.keys(imgs).length == 0) {
            loadingFinished();
        };
    };
    
    function loadingFinished() {
        clearTimeout(timeOut);
        $('.hiddenLoader').hide();
        $('.loading-wheel').fadeTo(500, 0, function() {
            $('.loading-wheel').remove();
        });
        $('#copy').css('visibility', 'visible');
    };
    
    Object.keys = Object.keys || function(o) {
        var result = [];
        for(var name in o) {
            if (o.hasOwnProperty(name))
              result.push(name);
        }
        return result;
    };
})();
