//////////////////////////////////////////////////////
// Wrapper for etestingplayer ////////////////////////
//////////////////////////////////////////////////////

etestingplayer = {
	
	//////////////////////////////////////////////
	//////// CONFIGURATION DEFAULT VALUES ////////
	//////////////////////////////////////////////
	
    // Notification environment either courseManager or default one for SITOS and CL
    notification : "default"
	,debugMode : false
	,courseTitle : "Bitmedia"
	,timeLimit : 2700
	,LESSON_STATUS_SUCCESS : "passed"
	
	,flashContent : null
	
	// Custom Close function ... will be overwritten from configParams if its present there
	,customClose : function(){
		window.close();	
	}
	
	////////////////////////////////////////////////////////////////////
	////////////// Public methods //////////////////////////////////////
	////////////////////////////////////////////////////////////////////
     
    // Find out which environment is present
    ,checkNotification : function(){
		// Guessing enviroment
		if (typeof parent.courseManager !== "undefined" || typeof window.courseManager !== "undefined") {
			this.notification = "courseManager";
		}else if (typeof window.contentlauncher !== "undefined") {
			this.notification = "contentLauncher";
		}else if (typeof scormManager.getParam("sitosVersion") !== "undefined") {
			//TODO: Sitos detection works not fine
			this.notification = "sitos";
		}else if (typeof window.openDatabase !== "undefined") {
			// A bit ugly, but makes it to work for Reload Player
			this.notification = "reloadPlayer";
		}
    }
	
	// CLOSE CONTENT 
    ,closeContent : function(showCourseManagerReport){
          switch(this.notification){
	          case "courseManager" :
			  		// Set true in closeItem for open the report view	
	      		   parent.courseManager.closeItem(showCourseManagerReport);
	      	  break;
			  case "sitos" :
			  case "contentLauncher" :
			  case "reloadPlayer" :		
	          default :
	               if (typeof scormManager.finish !== "function"){return false;} 	
				   this.trace("executing scormManager.finish from player wrapper");
				   scormManager.finish();
			  break;	
         }
    }
	
	// Close depending on environment
	,closeEnvironment : function(){
		switch (this.notification) {
			case "courseManager":
				// Is done by parent.courseManager.closeItem(); so do nothing
			break;
			case "sitos" :
				// Close for SITOS
				switch(scormManager.getParam("sitosVersion")){
					case "2" :
					case "3.7" :
					case "3.8" :
					default :
						top.opener.parent.document.location.reload();
						top.window.close();		
				}
			break;
		  	case "contentLauncher" :
				// Close for Content Launcher
				window.top.frames[1].setTimeout('ShowInfoTab()', 100);
			break;
			case "reloadPlayer" :
				// Close for reload player
				top.window.text.location.href="suspended.htm";
			break;
			default:
				// Call here the close function in your favourite flavour, is set in configParams
				this.customClose();
			break;
		}
		this.trace("closeEnvironment was done with notification "+this.notification);
	}
	
    // No params for this method
    ,commitChanges : function(){
         switch(this.notification){
	         case "courseManager" :
	            parent.commitChanges();
	         break;
			 case "sitos" :
			 case "contentLauncher" :
			 case "reloadPlayer" :
	         default :
	          	if (typeof scormManager.saveData !== "function"){return false}
	          	scormManager.saveData();
			 break;
         }
    }
	
    // For etest force to passed
    ,forcePassedTest : function(){
         switch(this.notification){
	         case "courseManager" :
	            this.setMaxPoints(1);
	    	    this.setMinPoints(0);
	    	    this.setUserScore(1);
				// For OLP courseManager set the item status itself, so setting points pass the test! 
	         break;
			 case "sitos" :
			 case "contentLauncher" :
			 case "reloadPlayer" :
	         default :
	          	if (typeof scormManager.setParam !== "function"){return false}
	          	this.setMaxPoints(1);
	          	this.setMinPoints(0);
	          	this.setUserScore(1);
	          	scormManager.setParam("status", this.LESSON_STATUS_SUCCESS);
	          	this.setMaxPoints = 
	          	this.setMinPoints = 
	          	this.setUserScore = function(points){return false;}
			 break;
         }
    }
	
	// Initialization interests of params either from LMS or if present from configParams
	// Be careful, order of interest params is important as well
    ,initializationInterestParams : [
			{paramAlias: "debugMode",		 		prop: "debugMode",			target:"scormManager"}
			,{paramAlias: "debugMode",		 		prop: "debugMode",			target:"etestingplayer"}
			,{paramAlias: "userName", 	 			prop: "userName",			target:"scormManager"}
    		,{paramAlias: "userId", 		    	prop: "userId",				target:"scormManager"}
    		,{paramAlias: "timeLimit", 		    	prop: "timeLimit",			target:"scormManager"}
			,{paramAlias: "timeLimit", 		    	prop: "timeLimit",			target:"etestingplayer"}
    		,{paramAlias: "masteryScore", 	    	prop: "masteryScore",		target:"scormManager"}
    		,{paramAlias: "suspendData", 		    prop: "suspendData", 		target:"scormManager"}
			,{paramAlias: "courseTitle",			prop: "courseTitle",		target:"etestingplayer"}
			// Initialization interest functions
			,{paramAlias: "customClose",			prop: "customClose",		target:"etestingplayer"}		
	 ]
	 
    // PLAYER WRAPPERS SHARED METHODS 
    // INITIALIZE
    ,initialize : function(){
		 this.checkNotification();
         switch(this.notification){
	         case "courseManager" :
			 	// Course manager handles the interestsParams of the single SCO, so only add target etestingplayer!
				this.getInitializationInterestParams("etestingplayer");
	         break;
			 case "sitos" :
			 case "contentLauncher" :
			 case "reloadPlayer" :
	         default :
				this.getInitializationInterestParams("all");
			 break;	      
         }
		 this.trace("notification detected:" + this.notification);
		 this.setDocumentTitle();  
    }
	
	// Get params for target "all" or only "etestingplayer"
	,getInitializationInterestParams : function(target){
		// Assign initializationInterestParams or configParams
        if(target == "all" && typeof scormManager.getParam !== "function"){return false}
      	for(var i in this.initializationInterestParams){
      		var param = this.initializationInterestParams[i].paramAlias;
      		var prop = this.initializationInterestParams[i].prop;
			var tar = this.initializationInterestParams[i].target; 
      		//this.trace("init etestingplayer [param:"+param+" value:"+prop+" target:"+tar+"]");
      		if(typeof param === "string" && typeof prop === "string" && typeof tar === "string"){
				var value = (target == "all") ? scormManager.getParam(param, prop) : "";
				// Check if a matching config value exists
				for(var j in configParams){
					var configValue = String(j);
					if(configValue == param || configValue == prop){
						// Overwrite maching config param in value
						value = configParams[param] || configParams[prop];
						this.trace("Param "+param+" is overwritten from config with value "+value);	
					}
				}		
      			//this.trace("initialised parameter:"+param+" with value:"+value);
				// write the param to the right target
      			if(target == "all" && tar == "scormManager" && typeof scormManager[prop] !== "undefined"){
      				scormManager[prop] = value;
      				this.trace("setted "+prop+" to scormManager with value: "+value);
      			}else if(tar == "etestingplayer" && typeof this[prop] !== "undefined"){
      				this[prop] = value;
      				this.trace("setted "+prop+" to etestingplayer with value: "+value);
				}else if(target == "etestingplayer"){
					this.trace("Environmet is courseManager so param "+param+" is not written to scormManager");	
				}else{
					this.trace("ERROR: setting param:"+param+" to "+tar+" failed");
				}
      		}
      	}	
	}
	
	,getSuspendData : function(){
		switch(this.notification){
	         case "courseManager" :
	    		// Do nothing
	    		void(0);
	         break;
			 case "sitos" :
			 case "contentLauncher" :
			 case "reloadPlayer" :
	         default :
			 	if (typeof scormManager.getParam !== "function"){return false}
	          	var suspendData = scormManager.getParam("suspendData");
			 break;
        }
		return suspendData;
	}
	
	,getScormRTEValues : function(){
		switch(this.notification){
	         case "courseManager" :
		 		// Set userName, userId, masteryScore and timeLimit
		 		this.flashContent.setUserName(scormManager.getParam("userName"));
				this.flashContent.setUserId(scormManager.getParam("userId"));
    			this.flashContent.setMasteryScore(parent.courseManager.masteryScore);
				this.flashContent.setItemStatus(parent.courseManager.currentItem.status.success.toString());
				this.flashContent.setTimeLeft(this.timeLimit);
	         break;
			 case "sitos" :
			 case "contentLauncher" :
			 case "reloadPlayer" :
	         default :
          		// Set userName, userId and masteryScore
				this.flashContent.setUserName(scormManager.getParam("userName"));
				this.flashContent.setUserId(scormManager.getParam("userId"));
				this.flashContent.setMasteryScore(scormManager.getParam("masteryScore"));
				this.flashContent.setItemStatus(scormManager.getParam("status"));
				// Set timeLimit either from suspendData or scorm param
				var suspendData = this.getSuspendData();
				this.timeLimit = (suspendData !== "undefined" && suspendData !== "") 
						          ? Number(suspendData) 
						          : Number(scormManager.getParam("timeLimit"));
				this.flashContent.setTimeLeft(this.timeLimit);
			 break;
         }
	}
	
	,getObjectives : function(){
		switch(this.notification){
	         case "courseManager" :
			 	// Do nothing
	    		void(0);
	         break;
			 case "sitos" :
			 case "contentLauncher" :
			 case "reloadPlayer" :
	         default :
				var ret = [];
				var count = scormManager.getNonAliasedParam("cmi.objectives._count");
				for(var i=0; i<count; i++)
				{
					var oObjective = {
						id: scormManager.getNonAliasedParam("cmi.objectives."+i+".id"),
						max: scormManager.getNonAliasedParam("cmi.objectives."+i+".score.max"),
						min: scormManager.getNonAliasedParam("cmi.objectives."+i+".score.min"),
						raw: scormManager.getNonAliasedParam("cmi.objectives."+i+".score.raw"),
						status: scormManager.getNonAliasedParam("cmi.objectives."+i+".status")
					}
					ret.push(oObjective);
				}
				this.flashContent.setObjectives(ret);
			 break;
        }
	}
			
	,getScormVersion : function(){
		var vers = (scormManager.API.version == "") ? "N/A" : scormManager.API.version;
		this.flashContent.setScormVersion(vers);
	}
			
	,getScormAdapterStatus : function(){		
		this.flashContent.setScormAdapterStatus(scormManager.API.isConnected.toString());
	}
	
	,useStoredObjectives : function(){
	   	return (Number(scormManager.getNonAliasedParam("cmi.objectives._count")) > 0);
	}
	
    // soundStatus is "ON"|"OFF"
    // if no param provided or incorrect type, puts the audio "ON"
    ,setAudioPref : function(soundStatus){
         switch(this.notification){
	         case "courseManager" :
	    		   parent.courseManager.setAudioPref(soundStatus);
	         break;
			 case "sitos" :
			 case "contentLauncher" :
			 case "reloadPlayer" :
	         default :
	          	if (typeof scormManager.setParam !== "function"){return false}
	          	if (typeof soundStatus !== "string"){soundStatus = "ON"}
	          	scormManager.setParam("userAudioPref", soundStatus);
			 break;
         }
    }
	
	// Set document title
	,setDocumentTitle : function(){
		switch(this.notification){
			case "sitos" :
			case "contentLauncher" :
			case "courseManager" :
			case "reloadPlayer" :
				// Title is already shown from environment
			break;
			default :
				if (typeof this.courseTitle === "string" && this.courseTitle != ""){
					document.title = this.courseTitle;
				} else {
					document.title = "Bitmedia";
				}
			break;	
		}
	}
	
    // Set flashvars for Etestingplayer
    ,setFlashvars : function(){
         switch(this.notification){
	         case "courseManager" :
	            // No Flashvars are used
	         break;
			 case "sitos" :
			 case "contentLauncher" :
			 case "reloadPlayer" :
	         default :
	            // Set required flashvars (adding more has no effect unless player implements them!)
	      		return [ {name: "suspendData"    ,value: scormManager.getParam("suspendData")}
	                     ,{name: "objectives"    ,value: useStoredObjectives().toString()}
	            	   ];
			 break;
         }
    }
	
    // no params for this method. Lesson status will be calculated based on minPoints, maxPoints, and userPoints
    ,setLessonStatus : function(){
         switch(this.notification){
	         case "courseManager" :
	            //For OLP courseManager set the item status itself, so do nothing!
	         break;
			 case "sitos" :
			 case "contentLauncher" :
			 case "reloadPlayer" :
	         default :    
	          	if (typeof scormManager.setParam !== "function"){return false}
	          	scormManager.setParam("status");
			 break;
         }	
    }
	
    // param should come as a number
    ,setMaxPoints : function(maxPoints){
         switch(this.notification){
	         case "courseManager" :
	    		   parent.courseManager.setItemMaxPoints(maxPoints);
	         break;
			 case "sitos" :
			 case "contentLauncher" :
			 case "reloadPlayer" :
	         default :   
	          	if (typeof scormManager.setParam !== "function"){return false}
	          	if (typeof maxPoints !== "number"){maxPoints = Number(maxPoints)}
	          	scormManager.setParam("maxPoints", maxPoints);
			 break;
         }
    }
	
    // param should come as a number
    ,setMinPoints : function(minPoints){
         switch(this.notification){
	         case "courseManager" :
	    		   parent.courseManager.setItemMinPoints(minPoints);
	         break;
			 case "sitos" :
			 case "contentLauncher" :
			 case "reloadPlayer" :
	         default :
	          	if (typeof scormManager.setParam !== "function"){return false}
	          	if (typeof minPoints !== "number"){minPoints = Number(minPoints)}
	          	scormManager.setParam("minPoints", minPoints);
			 break;
         }
    }
	
    // no params for this method. Session duration will be calculated based on the interval SCORM API connected - Current time 
    ,setSessionDuration : function(){
         switch(this.notification){
	         case "courseManager" :
			 	parent.setSessionDuration();
	         break;
			 case "sitos" :
			 case "contentLauncher" :
			 case "reloadPlayer" :
	         default :    
	          	if (typeof scormManager.setParam !== "function"){return false}
	          	scormManager.setParam("duration");
			 break;
         }
    }
	
    // Signals sent from the player 
    // param should come as a string
    ,setSessionLocation : function(location){
         switch(this.notification){
	         case "courseManager" :
			 	parent.setSessionLocation();
	         break;
			 case "sitos" :
			 case "contentLauncher" :
			 case "reloadPlayer" :
	         default :
	          	if (typeof scormManager.setParam !== "function"){return false}
	          	if (typeof location !== "string"){location = String(location)}
	          	scormManager.setParam("location", location);
			 break;
         }
    }
	
    // param should come as a number
    ,setUserScore : function(userScore){
         switch(this.notification){
	         case "courseManager" :
	    	 	parent.courseManager.setItemUserPoints(userScore);
	         break;
			 case "sitos" :
			 case "contentLauncher" :
			 case "reloadPlayer" :
			 default :
			 	if (typeof scormManager.setParam !== "function"){return false}
	          	if (typeof userScore !== "number"){userScore = Number(userScore)}
	          	scormManager.setParam("userPoints", userScore);
			 break;
         }
    }
	
	,storeLearnpath : function(learnpathItemsStr){
		switch (this.notification){
			case "courseManager" :
		 		parent.courseManager.handleLearnpath(learnpathItemsStr);
	        break;
			case "contentLauncher" :
				// Is made by the player itself, he store it in a LSO (local shared object) in the user data
				// Take care of set store in suspendDataAndLSO in params.jso of etesting
			break;
			case "sitos" :
			case "reloadPlayer" :
	        default :
				// Learnpath is not possible to store in this environments
			break;
		}
	}
	
	,setCompletion : function(completionStr){
		switch (this.notification){
			case "courseManager" :
		 		// Force item status passed if test is completed
				if(completionStr == "completed"){
					parent.courseManager.setItemStatus("", true);					
				}
	        break;
			case "sitos" :
			case "contentLauncher" :
			case "reloadPlayer" :
	        default :
				if (typeof scormManager.setParam !== "function"){return false}
	        	scormManager.setParam("status", completionStr);
			break;
		}
	}

	,setSatisfaction : function(satisfactionStr){
		switch (this.notification){
			case "courseManager" :
		 		// ?
	        break;
			case "sitos" :
			case "contentLauncher" :
			case "reloadPlayer" :
	        default :
	        	//scormManager.setParam(satisfaction);
			break;
		}
	}
	
	,setTimeLeft : function(timeLeft){
		switch (this.notification){
			case "courseManager" :
		 		// ?
	        break;
			case "sitos" :
			case "contentLauncher" :
			case "reloadPlayer" :
	        default :
	        	// Will be stored as suspend Data
				if (typeof scormManager.setParam !== "function"){return false}
				scormManager.setParam("suspendData", timeLeft.toString());
			break;
		}
	}
	
	,setObjective : function(itemIndex, itemId, itemTitle, itemRaw, itemMin, itemMax, itemStatus, itemTemplate){
		switch (this.notification){
			case "courseManager" :
		 		// ?
	        break;
			case "sitos" :
			case "contentLauncher" :
			case "reloadPlayer" :
	        default :
				if (typeof scormManager.setNonAliasedParam !== "function"){return false}
				
				// SITOS
				scormManager.setNonAliasedParam("sitos.objectives."+itemIndex+".id", itemId);
				scormManager.setNonAliasedParam("sitos.objectives."+itemIndex+".title", itemTitle);
				scormManager.setNonAliasedParam("sitos.objectives."+itemIndex+".score.raw", itemRaw);
				scormManager.setNonAliasedParam("sitos.objectives."+itemIndex+".score.min", itemMin);
				scormManager.setNonAliasedParam("sitos.objectives."+itemIndex+".score.max", itemMax);
				scormManager.setNonAliasedParam("sitos.objectives."+itemIndex+".status", itemStatus);
				scormManager.setNonAliasedParam("sitos.objectives."+itemIndex+".template", itemTemplate);
				
				// CMI MODEL
				scormManager.setNonAliasedParam("cmi.objectives."+itemIndex+".id", itemId);
				scormManager.setNonAliasedParam("cmi.objectives."+itemIndex+".score.raw", itemRaw);
				scormManager.setNonAliasedParam("cmi.objectives."+itemIndex+".score.min", itemMin);
				scormManager.setNonAliasedParam("cmi.objectives."+itemIndex+".score.max", itemMax);
				scormManager.setNonAliasedParam("cmi.objectives."+itemIndex+".status", itemStatus);
			break;
		}
	}
	
	// Trace for debug
	,trace : function(info){
		if (this.debugMode === true) {
			var tracePrefix = "[etestingplayer] ";
			if (window.console && window.console.firebug) { // Firebug
				if(typeof info == "string"){
					console.log(tracePrefix+info);
				}else{
					console.debug(tracePrefix+info);
				}
			}else if (window.console) { 					// Safari
				if(typeof info == "string"){
					window.console.log(tracePrefix+info);
				}else{
					//window.console.debug(tracePrefix+info);
				}
			}else { 										// Ugly browsers a.k.a IE any version
				alert(tracePrefix+info.toString());
			}
		}
	}
}