
 //window.alert = function() { };
var mServerName = 'http://webchat.a-cti.com:8082';
var mMaxPageViews = 0;
var mSecondsToLaunch = 30 * 1000; //convert to milliseconds
var proChat = { clientId: '1665981417' };
var mProactiveNow = null;
var mRequestUri = window.location.pathname;
var mArmingArrayUrls = [ ];
var mDisarmArrayUrls = [ ];
var mLaunchArrayUrls = [ ];


/**
 * Set the cookie in the browser
 */ 
function Set_Cookie( name, value, expires, path, domain, secure )
{
// set time, it's in milliseconds
var today = new Date();
today.setTime( today.getTime() );

/*
if the expires variable is set, make the correct
expires time, the current script below will set
it for x number of days, to make it for hours,
delete * 24, for minutes, delete * 60 * 24
*/
if ( expires )
{
expires = expires * 1000 * 60 * 60 * 24;
}
var expires_date = new Date( today.getTime() + (expires) );

document.cookie = name + "=" +escape( value ) +
( ( expires ) ? ";expires=" + expires_date.toGMTString() : "" ) +
( ( path ) ? ";path=" + path : "" ) +
( ( domain ) ? ";domain=" + domain : "" ) +
( ( secure ) ? ";secure" : "" );
}


// this fixes an issue with the old method, ambiguous values
// with this test document.cookie.indexOf( name + "=" );
/**
 * Get the cookie from the browser.
 *
 */
function Get_Cookie( check_name ) {
        // first we'll split this cookie up into name/value pairs
        // note: document.cookie only returns name=value, not the other components
        var a_all_cookies = document.cookie.split( ';' );
        var a_temp_cookie = '';
        var cookie_name = '';
        var cookie_value = '';
        var b_cookie_found = false; // set boolean t/f default f

        for ( i = 0; i < a_all_cookies.length; i++ )
        {
                // now we'll split apart each name=value pair
                a_temp_cookie = a_all_cookies[i].split( '=' );


                // and trim left/right whitespace while we're at it
                cookie_name = a_temp_cookie[0].replace(/^\s+|\s+$/g, '');

                // if the extracted name matches passed check_name
                if ( cookie_name == check_name )
                {
                        b_cookie_found = true;
                        // we need to handle case where cookie has no value but exists (no = sign, that is):
                        if ( a_temp_cookie.length > 1 )
                        {
                                cookie_value = unescape( a_temp_cookie[1].replace(/^\s+|\s+$/g, '') );
                        }
                        // note that in cases where cookie is initialized but no value, null is returned
                        return cookie_value;
                        break;
                }
                a_temp_cookie = null;
                cookie_name = '';
        }
        if ( !b_cookie_found )
        {
                return null;
        }
}

/**
 * Generate a unique clientguid.
 * 
 */
function generateClientGuid() {
	var chars = "0123456789abcdefghiklmnopqrstuvwxyz";
	var string_length = 13;
	var lClientGuid = '';
	for (var i=0; i<string_length; i++) {
		var rnum = Math.floor(Math.random() * chars.length);
		lClientGuid += chars.substring(rnum,rnum+1);
	}
	return lClientGuid;
}

function getBrowserType() {

    if(navigator.userAgent.match(/Safari/) ) {
        return "Safari";
        
    }  else if(navigator.userAgent.match(/Firefox\/2/) ) {
        return "Firefox2";
    
    } else if(navigator.userAgent.match(/Firefox\/3/) ) {
    	return "Firefox3";
    
    } else if(navigator.userAgent.match(/MSIE 7.0/)) {
    	return "IE7";
    
    } else if(navigator.userAgent.match(/MSIE 6.0/)) {
    	return "IE6";
    	
    } else if(navigator.userAgent.match(/MSIE 8.0/)) {
    	return "IE8";
    } else {
    	return "Firefox2"; //default behavior should work for all other browsers.
    }
}

function gupScript( name )
{
//alert("gup:: window.location.pathname = " + window.location.pathname);
//alert("gup:: window.location.href = " + window.location.href);
  name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
  var regexS = "[\\?&]"+name+"=([^&#]*)";
  var regex = new RegExp( regexS );
  var results = regex.exec( window.location.href );
  if( results == null )
     return "";
  else
     return results[1];
}


/*function getScriptParameter(name) {
	var scriptElem = document.getElementById("webchat");
	//alert(scriptElem.id);
//	alert("src = " + scriptElem.getAttribute("src"));
	name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
	var regexS = "[\\?&]"+name+"=([^&#]*)";
	var regex = new RegExp( regexS );
	var results = regex.exec( scriptElem.getAttribute("src") );
	if( results == null )
	     return "";
	else
	     return results[1];
}*/

//alert("window.location.href = " + window.location.pathname);
window.onload = function() {  
//getScriptParameter("clientId"); alert("path = " + getScriptParameter("pathname")); 
 //alert("onload");
//alert("pathname param = " + gup('pathname')); alert("clientId = " + gup('clientId'));
//alert(window.location.pathname);
   // create a clientguid 
   var sessionId = generateClientGuid();
   var proChatIcon = document.getElementById("startWrapper");
   var chatIcon = document.getElementById("chatIcon");
   if(proChatIcon == null || proChatIcon == undefined) {
	proChatIcon = document.createElement("div");
	proChatIcon.setAttribute("style","display:none;");
   }
   if(chatIcon == null || chatIcon == undefined) {
	chatIcon = document.createElement("div");
        chatIcon.setAttribute("style","display:none;");
	document.body.appendChild(chatIcon);
   }
   var proChatNo = document.getElementById("closeButton");
      
   function startChat()
   {
       /* window.open(mServerName + '/pages/chatFrame.jsp?domainName='+window.location.host+'&clientUrl='+window.location.href+'&clientId='+proChat.clientId+'&clientguid='+
                                                sessionId +'&isPopout=new','WebChat','width=390,height=325'); */
	   var lPath = mServerName+"/chatAction.do?clientUrl="+window.location.href+"&clientId="+proChat.clientId+"&clientguid="+sessionId+"&debug=false";
	   //alert('Path from Proactivechat.js'+lPath);
	   //if(popupchat.clientId == '2004618535' || popupchat.clientId == '1005456964' || popupchat.clientId == '1005956534')		
	   window.open(lPath,'WebChat','width=400,height=330');
        
        disableProactiveChat();
        
        // Google Analytics using clients existing on-page impl
        try {
        	pageTracker._trackPageview('/chatInteraction');
        	window.dump("Google Analytics detected. /chatInteraction");
        } catch(e) {
        	window.dump("Error calling pageTracker or pageTracker does not exist.\n");
        }
   }
   
   function startProChat() {
	   /* window.open(mServerName + '/pages/chatFrame.jsp?domainName='+window.location.host+'&clientUrl='+window.location.href+'&clientId='+proChat.clientId+'&clientguid='+
                                               sessionId +'&isPopout=new','WebChat','width=390,height=325'); */
	   var lPath = mServerName+"/chatAction.do?clientUrl="+window.location.href+"&clientId="+proChat.clientId+"&clientguid="+sessionId+"&debug=false&ChatServerPath="+window.location.host;
	   window.open(lPath,'WebChat','width=400,height=330');
       disableProactiveChat();
       
       // Google Analytics using clients existing on-page impl
       try {
    	pageTracker._trackPageview('/proactiveChatInteraction');
    	window.dump("Google Analytics detected. /proactiveChatInteraction");
       } catch(e) {
    	window.dump("Error calling pageTracker\n");
       }
  }

      // bind onclick event to multiple icons
     function bindOnclickEvent(eventToBind) {
	     var chatIcons = getElementsByClassName("chatIcon");
	     var proChatIcons = getElementsByClassName("proChatIcon"); 
	 //  alert(chatIcons[0]);
	     if(!chatIcons) return ;
	     for(var i=0; i<chatIcons.length; i++) {
	         chatIcons[i].onclick = eventToBind;
	         chatIcons[i].setAttribute("style","cursor:pointer");
	     }

    }

 //
 //alert("bind icons"); 
  chatIcon.onclick = startChat;  // UNCOMMENT ME 
  proChatIcon.onclick = startProChat;  //UNCOMMENT ME

// there might not be a proactive chat icon, so create an invisible one.
  if(proChatNo == null || proChatNo == undefined) {
	  proChatNo = document.createElement("div");
	  document.body.appendChild(proChatNo);
  }
  proChatNo.onclick = disableProactiveChat;

  bindOnclickEvent(startChat);  //UNCOMMENT ME
 //alert("done binding icons"); 
  function disableProactiveChat() {
        Set_Cookie('proactiveChat','false',30,'/');

		var proChatWrapper = document.getElementById("proActiveWrapper");
		        
        if(getBrowserType().match(/Firefox/)) {
                proChatWrapper.setAttribute("style","display:none");
        
        } else {
                proChatWrapper.style.display = "none";
        
        }
  }


  switch(proChat.clientId) {
      case "1004941260":
	      runProactiveChatAbandonCart(proChat.clientId,mSecondsToLaunch,mRequestUri);
	      break;
      default:
		//alert("default");
  	      runProactiveChat(mMaxPageViews,mSecondsToLaunch);
	      break;
  }

  function isUrlFound(pUrl,pPageArray) {
	//alert("pagearray len = " + pPageArray.length);
	for(var i=0; i<pPageArray.length; i++) {
	//	alert("pageArray " + pPageArray[i] + "\npUrl = " + pUrl);
		if(pPageArray[i] == pUrl) {			
			return true;
		}
	}
	return false;
  }


  function runProactiveChatAbandonCart(pClientId,pSecondsToLaunch,pUrl) {
       //alert("run abandon cart");
  	// get the cookie and determine the status
        if(Get_Cookie('proactiveChat') != 'false' && Get_Cookie('abandonedCheckoutTrigger') != 'false') {
//	    alert("switch");
	    switch(pClientId) {
               case "1004941260":    // Solestruck
//		  alert("case Soelstruck"); 
		  if(Get_Cookie('abandonedCheckoutTriggerArmed') == 'true') {
	//		alert("Trigger is ARMED!");
			// status is true so check for target page
			// IF url == HOMEPAGE then LAUCH CHAT
			if(isUrlFound(pUrl,mLaunchArrayUrls)) {
				//LAUNCH ICON
//				alert("You are on the LAUNCHING page");
				Set_Cookie("abandonedCheckoutTriggerArmed","false",null,"/");
				Set_Cookie("abandonedCheckoutTrigger","true",null,"/");
				runProactiveChat(0,2000);
			
			} else if(isUrlFound(pUrl,mDisarmArrayUrls)) { 
	                // else IF url == THANKYOUPAGE then DISARM
//	                	alert("You are on the DISARMING page");
				Set_Cookie("abandonedCheckoutTriggerArmed","false",null,"/");
				Set_Cookie("abandonedCheckoutTrigger","true",null,"/");
			}
                  } else {
	//		alert("trigger is NOT armed");
			// status is false so check for ARMING page
			//IF url == LASTCHECKOUTPAGE then ARM
	                if(isUrlFound(pUrl,mArmingArrayUrls)) {
	//		  alert("ARMING URL");
			  if(document.getElementById("progressbarPayment")) { // this is the last checkout page
//				alert("You are on the ARMING page");
                            Set_Cookie("abandonedCheckoutTriggerArmed","true",null,"/");
			    
			  } else {
alert('not last page');
				var leftSignIn = document.getElementById("leftSignIn");
				if(leftSignIn) {
				document.getElementById("leftSignIn").addEventListener("DOMNodeInserted", function() {
					alert("event fired");
				
					runProactiveChatAbandonCart(pClientId,pSecondsToLaunch,pUrl);
				},false);
				}//if
			  }
		        }
		  }
                  break;
	       default:
		  break;
	   }//switch
		
         }// if 
  }

  


  function runProactiveChat(pMaxPageViews,pSecondsToLaunch) {

  if(Get_Cookie('proactiveChat') != 'false') {
//	alert(Get_Cookie('pageviews') + ' pMaxPageViews == ' + pMaxPageViews);
   if(pMaxPageViews == 0 || Get_Cookie('pageviews') >= pMaxPageViews ) { //remove false to redeploy proactive chat
// alert("pageview criteria met"); 
   if(getBrowserType().match(/Firefox/)) {
  
     setTimeout(function() {
         var proChatWrapper = document.getElementById("proActiveWrapper");
	 if(proChatWrapper != null && proChatWrapper != undefined) {
	  //    alert("sdgdsfgsdf"); 
        	proChatWrapper.setAttribute("style","display:block;");
	 }

     },pSecondsToLaunch);
   } else {
//alert("not firefox?");  
     setTimeout(function() {
    //    alert("lauching in non FF browser"); 
	 var proChatWrapper = document.getElementById("proActiveWrapper");
	 if(proChatWrapper != null && proChatWrapper != undefined) {
         	proChatWrapper.style.display="block";
	 }

     },pSecondsToLaunch);
  }
  } else {
	var lPageViews = Get_Cookie('pageviews');
//	alert(lPageViews);
	Set_Cookie('pageviews',++lPageViews,30,'/');
  }
 } //end if !cookie
} // end runProactiveChat function

} //end onload


// bind onclick event to multiple icons
/*
	Developed by Robert Nyman, http://www.robertnyman.com
	Code/licensing: http://code.google.com/p/getelementsbyclassname/
*/
var getElementsByClassName = function (className, tag, elm){
	if (document.getElementsByClassName) {
		getElementsByClassName = function (className, tag, elm) {
			elm = elm || document;
			var elements = elm.getElementsByClassName(className),
				nodeName = (tag)? new RegExp("\\b" + tag + "\\b", "i") : null,
				returnElements = [],
				current;
			for(var i=0, il=elements.length; i<il; i+=1){
				current = elements[i];
				if(!nodeName || nodeName.test(current.nodeName)) {
					returnElements.push(current);
				}	
			}
			return returnElements;
		};
	}
	else if (document.evaluate) {
		getElementsByClassName = function (className, tag, elm) {
			tag = tag || "*";
			elm = elm || document;
			var classes = className.split(" "),
				classesToCheck = "",
				xhtmlNamespace = "http://www.w3.org/1999/xhtml",
				namespaceResolver = (document.documentElement.namespaceURI === xhtmlNamespace)? xhtmlNamespace : null,
				returnElements = [],
				elements,
				node;
			for(var j=0, jl=classes.length; j<jl; j+=1){
				classesToCheck += "[contains(concat(' ', @class, ' '), ' " + classes[j] + " ')]";
			}
			try	{
				elements = document.evaluate(".//" + tag + classesToCheck, elm, namespaceResolver, 0, null);
			}
			catch (e) {
				elements = document.evaluate(".//" + tag + classesToCheck, elm, null, 0, null);
			}
			while ((node = elements.iterateNext())) {
				returnElements.push(node);
			}
			return returnElements;
		};
	}
	else {
		getElementsByClassName = function (className, tag, elm) {
			tag = tag || "*";
			elm = elm || document;
			var classes = className.split(" "),
				classesToCheck = [],
				elements = (tag === "*" && elm.all)? elm.all : elm.getElementsByTagName(tag),
				current,
				returnElements = [],
				match;
			for(var k=0, kl=classes.length; k<kl; k+=1){
				classesToCheck.push(new RegExp("(^|\\s)" + classes[k] + "(\\s|$)"));
			}
			for(var l=0, ll=elements.length; l<ll; l+=1){
				current = elements[l];
				match = false;
				for(var m=0, ml=classesToCheck.length; m<ml; m+=1){
					match = classesToCheck[m].test(current.className);
					if (!match) {
						break;
					}
				}
				if (match) {
					returnElements.push(current);
				}
			}
			return returnElements;
		};
	}
	return getElementsByClassName(className, tag, elm);
};
