/** 
 * @projectDescription This jQuery Plugin is ...
 * 
 * supported browser: xxx, xxx
 * requires: jQuery >= 1.3.2 (tested with jQuery 1.3.2, xxx)
 * 	 optionally requires: if you want to enable the $.log... statements you need
 * 	 http://lab.namics.com/frontend/tools/js/debug/jquery.log/jquery.log.js
 * 
 * the loopelements has to have a backgroundcolor other than transparent (for IE)
 *
 * @example 
 * 	$.loop({debug:true});		// xxx
 * 
 * @author namics (noel.bossart@namics.com)
 * @version 0.1
 */

// closure wrapper (begin with semicolon)
;(function($) {
	
	/**
	 * @name loop
	 * @description this is the plugin main part and the public name of it
	 * extends default settings with input, prepares private variables and methods
	 * @param {object} options
	 * @return {$object} same jQuery collection as in input
	 * @example $('div.loop').loop({});
	 */
	$.fn.loop = function(options) {
		
		// extend default settings
		var settings = $.extend({}, $.fn.loop.defaults, options);
		
		// keep chaining
		return this.each(function(e) {              
			var myInstance = $.fn.loop.instance++;
			                   
			var info = function(txt){               
				if (settings.debug && typeof($.log) == "object") { 
					$.log.info('[jQuery.loop] index('+myInstance+', '+e+') - '+txt);
				}
			};
			var error = function(txt){               
				if (settings.debug && typeof($.log) == "object") { 
					$.log.error('[jQuery.loop] index('+myInstance+', '+e+') - '+txt);
				}
			};                             
			
			//
			// section: validation (plugin specific)
			//
			info('Start...');           
			
			
		    // cache the actual jQuery objects
			var $t = $(this);       
			$.fn.loop.targets[myInstance] = {};
			var me = $.fn.loop.targets[myInstance];
			me.$t = $t;  
			me.name = myInstance;  
			me.repeat = settings.repeat;
			me.url = settings.url;
			me.urlTarget = settings.urlTarget;
			me.fadeOut = settings.time.fadeOut;
			me.fadeIn = settings.time.fadeIn;
			me.target = settings.target;
			me.error = settings.errorTreesould;
			me.errorCount = 0;			
			me.specialEffect = settings.specialEffect;
			me.cache = settings.cache;
			me.count = 0;
			
			if(settings.urlTarget){                
				var $urlTarget = $(settings.urlTarget, $t);
				if($urlTarget.length > 0){
					me.url = $urlTarget.attr('href');
				}
			}   
			if(settings.directStart){
				jQuery.fn.loop.reload(me.name);
			}  
                  
			//$t.load(settings.url);         
			me.interval = setInterval("jQuery.fn.loop.reload('"+me.name+"')", settings.time.reload);
		});
	};
	
	$.fn.loop.instance = 0;
	$.fn.loop.targets = [];

	$.fn.loop.reload = function(myInstance){     
		var me = $.fn.loop.targets[myInstance];
		var $t = me.$t;     
		var url = me.url;
		var target = me.target;    
		var urlTarget = me.urlTarget;    
		var timeFadeIn = me.fadeIn;
		var timeFadeOut = me.fadeOut;  
		var target = me.target;  		 
		var salt = new Date().getTime();         
		
		if(!url || !me.repeat){        
			// Exit
			clearInterval(me.interval);
			return false;
		}                  
				
		if(me.cache === false){
			var myData = { salt: salt };
		}
				
		$.ajax({
			type: "GET",
			url: url,
			dataType: "html",
			data: myData, 
			success: function(data,textStatus){  	 
				if(textStatus == 'success'){                       
					var $data = $(data);
					if(me.count==0){

						$(target, $t).html(data);
						if(me.repeat !== true && (me.repeat > 1 || me.repeat !== false)){
							me.repeat--;                              
						} else if (me.repeat !== true){
							clearInterval(me.interval);
						}                             
						me.errorCount = 0;
						var $urlTarget = $data.filter(urlTarget);
						if($urlTarget.length > 0){
							me.url = $urlTarget.attr('href');
						}
					} else {
						
						if(me.specialEffect){
							
							$t.fadeOut(timeFadeOut, function() {
								if(me.repeat !== true && (me.repeat > 1 || me.repeat !== false)){
									me.repeat--;                              
								} else if (me.repeat !== true){
									clearInterval(me.interval);
								}                          
								me.errorCount = 0;
								var $urlTarget = $data.filter(urlTarget);
								if($urlTarget.length > 0){
									me.url = $urlTarget.attr('href');
								}
								$(target, $t).html($data.filter(target).html());
								
								$t.fadeIn(timeFadeIn);
								
							});
						} else {
							
							$t.stop(true,true);
							
							$t.fadeOut(timeFadeOut, function() {
								if(me.repeat !== true && (me.repeat > 1 || me.repeat !== false)){
									me.repeat--;                              
								} else if (me.repeat !== true){
									clearInterval(me.interval);
								}                          
								me.errorCount = 0;
								var $urlTarget = $data.filter(urlTarget);
								if($urlTarget.length > 0){
									me.url = $urlTarget.attr('href');
								}
								$(target, $t).html($data.filter(target).html());						

								$t.fadeIn(timeFadeIn);
								
							} );
							
						}
										
					}
					me.count+=1;					
				}  
			},
			error: function(){
				me.errorCount = me.errorCount +1;
			 	if(me.errorCount >= me.error){
					clearInterval(me.interval);
				}
			} 
		});         

	};
	
	/**
	 * @name plugintemplate.defaults
	 * @description these are the plugin defaults with a public interface.
	 * They are added as a property on the plugin main method
	 * They need to be called only once on a page to override for all (document ready block not necessary)
	 * @example $.fn.loop.defaults.debug = true;
	 */
	$.fn.loop.defaults = { 
		time: {
			fadeIn: 1000,					// ms for fadeIn
			fadeOut: 1000,					// ms for fadeOut
			// reload: 10000					// ms to reload
			reload: 10000					// ms to reload
		},  
		errorTreesould: 10,					// After this amount of unsuccessfull get request, the loop will be stopped 	
		repeat: true, 					 	// repeat the loop   
		target: '.looping',					// target container for the html  
	   	cache: true,						// salted URL's
		directStart: true,					// load directly, no waiting (initial Data not available)
		url: 'widget.html',  				// url
		urlTarget: 'a.loopTarget',			// dynamic URL given by a link href (can be inside the returned HTML also)
		specialEffect: true,				// specific for gkb: effect 'drop' (requires jquery-ui)
		debug: NX.debug						// display some output messages, requires: http://lab.namics.com/frontend/tools/js/debug/jquery.log/jquery.log.js
	};
})(jQuery);	
