//////////////////////////////////////////////////////
// Wrapper for matsplayer ////////////////////////////
//////////////////////////////////////////////////////
/*
 *	Last changes by : lkranabetter
 *	needs: 
 *		jsBitLib/wrapper/SCORM/scormManager.js 
 *		jsBitLib/config/configParams.js			
 * 
 */

matsplayer = {
	
	//////////////////////////////////////////////
	//////// CONFIGURATION DEFAULT VALUES ////////
	//////////////////////////////////////////////
	
    // Notification environment either courseManager or default one for SITOS and CL
    notification : "default"
    // Close Button visible true or false
    ,showCloseBtn : false
    // start on last location or on page one
    ,rememberLocation : true
    // Witch kind of counting points or pages to complete the lesson
    ,ROLLUP_POLICY : "points"
	,LESSON_STATUS_SUCCESS : "completed" // Comes from configParams needed for forced passed lesson
	,debugMode : false
	,courseTitle: "Bitmedia"
	
	// 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";
		}
    }
	
	,prepareContent : function(){
		// Chapter exercise and script download link modifications
		var startLink = document.getElementById('startLink');
		var parentThis = this;
		switch (this.notification) {
			case "contentLauncher" :
				startLink.onclick = function(){
					// Forced passed lesson for chapter exercises and scripts
					parentThis.forcePassedLesson();
					// Modify link for content launcher
					var dir = startLink.href.replace("file:///", "");
					var parts = decodeURI(dir.split('/').join('\\'));
					contentlauncher.properties.ShellExecute(parts, 'open');
					// Return false for disable href
					return false;
				}
			break;
			case "courseManager" :
			case "sitos" :
			case "reloadPlayer" :
			default :
				startLink.onclick = function(){
					// Forced passed lesson for chapter exercises and scripts
					parentThis.forcePassedLesson();
				}
			break;
		}	
	}
	
	// CLOSE CONTENT 
    ,closeContent : function(){
          switch(this.notification){
	          case "courseManager" :
			  		// Set false in closeItem for do not open the report view	
	      		   parent.courseManager.closeItem(false);
	      	  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" :
	            return false;
	         break;
			 case "sitos" :
			 case "contentLauncher" :
			 case "reloadPlayer" :
	         default :
	          	if (typeof scormManager.saveData !== "function"){return false}
	          	scormManager.saveData();
			 break;
         }
    }
	
    // For lessons force to passed
    ,forcePassedLesson : 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 lesson! 
	         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:"matsplayer"}
			,{paramAlias: "sendPercents", 	 		prop: "sendPercents",			target:"scormManager"}
    		,{paramAlias: "userName", 		    	prop: "userName",				target:"scormManager"}
    		,{paramAlias: "userId", 		    	prop: "userId",					target:"scormManager"}
    		,{paramAlias: "userPoints", 	    	prop: "userPoints",				target:"scormManager"}
    		,{paramAlias: "location", 		    	prop: "lastLocation", 			target:"scormManager"}
    		,{paramAlias: "userAudioPref", 	 		prop: "lastAudioPref",			target:"scormManager"}
    		,{paramAlias: "suspendData", 	    	prop: "suspendData",			target:"scormManager"}
    		,{paramAlias: "masteryScore", 	 		prop: "masteryScore",			target:"scormManager"}
			,{paramAlias: "lessonStatus", 	 		prop: "lessonStatus",			target:"scormManager"}
			,{paramAlias: "rememberLastProgress", 	prop: "rememberLastProgress",	target:"scormManager"}
			,{paramAlias: "showCloseBtn", 	 		prop: "showCloseBtn",			target:"matsplayer"}
			,{paramAlias: "rememberLocation", 		prop: "rememberLocation",		target:"matsplayer"}
			,{paramAlias: "ROLLUP_POLICY", 	 		prop: "ROLLUP_POLICY",			target:"matsplayer"}
			,{paramAlias: "courseTitle",			prop: "courseTitle",			target:"matsplayer"}
			,{paramAlias: "LESSON_STATUS_SUCCESS", 	prop: "LESSON_STATUS_SUCCESS",	target:"matsplayer"}
			// Initialization interest functions
			,{paramAlias: "customClose",			prop: "customClose",			target: "matsplayer"}		
	 ]
	 
    // 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 matsplayer!
				this.getInitializationInterestParams("matsplayer");
	         break;
			 case "contentLauncher" :
			 	// Check if sendPercent value in configParams is right for content launcher
				if(typeof configParams.sendPercents !== "undefined" && configParams.sendPercents == false){
					configParams.sendPercents = true;
					this.trace("Initialize change configParams.sendPercent to " + configParams.sendPercents);	
				}
				this.getInitializationInterestParams("all");
			 break;
			 case "sitos" :
			 case "reloadPlayer" :
	         default :
				// Check if sendPercent value in configParams is right for sitos
				if(typeof configParams.sendPercents !== "undefined" && configParams.sendPercents == true){
					configParams.sendPercents = false;
					this.trace("Initialize change configParams.sendPercent to " + configParams.sendPercents);	
				}
				this.getInitializationInterestParams("all");
			 break;	      
         }
		 this.trace("notification detected:" + this.notification);
		 this.setDocumentTitle();  
    }
	
	// Get params for target "all" or only "matsplayer"
	,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 matsplayer [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 == "matsplayer" && typeof this[prop] !== "undefined"){
      				this[prop] = value;
      				this.trace("setted "+prop+" to matsplayer with value: "+value);
				}else if(target == "matsplayer"){
					this.trace("Environmet is courseManager so param "+param+" is not written to scormManager");	
				}else{
					this.trace("ERROR: setting param:"+param+" to "+tar+" failed");
				}
      		}
      	}	
	}
	
    // 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 Matsplayer
    ,setFlashvars : function(){
         switch(this.notification){
	         case "courseManager" :
	            // Set required flashvars (adding more has no effect unless player implements them!)
	            if(typeof parent.courseManager === "undefined"){
	      			return [ {name: "lastVisitedPage"   ,value: "1"}
	      	               ,{name: "lastUserPoints"    	,value: 0}
	      	               ,{name: "lastAudioPref"     	,value: "ON"}
	      	               ,{name: "suspendData"       	,value: ""}
	      	               ,{name: "userName"       	,value: "John"}
	      	               ,{name: "userId" 	      	,value: "Doe"}
	      	               ,{name: "showCloseBtn" 	    ,value: "false"}
	      	               ,{name: "lessonResultMode"  	,value: "points"}
	      			       ];
	      		   }else{
	      			return [ {name: "lastVisitedPage"   ,value: this.startLocation()}
	      	               ,{name: "lastUserPoints"    	,value: parent.courseManager.currentItem.score.raw.toString()}
	      	               ,{name: "lastAudioPref"     	,value: parent.courseManager.getAudioPref()}
	      	               ,{name: "suspendData"       	,value: parent.courseManager.getUserNotes()}
	      	               ,{name: "userName"       	,value: parent.scormManager.userName}
	      	               ,{name: "userId" 	      	,value: parent.scormManager.userId}
	      	               ,{name: "showCloseBtn" 	    ,value: (this.showCloseBtn === true) ? "true" : "false"}
	      	               ,{name: "lessonResultMode"  	,value: this.ROLLUP_POLICY}
	      	             ];
	      	      }
	         break;
			 case "sitos" :
			 case "contentLauncher" :
			 case "reloadPlayer" :
	         default :
	            // Set required flashvars (adding more has no effect unless player implements them!)
	      		return [ {name: "lastVisitedPage"    ,value: this.startLocation()}
	                     ,{name: "lastUserPoints"    ,value: scormManager.userPoints}
	                     ,{name: "lastAudioPref"     ,value: scormManager.lastAudioPref}
	                     ,{name: "suspendData"       ,value: scormManager.suspendData}
	                     ,{name: "userName"       	 ,value: scormManager.userName}
	                     ,{name: "userId" 	         ,value: scormManager.userId}
	                     ,{name: "showCloseBtn" 	 ,value: (this.showCloseBtn === true) ? "true" : "false"}
	                     ,{name: "lessonResultMode"  ,value: this.ROLLUP_POLICY}
	            	    ];
			 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" :
	            return false;
	         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" :
	            return false;
	         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;
         }
    }
	
    // Suspend data (for notes)
    ,setUserNotes : function(userNotesStr){
         switch(this.notification){
	         case "courseManager" :
	    		parent.courseManager.setUserNotes(userNotesStr);
	         break;
			 case "sitos" :
			 case "contentLauncher" :
			 case "reloadPlayer" :
	         default :
	          	if (typeof scormManager.setParam !== "function"){return false}
	          	if (typeof userNotesStr !== "string"){userNotesStr = ""}
	          	scormManager.setParam("suspendData", userNotesStr);
			 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;
         }
    }
	
    // start on page 1 if rememberLocation = false in config
    ,startLocation : function(){
         var startOnPage = "1";
         switch(this.notification){
	         case "courseManager" :
			 	// Course manager always starts on page one
	         break;
			 case "sitos" :
			 case "contentLauncher" :
			 case "reloadPlayer" :
	         default :
	           startOnPage = (this.rememberLocation === true) ? scormManager.lastLocation : "1";
			 break;
         }
         // For quickTips start on the page matching to the related search term
         if(document.location.search != ""){
            var pageLocationA = document.location.search.split("=");
            if( pageLocationA[0] == "?page" && pageLocationA.length <= 2)
			{
				var page = pageLocationA.pop();
				startOnPage = (page.toString() != "" && page != 0) ? page.toString() : "1";
			}
         }
         return startOnPage;
    }
	
	// Trace for debug
	,trace : function(info){
		if (this.debugMode === true) {
			var tracePrefix = "[matsplayer] ";
			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());
			}
		}
	}
}

// Be sure object is present
matsplayer = window.matsplayer || {};