﻿/***************************************************************************************
**
**  File Name: fp_common.js
**
**  Summary: Common functions for FairPoint Verizon Email Settings Updater web flow
**
**  Description: This javascript contains general purpose functions 
**
**  Copyright SupportSoft Inc. 2006, All rights reserved.
***************************************************************************************/

/***************************************************************************************
** Globals
***************************************************************************************/
var install_lang = "en";
var install_lang_verbose = "english";

var OPEN_FOR_WRITE  = 1;
var OPEN_FOR_READ   = 2;
var OPEN_FOR_APPEND = 8;

/***************************************************************************************
** Helper Functions
***************************************************************************************/
function ss_ConvertSafelyRequested(converted)
  {  
  //Look through the string and subsitute encoded characters back to their "dangerous" equivilant  
  var result = converted;

  while (result.indexOf("&lt;") > -1)   { result = result.replace("&lt;", "<");    }
  while (result.indexOf("&gt;") > -1)   { result = result.replace("&gt;", ">");    }
  while (result.indexOf("&quot;") > -1) { result = result.replace("&quot;", "\""); }
  while (result.indexOf("&#37;") > -1)  { result = result.replace("&#37;", "%");   }
  while (result.indexOf("&#39;") > -1)  { result = result.replace("&#39;", "\'");  }
  while (result.indexOf("&#92;") > -1)  { result = result.replace("&#92;", "\\");  }
  while (result.indexOf("&#40;") > -1)  { result = result.replace("&#40;", "(");   }
  while (result.indexOf("&#41;") > -1)  { result = result.replace("&#41;", ")");   }
  while (result.indexOf("&#43;") > -1)  { result = result.replace("&#43;", "+");   }

  return result;
}

/*******************************************************************************
** Name:        ss_utl_String_condenseSpaces
**
** Purpose:     Replaces all groups of spaces with a single space
**
** Parameter:   bCrLf : Bool if true condenses carriage return; line feeds
**                      and tabs too
**
** Return:      resultant string object
*******************************************************************************/
String.prototype.condenseSpaces = function ss_utl_String_condenseSpaces(bCrLf)
{
  if((typeof bCrLf != "undefined") && bCrLf)
    return this.replace(/\s+/g, " ");
  else
    return this.replace(/\ +/g, " ");
}

/*******************************************************************************
** Name:        ss_utl_Array_push
**
** Purpose:     Extention to native JavaScript Array type to support .push in
**              environments where it is not supported (like Internet Explorer 5.0x)
**
** Parameter:   none
**
** Return:      resultant array object
*******************************************************************************/
if (typeof (Array.prototype.push) == 'undefined' && typeof ([].push) == 'undefined')
{
  Array.prototype.push = function ss_utl_Array_push()
  {
    for (var i=0;i<arguments.length; i++)
      this[this.length]=arguments[i];
    return this.length;
  }
}

/*******************************************************************************
** Name:        ss_utl_EncodeBase64
**
** Purpose:     Changes the input to a base64 encoded string
**
** Parameter:   sInput : String to be encoded
**
** Return:      A base64 encode string or "" {if null was passed}
*******************************************************************************/
function ss_utl_EncodeBase64(sInput)
{
  var keyStr = "ABCDEFGHIJKLMNOP" +  "QRSTUVWXYZabcdef" +
          "ghijklmnopqrstuv" +   "wxyz0123456789+/" +  "=";

  var output = "";
  var chr1, chr2, chr3 = "";
  var enc1, enc2, enc3, enc4 = "";
  var i = 0;

  if (sInput == "") return "";

  do {
    chr1 = sInput.charCodeAt(i++);
    chr2 = sInput.charCodeAt(i++);
    chr3 = sInput.charCodeAt(i++);

    enc1 = chr1 >> 2;
    enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
    enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
    enc4 = chr3 & 63;

    if (isNaN(chr2)) {
    enc3 = enc4 = 64;
    } else if (isNaN(chr3)) {
    enc4 = 64;
    }

    output = output +
    keyStr.charAt(enc1) +
    keyStr.charAt(enc2) +
    keyStr.charAt(enc3) +
    keyStr.charAt(enc4);
    chr1 = chr2 = chr3 = "";
    enc1 = enc2 = enc3 = enc4 = "";
  } while (i < sInput.length);

  return output;
}

/*******************************************************************************
** Name:        ss_utl_DecodeBase64
**
** Purpose:     Decodes a base64 encoded string
**
** Parameter:   sInput : String to be decoded
**
** Return:      The decoded string or "" {if null was passed}
*******************************************************************************/
function ss_utl_DecodeBase64(sInput)
{
  var keyStr = "ABCDEFGHIJKLMNOP" +  "QRSTUVWXYZabcdef" +
          "ghijklmnopqrstuv" +   "wxyz0123456789+\/" +  "=";

  var output = "";
  var chr1, chr2, chr3 = "";
  var enc1, enc2, enc3, enc4 = "";
  var i = 0;

  if (sInput == "") return "";
  // remove all characters that are not A-Z, a-z, 0-9, +, /, or =
  var base64test = /[^A-Za-z0-9\+\/\=]/g;
  if (base64test.exec(sInput)) {
    g_Logger.Debug("ss_utl_DecodeBase64()",
          "There were invalid base64 characters in the input text.\n" +
          "Valid base64 characters are A-Z, a-z, 0-9, ´+´, ´/´, and ´=´\n" +
          "Expect errors in decoding.");
  }
  sInput = sInput.replace(/[^A-Za-z0-9\+\/\=]/g, "");

  do {
    enc1 = keyStr.indexOf(sInput.charAt(i++));
    enc2 = keyStr.indexOf(sInput.charAt(i++));
    enc3 = keyStr.indexOf(sInput.charAt(i++));
    enc4 = keyStr.indexOf(sInput.charAt(i++));

    chr1 = (enc1 << 2) | (enc2 >> 4);
    chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
    chr3 = ((enc3 & 3) << 6) | enc4;

    output = output + String.fromCharCode(chr1);

    if (enc3 != 64) {
      output = output + String.fromCharCode(chr2);
    }
    if (enc4 != 64) {
      output = output + String.fromCharCode(chr3);
    }

    chr1 = chr2 = chr3 = "";
    enc1 = enc2 = enc3 = enc4 = "";
  } while (i < sInput.length);

  return output;
}

/*******************************************************************************
** Name:         ss_net_TestConnect
**
** Purpose:      Test a network or Internet connection
**
** Parameter:    oNet - (Optional) instance of sdcnetcheck ctl.  If none specified
**                        function creates an instance and deletes it.
**               sAddress -- IP Address or name address (like www.yahoo.com) to be tested
**               nPort -- integer value of port to be tested (defaults to 80 if none specified)
**               nTimeout -- time out in milliseconds (defaults to 30000ms if none specified)
**
** Return:       true/false
*******************************************************************************/
function ss_net_TestConnect(oNet, sAddress, nPort, nTimeout)
{
  var result = false;

  try
  {
    if (oNet == null) oNet =  new ActiveXObject("SPRT.SdcNetCheck");
    if (typeof(nPort) == "undefined" || nPort == 0) port = 80;
    if (typeof(nTimeout) == "undefined") nTimeout = 30000;
    
    result = oNet.TestConnect(sAddress, nPort, nTimeout);
  }
  catch (err)
  {
    //g_Logger.Error('ss_net_TestConnect', err.message + " -- sAddress: " + sAddress + " nPort: " + nPort + " nTimeout: " + nTimeout);
  }

  return result;
}

/*******************************************************************************
** Name:         ss_con_GetFiles
**
** Purpose:      Get list of files from a directory that match a criteria
**
** Parameter:    sFolderName  - folder name
**               
**               nMatchExp    - (optional) if defined then function includes only
**                              those files whose names match the expression
**
** Return:       array of file names 
*******************************************************************************/
function ss_con_GetFiles(sFolderName, nMatchExp)
{
  var aFiles = new Array();
  try {
    
    var oSprtExt = new ActiveXObject("SPRT.External");
    var oFSObject = oSprtExt.CreateInternalObject("filesystem");
    var oFolder = oFSObject.GetFolder(sFolderName);
    
    var colFiles = new Enumerator(oFolder.Files);
    if(typeof nMatchExp != "undefined" && nMatchExp != null && nMatchExp != "") {
      for ( ; !colFiles.atEnd(); colFiles.moveNext()) {
        var sFileName = colFiles.item().name;
        if(sFileName.match(nMatchExp) != null) 
          aFiles.push(sFileName);
      }
    } else {
      for ( ; !colFiles.atEnd(); colFiles.moveNext()) {
        aFiles.push(colFiles.item().name);
      }  
    }
    
    oFSObject = null;
    oSprtExt = null;
  } catch(ex) {
    //alert(ex.message);
  }

  return aFiles;
}

/*******************************************************************************
** Name:        ss_xml_NodeGetText
**
** Purpose:     Retrieves the CDATA or Text of the specified node
**
** Parameter:   oNode -- element to retrieve the data from
**
** Return:      String text of the node, or "" if null or text not found.
*******************************************************************************/
function ss_xml_NodeGetText ( oNode )
{
  try
  {
    // if we have CDATA, return that.
    // if we find a TEXT node, return that.
    if (oNode != null) 
    {
      if (oNode.nodeType in {3:true,1:true})
      {
        var sText = oNode.text;
        var sCData = oNode.cdata;
        var sReturn = sText || sCData || "";
        return sReturn;
      }
    }
  } catch (e) {
    //alert(e.message);
    throw(e);
  }
  return "";
}

/*******************************************************************************
** Name:         ss_utl_LoadDOM (OVERRIDE)
**
** Purpose:      Function loads the XML returned from the sUrl using the 
**               FileSystem interface from within sprtexternal.dll.
**
** Parameter:    sFile      -- the fully qualified url to hit
**               
** Return:       null in async calls and/or DOM object in synchronous calls
*******************************************************************************/
function ss_utl_LoadDOM(sFile)
{
  try {
    var oDOM   = new ActiveXObject("Microsoft.XMLDOM");
    var oSprtExt = new ActiveXObject("SPRT.External");
    var xml = oSprtExt.ReadFile(sFile);
    oDOM.loadXML(xml);
    return oDOM;
  } catch (ex) {
    //alert(ex.message);
    return null;
  }
}

/*******************************************************************************
** Name:         ss_utl_LoadXML
**
** Purpose:      Loads given xml into DOM object
**
** Parameter:    sXML   - XML string to load
**               bAsync - used to turn ON async; <optional for sync>
**               
** Return:       DOM object if successful else null
*******************************************************************************/
function ss_utl_LoadXML(sXML, bAsync)
{
  try {
    var oDOM = new ActiveXObject("Microsoft.XMLDOM");
    bAsync = (typeof bAsync != "undefined") ? bAsync : false;
    oDOM.async = bAsync;
    oDOM.loadXML(sXML);
    
    if (oDOM.parseError.errorCode != 0) {
      var sMsg = "  Reason: " + oDOM.parseError.reason + "<br>" +
                 "  Code: " + oDOM.parseError.errorCode + "<br>" +
                 "  Line: " + oDOM.parseError.line + "<br>" +
                 "  Linepos: " + oDOM.parseError.linepos
      alert("ss_utl_LoadXML()", sMsg);
      return null;
     } else {
      return oDOM;
     }
  } catch (ex) {
    alert("ss_utl_LoadXML()", ex.message);
    return null;
  }
}

/*******************************************************************************
** Name:         ss_con_CreateTextFile
**
** Purpose:      Creates a text file in the specified location
**
** Parameter:    fn         - File name
**               bOverwrite - If bOverwrite is specified, it will overwrite
**                            the file if already exists. Default is false.
**               bUnicode   - To create a Unicode file, set bUnicode to true.
**                            Default value is false. Only UCS-2 and MB files
**                            can be created. if Unicode is specified as true,
**                            then the file is created as UCS-2 otherwise in MB
**
** Return:       TextStream object
*******************************************************************************/
function ss_con_CreateTextFile(fn, bOverwrite, bUnicode)
{
  var oFile;
  try {
    var oSprtExt = new ActiveXObject("SPRT.External");
    var oFileSystem = oSprtExt.CreateInternalObject("filesystem");
    
    oFile = oFileSystem.CreateTextFile(fn, bOverwrite, bUnicode);
  } catch(ex) {
    //alert(ex.message);
  }
  return oFile;
}

/*******************************************************************************
** Name:         ss_con_WriteFile
**
** Purpose:      Writes passed data to the file
**
** Parameter:    fileobj - file handle to write to (not the file name)
**               data    - data to write out
**
** Return:       None
*******************************************************************************/
function ss_con_WriteFile(fileobj, data)
{
  try {
    fileobj.WriteLine(data);
    return true;
  } catch(ex) {
    //alert(ex.message);
  }
  return false;
}

/*******************************************************************************
** Name:         stripDomain
**
** Purpose:      Returns the user id portion of the email address minus the domain
**
** Parameter:    a valid email address
**
** Return:       string - user id if successful, otherwise -1 for failure
*******************************************************************************/ 
function stripDomain() {
  if(arguments.length > 0){
    return arguments[0].slice(0,arguments[0].indexOf("@"));
  }
  else 
    return -1;
}

/*******************************************************************************
** Name:         ss_ShowPageText
**
** Purpose:      Shows Hides objects
**
** Parameter:    sID = ID of the HTML element
**               bShow = True shows the object, False hides the object
**
** Return:       true/false
*******************************************************************************/
function ss_ShowPageText(sID, bShow){
  if(bShow)
    document.getElementById(sID).style.display = "inline";
  else
    document.getElementById(sID).style.display = "none";
}

/*******************************************************************************
** Name:         ss_con_SetRegValueByType
**
** Purpose:      Sets registry value by type
**
** Parameter:    regRoot registry root
**               regKey registry key
**               regVal registry value name
**               nType  value type  (1: REG_SZ, 3: REG_BINARY, 4: REG_DWORD, 7: REG_MULTI_SZ)
**               sData registry value data stored as REG_SZ
**
** Return:       true/false
*******************************************************************************/
function ss_con_SetRegValueByType(regRoot, regKey, regVal, nType, sData)
{
  var bRet = false;
  var sType = "";
  //Account for Type being in string format
  switch(nType){
    case 1: sType = "REG_SZ"; break;
    case 3: sType = "REG_BINARY"; break;
    case 4: sType = "REG_DWORD"; break;
    case 7: sType = "REG_MULTI_SZ"; break;
    default:
  }
 
  try  {
    var oSI = new ActiveXObject("SPRT.SmartIssue");
    bRet  = oSI.SetRegValueEx(regRoot, regKey, regVal, sType, sData);
    oSI = null;
  } catch (ex) {
    sMsg = "-root:" + regRoot + "; key:" + regKey + "; val:" + regVal;
    //alert(ex.message + sMsg);
  }
  return bRet;
}

/*******************************************************************************
** Name:         ss_con_pvt_ConvertUnicodeHexToString
**
** Purpose:      Converts Unicode hex string (reg binary) to a string
**
** Parameter:    unicode hex string
**
** Return:       string
*******************************************************************************/
function ss_con_pvt_ConvertUnicodeHexToString(hexStr)
{
  var i = 0;
  var resultStr = "";
 
  while (i + 3 < hexStr.length)
  {
    var lowerbyteStr = hexStr.charAt(i) + hexStr.charAt(i + 1);     // string representation of lower byte
    var lowerbyteVal = parseInt(lowerbyteStr, 16);                  // numerical value of lower byte
    var upperbyteStr = hexStr.charAt(i + 2) + hexStr.charAt(i + 3); // string representation of upper byte
    var upperbyteVal = parseInt(upperbyteStr, 16);                  // numerical value of upper byte

    var charCode = (upperbyteVal * 256) + lowerbyteVal;
    if (charCode != 0) resultStr += String.fromCharCode(charCode);
    
    
    i += 6;
  }
 
  return resultStr;
}

/*******************************************************************************
** Name:         ss_con_GetRegUnicodeStringValue
**
** Purpose:      Reads a binary reg value as a UNICODE string
**
** Parameter:    regRoot Registry Root
**               regKey Registry key
**               regVal Registry Value Name
**
** Return:       string
*******************************************************************************/
function ss_con_GetRegUnicodeStringValue(regRoot, regKey, regVal)
{
  var str = "";
  try {
    var oSI = new ActiveXObject("SPRT.SmartIssue");
    str = ss_con_pvt_ConvertUnicodeHexToString(oSI.GetRegValueEx(regRoot, regKey, regVal));
    
    //cleanup
    oSI = null;
  }  
  catch(ex) { /*alert(ex.message); */}
  
  return str;
}

/*******************************************************************************
** Name:         ss_GetArgs
**
** Purpose:      Parses the querystring
**
** Parameter:    none
**
** Return:       array - (argument / value) pairs
*******************************************************************************/
function ss_GetArgs() {

  var args = new Object();
  var query = location.search.substring(1);
  
  var pairs = query.split("&");
  for(var i = 0; i < pairs.length; i++) {
    var pos = pairs[i].indexOf('=');
    if (pos == -1) continue;
    var argname = pairs[i].substring(0,pos);
    var value = pairs[i].substring(pos+1);
    args[argname] = unescape(value);
  }
  return args;
}


/***************************************************************************************
** Event Handlers
***************************************************************************************/
function OnPrint() {
  window.print();
}


  




