/**
 * AdTracker - requires jQuery for getting a list of all iframes
 * which have been included into the original html by ad-service
 * for displaying the ad. 
 * 
 * hint: use jquery from http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js
 *
 * howto:
 * _BEFORE_ Google-Adsense show_ads.js inclusion do:
 *  AdTracker.register('MyUniqueAdNameForThisAd', google_ad_format, google_ad_type);
 *
 * _AFTER_ show_ads.js do:
 *  AdTracker.track('MyUniqueAdNameForThisAd');
 */
var iFrame = 
{
	stack: new Array(),
		
	add: function (unique_identifier, unique_ad_identifier )
	{
		if( !this.isKnown( unique_identifier ) )
		{
			this.stack.push(
				new Array(
					unique_identifier, 
					(new Date()).getTime(), 
					unique_ad_identifier
				)
			);
			return true;
		}
		return false;			
	},
	
	isKnown: function( unique_identifier )
	{
		for(var i=0; i < this.stack.length; i++)
		{
			if(this.stack[i][0] == unique_identifier)
				return true;
		}
		return false;		
	},
	
	get: function ( unique_identifier )
	{
		for(var i=0; i < this.stack.length; i++)
		{
			if(this.stack[i][0] == unique_identifier)
				return this.stack[i];
		}		
	}
};
 
 
var AdTracker = 
{
	adStack: new Array(),
	
	register: function ( unique_ad_identifier, origin, ad_format, ad_type )
	{
		this.adStack.push(
			new Array(
				unique_ad_identifier,
				(new Date()).getTime(), 
				0, // int for tracking ad-runtime
				origin,
				ad_format,
				ad_type
			)
		);
	},
	
	track: function ( unique_ad_identifier )
	{
		var self = this;
		
		$('iframe').each(
			function(iframe_index)
			{
				if( iFrame.add ( iframe_index, unique_ad_identifier ) )
				{  
					$(this).attr('adtracker:iframe', iframe_index);
					$(this).attr('adtracker:ad', unique_ad_identifier);
					
					$(this).load(
						function() 
						{
							self.updateAdRuntime($(this).attr('adtracker:ad'), (new Date()).getTime());
						}
					);
				}
			}
		);			
	},
	
	send: function ( )
	{
		$.each( 
			this.adStack, 
			function(ad_index, ad)
			{
				unique_ad_identifier = ad[0];
				ad_started = ad[1];
				ad_finished = ad[2];
				ad_origin = ad[3];
				ad_format = ad[4];
				ad_type = ad[5];
				calculation = ( ( ad_finished - ad_started ) / 1000 );
				if(calculation < 0)
				{
					calculation = 0.001;
				}
				(new Image()).src = 'http://www.hosting64.de/adtracker.gif?origin=' + ad_origin + '&format=' + ad_format + '&type=' + ad_type + '&runtime=' + calculation;
			}
		);	
	},	
	
	updateAdRuntime: function ( unique_ad_identifier, runtime )
	{
		for(var i=0; i < this.adStack.length; i++)
		{
			if(this.adStack[i][0] == unique_ad_identifier)
			{
				if(this.adStack[i][2] < runtime)
				{								
					this.adStack[i][2] = runtime;
				}
			}
		}							
	}
};

$(document).ready(
	function() 
	{
		AdTracker.send();
	}
);