/**
 * <p>Logs a user action. This method returns the XML message sent
 * to the logging server or <tt>null</tt> if the web browser does
 * not support logging.</p>
 *
 * @param     action_id     action identifier
 * @param     info_type     optional, type of data in the <tt>info</tt> field
 * @param     info          optional, information to be logged
 * @return    the XML message send to the logging server, represented as a string
 */
function logUserAction(action_id, info_type, info) {
	var timezone = "UTC";
	var timestamp = _formatTimestamp(new Date());

	var xml = '<?xml version="1.0" encoding="UTF-8"?><log_action ';
		xml += info;
		xml += '</log_action>';

	var escapedxml=(xml);
	
	var tracer=new Image();
	tracer.src="../java/tracer.php?l="+escapedxml;

	return xml;
}


/**
 * <p>Logs a user action in full XML Mode. This method returns the XML message sent
 * to the logging server or <tt>null</tt> if the web browser does
 * not support logging.</p>
 *
 * @param     action_id     action identifier
 * @param     info_type     optional, type of data in the <tt>info</tt> field
 * @param     info          optional, information to be logged
 * @return    the XML message send to the logging server, represented as a string
 */
function logUserActionFullXML(user_id, session_id, action_id, info_type, info, curr, isStart) {
	/*Get the corresponding time zone of the local time*/
	var timezone = _getTimeZone();

	/*Get either a local or a GMT time*/
	var timestamp = _formatLocalTimestamp(curr);
	var info_esc = escape(info);
	
	var xml = '<?xml version="1.0" encoding="UTF-8"?>';
	xml+='<log_action auth_token="NA_AuthToken" session_id="'+session_id+'" user_guid="'+user_id+'" '
		+'date_time="'+timestamp+'" timezone="'+timezone+'" action_id="" source_id="JAVA_SCRIPT" '
		+'external_object_id="" info_type="tutor_message.dtd">'+info_esc+'</log_action>';
	
	var tracer=new Image();
	if(isStart) xml = xml + "&start=yes";
    tracer.src="../java/tracer.php?l="+xml;
	
	return xml;
}

/**
 * <p>Logs a user action in full XML Mode. This method returns the XML message sent
 * to the logging server or <tt>null</tt> if the web browser does
 * not support logging.</p>
 *
 * @param     action_id     action identifier
 * @param     info_type     optional, type of data in the <tt>info</tt> field
 * @param     info          optional, information to be logged
 * @return    the XML message send to the logging server, represented as a string
 */
function logUserActionFullXML1(user_id, session_id, action_id, info_type, info, curr, isStart) {
	/*Get the corresponding time zone of the local time*/
	var timezone = _getTimeZone();

	/*Get either a local or a GMT time*/
	var timestamp = _formatLocalTimestamp(curr);
	var info_esc = escape(info);
	
	var xml = '<?xml version="1.0" encoding="UTF-8"?>';
	xml+='<log_action auth_token="NA_AuthToken" session_id="'+session_id+'" user_guid="'+user_id+'" '
		+'date_time="'+timestamp+'" timezone="'+timezone+'" action_id="" source_id="JAVA_SCRIPT" '
		+'external_object_id="" info_type="tutor_message.dtd">'+info_esc;
	
	var tracer=new Image();
	if(isStart) xml = xml + "&start=yes";
    tracer.src="../java/tracer.php?l="+xml;
	
	return xml;
}

/**
 * <p>Private method, used by <tt>logUserAction</tt> to generate a
 * timestamp in the proper format for logging. The resulting string
 * contains the specified date, converted to UTC.</p>
 *
 * @param     timestamp     date object, the timestamp to format as a string
 * @return    timestamp string
 */
function _formatTimestamp(timestamp) {
	var s = "";

	var year = timestamp.getUTCFullYear();
	s += year + "/";

	var month = timestamp.getUTCMonth()+1;
	s += ((month < 10) ? ("0" + month) : month) + "/";

	var date = timestamp.getUTCDate();
	s += ((date < 10) ? ("0" + date) : date) + " ";

	var hours = timestamp.getUTCHours();
	s += ((hours < 10) ? ("0" + hours) : hours) + ":";

	var mins = timestamp.getUTCMinutes();
	s += ((mins < 10) ? ("0" + mins) : mins) + ":";

	var secs = timestamp.getUTCSeconds();
	s += ((secs < 10) ? ("0" + secs) : secs);

	return s;
}

/**
 * <p>Private method, used by <tt>logUserAction</tt> to generate a
 * timestamp in the proper format for logging. The resulting string
 * contains the specified date, in local time.</p>
 *
 * @param     timestamp     date object, the timestamp to format as a string
 * @return    timestamp string
 */
function _formatLocalTimestamp(timestamp) {
	var s = "";

	var year = timestamp.getFullYear();
	s += year + "/";

	var month = timestamp.getMonth()+1;
	s += ((month < 10) ? ("0" + month) : month) + "/";

	var date = timestamp.getDate();
	s += ((date < 10) ? ("0" + date) : date) + " ";

	var hours = timestamp.getHours();
	s += ((hours < 10) ? ("0" + hours) : hours) + ":";

	var mins = timestamp.getMinutes();
	s += ((mins < 10) ? ("0" + mins) : mins) + ":";

	var secs = timestamp.getSeconds();
	s += ((secs < 10) ? ("0" + secs) : secs);

	return s;
}

/*Get the current time zone where the user is*/
function _getTimeZone(){
	var rightNow = new Date();
	var jan1 = new Date(rightNow.getFullYear(), 0, 1, 0, 0, 0, 0);  // jan 1st
	var june1 = new Date(rightNow.getFullYear(), 6, 1, 0, 0, 0, 0); // june 1st
	var temp = jan1.toGMTString();
	var jan2 = new Date(temp.substring(0, temp.lastIndexOf(" ")-1));
	temp = june1.toGMTString();
	var june2 = new Date(temp.substring(0, temp.lastIndexOf(" ")-1));
	var std_time_offset = (jan1 - jan2) / (1000 * 60 * 60);
	var daylight_time_offset = (june1 - june2) / (1000 * 60 * 60);
	var dst;
	if (std_time_offset == daylight_time_offset) {
		dst = "0"; // daylight savings time is NOT observed
	} 
	else {
		// positive is southern, negative is northern hemisphere
		var hemisphere = std_time_offset - daylight_time_offset;
		if (hemisphere >= 0)
			std_time_offset = daylight_time_offset;
		dst = "1"; // daylight savings time is observed
	}
	
	var offset = _convert(std_time_offset);
	var value = offset + "," + dst;
	return _getTimeZoneHelper(value);

}

/*A helper method to help the getTimeZone() method.*/
function _getTimeZoneHelper(key){
	var keys = new Array("-12:00,0", "-11:00,0", "-10:00,0", "-09:00,1", "-08:00,1",
						 "-07:00,0", "-07:00,1", "-06:00,0", "-06:00,1", "-05:00,0", 
						 "-05:00,1", "-04:00,0", "-04:00,1", "-03:30,1", "-03:00,0",
						 "-03:00,1", "-02:00,1", "-01:00,0", "-01:00,1", "00:00,0",
						 "00:00,1", "+01:00,1", "+01:00,0", "+02:00,1", "+02:00,0",
						 "+03:00,1","+03:00,0", "+03:30,0", "+04:00,0", "+04:00,1",
						 "+04:30,0","+05:00,1", "+05:00,0", "+05:30,0", "+05:45,0",
						 "+06:00,0", "+06:00,1", "+06:30,0", "+07:00,0", "+07:00,1",
						 "+08:00,0", "+08:00,1", "+09:00,0", "+09:00,1", "+09:30,0", 
						 "+09:30,1", "+10:00,0", "+10:00,1", "+11:00,0", "+12:00,1",
						 "+12:00,0", "+13:00,0");
	var values = new Array("IDLW","NT","AHST","YST","PST","MST","MST","CST","CST",
							"EST","EST","AST","AST","GMT-3.30","GMT-3.00","GMT-3.00","AT",
							"WAT","WAT","UTC","UTC","CET","CET","EET","EET","BT","BT",
							"GMT\+3.30","GMT\+4.00","GMT\+4.00","GMT\+4.30","GMT\+5.00",
							"GMT\+5.00","GMT\+5.30","GMT\+5.45","GMT\+6.00","GMT\+6.00",
							"GMT\+6.30","GMT\+7.00","GMT\+7.00","CCT","CCT","JST","JST",
							"Australian Central Standard","Australian Central Standard",
							"GST","GST","GMT\+11.00","IDLE","IDLE","GMT\+13.00");
	var totalKeys = 52;
	var i = 0;
	while(i < totalKeys){
		if(keys[i] == key) break;
		i++;
	}
	return values[i];
}

function _convert(value) {
	var hours = parseInt(value);
   	value -= parseInt(value);
	value *= 60;
	var mins = parseInt(value);
   	value -= parseInt(value);
	value *= 60;
	var secs = parseInt(value);
	var display_hours = hours;
	// handle GMT case (00:00)
	if (hours == 0) {
		display_hours = "00";
	} else if (hours > 0) {
		// add a plus sign and perhaps an extra 0
		display_hours = (hours < 10) ? "+0"+hours : "+"+hours;
	} else {
		// add an extra 0 if needed 
		display_hours = (hours > -10) ? "-0"+Math.abs(hours) : hours;
	}
	
	mins = (mins < 10) ? "0"+mins : mins;
	return display_hours+":"+mins;
}


/*Helper method to deal with the NTP Network Time Protocal*/
var NTP = {
  cookieShelfLife : 7, //7 days
  requiredResponses : 2,
  serverTimes : new Array, 
  serverUrl : "/sandbox/gettime.php",
  resyncTime : 10, // minutes
  sync : function(){
    // if the time was set within the last x minutes; ignore this set request; time was synce recently enough
	 var offset = NTP.getCookie("NTPClockOffset");
	 if (offset){try{
	 var t = offset.split("|")[1];
	 var d = NTP.fixTime()-parseInt(t);
	 if (d < (1000 * 60 * NTP.resyncTime)){return false;} // x minutes; return==skip
	 }catch(e){}
     }
     NTP.serverTimes = new Array;
     NTP.getServerTime();
  },
  getNow : function(){
      var date = new Date();
      return (date.getTime() + (date.getTimezoneOffset() * 60000));
  },
  parseServerResponse : function(data){
     var offset = parseInt(data.responseText.split(":")[0]);
     var origtime = parseInt(data.responseText.split(":")[1]);
     var delay = ((NTP.getNow() - origtime) / 2);
     offset = offset - delay;
     NTP.serverTimes.push(offset);
     
     // if we have enough responces set cookie
     if (NTP.serverTimes.length >= NTP.requiredResponses){
        // build average
	var average = 0;
	var i=0;
	for (i=0; i < NTP.serverTimes.length;i++){
	   average += NTP.serverTimes[i];
	}
	average = Math.round(average / i);
	NTP.setCookie("NTPClockOffset",average);	
	NTP.setCookie("NTPClockOffset",average+'|'+NTP.fixTime()); // save the timestamp that we are setting it
     }
     else{
        NTP.getServerTime();
     }

  },
  getServerTime : function(){
     try{
      var req = new Ajax.Request(NTP.serverUrl,{
          onSuccess : NTP.parseServerResponse,
	  method : "get",
	  parameters : "t=" + NTP.getNow()
          });
      }
      catch(e){
         return false;
         //prototype.js not available
      }
  },
  setCookie : function(aCookieName,aCookieValue){
     var date = new Date();
     date.setTime(date.getTime() + (NTP.cookieShelfLife * 24*60*60*1000));
     var expires = '; expires=' + date.toGMTString();
     document.cookie = aCookieName + '=' + aCookieValue + expires + '; path=/';
  },
  getCookie : function(aCookieName){
     var crumbs = document.cookie.split('; ');
             for (var i = 0; i < crumbs.length; i++)
            {
                var crumb = crumbs[i].split('=');
                if (crumb[0] == aCookieName && crumb[1] != null)
                {
                    return crumb[1];
                }
            }
      return false;
  },
  fixTime : function(timeStamp){
      if(!timeStamp){timeStamp = NTP.getNow();}
      var offset = NTP.getCookie("NTPClockOffset") ;
      if (!offset){offset = 0;}else{offset=offset.split("|")[0];}
      return timeStamp + parseInt(offset);
  }  
}




