/*
 * Copyright (c) contentmetrics GmbH, 2008, 2009
 * THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
 * APPLICABLE LAW.  EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
 * HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
 * OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
 * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE.  THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
 * IS WITH YOU.  SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
 * ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
 *
 * Autor:   Frank Raether, 04-03-2008
 * Code:    JavaScript Library zum Tracken von generischen Events in Flash Applikationen mit Omniture SiteCatalyst
 * Kunde:   -
 * Version: V4.0, last changed 04.08.2009
 */

/* constructor for a  flashtracking object
 * Configuration Settings
 * A List of names, determing the following transitions:
 * csobject 	-	Omniture Object Name as String
 * cfile		-	Variable for FlashName
 * cscene		-	Variable for FrameName
 * ctime		-	Variable for Sekunde
 * caction		-	Variable for EventBezeichnung
 * cevent		-	Event for counting EventBezeichnung
 * ccookiename	-	Name of the Cookie
 * csearchterm	-	Variable for Searchterms in Flash Application
 * clinkname	-	Name of a link.
 *
 * Setting linkname will cause Flash Events to be tracked as custom links rather than pageviews
 * An empty cookiename will switch use of cookies off, capturing every single call,
 * regardless of Parameter 'UseCookie'
 *
 */
function cmFlashTracker(csobject, cfile, cscene, ctime, caction, cevent, ccookiename, csearchterm, clinkname) {

	this.run = 0;
	// must be defined before usage!
	this.tmp = ""
		+	"{\n"
		+	"	var elem = document.getElementById('ftdebug');\n"
		+	" 	if ( elem == null || typeof(elem) == 'undefined' ) {\n"
		+	"		var s = dstring.replace(/;/g,\";\\n\");\n"
		+	"		s = s.replace(/,/g,\",\\n\");\n"
		+	"		s = s.replace(/:/g,\":\\n\");\n"
		+	"		if ( this.debug == true ) {\n"
		+	"			alert(s);\n"
		+	"		}\n"
		+	"	} else {\n"
		+	"		if ( this.debug == true ) elem.innerHTML += ('<br><br>'+dstring+'');\n"
		+	"	}\n"
		+	"}";
	this.msg = new Function ("dstring", this.tmp);
	
	// Version for internal CVS
	this.myVersion 		= "V4.0";
	this.sobject 		= csobject
	this.file 			= cfile;
	this.scene 			= cscene;
	this.time 			= ctime;
	this.action 		= caction;
	this.event 			= cevent;
	this.cookiename 	= ccookiename;
	this.searchterm 	= csearchterm;
	this.linkname		= typeof(clinkname)=="undefined"?false:clinkname;

	this.cmft_plugin 	= null;

	// default settings for the event to action map
	this.e2aMap = new Array();
	this.e2aMap[0] = new Object();	// 0 is the default element !
	this.e2aMap[0].action = "*";
	this.e2aMap[0].event = this.event;
	this.e2aMapHigh = 0;

	// turn on debugging
	this.debug 			= false;
	// debugging on demand
	//this.debug 			= document.location.search.indexOf('cm_debug=true')>-1;

	// cookie settings
	this.flashfromcookiecaptured = false;

	
	//this.msg("Linkname: " + this.linkname);

	/*
	 * The function captureFlashEvents should be called with appropriate values from out a flash app whenever
	 * button clicks a/o player events shall be tracked down to e given tracking system. Current implementation supports
	 * omniture sitecatalyst versions H.x. Support of other tracking tools can be adopted by changing the generic code
	 * w/o changing anything within ActionScript of the Flash app's.
	 * This Function should be called with the ActionScript function getUrl(...):
	 * ...
	 *    getUrl("javascript:captureFlashEvents(....)" <javascript:captureFlashEvents(....)> );
	 * ...
	 * The Script needs to be available in the current surrounding HTML page itself and must apply to the Flash
	 * sandbox model.
	 *
	 * Parameters:
	 * FlashName        -        Name of Flash File as String
	 * Scene	        -        Name of a Frame/scen if applicable, or % of film exposed
	 * Sekunde          -        Time since start for Media as String, format should be something like '00:00'
	 * EventBezeichnung -        Name of the Event as String
	 * UseCookie        -        wheher data should be stored in a cookie for the next page to
	 *                           submit data to the underlying tracking system as Boolean
	 */
	//flashscene enthaelt ggf. prozentangabe
	this.tmp = ""
		+	"{\n"
		+	"		this.run++;\n"
		+	"	    this.msg(' ' + this.run + ' ------------------ ');\n" 
		+	"	    var s_object=this.sobject+'.';\n" 
		+	"	    if(s_object=='.')s_object='';\n"
		+	"		var FlashName = flashfile;\n"
		+	"		if ( this.file == 'products' ) \n"
		+	"			flashfile = \";\" + FlashName;\n"
		+ 	"		var fire = '';\n"
		+	"	    var ex =  s_object + this.file   + '=\"' + flashfile   + '\";';\n" 
		+	"	        ex += s_object + this.scene  + '=\"' + flashscene  + '\";';\n" 
		+	"	        ex += s_object + this.time   + '=\"' + flashtime   + '\";';\n" 
		+	"	        ex += s_object + this.action + '=\"' + flashaction + '\";';\n" 
		+	"	    if(searchterm){    \n" 
		+	"	        ex += s_object + this.searchterm + '=\"' + this.normalizeString(searchterm) + '\";';\n" 
		+	"		}    \n"
		+	"		var cevent = this.getActionEvent(flashaction);\n"
		+	"		var actionevent = false;\n"
		+	"		if ( cevent != null ) {\n"
		+	"			actionevent = true;\n"
		+	"			flashaction = false;\n"
		+	"		}\n"
		+	"	    if(flashaction){\n" 
		+	"	    	ex+='if(!'+s_object+'events){'+s_object+'events=\"'+this.event+'\";}';\n" 
		+	"	    	ex+='else if('+s_object+'events.indexOf(\"'+this.event+'\")==-1){'+s_object+'events+=\",\"+\"'+this.event+'\";}';\n"
		+	"		}\n"
		+	"	    if(actionevent){\n" 
		+	"	    	ex+='if(!'+s_object+'events){'+s_object+'events=\"'+cevent+'\";}';\n" 
		+	"	      	ex+='else if('+s_object+'events.indexOf(\"'+cevent+'\")==-1){'+s_object+'events+=\",\"+\"'+cevent+'\";}';\n" 
		+	"	    }\n" 
		+	"	    this.msg('cm_captureflash '+ex);\n" 
		+	"	    if(UseCookie && this.cookiename) { \n"
		+	"			this.msg('Track with cookie');\n"
		+	"	        var cookieval=ex;\n" 
		+	"	        ex=s_object+ \"c_w('\" + cookiename + \"','\" + cookieval + \"',0);\";\n" 
		+	"	    } else {\n"
		+	"			this.msg('Track direct');\n"
		+	"			if ( this.linkname != false ) {\n"
		+	"	        	ex += s_object + \"linkTrackVars='\" + this.file + \",\" + this.scene + \",\" + this.time + \",\" + this.action + \",\" + this.searchterm + \",events';\";\n" 
		+	"				ex += s_object + \"linkTrackEvents='\" + this.event + \",\" + this.flashstarts + \"';\";\n" 
		+	"				fire = s_object + \"tl(null,'o','\" + this.linkname +\"');\";\n"
		+	"			} else {\n"
		+	"				fire = this.analyticsEvent(FlashName, '');\n"
		+	"			}\n"
		+	"	    }\n"
		+	"	    this.msg('will fire: '+ex);\n" 
		+	"	    eval(ex);\n"
		+	"		ex='';\n"
		+	"		this.msg('plugin: ' + typeof(this.cmft_plugin));\n"
		+	"		if ( typeof(this.cmft_plugin) == 'function' ) {	\n"
		+	"			try {\n"
		+	"				this.cmft_plugin();\n"
		+	"			} catch (e) {\n"
		+	"				alert('cmft_plugin error: ' + e);\n"
		+	"			}\n"
		+	"		}\n"
		+	"		eval(fire);\n"
		+	"		fire = '';\n"
		+	"	    this.flashfromcookiecaptured=true;\n" 
		+	"		ex+=s_object+\"linkTrackVars\"+'=\"None\";';\n" 
		+	"		ex+=s_object+\"linkTrackEvents\"+'=\"None\";'\n" 
		+	"		ex+=s_object+this.file+'=\"\";';\n" 
		+	"	  	ex+=s_object+this.scene+'=\"\";';\n" 
		+	"	   	ex+=s_object+this.time+'=\"\";';\n" 
		+	"	  	ex+=s_object+this.action+'=\"\";';\n" 
		+	"		ex+=s_object+this.searchterm+'=\"\";';\n" 
		+	"		ex+=s_object+'events=this.delevent('+s_object+'events,\"'+this.event+'\");';\n" 
		+	"		ex+=s_object+'events=this.delevent('+s_object+'events,\"'+cevent+'\");';\n" 
		+	"		this.msg('garbage: '+ex);\n" 
		+	"	   	eval(ex);\n" 
		+	"}";
	this.captureFlashEvents = new Function("flashfile","flashscene","flashtime","flashaction","UseCookie","searchterm", this.tmp );

	this.tmp = ""
		+	"{\n"
		+	"	this.msg(\"delete event: \" + ev);\n"
		+	" 	if ( typeof(events) == 'undefined' || typeof(ev) == 'undefined') return events;\n"
		+	"	var eva = events.split(',');\n"
		+	"	for ( var i = 0; i < eva.length; i++ ) {\n" 
		+	"		if ( eva[i] == ev ) {\n"
		+	"			eva.splice(i,1);\n"
		+	"			i--;\n"
		+	"		}\n"	
		+	"	}\n"
		+	"	this.msg(\"events after: \" + eva.join(','));\n"
		+	"	return eva.join(',');\n" 
		+	"}";
	this.delevent = new Function("events","ev", this.tmp );

	this.tmp = "\n" 
		+	"{\n" 
		+	"var s_object=this.sobject+'.';\n" 
		+	"if(s_object=='.')s_object='';\n" 
		+	"if(!this.flashfromcookiecaptured){\n" 
		+	"    var cookiename=this.cookiename;\n" 
		+	"    var cookieval='';\n" 
		+	"    ex=\"cookieval=\" +s_object+ \"c_r('\" +cookiename+ \"');\";\n" 
		+	"    this.msg('this.captureflashfromcookie '+ex);\n" 
		+	"    eval(ex);\n" 
		+	"    this.msg('this.captureflashfromcookie '+cookieval);\n" 
		+	"    if(cookieval){\n" 
		+	"    	eval(cookieval);"
	   	+	"       cookieval='';\n" 
		+	"    	ex=s_object+ \"c_w('\" +cookiename+ \"','\" +cookieval+ \"',0);\" ;\n" 
		+	"    	eval(ex);\n" 
		+	"    	this.msg('this.captureflashfromcookie '+ex);\n" 
		+	"    	this.flashfromcookiecaptured=true;\n" 
		+	"    }"
	 	+	"}else{	\n" 
		+	"	ex=s_object+this.file+'=\"\";';\n" 
		+	"	ex+=s_object+this.scene+'=\"\";';\n" 
		+	"	ex+=s_object+this.time+'=\"\";';\n" 
		+	"	ex+=s_object+this.action+'=\"\";';\n" 
		+	"	ex+=s_object+this.searchterm+'=\"\";';\n" 
		+	"	this.msg('this.captureflashfromcookie '+ex);\n" 
		+	"	eval(ex);\n" 
		+	"	}\n" 
		+	"}";
		
	this.captureflashfromcookie = new Function ("", this.tmp );

	this.tmp = ""
		+	"{\n"
		+	"	return (st=='\"\"')?'':st;\n"
		+	"}";
	this.antiquote = new Function ("st", this.tmp );

	this.tmp = ""
		+	"{"
		+	"	var pn = '';\n"
		+	"	try { pn = eval(this.sobject + \".pageName\"); } catch(e) {}\n"
		+	"	var ex = this.sobject + \" = s_gi(s_account);\";\n"
		+	"	ex += this.sobject + \".pageName='\" + ((typeof(pn)!='undefined'&&pn!='')?pn:p) + \"';\";\n"
		+	"	ex += this.sobject + \".pageType='\" + t + \"';\";\n"
		+	"	ex += \"var s_code=\" + this.sobject + \".t();\";\n"
		+	"	ex += \"if(s_code)document.write(s_code);\";\n"
		+	"	return(ex);\n"
		+	"}";
	this.analyticsEvent = new Function ("p","t", this.tmp );

	this.tmp = ""
		+	"{"
		+	"	this.msg('FilmName='+FilmName+', EventBezeichnung='+EventBezeichnung+', Zeit='+Zeit+', Prozent='+Prozent+'searchterm='+searchterm);"
		+	"	this.captureFlashEvents(FilmName,antiquote(Prozent),antiquote(Zeit),antiquote(EventBezeichnung),'',antiquote(searchterm));"
		+	"}";	
	this.analyticsFlashEvent = new Function ("FilmName", "EventBezeichnung", "Zeit", "Prozent", "UseCookie", "searchterm", this.tmp	);

	/*
	 * Normalisiert strings, z.B. für Suchworttracking
	 * @param {string}s_in Suchwort wie eingetippt
	 * @returns {string} Normalisiertes Suchwort
	 */
	this.tmp = ""
		+	"{\n"
		+	"	var st = s_in;\n"
		+	"	if ( typeof(s_in) != 'undefined' ) {\n"
		+	"    st=s_in.toLowerCase();	//kleinschreibung\n"
		+	"    while(st.indexOf(' ')==0)st=st.substr(1,st.length-1);	//führende leerzeichen raus\n"
		+	"    while(st.substr(st.length-1,1)==' ')st=st.substr(0,st.length-1);	//schliessende leerzeichen raus\n"
		+	"   	while(st.match(/[ ]{2}/))st=st.replace('  ',' ');	//doppelte leerzeichen raus\n"
		+	"    st=st.replace(/ä/ig,'ae');	//ersetze umlaute\n"
		+	"    st=st.replace(/ö/ig,'oe');	//ersetze umlaute\n"
		+	"    st=st.replace(/ü/ig,'ue');	//ersetze umlaute\n"
		+	"    st=st.replace(/ß/ig,'ss');	//ersetze esszet\n"
		+	"	}\n"
		+	"   return st;\n"
		+	"}";
	this.normalizeString = new Function("s_in", this.tmp);

	/*
	 * search for an action and get the according event from the event to action map
	 * null if not specified, default needs to be pulled explicitly
	 */
	this.tmp = "" 
		+	"{\n"
		+	"	for ( var i = 1; i < this.e2aMap.length; i++ ) { \n"
		+ 	"		if ( (this.e2aMap[i]).action == caction ) { \n"
		+	"			this.msg('mapped: ' + caction + ' - ' + (this.e2aMap[i]).event);\n"
		+	"			return (this.e2aMap[i]).event;\n"
		+	"		}\n"
		+	"	}\n"
		+	"	return null;\n"
		+	"}";
	this.getActionEvent = new Function ( "caction", this.tmp);

	/*
	 * add an action / event tupel to the map
	 */
	this.tmp = ""
		+	"{\n"
		+	"	this.e2aMapHigh++;\n"
		+	"	this.e2aMap[this.e2aMapHigh] = new Object();\n"
		+	"	this.e2aMap[this.e2aMapHigh].action = caction;\n"
		+	"	this.e2aMap[this.e2aMapHigh].event = cevent;\n"
		+	"}";
	this.setActionEvent = new Function ( "caction", "cevent", this.tmp);

	this.tmp = "";
	
} // cm_flashtracking Object

// now the methods can be used like
// cm_ft.captureFlashEvents(...);
//
// the name of the object may be changed both in this file and the Flash Application to be tracked !
//
// DPAG Spezifika:

// create the flash tracking Object PRIOR TO ALL OTHER ACTIONS!
var cm_ft = new cmFlashTracker(	"wpmsc",	// sitecatalyst object name
                                "prop31",	// flash file name
                                "prop32",	// scene name
                                "prop33",	// seconds since start
                                "prop34",	// user action name
                                "event33",	// # of user actions unless start or end
                                 null,		// name of cookie, unused
                                 null,		// internal search term, unused
                                 false);	// customlink instance name, unused


cm_ft.setActionEvent("playClick", "event31");
cm_ft.setActionEvent("FilmEnde", "event32");

function thePlugin()
{
	// event1 abschalten (pageView Zählung in der wpmsc plugin section)
	wpmsc.isPageView = false;
	// eVars setzen.
	wpmsc.eVar23 = wpmsc.prop31;
	// eVars mit name des Films voran
	wpmsc.eVar24 = wpmsc.prop31 + ":" + wpmsc.prop32;
	wpmsc.eVar25 = wpmsc.prop31 + ":" + wpmsc.prop33;
	wpmsc.eVar26 = wpmsc.prop31 + ":" + wpmsc.prop34;

	// nur zum test des try/catch Blocks:
	// in Produktivumgebung löschen!
	// if ( kaputttesten )
	// 	wpmsc.pageName = TestVariable_Die_Es_nicht_Gibt
	// bis hier
}
cm_ft.cmft_plugin = thePlugin;		// ACHTUNG: NICHT thePlugin() weil wir es ja NICHT HIER AUFRUFEN sondern ZUWEISEN WOLLEN!
									//				                                                            ^^ !!!

// Ende.
