//Global array that contains the items of the BreadCrumb
var ctbSection;
//Global Boolean flag to determine the checkout process
var checkoutPage;

/*
	This function is used to set the section , 
	category and sub-category for all tagged pages
*/
 function loadLiveChat(){	
	
	ctbSection=loadBreadCrumb();	
	
	//Please remove the following section to enable live chat functionality for all pages
   	//if(ctbSection.length < 1 || (ctbSection[1]!='Grants' && ctbSection[1]!='Services' && ctbSection[1]!='Products'))
   	//	return; 
    
	checkoutPage=isCheckoutPage();
	insertChatButtonDiv();	
	
   //Set the CustomerType & VisitorID variable
   liveChatVisitor();
      
   //Set the section,category & sub-category variables
   if( ctbSection.length > 1 ){	  
	   lpAddVars( 'page', 'Section', ctbSection[1] );
   }
   if( ctbSection.length > 2 ){	         
	   lpAddVars( 'page', 'Category', ctbSection[2]);
   }
   if( ctbSection.length > 3 ){	   
	   lpAddVars( 'page', 'SubCategory', ctbSection[3]);
   }
   
   //Set the checkout page variables if necessary
   if(checkoutPage)
	   setConversionStage();
   
   //Set onclick event of the NextStep buttons
   $("div .sideCol .entry.icons").children("div[rel]").each(function(){
   		var rel=$(this).attr("rel");   		
   		$(this).children("a").click(function(){   			
	    	lpSendData( 'page', 'NextStepSelection',rel);
	    });
	});
	
   //Set error name and error counter for Custom Error
   var errors=getCustomErrors();
   if(errors && errors.length!=0){
	   ctbErrors.push(errors);
	   addLiveChatErrors(errors);
   }
   
   //Set CartTotal for all pages
   setCartTotalValue();
   
}

/*
 * This function is used to determine whether 
 * the page is part of the checkout process or
 * not
 */
 function isCheckoutPage(){
	 if(ctbSection[1]== 'Store' || ctbSection[1]=='Login'){
		 if($("#checkoutProgress").length!=0 || ctbSection[2]== 'Order Confirmation')
			 return true;
		 else
			 return false;
	 }else
		 return false;
}
 /*
  * This function is used to load the 
  * section,category & subcategory values 
  * from breadcrumb
  */
 function loadBreadCrumb(){
	 var sections=new Array(); 
	 var anchors=$(".breadcrumb a");
	 if($("#changePwdFlag").val()!="Y"){
		 if(anchors.length == 0){
			 sections.push("");
			 sections.push("Home");
			 return sections;
		 }
		 
		 for(var i=0;i<anchors.length;i++){
			sections.push(getText($(anchors[i]).text()));		
		 }
		 
		 var lastAnchorText=sections[sections.length-1];
		 
		 var val=getText($(".breadcrumb").text());
		 var position=val.indexOf(lastAnchorText)+lastAnchorText.length;
		 position=val.indexOf("/",position);   
		 sections.push($.trim(val.substring(position+1,val.length)));
		 return sections;
     }else{         
		 return sections;
	 }
}
/*
	This function is used to set lpUnitValues
*/
 function lpUnitValues(){   	
	 if (ctbSection[1] == "Store" || ctbSection[1] == "Login"){
		 if(checkoutPage)
			 lpUnit='store';
		 else
			 lpUnit='products';
	}else{
 		lpUnit='products';
	}
   
}

/*
	This function is used to set VisitorID and  CustomerType
*/
function liveChatVisitor(){
	if($("#loggedStatus").val()=="N"){
		lpAddVars( 'page', 'CustomerType', 'Anonymous' );
	}else{
		lpAddVars( 'page', 'CustomerType', 'Registered' );
		lpAddVars( 'visitor', 'VisitorID', $("#loggedUser").val() );	
	}
}
/*
	This function is used to remove whitespace from
	a given string
*/
function getText(text){
	if(!text ||	text.length == 0)
		return text;
	text=text.replace(/[\n\r\t\v\u2028\u2029]/g,'');
	return $.trim(text);
}

/*
 * This function is used to insert the chat button div 
 * for NextStep Section
 */
function insertChatButtonDiv(){
		
	if(ctbSection[1]=='Login' || ctbSection[1] == 'Store'){			
		var storeProductSearchDiv=$("#storeProductSearchOuter");
		if(storeProductSearchDiv.length==0)
			return;
		
		if(checkoutPage){
			storeProductSearchDiv.before('<div id="lpButtonCheckout" class="storeChatButton" ></div>');
		}
	    else{
		   if( ctbSection.length > 3 ){
			   storeProductSearchDiv.before('<div id="lpButtonSubCategory" class="storeChatButton" ></div>');
	       }else{
	    	   storeProductSearchDiv.before('<div id="lpButtonCategory" class="storeChatButton" ></div>');
	       }
	   }
	}else{
		if ( $(".sideCol .icons").length ) {
		   if(ctbSection[1] == 'eNewsletter')
			   return;
	       if( ctbSection.length > 3 ){
	    	   $(".sideCol .icons div.liveChatButton").attr("id","lpButtonSubCategory");
	       }else{
	    	   $(".sideCol .icons div.liveChatButton").attr("id","lpButtonCategory");
	       }
	   }
	}
}


/*
 * This method is used to send ProductOfferingClick variable depending
 * on the whether a category has any further sub categories.
 * Here 'h5Element' represents the header element of the accordian of a category 
 * in the product offering page
 */
function setProductOffering(h5Element){
	try{
		lpSendData( 'page', 'ProductOfferingClick',getText(h5Element.children("a").eq(0).text()));			
	}catch(e){}
}


/*
 * This method is used to send ProductOfferingClick variable depending
 * on the whether a category has any further sub categories.
 * Here 'h5Element' represents the header element of the accordian of a category 
 * in the product offering page and 'subCategories' is the html(comes via AJAX call) 
 * that contains the subcategory details of the corresponding category.
 */
function _setProductOffering(h5Element,subCategories){
	try{
		if(h5Element.attr("rel") == "G"){
			if(h5Element.next().find("ul .ui-accordion-content").length != 0){			
				lpSendData( 'page', 'ProductOfferingClick',getText(h5Element.children("a").eq(0).text()));
				return;
			}
		}
		if(subCategories && subCategories.length!=0)		
			lpSendData( 'page', 'ProductOfferingClick',getText(h5Element.children("a").eq(0).text()));
	}catch(e){}
}

/*
 * This function is used to set ConversionAction variable depending on whether 
 * the page is part of the checkout page
 */
function  setConversionStage(){
	
	//var sectionValue = ctbSection[1];
	var sectionValue = ctbSection[ctbSection.length-1];
	
	if(sectionValue == 'Login'){
		lpAddVars( 'page', 'ConversionStageNumber',1);
		lpAddVars( 'page', 'ConversionStage','Login');
	}
	if(sectionValue == 'Shopping Cart'){
		lpAddVars( 'page', 'ConversionStageNumber', 2 );
		lpAddVars( 'page', 'ConversionStage','Review Cart');
	}
	if(sectionValue == 'Shipping and Payment'){
		lpAddVars( 'page', 'ConversionStageNumber', 3 );
		lpAddVars( 'page', 'ConversionStage','Shipping & Payment');
	}
	if(sectionValue == 'Submit Order'){
		lpAddVars( 'page', 'ConversionStageNumber', 4 );
		lpAddVars( 'page', 'ConversionStage','Submit Order');	
	}
}

/*
 * This function is used to set the cart total variable 
 * to live chat
 */
function setCartTotalToLiveChat(cartTotal){
	try{
		lpAddVars( 'page', 'CartTotal', cartTotal );
	}catch(e){}
}

/*
 * This function is used to set order confirmation 
 * variables
 */
function setOrderConfirmationVarsToLiveChat(){
	try{
		lpAddVars( 'page', 'OrderNumber', $('#orderNumber').val() );
		lpAddVars( 'page', 'OrderTotal', $('#orderTotal').val() );
	}catch(e){}
}


/*
 * This function is used to set ErrorName and ErrorCounter  
 * variables
*/
function getCustomErrors(){ 
 	var errors=$("table td[id='text']");
 	var msgs;
 	if(errors.length!=0){
 		msgs=new Array();
 		for(var i=0;i<errors.length;i++)
 			msgs.push(errors.eq(i).text()); 		     	
	}
	return msgs;
}

/*
 * This function is used to form error messages
 * out of the list of error messages
 */
function getErrorMsg(errors){
	var msg='';
	var length=errors.length;
	for(var i=0;i<length;i++){			
		msg+=errors[i];
		if(i!=(length-1))
			msg+=',';
	}
	return msg;
}
/* 
* This function is used to set ConversionAction variable 
* for live chat 
*/
function setConversionAction(action){ 
    try{    	
        lpSendData( 'session', 'ConversionAction', action);         
    }catch(e){}
}

/*
 * This function is used to capture the list of errors
 * in the next step section modal window
 */
function getNextStepModalErrors(){
	var errors=null;	
	var labels=$("label.errors:visible");	
	if(labels.length!=0){
		errors=new Array();
		var label;
		var fieldName;
		for(var i=0;i<labels.length;i++){
			label=labels.eq(i);
			fieldName=label.parent().prev().text();
			errors.push(fieldName+":"+label.text());
		}
	}
	return errors;
}

/*
 * This function is used to add ErrorName & ErrorCounter
 */
function addLiveChatErrors(errors){
	try{
		if(errors && typeof(errors)=='object' && errors.length && errors.length!=0){			
			lpAddVars( 'page', 'ErrorName', errors.join());
			lpAddVars( 'page', 'ErrorCounter', errors.length);
		}
	}catch(e){}
}

/*
 * This function is used to set ErrorName & ErrorCounter
 */
function setLiveChatErrors(errors){
	try{
		if(errors && typeof(errors)=='object' && errors.length && errors.length!=0){			
			lpSendData( 'page', 'ErrorName', errors.join());
			lpSendData( 'page', 'ErrorCounter', errors.length);
		}
	}catch(e){}
}


//Global scoped array for storing the errors messages
var ctbErrors=new Array();

/*
 * This function is used to set the ErrorName & 
 * ErrorCounter for a given error string
 */
function getReviewCartError(msg){
	if(msg && msg.length!=0){
		ctbErrors.push(msg);
		setLiveChatErrors(ctbErrors);
	}	
}

/*
 * This function is used to set the ErrorName & 
 * ErrorCounter accordingly for a given array of error strings
 */
function getReviewCartErrors(msg){
	if(msg && msg.length!=0){
		for(var i=0;i<msg.length;i++){
			if(msg[i])
				ctbErrors.push(msg[i]);
		}
		setLiveChatErrors(ctbErrors);
	}
}

/*
 * This function is used to set the CartTotal for all the pages
 */
function setCartTotalValue(){
try{
 	if($("#liveChatNumberOfItem").val()!=0){
		lpAddVars( 'page', 'CartTotal', $("#liveChatCartTotal").val());
	}
  }catch(e){}
}


