// This function is called from flash movies with kpi support. Expects true as return value.
// (implements and uses flash class com/powerchallenge/communication/Kpi.as)

if ( !com ) var com = {};
if ( !com.powerchallenge ) com.powerchallenge = {};

com.powerchallenge.kpi = 
{
	GOOGLE_KPI_ENABLED:true,
	INTERNAL_KPI_ENABLED:true,
	INTERNAL_KPI_URL:'com/authenticated/xml/setItemsTried.php',
	m_postBuffer:new Array(),
	m_timer:null,
	postEvent:function( eventName, eventParam )
	{
		var self = this;
		if ( this.m_timer === null )
			this.m_timer = setTimeout( function(){ self.time() }, 10000);

		if ( eventName == "item_tried_on" )
			this.addToKpiBuffert( eventName, eventParam );
		else
			this.doGoogleAnalyticsPost(eventName);

		return true;
	},
	time:function()
	{
		this.sendAndFlush();
	},
	sendAndFlush:function()
	{
		if ( this.m_postBuffer.length == 0 )
			return;

		var xmlPostData = '<?xml version="1.0" standalone="yes"?>';
		xmlPostData += '\n<internalKpiData>';
		var len = this.m_postBuffer.length;
		for ( var i = 0; i < len; ++i )
		{
			xmlPostData += '\n\t<event type="';
			xmlPostData += this.m_postBuffer[i][0] + '" item_id="';
			xmlPostData += this.m_postBuffer[i][1] + '" count="'
			xmlPostData += this.m_postBuffer[i][2] + '" />';
		}
		xmlPostData += '\n</internalKpiData>';
		this.m_postBuffer = null;
		this.m_postBuffer = new Array();
		this.m_timer = null;
		this.doInternalKpiPost( xmlPostData );
	},
	doGoogleAnalyticsPost:function(eventName)
	{
		if ( !this.GOOGLE_KPI_ENABLED || !trackPageEvent )
			return;

		trackPageEvent( "kpi/player_editor/"+eventName );
		//uncomment below when moving to the new ga code
		//pageTracker._trackPageView("/kpi/player_studio/" );
	},
	doInternalKpiPost:function( postData )
	{
		if ( !this.INTERNAL_KPI_ENABLED )
			return;
		
		ajaxPost( this.INTERNAL_KPI_URL, postData, null, null );
	},
	addToKpiBuffert:function( eventName, eventParam )
	{
		var index = -1;
		for ( var i = 0; i < this.m_postBuffer.length; ++i )
		{
			if ( this.m_postBuffer[i][0] == eventName && this.m_postBuffer[i][1] == eventParam )
			{
				index = i;
				break;
			}
		}
		if ( index !== -1 )
			this.m_postBuffer[index][2]++;
		else
			this.m_postBuffer.push( [eventName, eventParam, 1] );
	}
};

function flashKpiEvent(eventName, eventParam) 
{
	return com.powerchallenge.kpi.postEvent( eventName, eventParam );
}

