(function($) {

	var optiontg		= new Array;
	var obj_img			= new Array;
	var theClass		= new Array;
	var imageposition	= new Array;
	var preloadInterval = new Array;
	var imgLength;
	
	$.fn.tgPreload= $.fn.tgPreload = function(options){
		
		init = function(tgp){
			optiontg[tgp.id] = $.extend({}, $.fn.tgPreload.defaults, options);
			 
					obj_img[tgp.id]			= new Array();
					theClass[tgp.id]		= new Array();
					imageposition[tgp.id]	= 0;
					
					$.each($('#'+tgp.id+' .' + optiontg[tgp.id].childClass + ''), function(i,item){
						theClass[tgp.id][i] = $(item).find('a');
						obj_img[tgp.id][i] = $(item).find('img').attr('src');						
						$(item).find('img').remove();
					});
					
			$.loadBefore(tgp);
	
		};
		
		$.transitionpreload = function(tgp){
			preloadInterval[tgp.id] = setInterval(function() { $.ownanimate(tgp) }, optiontg[tgp.id].speed);
		};
		
		$.ownanimate = function(tgp){
				
				if  (imageposition[tgp.id] == obj_img[tgp.id].length) {
					clearInterval(preloadInterval[tgp.id]);
					$('.load').delay(1000).removeClass('load').addClass('done');
					$.inHover(tgp);
				}
					
				$('.image_ke'+imageposition[tgp.id]).animate({ opacity : 1.00}, optiontg[tgp.id].animateSpeed);
				
				imageposition[tgp.id]++;

		};
		
		$.loadBefore = function(tgp){
		
			imgLength = $('#'+tgp.id+' .' + optiontg[tgp.id].childClass + '').length;
			$('#'+tgp.id+' .' + optiontg[tgp.id].childClass + '').each(function(a){
					
					var img = new Image();
					var imgSrc = obj_img[tgp.id][a];
					
						$(img).css({ display : 'block', opacity : 0 }).load(function(){
							$(img).addClass('semi_img').addClass('image_ke'+a).insertBefore($(theClass[tgp.id][a]));

							if( $('.semi_img').length == imgLength ){
								$.transitionpreload(tgp);	
							}
						}).attr('src', imgSrc);
			});
		
		};
		
		$.inHover = function(tgp){
			$('#'+tgp.id+' .' + optiontg[tgp.id].childClass + '').each(function(k){
				$(this).hover(function(){
					$(this).css('background-position', 'center center');
					$('.image_ke'+k).stop().animate({opacity : 0.5}, 500);
				}, function(){
					$('.image_ke'+k).stop().animate({opacity : 1.0}, 500);
				});
			});
		}

		this.each (
			function(){ init(this); }
		);


	};
	
	// default values
	$.fn.tgPreload.defaults = {
		speed : 500,
		animateSpeed : 500,
		childClass : "inner_thumbnail"
	};	
	
})(jQuery);
	
