/*
	Programmer: Lukasz Czerwinski
	CodeCanyon: http://codecanyon.net/user/Lukasz_Czerwinski
*/

(function($){
$.fn.preloader = function(settings){
	//Global variables 
	var el;
	//Default settings
	settings = jQuery.extend({
		Speed		: 360,				//Speed animations 
		Style		: "default",		//Style preloader
		Height		: 0,				//(false) Default height for IMG
		Width		: 0,				//(false) Default width for IMG
		Scroll		: 1,				//(true)
		Title		: 1					//(true) Short description
	}, settings);
	//Basic element
	el = $(this);
	//Hide IMG
	el.css("display", "none");
	//Load
	jQuery.each(el, function(i){ 
		//This IMG
		var thisImage = $(this);
		var box = thisImage.parent();
		
		//get position
		var pos = box.offset();
		
		
		thisImage.attr("id", i);
			//Link CSS
			box.css({
				"display": "block",
				"z-index": 10
			});
			//Wrap the IMG
			box.wrap("<div class='preloader'></div");
			//Add div with preloader
			box.parent(".preloader").append("<div class='"+settings.Style+"'></div>");
				
					if(settings.Scroll) {
				    	if(pos.top < ($(document).scrollTop()+document.documentElement.clientHeight)) {
							 loadImg(el.parents().children("#"+i), el.parents().children("#"+i).attr("src"), box)
						}
						$(window).bind("scroll", function() {
							if(pos.top < ($(document).scrollTop()+document.documentElement.clientHeight)) {
								 loadImg(el.parents().children("#"+i), el.parents().children("#"+i).attr("src"), box)
							}	
						});
					} else {
						loadImg(thisImage, thisImage.attr("src"), box);
					}
		//Set sizes
		el.parents(".preloader").css({
			height	: (settings.Height) ? settings.Height : thisImage.attr("height")+2,
			width	: (settings.Width) ? settings.Width  : thisImage.attr("width")+2
		});
		//Size IMG
		(settings.Height) ? thisImage.attr("height", settings.Height) : thisImage.attr("height", thisImage.attr("height"));
		(settings.Width) ? thisImage.attr("Width", settings.Width) : thisImage.attr("width", thisImage.attr("width"));
		//Add description  
		if(settings.Title) {
			thisImage.parents(".preloader").append("<div class='alt'>"+thisImage.attr("alt")+"</div>");
		}
		return true;
	}); 
	
	//Load
	function loadImg (IMG, SRC, BOX) {
				//Get the SRC
		var srcImg = SRC;
		var img = new Image();
		//Load the IMG
		img.onload = function () {
			//Remove div with preloader
			BOX.parent(".preloader").children("."+settings.Style).fadeOut(settings.Speed, function(){
				$(this).remove();
				IMG.fadeIn(settings.Speed);
				IMG.removeAttr("id");
				//IE
				img.onload = function() {};
			});
		};
		img.src = srcImg;
	}
	//Show and hide description 
	el.parents(".preloader").hover(
		function(){
			$(this).children(".alt").stop(true, true).delay(150).slideDown(200);
		},
		function(){
			$(this).children(".alt").stop(true, true).delay(150).slideUp(200);
		});
}
})(jQuery); //The end :)