ErrorFinder = {
  
  errors: new Array,
  serverErrors: new Array,
  clientErrors: new Array,
  
  // parse html doc to find errors returned by server
  findServerErrors: function() {
    this.serverErrors = [];
    errors = $$('#error_msg .msg_container').concat($$('#noentry_msg .msg_container'))
    for(var i=0; i<errors.length; i++) {
      node = errors[i];
      var children = node.childNodes;
      for(var j=0; j<children.length; j++) {
        if(children[j].nodeType == 3)
          textMsg = children[j].nodeValue;
      }
      this.serverErrors[this.serverErrors.size()] = textMsg;
    }
    if(this.serverErrors[0] == '.' && this.serverErrors.size() ==1) 
      this.serverErrors = new Array;
    return this.serverErrors;
  },
  
  // parse html doc to find errors generated by JavaScript
  findClientErrors: function() {
    this.clientErrors = [];
    var errorDivs = $$('div.error_message');
    //this.clientErrors[this.clientErrors.length] = err.innerHTML.strip()
    for(var i=0; i < errorDivs.length; i++){
      var parent = errorDivs[i].parentNode;
      var nodes = parent.childNodes;
      
      // find a label tag (bad hack, in Prototype 1.6 I would use "select" )
      for(j=0; j<nodes.length; j++){
        if (nodes[j].tagName == "LABEL") {
          var children = nodes[j].childNodes
          for(var k=0;k<children.length; k++){
            if(children[k].nodeType == 3)
              var fieldName = children[k].nodeValue.strip();
          }
          break;
        }
      }
      var errorMsg = errorDivs[i].innerHTML.strip();
      
      // add error
      this.clientErrors[this.clientErrors.size()] = fieldName + ": " + errorMsg;
    }
    return this.clientErrors;
  },
  
  findErrors: function() {
    this.errors = this.findServerErrors().concat(this.findClientErrors())
    return this.errors;
  },
  
  errorsToString: function(){
    return this.errors.join(" || ");
  },
  
  errorCounter: function(){
    return this.errors.size();
  }
  
}

function modifyButtonOnClicks(){ 
  buttonIds = ['loanapp_step_1_continue_submit',
               'loanapp_step_2_submit_submit',          // reg step 2 
               'loan_application_apply_submit'];        // apply for a loan 

 for (var i = 0; i < buttonIds.length; i++) {
   if (button = $(buttonIds[i])) {
     onClick = "ErrorFinder.findErrors(); javascript:lpSendData('page','ErrorCounter', ErrorFinder.errorCounter());";
     button.parentNode.setAttribute("onClick", onClick);
   }
 }
} 


// set lpUnit and lpLanguage
function setLpVariables(){
     
 modifyButtonOnClicks();
  lpAddVars('page', 'unit', lpVars.lpUnit);
  lpAddVars('page','language',lpVars.lpLanguage);
  ErrorFinder.findErrors()

  var errorsString = ErrorFinder.errorsToString();
  var errorCount = ErrorFinder.errorCounter();
  if(errorCount > 0){
    lpAddVars('page','ErrorName', errorsString);
    lpAddVars('page','ErrorCounter', errorCount);
  }
  if (typeof(lpVars.section) != 'undefined')
    lpAddVars('page', 'Section', lpVars.section);
  if(typeof(lpVars.customerId) != 'undefined')
    lpAddVars('session','CustomerID', lpVars.customerId);
  if(typeof(lpVars.customerStatus) != 'undefined')
    lpAddVars('session','CustomerStatus', lpVars.customerStatus);
  if(typeof(lpVars.conversionStage) != 'undefined')
    lpAddVars('page','ConversionStage', lpVars.conversionStage);
  if(typeof(lpVars.orderTotal) != 'undefined')
    lpAddVars('page', lpUnit + '_order_total', lpVars.orderTotal);
    lpAddVars('page', 'order_total', lpVars.orderTotal);
  if(typeof(lpVars.loanId) != 'undefined')
    lpAddVars('page','LoanId', lpVars.loanId);
}

var lpMTagConfig = {
        "lpServer" : "sales.liveperson.net",
        "lpNumber" : "69445590",
        "lpProtocol" : (document.location.toString().indexOf("https:")==0) ? "https" : "http",
    "lpTagLoaded" : false,
    "pageStartTime" : (new Date()).getTime() //pageStartTime is set with a timestamp as soon as the page starts loading
  }

function lpAddMonitorTag(src)
{
  if (!lpMTagConfig.lpTagLoaded)
  {
    if(typeof(src)=="undefined"||typeof(src)=="object"){src=lpMTagConfig.lpMTagSrc?lpMTagConfig.lpMTagSrc:"/hcp/html/mTag.js";}if(src.indexOf("http")!=0){src=lpMTagConfig.lpProtocol+"://"+lpMTagConfig.lpServer+src+"?site="+lpMTagConfig.lpNumber;}else{if(src.indexOf("site=")<0){if(src.indexOf("?")<0)src=src+"?";else src=src+"&";src=src+"site="+lpMTagConfig.lpNumber;}};var s=document.createElement("script");s.setAttribute("type","text/javascript");s.setAttribute("charset","iso-8859-1");s.setAttribute("src",src);document.getElementsByTagName("head").item(0).appendChild(s);  
  }
}
/*
The code below send a PAGEVAR to LP with the time [iin seconds] it took the page to load. Code is executed in the onload event
*/
lpMTagConfig.calculateSentPageTime = function () {
  var t = (new Date()).getTime() - lpMTagConfig.pageStartTime;
  lpAddVars('page','pageLoadTime', Math.round(t/1000)+" sec");
};

if (window.attachEvent)window.attachEvent("onload",lpMTagConfig.calculateSentPageTime);
else window.addEventListener("load",lpMTagConfig.calculateSentPageTime,false);

//Load mtag.js inline if this is a Confermation Page else load it on page load event
if (window.attachEvent)window.attachEvent("onload",lpAddMonitorTag);
else window.addEventListener("load",lpAddMonitorTag,false);

//Variables Arrays - By Scope
if (typeof(lpMTagConfig.pageVar)=="undefined") lpMTagConfig.pageVar = new Array();
if (typeof(lpMTagConfig.sessionVar)=="undefined") lpMTagConfig.sessionVar = new Array();
if (typeof(lpMTagConfig.visitorVar)=="undefined") lpMTagConfig.visitorVar = new Array();
//Extra actions to be taken once the code executes
if (typeof(lpMTagConfig.onLoadCode)=="undefined") lpMTagConfig.onLoadCode = new Array();
//Dynamic Buttons Array
if(typeof(lpMTagConfig.dynButton)=="undefined") lpMTagConfig.dynButton=new Array();

// Function that sends variables to LP - By Scope
function lpAddVars(scope,name,value) {
  if (name.indexOf('OrderTotal')!=-1 || name.indexOf('OrderNumber')!=-1){
    if  (value=='' || value==0 || (typeof(value) =='undefined' )) return; // pass 0 value to all but OrderTotal

    else lpMTagConfig.sendCookies = false
  }
  if(typeof(value) =='undefined') return;
  value=lpTrimSpaces(value.toString());
  switch (scope){
    case "page": lpMTagConfig.pageVar[lpMTagConfig.pageVar.length] = escape(name)+"="+escape(value); break;
    case "session": lpMTagConfig.sessionVar[lpMTagConfig.sessionVar.length] = escape(name)+"="+escape(value); break;
    case "visitor": lpMTagConfig.visitorVar[lpMTagConfig.visitorVar.length] = escape(name)+"="+escape(value); break;
  } 
}
// Preventing long cookie transfer for IE based browsers.
function onloadEMT() { 
  var LPcookieLengthTest=document.cookie;
  if (lpMTag.lpBrowser == "IE" && LPcookieLengthTest.length>1000){
    lpMTagConfig.sendCookies=false;
  }
}

//The Trim function returns a text value with the leading and trailing spaces removed
function lpTrimSpaces(stringToTrim) {
  return stringToTrim.replace(/^\s+|\s+$/g,"");
}
// Immediate Data submission function
function lpSendData(varscope,varname,varvalue){
if(typeof(lpMTag)!="undefined" && typeof(lpMTag.lpSendData)!="undefined")
  lpMTag.lpSendData(varscope.toUpperCase() +"VAR!"+ varname + "=" + varvalue, true);
}

// This need to be add to afterStartPage will work
lpMTagConfig.ifVisitorCode = [];

// The unit variable purpose is to route the chat or call to the designated skill. <LOB> should be replaced with the skill name, i.e. : sales

try{
  if (typeof(lpUnit)=="undefined")  var lpUnit=lpVars.lpUnit;
  //if(typeof(lpAddVars)!="undefined")  lpAddVars("page","unit",lpUnit);
  if (typeof(lpLanguage)=="undefined")  var lpLanguage=lpVars.lpLanguage;
  //if(typeof(lpAddVars)!="undefined")  lpAddVars("page","language",lpLanguage);
  lpMTagConfig.defaultInvite ='chat'+'-' + lpUnit+"-"+lpLanguage;
  }catch(e){}

lpMTagConfig.onLoadCode[lpMTagConfig.onLoadCode.length] = onloadEMT;

//creating button object
if(typeof(lpMTagConfig.db1)=="undefined"){
      lpMTagConfig.db1 = new Object();
}
//overriding busy action
lpMTagConfig.db1.busyAction = function (objName) {
      objRef = eval(objName);
      var chatWinURL = objRef.getActionURL("Busy");
      chatWinURL = chatWinURL.replace(/forceOffline/,"SESSIONVAR%21BusyClickOverride");
      window.open(chatWinURL,'chat'+lpMTagConfig.lpNumber,'width=472,height=320,status=0,resizable=0,menubar=no,scrollbars=no,location=no');
};
//overriding offline action
lpMTagConfig.db1.offlineAction = function (objName) {
      objRef = eval(objName);
      var chatWinURL = objRef.getActionURL("Offline");
      window.open(chatWinURL,'chat'+lpMTagConfig.lpNumber,'width=472,height=320,status=0,resizable=0,menubar=no,scrollbars=no,location=no');
};

// LP Button Code-
if(typeof(lpMTagConfig.dynButton)!="undefined") {
    lpMTagConfig.dynButton[lpMTagConfig.dynButton.length] ={"name":"chat-"+lpVars.lpUnit+"-"+lpVars.lpLanguage,"pid":"lpButtonDiv","afterStartPage":true,'ovr':'lpMTagConfig.db1'};
}

