
//===================================================
// eMFrameScripts.js
//===================================================
//Assumes definitions defined in BrowserVersions.js

//To avoid conflicts with developers js function, the following iman object should be used to access all function
var iman = new iman();
dojo.require("dojo.io.*");
function iman()
{

   // ================  Utility Methods =====================
   function urlEncode(str)
   {
      if(BrowserCharset != null && BrowserCharset.toLowerCase() == "utf-8")
      {
         // if(MS55 || NN6)                    doesn't work on Safari
         if ( encodeURIComponent )
         {
            var r = encodeURIComponent(str);
         }
         else
         {
            //REMIND: Fix to use real utf-8 algorithm.  This is not THAT big of a deal since we are only going to support IE5.5 and above and NS6 and above for utf-8.
            var r = escape(str,1);
            //return r.replace(/\+/g,"%2B");  //since the stinking ,1 doesn't always work
            r=replace(r, "+", "%2B");
            r=replace(r, " ", "+");
         }
      }
      else
      {
         var r = escape(str,1);
         //return r.replace(/\+/g,"%2B");  //since the stinking ,1 doesn't always work
         r=replace(r, "+", "%2B");
         r=replace(r, " ", "+");
      }
      return r;
   }
   
   function debug(str)
   {
//   	debugAjax(str);return;
	return;
   	if(fw_isDebugEnabled){
	   	if(!MS55){
	   		if(top.Branding && top.Branding.console)
	   		{
	   			top.Branding.console.log(fw_respId+":"+str);
	   		}else if(window.console){
	   			window.console.log(str);
	   		}
	   	}else{
	//		window.alert(str);
   			debugAjax(str);
		}
	}
   }
   
   function debugAjax(str){
	var params = new Array();
	 params['logMsg'] = str;
	 params['fw_fromId'] = fw_respId;
	 params['taskId'] = fw_taskId;
	 var bindArgs = {
	  url: "jslogservice",
	  error: function(type, data, evt){/*alert("Error:  Unable to log ajax log message. type= "+type+"  data="+data+"  evt="+evt); */ },
		    mimetype: "text/plain",
	  content: params,
		    load: function(type, data, evt){
//		     alert("success"+data);
		    }
	 };
	 var req = dojo.io.bind(bindArgs);			 
//  dojo.event.connect(req, "load", this, "populateDiv");
   }
   
   function debugOV(str)
   {
   	if(!MS55){
   		debug(str);
   	}else{
//		window.alert(str);
//   		debugAjax(str);
		debug(str);
	}
   }
   
   function urlDecode(str)
   {
      str = replace(str, "+", " ");
      if(BrowserCharset != null && BrowserCharset.toLowerCase() == "utf-8")
      {
         // if(MS55 || NN6)                    doesn't work on Safari
         if ( decodeURIComponent )
         {
            return decodeURIComponent(str);
         }
         else
         {
            //REMIND: Fix to use real utf-8 algorithm.  This is not THAT big of a deal since we are only going to support IE5.5 and above and NS6 and above for utf-8.
            return unescape(str);
         }
      }
      else
      {
         return unescape(str);
      }
   }
   
   function pack(list)
   {
      if(!list || !list.length || list.length<1)
      {
         return "PP";
      }
   
      var s = "P:" + urlEncode(list[0]);
      for(var i=1; i<list.length; i++)
      {
         s += ":" + urlEncode(list[i]);
      }
   
      return s + "P";
   }
   
   function unpack(s)
   {
      if(!s)
      {
         return null;
      }
   
      if(s == "PP")
         return new Array();
   
      if(s.length < 3 || s.charAt(0) != 'P' || s.charAt(1) != ':' || s.charAt(s.length - 1) != 'P')
      {
         var list = new Array();
         list[0] = s;
         return list;
      }
   
      s = s.substring(2, s.length-1);
   
      var tmplist = s.split(":");
      var list = new Array();
      for(var i=0; i<tmplist.length; i++)
      {
         list[i] = urlDecode(tmplist[i]);
      }
   
      return list;
   }
   
   function packSelect(sel)
   {
      var o = sel.options;
      var list = new Array();
   
      for(var i=0; i<o.length; i++)
      {
         list[i] = o[i].value;
      }
      return pack(list);
   }
   
   function formatMessage(format, params)
   {
      for(var i=0; i<params.length; i++)
      {
         format = replace(format, "{" + i + "}", params[i]);
      }
      return format;
   }
   
   function replace(s, s1, s2)
   {
      var l = s.split(s1);
      return l.join(s2);
   }
   
   //When working in a popup window, this function should be called on the "OK" button action.
   //This ensures that the parent window is still open. If task has changed or parent window is
   //no longer open, an alert will fire telling the user that their changes have not been saved,
   //and the window will be closed.
   function parentIsOpen(o)
   {
       if(!o)
       {
           alert(ParentWindowChangedErrorAlertMessage);
           window.close();
           return false;
       }
       else
       {
           return true;
       }
   }
   
   function toggleDivVisibility(id)
   {
      var el = document.getElementById(id).style;
      if (el.visibility=="visible") el.visibility = "hidden";
      else el.visibility = "visible";
   }
   
   function toggleDivDisplay(id)
   {
      var el = document.getElementById(id).style;
      if (el.display=="none") el.display = "block";
      else el.display = "none";
   }
   
   // ================  Encoding Methods =====================
   // static data for toDisplay
   _trans = new Array();
   _trans["&"] = "&amp;";
   _trans["<"] = "&lt;";
   _trans[">"] = "&gt;";
   _trans["$"] = "&#36;";
   _trans["\t"] = "&nbsp;&nbsp;&nbsp;&nbsp;";
   _trans[" "] = "&nbsp;";
   _trans["\""] = "&quot;";
   function toDisplay(str)
   {
      if (str==null || str.length==0)
      {
         return str;
      }
   
      var newStr = "";
      var charStr;
      var charValue;
      var index = 0;
   
      // Walk string, (Unicode)
      while (index < str.length)
      {
         charValue = str.charCodeAt(index);
         charStr = str.charAt(index);
   
         if( charValue >= 126 )
         {
            newStr += "&#" + charValue + ";";
         }
         else
         {
            if (charStr == "\r")
            {
               newStr += "<BR>";
               if( (index < str.length-1) && (str.charAt(index+1) == "\n") )
               {
                  index++;
               }
            }
            else if (charStr == "\n")
            {
               newStr += "<BR>";
               if ((index < str.length-1) && (str.charAt(index+1) == "\r"))
               {
                  index++;
               }
            }
            else if (charValue == 27)
            {
               newStr = newStr = "&#27;";
            }
            else if (_trans[charStr] != null)
            {
               newStr += _trans[charStr];
            }
            else
            {
               newStr += charStr;
            }
         }
         index++;
      }
      return newStr;
   }
   
   function xmlEncode(str)
   {
      if (str==null || str.length==0)
      {
         return str;
      }
   
      var newStr = "";
   
      for(var i=0; i<str.length; i++)
      {
         var charValue = str.charCodeAt(i);
         var charStr = str.charAt(i);
   
         if(charValue >= 126 || charValue < 30)
         {
            newStr += "&#" + charValue + ";";
         }
         else if (_xmlEscape[charStr] != null)
         {
            newStr += _xmlEscape[charStr];
         }
         else
         {
            newStr += charStr;
         }
      }
   
      return newStr;
   }
   
   // static data for xmlEncode
   _xmlEscape = new Array();
   _xmlEscape["&"]="&amp;";   //do the & first so we don't recurse
   _xmlEscape["'"]="&apos;";
   _xmlEscape[">"]="&gt;";
   _xmlEscape["<"]="&lt;";
   _xmlEscape["\""]="&quot;";
   function xmlDecode(src)
   {
      if(src==null || src.length==0)
      {
         return "";
      }
   
      // replace &quot; with " etc
      for(i in _xmlEscape)
      {
         src=replace(src, _xmlEscape[i], i);
      }
   
      var charCode = "";
      var dst = "";
      var idxSrc=0;
   
      // replace #2b; with char for 2b
      while(idxSrc < src.length)
      {
         var ch = src.charAt(idxSrc++);
         if(ch=="&" && src.charAt(idxSrc)=='#')
         {
            // We have an escape char; Read in char code
            idxSrc++;
   
            ch=src.charAt(idxSrc++);
            while (ch!=';')
            {
               charCode += ch;
               ch=src.charAt(idxSrc++);
            }
   
            ch = String.fromCharCode(parseInt(charCode));
            charCode = "";
         }
   
         dst += ch;
      }
   
      return dst;
   }
   
   // static data for toScript
   _toScript = new Array();
   _toScript["\\"]="\\\\";
   _toScript["\""]="\\\"";
   _toScript["\'"]="\\\'";
   _toScript["\n"]="\\n";
   _toScript["\r"]="\\r";
   function toScript(s)
   {
      if (s!=null && s.length>0)
      {
         for(var i in _toScript) s=replace(s, i, _toScript[i]);
      }
      return s;
   }
   
   // static data for toTag
   // cannot replace # or ; with anything
   _toTag = new Array();
   _toTag["&"]="&#38;";    //do the & first so we don't recurse
   _toTag["<"]="&#60;";
   _toTag[">"]="&#62;";
   _toTag["\'"]="&#39;";
   _toTag["\""]="&#34;";
   _toTag["\x1B"]="&#27;"; //escape
   function toTag(s)
   {
      if (s!=null && s.length!=0)
      {
         for(var i in _toTag) s=replace(s, i, _toTag[i]);
      }
      return s;
   }
   
   
   //----------------- New function since 2.0.2 ---------------------------------
   //These function can only be accessed through the iman object (ie, iman.xxxxx())
   
   function formatMessageSingle(format, param)
   {
      var list = new Array();
      list[0] = param;
      return formatMessage(format, list);
   }
   
   //remove leading spaces from a string
   function trimLeft(s)
   {
      if (s==null || s.length==0) {return "";}
      var i = 0;
      while (i<s.length && s.charAt(i)==" ") {i++;}
      if (i==s.length) {return s;}
      s = s.substr(i);
      return s;
   }
   
   //remove trailing spaces from a string
   function trimRight(s)
   {
      if (s==null || s.length==0) {return "";}
      var i = s.length-1;
      while (i>-1 && s.charAt(i)==" ") {i--;}
      s = ((i==-1)?"":s.substr(0,i+1)); 
      return s;
   }
   
   //remove leading and trailing spaces from a string
   function trim(s)
   {
      if (s==null || s.length==0) {return "";}
      s = trimLeft(s);
      s = trimRight(s);
      return s;
   }
   
   // prevent default action and event propagation/bubbling for event
   function cancelEvent(evt)
   {
      if (evt!=null)
      {
         if (NN6)
         {
            evt.preventDefault();   //prevent default action
            evt.stopPropagation();  //prevent event from propagating
            //alert("NN6 cancelled event = "+evt.type);
         }
         else
         {
            evt.returnValue=false;  //prevent default action
            evt.cancelBubble=true;  //prevent event from bubbling (propagating)
            //alert("IE cancelled event = "+evt.type);
         }
      }
   }
   
   //find the x,y screen position of an html element
   function getScreenPos(elementId)
   {
      var point=new Object();
   
      var o=document.getElementById(elementId);
      if(o)
      {
         point.x=getPageOffsetLeft(o);
         point.y=getPageOffsetTop(o);
      }
      else
      {
         point.x=0;
         point.y=0;
      }
   
      // Add in window offset
      if (isNaN(window.screenX))
      {
         point.x = point.x-document.body.scrollLeft+window.screenLeft;
         point.y = point.y-document.body.scrollTop+window.screenTop;
      }
      else
      {
         point.x=point.x+window.screenX+(window.outerWidth-window.innerWidth)-window.pageXOffset;
         point.y=point.y+window.screenY+(window.outerHeight-24-window.innerHeight)-window.pageYOffset;
      }
   
      return point;
   }
   
   function getPageOffsetLeft (el)
   {
      var ol=el.offsetLeft;
      while ((el=el.offsetParent) != null) { ol += el.offsetLeft; }
      return ol;
   }
   
   function getPageOffsetTop (el)
   {
      var ot=el.offsetTop;
      while((el=el.offsetParent) != null) { ot += el.offsetTop; }
      return ot;
   }
   
   function parseXmlString(xmlString) 
   {
      var xmlDoc;
      try
      {
         if (navigator.appName == "Microsoft Internet Explorer")
         {
            xmlDoc = new ActiveXObject( 'Msxml2.DOMDocument' );
            xmlDoc.async = false;
            xmlDoc.loadXML( xmlString );
         }
         else
         {
            xmlDoc = new DOMParser().parseFromString(xmlString, "text/xml" );
         }
      }
      catch (e)
      {
         xmlDoc = null;
      }
      return xmlDoc;
   }
   
   function xmlToString(xmlDoc)
   {
     var	xmlString;
     try
     {
         if (navigator.appName == "Microsoft Internet Explorer")
         {
              xmlString = xmlDoc.xml;
         }
         else
         {
             xmlString = new XMLSerializer().serializeToString( xmlDoc );
         }
     }
     catch (e)
     {
         xmlString = null;
     }
     return xmlString;
   }
   
   
   // Completes the current task; framework will return control to calling task, go to homepage, or close the window
   // @param win window to complete task; useful when using frames
   function closeTask(win)
   {
      if(!win) win = window;
      var date = new Date();
      win.location = "frameservice?NPService=fw.LaunchService&NPAction=Return&returnID="+window.fwTaskId+"&unique=" + date.getTime();
   }
   
   function getModulesPath()
   {
      return fw_modulesPath;
   }
   
   function getLanguageCode()
   {
      return fw_lang;
   }
   
   //split comma-separated list of strings into an array ignoring double commas and leading/trailing spaces
   function commaSplit(s)
   {
      var a = new Array();
      if (s==null || s.length==0)
      {
         return a;
      }
   
      var val = "";
      var ch = "";
      for (var i = 0; i<s.length; i++)
      {
         // get next char.  see if it is a comma
         if ((ch = s.charAt(i))!=',')
         {
            // not a comma.
            val += ch;                             // add char to the value buffer
         }
         else
         {
            // yes, it is a comma.
            // see if next char is also a comma
            if ((i+1<s.length)&&(s.charAt(i+1)==','))
            {
               // two commas in a row.
               val += ",";                        // just add one comma to value buffer
               i++;                               // skip the second comma
            }
            else
            {
               // just a single comma
               a[a.length] = trim(val);          // convert to string and add to vector
               val = "";                         // clear the val buffer
            }
         }
      }
      a[a.length] = trim(val);                   // add the last value
      return a;
   }
   
   //convert the string array into a single comma-separated string (duping commas) 
   function commaSepStr(a)
   {
      var s="";
      if (a!=null && a.length>0)
      {
         for (var i=0; i<a.length; i++)
         {
            s += ((i>0)?", ":"")+dupCommas(a[i]);
         }
      }
      return s;
   }
   
   //parse string doubling any commas found (ie, s="a,b" return "a,,b"
   function dupCommas(s)
   {
      //make sure we have a string with some length
      if (s==null || s.length==0)
      {
         ret = "";  //no string, return null string
      }
      //see if we have any commas in string
      else if (s.indexOf(",")==-1)
      {
         ret = s;    //no commas in string; nothing to do
      }
      //build string with double commas
      else
      {
         var ret = "";
         for (var i=0; i<s.length; i++)
         {
            var c = s.charAt(i);
            if (c==",")
            {
               ret += ",,";
            }
            else
            {
               ret += c;
            }
         }
      }
      return ret;
   }

   //functions defined through 2.0.2
   this.urlEncode = urlEncode;
   this.urlDecode = urlDecode;
   this.pack = pack;
   this.unpack = unpack;
   this.packSelect = packSelect;
   this.formatMessage = formatMessage;
   this.replace = replace;
   this.parentIsOpen = parentIsOpen;
   this.toggleDivVisibility = toggleDivVisibility;
   this.toggleDivDisplay = toggleDivDisplay;
   this.toDisplay = toDisplay;
   this.xmlEncode = xmlEncode;
   this.xmlDecode = xmlDecode;
   this.toScript = toScript;
   this.toTag = toTag;
   
   //functions defined after 2.0.2
   this.formatMessageSingle = formatMessageSingle;
   this.trimLeft = trimLeft;
   this.trimRight = trimRight;
   this.trim = trim;
   this.cancelEvent = cancelEvent;
   this.getScreenPos = getScreenPos;
   this.getPageOffsetLeft = getPageOffsetLeft;
   this.getPageOffsetTop = getPageOffsetTop;
   this.parseXmlString = parseXmlString;
   this.xmlToString = xmlToString;
   this.closeTask = closeTask;
   this.getModulesPath = getModulesPath;
   this.getLanguageCode = getLanguageCode;
   this.commaSplit = commaSplit;
   this.commaSepStr = commaSepStr;
   this.dupCommas = dupCommas;
   this.debug = debug;
   this.debugOV = debugOV;
}

//Function pointers for 2.0.2 backwards compatibility 
   var urlEncode =             iman.urlEncode;
   var urlDecode =             iman.urlDecode;
   var pack =                  iman.pack;
   var unpack =                iman.unpack;
   var packSelect =            iman.packSelect;
   var formatMessage =         iman.formatMessage;
   var replace =               iman.replace;
   var parentIsOpen =          iman.parentIsOpen;
   var toggleDivVisibility =   iman.toggleDivVisibility;
   var toggleDivDisplay =      iman.toggleDivDisplay;
   var toDisplay =             iman.toDisplay;
   var xmlEncode =             iman.xmlEncode;
   var xmlDecode =             iman.xmlDecode;
   var toScript =              iman.toScript;
   var toTag =                 iman.toTag;
