/**
* JS for MissionControl API
* @version $Id: base.js 1 2009-02-09 15:18:22Z tacker $
* @author Global Media GmbH | http://www.global-media.de/
*
* Important changes in API:
*  - r162: Explicit referer tracking has been removed. Referers are now tracked alongside the access track.
*/
var MissionControl = new Class({
	Implements: Events,
	STATUS_DATA_ERROR: 1,
	apiurl: null,
	trackPid: false,
	pid: null,
	language: null,
	trackData: new Object,
	country: null,
	lottery: null,
	fetchEcards: true,
	defaultEcard: null,
	ecards: null,
	enableCookieTest: false,
	cookieTestName: 'cookiecheck',
	cookieTest: null,
	flashLoadReady: false,
	flashProxy: null,
	sendEcardPending: false,
	addLotteryParticipationPending: false,
	initialize: function( myOptions )
	{
		for ( var i in myOptions ) {
			this[ i ] = myOptions[ i ];
		}
		
		if ( this.flashProxyPath ) {
			this.flashProxyHandlerCount = 0;
			new Asset.javascript( this.flashProxyPath + 'swfobject.js', {
				onload: function() {
					window.addEvent( 'domready', function() {
						var params = {
							menu: 'false',
							scale: 'noScale',
							allowScriptAccess: 'always',
							bgcolor: '#FFFFFF',
							wmode: 'transparent'
						};
						var flashContainer = new Element( 'div', { styles: { position: 'absolute', width: '0px', height: '0px' } } );
						var flashReplacement = new Element( 'div', { id: 'FlashProxy' } ).inject( flashContainer );
						flashContainer.inject( document.body, 'top' );
						var recallfunc = null;
						
						window[ 'flashProxyHandler' + ++this.flashProxyHandlerCount ] = function() {
							this._flashIsReady();
						}.bind( this );
						
						swfobject.embedSWF( this.flashProxyPath + 'FlashProxy.swf', flashReplacement.id, '1', '1', '9.0.0', '', { ready : 'flashProxyHandler' + this.flashProxyHandlerCount } , params, {} );
					}.bind( this ) );
				}.bind( this )
			} );
		}
		
		// detect pid
		if( this.trackPid ) {
			if( this.getCookieData( 'pid' ) ) {
				this.pid = this.getCookieData( 'pid' );
			}
			if( this.pid !== null && this.pid.length > 0 ) {
				this.setCookieData( 'pid', this.pid );
				this.trackData[ 'pid' ] = this.pid;
			}
		}

		// detect referer
		var referer = '';
		if( this.getCookieData( 'referer' ) ) {
			referer = this.getCookieData( 'referer' );
		} else {
			if ( document.referrer.length > 0 && document.referrer.search( window.location.hostname ) < 0 ) {
				referer = document.referrer;
			}
		}
		if( referer.length > 0 ) {
			this.trackData[ 'referer' ] = referer;
			this.setCookieData( 'referer', referer );
		}

		// Preload ecards
		if ( this.fetchEcards ) {
			this.doRequest( this.apiurl + 'ecard', {
				'onComplete': function( response ) {
					if ( this.checkApiResponse( response ) ) {
						this.ecards = response.result;
						if ( response.length === 1 ) this.defaultEcard = response.result[ 0 ].id;
					}
				}.bind( this )
			} );
		}

		// Check for cookies
		if ( this.enableCookieTest ) {
			if( this.getCookieData( this.cookieTestName ) === this.cookieTestName ) {
				this.track( 'cookies_enabled' );
				this.cookieTest = true;
			} else {
				this.track( 'cookies_disabled' );
				this.cookieTest = false;
			}
		}
	},
	_flashIsReady: function() {
		this.flashLoadReady = true;
	},
	getFlashProxy: function() {
		if ( this.flashProxyPath && this.flashProxy === null ) {
			this.flashProxy = $( 'FlashProxy' );
		}
		return this.flashProxy;
	},
	track: function( trackname, myData )
	{
		if ( typeof myData === 'undefined' ) myData = {};
		myData = $merge( myData, this.trackData );
		if ( this.language !== null && typeof myData.language === 'undefined' ) myData.language = this.language;
		if ( this.country !== null && typeof myData.country === 'undefined' ) myData.country = this.country;
		this.doRequest( this.apiurl + 'track/' + trackname, {
			data: myData
		} );
	},
	addLotteryParticipation: function( email, custom, pollId, pollChoices )
	{
		if( this.addLotteryParticipationPending ) return;
		this.addLotteryParticipationPending = true;
		myData = { 'email': email };
		myData = $merge( myData, this.trackData );
		if ( typeof custom !== 'undefined' ) myData.custom = custom;
		if ( this.language !== null ) myData.language = this.language;
		if ( this.country !== null ) myData.country = this.country;
		
		if( typeof pollId !== 'undefined' && typeof pollChoices !== 'undefined' ) {
			myData.poll_id = pollId;
			myData.poll_choice = pollChoices;
		}		
		
		this.doRequest( this.apiurl + 'lottery/' + this.lottery + '/participate', {
			data: myData,
			'onComplete': function( response ) {
				if ( this.checkApiResponse( response ) ) {
					this.fireEvent( 'lotteryparticipation', new Array( true, response ) );
				} else {
					this.fireEvent( 'lotteryparticipation', new Array( false, response ) );
				}
				this.addLotteryParticipationPending = false;
			}.bind( this )
		} );
	},
	getPollChoices: function( poll ) {
		this.doRequest( this.apiurl + 'poll/' + poll, {
			'onComplete': function( response ) {
				this.fireEvent( 'pollchoices', new Array( this.checkApiResponse( response ), response ) );
			}.bind( this )
		} );
	},
	doRequest: function( url, options ) {
		if( this.flashProxyPath && ! this.flashLoadReady ) {
			( function() { this.doRequest( url, options ); } ).bind( this ).delay( 500 );
			return;
		}
		
		if( ! options.method ) {
			options.method = options.data ? 'post' : 'get';
		}
		
		var flashProxy = this.getFlashProxy();
		if ( flashProxy ) {
			// callback fürs flash im window-scope
			if ( options.onComplete ) {
				var wrappedOnComplete = options.onComplete;
				// für jeden aufruf muss eine neue globale funktion erzeugt werden, um überschneidungen zu vermeiden
				window[ 'flashProxyHandler' + ++this.flashProxyHandlerCount ] = function( response ) {
					try {
						response = JSON.decode( response );
					} catch( error ) {
						response = null;
					}
					wrappedOnComplete( response );
				}.bind( this );
				options.onComplete = 'flashProxyHandler' + this.flashProxyHandlerCount;
			}
			if ( options.data ) {
				// data url encoden
				options.data = Hash.toQueryString( options.data );
			}
			flashProxy.request( url, options );
		} else {
			options = options || {};
			options.url = url;
			var data = options.data
			delete options.data;
			if( options.method === 'post' )
				new Request.JSON( options ).post( data );
			else
				new Request.JSON( options ).get( data );
		}
	},
	sendEcard: function( from, to, message, ecard, custom )
	{
		if( this.sendEcardPending ) return;
		this.sendEcardPending = true;
		if ( ( typeof ecard === 'undefined' || ecard === null ) && this.defaultEcard !== null ) {
			ecard = this.defaultEcard;
		} else {
			this.fireEvent( 'sendecard', false );
			this.sendEcardPending = false;
			return false;
		}
		var myData = { 'from': from, 'to': to };
		myData = $merge( myData, this.trackData );
		if ( this.language !== null ) myData.language = this.language;
		if ( this.country !== null ) myData.country = this.country;
		if ( typeof message !== 'undefined' ) myData.message = message;
		if ( typeof custom !== 'undefined' ) myData.custom = custom;
		
		this.doRequest( this.apiurl + 'ecard/' + ecard, {
			data: myData,
			onComplete: function( response ) {
				if ( this.checkApiResponse( response ) ) {
					this.fireEvent( 'sendecard', new Array( true, response ) );
				} else {
					this.fireEvent( 'sendecard', new Array( false, response ) );
				}
				this.sendEcardPending = false;
			}.bind( this )
		} );
	},
	confirmEcard: function( ecard, token )
	{
		var myData = { 'token': token };
		myData = $merge( myData, this.trackData );
		this.doRequest( this.apiurl + 'ecard/' + ecard + '/confirm', {
			data: myData,
			onComplete: function( response ) {
				if ( this.checkApiResponse( response ) ) {
					this.fireEvent( 'confirmecard', new Array( true, response ) );
				} else {
					this.fireEvent( 'confirmecard', new Array( false, response ) );
				}
			}.bind( this )
		} );
	},
	confirmLottery: function( lottery, token )
	{		
		this.doRequest( this.apiurl + 'lottery/' + lottery + '/confirm', {
			data: { 'token': token },
			'onComplete': function( response ) {
				if ( this.checkApiResponse( response ) ) {
					this.fireEvent( 'confirmlottery', new Array( true, response ) );
				} else {
					this.fireEvent( 'confirmlottery', new Array( false, response ) );
				}
			}.bind( this )
		} );
	},
	isDataError: function( response )
	{
		if ( typeof response === 'undefined' || response === null ) return false;
		return ( typeof response.code !== 'undefined' && response.code === this.STATUS_DATA_ERROR );
	},
	getErrorFields: function( response )
	{
		var fields = {};
		for( var i = 0; i < response.result.length; i++ ) {
			fields[ response.result[ i ].param ] = true;
		}
		return fields;
	},
	checkApiResponse: function( response )
	{
		if ( typeof response === 'undefined' || response === null ) return false;
		if ( typeof response.code === 'undefined' ) return false;
		if ( typeof response.status === 'undefined' ) return false;
		if ( response.code !== 0 ) return false;
		if ( response.status !== 'OK' ) return false;
		return true;
	},
	getCookieData: function( ident ) {
		return Cookie.read( 'missioncontrol[' + ident + ']' );
	},
	setCookieData: function( ident, value ) {
		return Cookie.write( 'missioncontrol[' + ident + ']', value );
	},
	getCookieCheckResult: function()
	{
		if ( this.cookieTest === null ) {
			return 'unchecked';
		} else if ( this.cookieTest === false ) {
			return 'failed ' + this.getCookieData( this.cookieTestName );
		} else {
			return 'passed';
		}
	},
	getPid: function()
	{
		return this.pid;
	}
});
