function loadImages(selector) {
    // ex. loadImages('div.somediv img.load');
    
    $(selector).each(function(index, element){
        if (!element.complete) {
            var elHeight = $(this).height();
            var elWidth = $(this).width();
            var elPosition = $(this).position();
            $(this).parent().css({"position": "relative"});
            var spinner = $("<ins></ins>").height(elHeight).width(elWidth).css({
                "background": "transparent url('http://jonatanflores.com/wp-content/themes/grid-a-licious/images/loading-image.gif') no-repeat center center",
                "position": "absolute"
            }).addClass("loader");
            $(this).before(spinner);
            $(this).css("visibility", "hidden");
        }
    });
    
    $(selector).load(function(event){
        var spinnerDiv = $(this).prev("ins.loader");
        if (spinnerDiv.length > 0) {
            $(this).hide();
            $(this).css({"visibility": "visible"});
            $(this).fadeIn(250);
            $(this).prev("ins.loader").fadeOut(250, function(){
                $(this).hide();
                //$(this).remove();
            });
            $(this).removeClass("load");
        }
    }).each(function(){
        if(this.complete) {
            $(this).trigger("load");
        }
    });
}

function fadeImages() {
    /* * Fade Images * */
    $(".work_image").fadeTo("normal", 0.6); // This sets the opacity of the thumbs to fade down to 30% when the page loads
    $(".work_image").hover(function(){
    	$(this).fadeTo("slow", 1.0); // This should set the opacity to 100% on hover
    },function(){
    	$(this).fadeTo("slow", 0.6); // This should set the opacity back to 30% on mouseout
    });
}


$(document).ready(function() {
    /* * Return to top * */
    $('#returntotop').click(function(){
        return !$('html,body').animate({scrollTop:0});
    });
    
    fadeImages();

    /* * Images Loder * */
    loadImages('div.eachpost img.work_image');
    
    $("#work_box").sexyCycle({
		easing: 'easeOutElastic',
		speed: 400,
		next: '.next2',
		prev: '.prev2',
		cycle: false,
		start: 2
    });
    // loopedSlider for image gallery
	jQuery("#loopedSlider").loopedSlider({
		autoStart: 0, 
		slidespeed: 600, 
		containerClick: true,
		autoHeight: true
	});
    
    
});


$(function(){
	var vg = $("#allposts").vgrid({
		easeing: "easeOutQuint",
		time: 800,
		delay: 20,
		selRefGrid: "#allposts div.eachpost",
		selFitWidth: ["#container", "#footer"],
		gridDefWidth: 240 + 15 + 15 + 5,
		forceAnim: 1	});
	
	$(window).load(function(e){
		setTimeout(function(){ 
			// prevent flicker in grid area - see also style.css
			$("#allposts").css("paddingTop", "0px");
		}, 1000);
	});


});
