/*
Description: FADE IMAGES LOOP
Author: wpworks.net
Author URI: http://www.wpworks.net
*/

var wpw_fade_speed = 2000;
var wpw_loop_speed = 3000;

var fadeImages = function(){
	var $ = jQuery; 
	var main_container = $('#main_content_center, #main_content_center_page');
	var items = [];
	var current_index = 0;
	var loop_timer = 0;
	
    var resize_images = function(){
    	var cw = WPW.cW * 0.7;
    	var ch = WPW.cH * 0.6;
    	
    	if(cw > 1000)cw = 1000;
    	if(ch > 1000)ch = 1000 ;
    	if(cw < 200)cw = 200;
    	if(ch < 200)ch = 200;
    	
    	
    	
		$('img', '#main_content_center').each(function(index){
			var img = $(this);
			WPW.ResizeImage({
				img:img, 
				t_w:function(){return cw;},
				t_h:function(){return ch;},
				scale_mode:"fit_h",
				position_mode:"cc",
				force_fit: true,
				canvas_check: false
			}); 
			
			
			
			img.css('left', parseInt(WPW.cW*0.5 - img.width()/2), 10);
			img.css('top', parseInt(WPW.cH/2 - img.height()/2), 10);
			
			
		});
    }	
	
    $('body').bind('RefreshSize', function(){
		resize_images();
    });  	
	
	$('img', main_container).each(function(){
		var img = $(this);
		var new_img = new Image();
		new_img = $(new_img);
		new_img.data('src', img.attr("src"));
		
		items.push(new_img);
		img.remove();

	});
    
    var changeIndex = function(){
    	clearInterval(loop_timer);
    	current_index ++ ;
    	if(current_index > items.length-1)current_index = 0;
    	
    	displayCurrentItem();
    }
    
    var doLoop = function(){
    	clearInterval(loop_timer);
    	loop_timer = setInterval(function(){changeIndex();}, wpw_loop_speed);
    }
    
    var show = function(item){
    	
    	if(!item.data('onScreen')){
    		item.data('onScreen', true);
    		item.hide().fadeOut(0);
    		main_container.append(item);
    		WPW.windowResize();
    		item.delay(wpw_fade_speed/3).fadeIn(wpw_fade_speed, function(){doLoop();});
    	}
    }    
    
    var showImage = function(item){
    	if(item.data('loaded')){
    		show(item);
    	} else {
    		item.unbind('load');
			item.load(function(){
				
				item.data('loaded', true);
				show(item);
				WPW.windowResize();
			}).attr('src', item.data('src'));  		
    	}
    }
    

    
    var hideImage = function(item){
    	if(item.data('onScreen')){
    		item.data('onScreen', false);
    		item.fadeOut(wpw_fade_speed, function(){item.detach()});
    	}
    }
    
    
    function displayCurrentItem(){
    	 
    	for(var i = 0; i<items.length; i++){
    		if(i == current_index){
    			showImage(items[i]);
    		} else {
    			hideImage(items[i]);
    		}
    	}
    }
    
    displayCurrentItem();
    
  
    
    resize_images();
};

WPW.Core.register("fadeImages");


