/**
 * Issues:
 * make temp file path in to some sort of global variable
 * Where to put error formater
 */


/**
 * Log Object
 */
var Log = new Object();

/**
 * Defaulte Object properties
 */
Log.CLASS_NAME = "Log";
//Log.getClassName = getClassName;

/**
 * Root name of log file. Date is added
 * to this to create the final log file name.
 * Log.LOG_FILE_NAME + "YYYY_MM_DD"
 */
Log.LOG_FILE_NAME = "wmca_kiosk_";

/**
 * Path to the primary log file.
 */
Log.LOG_FILE_PATH = "c:\\inetpub\\ftproot\\logs\\";

/**
 * The session ID to be set by Java in the begin_nav.
 * Be careful to avoid overwriting.
 */
Log.SESSION_ID = "";

/**
 * Gets the session ID either from Log.SESSION_ID or the cookie.
 */
Log.getSessionId = _getLogSessionId;

/**
 * URI of the page logged from.
 */
Log.PAGE_URI = window.location.pathname;

/**
 * Methods for logging messages
 */
Log.logMessage = _logMessage;
Log.logMessageScope = _logMessageScope;
Log.logPageBegin = _logPageBegin;
Log.logPageEnd = _logPageEnd;
Log.logSessionStart = _logSessionStart;
Log.logError = _logError;
Log.logErrorScope = _logErrorScope;
Log.logBeginTask = _logBeginTask;
Log.logCompletedTask = _logCompletedTask;
Log.logBeginTaskScope = _logBeginTaskScope;
Log.logCompletedTaskScope = _logCompletedTaskScope;


/**
 * Gets the session Id from either Log.SESSION_ID (usual)
 * or gets it from the cookie if not defined (for print pages, etc)
 * returns "[null]" if neither works
 */
function _getLogSessionId() {
  if( Log.SESSION_ID ) {
    return Log.SESSION_ID;
  } else if( wmcaCookie.getSessionId && (wmcaCookie.getSessionId() != null) ) {
    return wmcaCookie.getSessionId();
  } else {
    return "[null]";
  }
}

/**
 * Logs a message - specify the message, scope is assumed to be "PAGE"
 * return true if successful
 */
function _logMessage( message ) {
  if( !message ) message = "";
  var theDate = new Date();
  var logString = _logToString( message, "PAGE", theDate );
  var loggingSucceeded = _writeLogFile( logString, theDate );
  return loggingSucceeded;
}

/**
 * Logs a message - specify the message and the scope
 * return true if successful
 */
function _logMessageScope( message, scope ) {
  if( !message ) message = "";
  if( !scope ) scope = "";
  var theDate = new Date();
  var logString = _logToString( message, scope, theDate );
  var loggingSucceeded = _writeLogFile( logString, theDate );
  return loggingSucceeded;
}

/**
 * Logs a message for page end - (use in begin_nav or near top of page)
 * return true if successful
 */
function _logPageBegin() {
  var theDate = new Date();
  var logString = _logToString( "BEGIN", "PAGE", theDate );
  var loggingSucceeded = _writeLogFile( logString, theDate );
  return loggingSucceeded;
}

/**
 * Logs a message for page end - (use in page unload)
 * return true if successful
 */
function _logPageEnd() {
  var theDate = new Date();
  var logString = _logToString( "END", "PAGE", theDate );
  var loggingSucceeded = _writeLogFile( logString, theDate );
  return loggingSucceeded;
}

/**
 * Logs a message for session start
 * return true if successful
 */
function _logSessionStart() {
  var theDate = new Date();
  var logString = _logToString( "START **************************", "SESSION", theDate );
  var loggingSucceeded = _writeLogFile( logString, theDate );
  return loggingSucceeded;
}

function _logBeginTask( task ) {
  if( !task ) task = "";
  var theDate = new Date();
  var logString = _logToString( "Begin " + task, "PAGE", theDate );
  var loggingSucceeded = _writeLogFile( logString, theDate );
  return loggingSucceeded;
}

function _logCompletedTask( task ) {
  if( !task ) task = "";
  var theDate = new Date();
  var logString = _logToString( "Completed " + task, "PAGE", theDate );
  var loggingSucceeded = _writeLogFile( logString, theDate );
  return loggingSucceeded;
}

function _logBeginTaskScope( task, scope ) {
  if( !task ) task = "";
  if( !scope ) scope = "";
  var theDate = new Date();
  var logString = _logToString( "Begin " + task, scope, theDate );
  var loggingSucceeded = _writeLogFile( logString, theDate );
  return loggingSucceeded;
}

function _logCompletedTaskScope( task, scope ) {
  if( !task ) task = "";
  if( !scope ) scope = "";
  var theDate = new Date();
  var logString = _logToString( "Completed " + task, scope, theDate );
  var loggingSucceeded = _writeLogFile( logString, theDate );
  return loggingSucceeded;
}
/**
 * Logs a message for errors.
 * "ERROR: " is added to the front of whatever
 * is passed for the message parameter
 * "optional" errorObj - pass the error object
 * from a catch statement and it will be formatted
 * and added to the message string
 */
function _logError( task, errorObj ) {
  if( !task ) task = "";
  var theDate = new Date();
  var errorMessage = "ERROR: " + task + ( (errorObj) ? " " + errorToString( errorObj ) : "" );
  var logString = _logToString( errorMessage, "PATH", theDate );
  var loggingSucceeded = _writeLogFile( logString, theDate );
  return loggingSucceeded;
}

function _logErrorScope( task, scope, errorObj ) {
  if( !task ) task = "";
  if( !scope ) scope = "";
  var theDate = new Date();
  var errorMessage = "ERROR: " + task + ( (errorObj) ? " " + errorToString( errorObj ) : "" );
  var logString = _logToString( errorMessage, scope, theDate );
  var loggingSucceeded = _writeLogFile( logString, theDate );
  return loggingSucceeded;
}

//"PRIVATE" METHODS

/**
 * Writes to the primary log file.
 * If this fails an attempt is made
 * to log in the temp directory.
 * If this fails the message is not logged.
 */
function _writeLogFile( logString, theDate ) {
  //try write to primary
  var primeLogFileUri = Log.LOG_FILE_PATH + Log.LOG_FILE_NAME + _formatUTCDate( theDate, "%YYYY_%MM_%DD" ) + ".log";
  var loggingSucceeded = writeToFile( primeLogFileUri, logString );

  //if primary failed try writing to temp directory
  if( !loggingSucceeded ) {
    var secLogFileUri = "c:\\temp\\" + Log.LOG_FILE_NAME + _formatUTCDate( theDate, "%YYYY_%MM_%DD" ) + ".log";
    loggingSucceeded = writeToFile( secLogFileUri, logString );
  }
  //return boolean indicating success
  return loggingSucceeded;
}

/**
 * Gets the log string.
 * Returns a tab delimited list of log parameters.
 * UTC-DATE\tUTC-TIME\tSESSIONID\tPAGE_URI\tSCOPE\tMESSAGE
 * Used in the various logMessage... methods to pass the
 * string to _writeLogFile().
 */
function _logToString( message, scope, dateObj ) {
  var theOutput = "";

  //Date
  theOutput += _formatUTCDate( dateObj, "%MM/%DD" );
  theOutput += "\t";  //tab

  //Time
  theOutput += _formatUTCDate( dateObj, "%hh:%mm:%ss:%.sss" );
  theOutput += "\t";  //tab

  //Session Id
  theOutput += Log.getSessionId();
  theOutput += "\t";  //tab

  //The path
  theOutput += Log.PAGE_URI;
  theOutput += "\t";  //tab

  //The scope
  theOutput += ( (scope) ? scope : "[null]" );
  theOutput += "\t";  //tab

  //The message
  theOutput += ( (message) ? message : "[null]" );

  return theOutput;
}

//RELATED GLOBAL FUNCTIONS
var wmcaCookie = new Object();
wmcaCookie.getValueByName = getCookie;
wmcaCookie.getSessionId = _getCookieSessionId;
wmcaCookie.getComWmVisitor = _getCookieComWmVisitor;
wmcaCookie.getKioskInfo = _getCookieKioskInfo;

/**
 * Gets the session Id.
 */
function _getCookieSessionId() {
  return wmcaCookie.getValueByName( "KioskSessionId" );
}

/*
 * Gets the value for com.wm.visitor.
 */
function _getCookieComWmVisitor() {
  return wmcaCookie.getValueByName( "com.wm.visitor" );
}

/*
 * Gets the value for kiosk_info.
 */
function _getCookieKioskInfo() {
  return wmcaCookie.getValueByName( "kiosk_info" );
}

//What object might this be a method of?
/**
 * Adds zeros to the left of a number or string (theNumber) so that
 * the result is the specified length (places).
 * Used to generate sortable dates and times. 
 * E.g. changes 9 to 09 for use in date like 09/12
 */
function addEmptyDigits( theNumber, places ) { 
  if( !places ) var places = 2;
  var theOutput = theNumber; 
  tempNum = theNumber + "";
  for(var i=2; i<=places; i++ ) {
    if( tempNum.length < i ) theOutput = "0" + theOutput;
  }
  return theOutput;
}

/**
  * Date Formater (UTC)
  * Returns a string from a Date Object based on the specified format 
  * %YYYY %MM %DD %mm %ss %.sss (milliseconds)
  * 2002 09 03 01 006
  * %% = is replaced with %
  */
function _formatUTCDate( dateObj, theFormat ) {
  theOutput = theFormat;
  theOutput = theOutput.replace( /%YYYY/g, dateObj.getUTCFullYear() );
  theOutput = theOutput.replace( /%MM/g, addEmptyDigits( dateObj.getUTCMonth() + 1 ) );
  theOutput = theOutput.replace( /%DD/g, addEmptyDigits( dateObj.getUTCDate() ) );
  theOutput = theOutput.replace( /%hh/g, addEmptyDigits( dateObj.getUTCHours() ) );
  theOutput = theOutput.replace( /%mm/g, addEmptyDigits( dateObj.getUTCMinutes() ) );
  theOutput = theOutput.replace( /%ss/g, addEmptyDigits( dateObj.getUTCSeconds() ) );
  theOutput = theOutput.replace( /%\.sss/g, addEmptyDigits( dateObj.getUTCMilliseconds(), 3 ) );
  theOutput = theOutput.replace( /%%/g, "%" );
  return theOutput;
}

/**
 * Takes the error object and returns a string based
 * on JavaScript Error object properties
 * name facility code error code description
 */
function errorToString( errorObj ) {
  //add checks to make sure this is an error obj
  return errorObj.name + " (" + (errorObj.number>>16 & 0x1FFF)  + "/" + (errorObj.number & 0x1FFF)  + ") - " + errorObj.description;
}

/**
 * Opens a local file and appends a string to it.
 * Returns boolean indicating succes of opening/writing.
 */
function writeToFile( fileUri, text ) {
  try {
    var fs = new ActiveXObject("Scripting.FileSystemObject");
    
    try {
      //open file, 8=appends to file, true=will create file if doesn't already exist
      var a = fs.OpenTextFile( fileUri, 8, true );
      a.Writeline( text );
      a.Close();
    }
    catch ( er ) {
      return false;
    }
  }
  catch ( e ) {
    return false;
  }
  return true;
}