
var gRmFx_Messenger;	// (***TB1** not supported) TB2, TB3, PB, SM 
var gRmFx_AB3;			// true: TB/AB3 installed 

    
/**
 * Reminderfox Utilities - general
 */

function rmFxUtil () { 
} 

	rmFxUtil.encodeUTF8	= function (text) {
	// =========================================================================
		return rmFxUtil.convertFromUnicode("UTF-8", text).replace(/(\r\n)|\n/g, "\r\n");
	}
				
	rmFxUtil.convertFromUnicode = function (aCharset, aSrc) {
	// =========================================================================
		var unicodeConverter = Components.classes["@mozilla.org/intl/scriptableunicodeconverter"]
                                     .createInstance(Components.interfaces.nsIScriptableUnicodeConverter);
    	unicodeConverter.charset = aCharset;
    	return unicodeConverter.ConvertFromUnicode(aSrc);
	}
	
	rmFxUtil.getIOService = function () {
	// =========================================================================
		if (rmFxUtil.getIOService.mObject === undefined) {
			rmFxUtil.getIOService.mObject = Components.classes["@mozilla.org/network/io-service;1"]
							.getService(Components.interfaces.nsIIOService2);
		}
		return rmFxUtil.getIOService.mObject;
	}

	rmFxUtil.buildUIDFile = function  (rmFx_UID) {
	// =========================================================================
		var tempDir = Components.classes["@mozilla.org/file/directory_service;1"]
			.getService(Components.interfaces.nsIProperties)
			.get("TmpD", Components.interfaces.nsIFile);
			
		tempDir.append( "tempMsg" + rmFx_UID );

		return  tempDir.path;
	}

   rmFxUtil.filePath4storePath = function  (fileName) {
   // =========================================================================
      // set 'path' to same dir as 'reminderfox.ics' file      
      var sfile = Components.classes["@mozilla.org/file/local;1"]
            .createInstance(Components.interfaces.nsILocalFile);
        
      sfile.initWithPath(reminderFox_getReminderStoreFile().parent.path);
      sfile.append(fileName);
      return sfile.path;
   }      
      
      
	rmFxUtil.readInFileContents = function (tmpFile) {
	// =========================================================================
		var sfile = Components.classes["@mozilla.org/file/local;1"]
				.createInstance(Components.interfaces.nsILocalFile);
		sfile.initWithPath(tmpFile);
	
		var is = Components.classes["@mozilla.org/network/file-input-stream;1"]
			.createInstance( Components.interfaces.nsIFileInputStream );
		try {
			is.init( sfile,0x01, 00004, null);
		}
		catch ( e ) {
			rmFxUtil.PromptAlert("Could not read reminder file: " + e.name  +  " -- " + e.message);
			return null;
		}		
		// Now, read from the stream
		var scriptableStream = Components.classes["@mozilla.org/scriptableinputstream;1"]
		                                 .createInstance(Components.interfaces.nsIScriptableInputStream);
		scriptableStream.init(is);
		var converter = Components.classes["@mozilla.org/intl/scriptableunicodeconverter"]
		                          .createInstance(Components.interfaces.nsIScriptableUnicodeConverter);
		converter.charset = "UTF-8";  // The character encoding you want, using UTF-8 here
		
		var chunk = scriptableStream.read(scriptableStream.available());
		scriptableStream.close();
		var input = null;
		try {
			 input = converter.ConvertToUnicode(chunk);
		}
		catch( e ) {
			input = chunk;
		}		
		return input;
	}   
    
  	rmFxUtil.makeMsgFile =	function (content, tempFile) {
	// =========================================================================
  		var sfile = Components.classes["@mozilla.org/file/local;1"]
				.createInstance(Components.interfaces.nsILocalFile);
		try {
		 sfile.initWithPath(tempFile);
		} catch (ex) {
			return null;
		}
		if (sfile.exists()) {
			sfile.remove(true);
		}
		sfile.create(sfile.NORMAL_FILE_TYPE, 0600);
		var stream = Components.classes['@mozilla.org/network/file-output-stream;1']
				.createInstance(Components.interfaces.nsIFileOutputStream);
		stream.init(sfile, 2, 0x200, false); 		// open as "write only"
		stream.write(content, content.length);
		stream.close();
		return sfile;
	}	

	rmFxUtil.makeMsgFile8 =	function (outputStr, file) {
	// =========================================================================
		var sfile = Components.classes["@mozilla.org/file/local;1"]
				.createInstance(Components.interfaces.nsILocalFile);
		sfile.initWithPath(file);
		
		var outputStream = Components.classes["@mozilla.org/network/file-output-stream;1"]
			.createInstance( Components.interfaces.nsIFileOutputStream );
		outputStream.init( sfile, 0x04 | 0x08 | 0x20, 420, 0 );
		
		var converter = Components.classes["@mozilla.org/intl/scriptableunicodeconverter"]
		                          .createInstance(Components.interfaces.nsIScriptableUnicodeConverter);
		converter.charset = "UTF-8";
		
		var chunk = null;
		try {
			chunk = converter.ConvertFromUnicode(outputStr);
		}
		catch( e ) {
			chunk = outputStr;
		}
		outputStream.write(chunk, chunk.length);	
		
		 var fin = converter.Finish();
		 if (fin.length > 0)
		   outputStream.write(fin, fin.length);
		 outputStream.close();
		 return sfile;
	}

    /**
     *     Debugging support, prompts an Alert and writes it to console
     */
	rmFxUtil.PromptAlert = function (msgErr) {
	// =========================================================================
		var promptService = Components.classes["@mozilla.org/embedcomp/prompt-service;1"]
			.getService(Components.interfaces.nsIPromptService);

      var loggedAt =  " [[ " + Components.stack.caller.filename + "   ln#  " 
                  + Components.stack.caller.lineNumber + "]]   \n";                    

		promptService.alert(window, "ReminderFox Alert : \n\n",  msgErr);
		rmFxUtil.dump2Console ("promptAlert", msgErr, loggedAt)
	};

	rmFxUtil.dump2Console = function (logControl, logString, loggedAt) {
	// =========================================================================
      var loggingString = ",promptAlert,error,general";
      
      try {
         loggingString = reminderFox_prefs.getCharPref(REMINDER_FOX_PREF + ".debug.LogControl")
                + loggingString;
      } catch (ex) {}
	
		if (loggingString.search(logControl) != -1) {
			var rmFx_consoleService = Components.classes["@mozilla.org/consoleservice;1"]
		    	.getService(Components.interfaces.nsIConsoleService);

	      if (loggedAt == null) {
	         loggedAt =  " [[ " + Components.stack.caller.filename + "    ln#  " 
	                  + Components.stack.caller.lineNumber + "]]  ";                    
	      }
	      rmFx_consoleService.logStringMessage("ReminderFox  \n"  + logString
	                 + "\n{log: " + logControl + "}  " + loggedAt);  
		}
	};	 
   /**
    *    Generic function to copy the data to Clipboard 
    */
	rmFxUtil.copytoClipboard = function (data)  {
	// =========================================================================
	// Generic function to copy the data to Clipboard 
		var clipboard = Components.classes["@mozilla.org/widget/clipboardhelper;1"];
		clipboard = clipboard.getService(Components.interfaces.nsIClipboardHelper);
		clipboard.copyString(data );
	};	

   /**
    *    Generic function to get the text from Clipboard 
    *    @note:  ev. change to "transferable.getAnyTransferData(bestFlavour, dataObj, len);"
    *             see 'rmFxDragDrop.js'
    */ 
   rmFxUtil.copyTextfromClipboard = function ()  {                //gW_AddEvent
   // =========================================================================
      var clip = Components.classes["@mozilla.org/widget/clipboard;1"].getService(Components.interfaces.nsIClipboard);
      if (!clip) return null;
   
      var trans = Components.classes["@mozilla.org/widget/transferable;1"].createInstance(Components.interfaces.nsITransferable);
      if (!trans) return null;
      
      trans.addDataFlavor("text/unicode");     

      clip.getData(trans, clip.kGlobalClipboard);  
         
      var str       = new Object();  
      var strLength = new Object();  
      
      try {   // 'try' to prevent error with empty or non-text clipboard content
         trans.getTransferData("text/unicode", str, strLength);  
      
         if (str) str       = str.value.QueryInterface(Components.interfaces.nsISupportsString);  
         if (str) pastetext = str.data.substring(0, strLength.value / 2);  
      
         if (pastetext != "") return pastetext;
      } catch (ex) {};
      return null; 
   },


	/**
	 * 
	 * 	rmFxUtil Dialog Confirm Service to support 2 or 3 key choice
	 * 
	 <br>            [key0] [key1]
	 <br>       or   [key0] [key2] [key1]
	 * 
	 * 	@param	title, the headline of dialog
	 * 	@param	msg, typically a question
	 * 	@param	key0
	 * 	@param	key1
	 * 	@param	key2, optional, decides if 2 or 3 buttons
	 */
	rmFxUtil.ConfirmEx = function (title, msg, key0, key1, key2) {
	// =========================================================================
		var promptService = Components.classes["@mozilla.org/embedcomp/prompt-service;1"]
			.getService(Components.interfaces.nsIPromptService);
	
		var flags =
			promptService.BUTTON_TITLE_IS_STRING * promptService.BUTTON_POS_0 +
			promptService.BUTTON_TITLE_IS_STRING * promptService.BUTTON_POS_1; 		// flags = [integer] 32639

		if (!!key2) {
		var flags =
			promptService.BUTTON_TITLE_IS_STRING * promptService.BUTTON_POS_0 +
			promptService.BUTTON_TITLE_IS_STRING * promptService.BUTTON_POS_1 +
			promptService.BUTTON_TITLE_IS_STRING * promptService.BUTTON_POS_2;		// flags = [integer] 8355711
		} 
		return  promptService.confirmEx(window,
				title, msg,	flags, key0, key1, key2, null, {});		  
	};

	
	
	// Utilities  from \mail\components\preferences\applications.js

	rmFxUtil.getDisplayNameForFile = function (aFile) {		// +++2do gW_OSspecfic ???
	// =========================================================================
	/*
	//@line 85 "e:\buildbot\win32_build\build\mail\components\preferences\applications.js"
	*/
	  if (aFile instanceof Components.interfaces.nsILocalFileWin) {
	    try {
	      return aFile.getVersionInfoField("FileDescription");
	    }
	    catch(ex) {
	      // fall through to the file name
	    }
	  }
	/*
	//@line 108 "e:\buildbot\win32_build\build\mail\components\preferences\applications.js"
	*/
	  return aFile.leafName;
	}

	rmFxUtil.getLocalHandlerApp = function (aFile) {		// +++2do gW_OSspecfic ???
	// =========================================================================
	  var localHandlerApp = Components.classes["@mozilla.org/uriloader/local-handler-app;1"]
	                                  .createInstance(Components.interfaces.nsILocalHandlerApp);
	  localHandlerApp.name = rmFxUtil.getDisplayNameForFile(aFile);
	  localHandlerApp.executable = aFile;

	  return localHandlerApp;
	}

    rmFxUtil.isValidHandlerExecutable = function (aExecutable) { // +++2do gW_OSspecfic ???
    // =========================================================================
        return aExecutable &&
               aExecutable.exists() &&
               aExecutable.isExecutable() &&

    //@line 905 "e:\buildbot\win32_build\build\mail\components\preferences\applications.js"
       aExecutable.leafName != ".exe";
    //@line 913 "e:\buildbot\win32_build\build\mail\components\preferences\applications.js"
      }

 
    rmFxUtil.localeDate = function (dateandtime) { 
    // =========================================================================
       var locDate = dateandtime.toLocaleString();
    	return locDate.substring(0, locDate.lastIndexOf(" "));
    }
    
/**
 *    Add CATEGORIES item to reminder, no dups 
 */
    rmFxUtil.addCategory4Import = function (reminder, categoryItem) {

	    var categoryItemLC = categoryItem.toLowerCase(); //   "invitation";  
	    if ( reminder.categories != null && reminder.categories.length > 0 ) {
	        if (reminder.categories.toLowerCase().indexOf(categoryItemLC) == -1){
	             reminder.categories = reminder.categories + ", " + categoryItem;}
	        }   else { reminder.categories = categoryItem;
	    }
	    return reminder;
    }
 

   
  // function exHtml(xString){
  //    return xString.replace(new RegExp(/</g),"&lt;").replace(new RegExp(/>/g),"&gt;")
  // }   
