/*
Copyright © Interactive Services 2013 - 2015 All Rights Reserved.  
No part of this code may be used, with or without modification, without prior consent from Interactive Services. 
Version 2.1, 01 March 2015
*/

(function($){   
	$.extend({
	    aicc:function(p){  
	    		//GET THE VALUE OF THE SID AND THE URL                 
	        var _sid      = getUrlVar('AICC_SID');
	        var _url      = getUrlVar('AICC_URL');
	           
	        //DETERMINE WHICH ACTION NEEDS TO BE CALLED       
	        if(p['action']=='set'){
	        	setAICC(p['score'],p['time'],p['credit'],p['location'],p['status'],p['suspend_data']);
	        }else if(p['action']=='get'){
	        	getAICC();
	        }else if(p['action']=='exit'){
	        	exitAICC();
	        }
	        
	        //EXTRACT THE SID AND THE URL FROM THE URL STRING
	        function getUrlVar(urlVar){
	            var match = RegExp('[?&]' + urlVar.toLowerCase() + '=([^&]*)').exec(window.location.search.toLowerCase());
	            var matchTxt = unescape(match && decodeURIComponent(match[1].replace(/\+/g, ' '))); 
	            //ERROR CHECKING IF THE VALUES AREN'T FOUND
	            if(matchTxt=="null" || matchTxt==""){
		            if(COMMUNICATION_ERRORMESSAGE){generateErrorAlert(errorAicc1, "n/a", urlVar+" returned "+matchTxt)}
								logText("getUrlVar("+urlVar+") failed. Error Code: n/a", "failure")
							}
	            return matchTxt
	        }
	        //SET THE ALL THE VALUES ON THE AICC DATABASE
	        function setAICC(s,t,c,l,ls,sd){
	            $.post(_url,{command:"PutParam",version:"2.2",session_id:_sid, aicc_data:"[CORE]\nlesson_location="+l+"\ncredit="+c+"\nscore="+s+"\ntime="+t+"\nlesson_status="+ls+"\n[core_vendor]\n[core_lesson]\nislsuspenddata="+sd},function(r){                
	                p['response'].call(this,splitString(r));
	            })
	            .error(function(){
	            	//ERROR CHECK IF SETAICC FAILED
	            	if(COMMUNICATION_ERRORMESSAGE){
	            		errorAicc3 = errorAicc3.replace('[%%setvalue%%]',"[CORE]\nlesson_location="+l+"\ncredit="+c+"\nscore="+s+"\ntime="+t+"\nlesson_status="+ls+"\n[core_vendor]\n[core_lesson]\nislsuspenddata="+sd);
	            		generateErrorAlert(errorAicc3, "n/a", "setAICC() failed.")
	            		logText("setAICC() failed. Error Code: n/a", "failure")
	            	}
	            });
	        }
	        //GET ALL THE VALUES FROM THE DATABASE
	        function getAICC(){
	            $.get(_url,{command:"GetParam",version:"2.2",session_id:_sid},function(r){
	                p['response'].call(this,splitString(r));   
	            })
	            .error(function(){
	            	//ERROR CHECK IF GETAICC FAILED
	            	if(COMMUNICATION_ERRORMESSAGE){
	            		generateErrorAlert(errorAicc2, "n/a", "getAICC() failed.")
	            		logText("getAICC() failed. Error Code: n/a", "failure")
	            	}
	            });
	        }
	        //SHUT DOWN THE CONNECTION TO THE AICC DATABASE
	       function exitAICC(){
	       			exitPageStatus = true;
	            $.get(_url,{command:"ExitAU",version:"2.2",session_id:_sid},function(r){
	                p['response'].call(this,splitString(r));   
	            })
	            .error(function(){
	            	if(COMMUNICATION_ERRORMESSAGE){
	            		generateErrorAlert(errorAicc4, "n/a", "exitAICC() failed.")
	            		logText("exitAICC() failed. Error Code: n/a", "failure")
	            	}
	            });
	       }
	       //CONVERT THE RETURN DATA INTO AN OBJECT WITH ALL THE ATTRIBUTES AND VALUES
	       function splitString(str){
		        var obj = {}; 
		    		str = str.replace(/\r|\n/g, "replaced") //REMOVE THE CARRIAGE RETURNS AND NEW LINES
		    		tempArray = str.split("replaced") //SPLIT INTO AND ARRAY
		    		
		    		for(var i=0; i<tempArray.length; i++){
		    			if(tempArray[i].indexOf("=")!=-1){ //IF THE ARRAY ELEMENT CONTAINS AND EQUALS THEN SPLIT ON THE EQUALS AND ASSIGN THE VALUE
		    				obj[tempArray[i].split("=")[0]]=tempArray[i].split("=")[1]
		    			}
		    		}
		        return obj;
	       }
	    }
	}); 
})(jQuery);