var BUSINESS_TYPE_INITIAL_TEXT = "Enter one or more keywords e.g. cafe, salon.\nPlease use commas to separate multiple search terms.";

var businessTypePrefix = "";
var lastValidatedBusinessTypeText = "";


/*
var businessTypeBrowseIFRAMELoaded = false;

var businessTypeBrowseChild = null;
function setBusinessTypeBrowseChild( daObject )
{   businessTypeBrowseChild = daObject;
	  resetSelectionsInBusinessTypeBrowseChildIframe();
}

function resetSelectionsInBusinessTypeBrowseChildIframe()
{
	 //alert("resetSelectionsInBusinessTypeBrowseChildIframe businessTypePrefix="+businessTypePrefix);
	 
	 if(businessTypePrefix == null || businessTypePrefix == "")
	 {  //alert("resetSelectionsInBusinessTypeBrowseChildIframe: No businessTypePrefix set!");
	 	  return;
	 }
	
	 if(businessTypeBrowseChild != null) 
	 {	 
		  try{  
		  		 	
		 	  // BC 27 Feb 2009: Gemini 3110
		 	  // pre-populate it with selected ids
		 	  var idsToAdd = new Array();
			  var listObject = document.getElementById(businessTypePrefix+"selectedBusinessTypeList");
			  if(listObject != null)
			  {
					  for(var i=0; i < listObject.childNodes.length; i++)
					  {
						    if(listObject.childNodes[i].tagName == "LI")
						    {  idsToAdd[idsToAdd.length] = listObject.childNodes[i].id;
						    }
					  }				  	
			  }
			  //alert("idsToAdd.length="+idsToAdd.length);
 	
		 	
			  // remove all unselected
			  var currentBrowseSelections = businessTypeBrowseChild.getAllSelectedIdsArray( );
			  //alert("currentBrowseSelections.length = "+currentBrowseSelections.length);
			  var currentlySelectedInBrowse = new Array();
			  for(var i=0; i < currentBrowseSelections.length; i++)
			  {       currentlySelectedInBrowse[currentlySelectedInBrowse.length] = currentBrowseSelections[i];
			  	    
  	
			  } 
			  for(var i=0; i < currentlySelectedInBrowse.length; i++)
			  {       var id = currentlySelectedInBrowse[i];
			  	
			  	      //alert(id+" is selcted = "+businessTypeBrowseChild.isInAllSelectedIdsArray( id ));
			  	    
	              if( businessTypeBrowseChild.document.getElementById(id+"-icon") && businessTypeBrowseChild.isInAllSelectedIdsArray( id ))
				    	  {  
				    	  	  //alert("resetSelectionsInBusinessTypeBrowseChildIframe UNCHECKING "+id);
				    	  	  businessTypeBrowseChild.webFXTreeHandler.checkOrUncheck( businessTypeBrowseChild.document.getElementById(id+"-icon") );
				    	  }					  	   
			  }
				  	
			  for(var i=0; i < idsToAdd.length; i++)
			  {
			        var id = idsToAdd[i];
			    	  
			    	  if( businessTypeBrowseChild.document.getElementById(id+"-icon")  && !businessTypeBrowseChild.isInAllSelectedIdsArray( id ))
			    	  {  
			    	  	  //alert("resetSelectionsInBusinessTypeBrowseChildIframe CHECKING "+id);
			    	  	  businessTypeBrowseChild.webFXTreeHandler.checkOrUncheck( businessTypeBrowseChild.document.getElementById(id+"-icon") );
			    	  }
			    	  else
			    	  {  businessTypeBrowseChild.addToAllSelectedIdsArray( id );
			    	  }
			  } 
	
		  }catch(error)
		  {  alert("JS error: business-type-m2m.js.resetSelectionsInBusinessTypeBrowseChildIframe, "+error.message+", businessTypePrefix="+businessTypePrefix);
		  }	 	  
      
	 }	  
}
*/
  
  /*
   * Populate the right list with the selected business types

  function setBusinessTypeRightList()
  { removeAllFromList("rightBusinessTypeList");
  
	  var listObject = document.getElementById(businessTypePrefix+"selectedBusinessTypeList");
	  
	  try{ 
	  	
		  for(var i=0; i < listObject.childNodes.length; i++)
		  {
		    if(listObject.childNodes[i].tagName == "LI")
		    {  
		    	 // Gemini issue 4464 - show full name as roll-over tooltip. We won't be able to keep the original search text in this case but not critical.
		    	 //addToList("rightBusinessTypeList", listObject.childNodes[i].innerHTML, listObject.childNodes[i].title, listObject.childNodes[i].id);
		    	 addToList("rightBusinessTypeList", listObject.childNodes[i].innerHTML, listObject.childNodes[i].innerHTML, listObject.childNodes[i].id);
		    
		    	
		    	 // BC 25 Mar 2009 - make sure is not in left list
		    	 removeFromSelect("leftBusinessTypeList", listObject.childNodes[i].innerHTML);		    
		    
		    }
		  } 

	  }catch(error)
	  {  alert("JS error: business-type-m2m.js.setBusinessTypeRightList, "+error.message+", businessTypePrefix="+businessTypePrefix);
	  }
	  
  }  
  
     */
  
  function findBusinessType(prefix)
  {
          businessTypePrefix = prefix;
          
          var text = document.getElementById(businessTypePrefix+"businessType").value.trim().replace(/\n/g, "").replace(/\\/g, "");

          if(text == lastValidatedBusinessTypeText.trim().replace(/\n/g, ""))
			    {  // no change in text so do nothing
			    	 //alert("findBusinessType no change since last validated");
			    	 return;
			    }
			    else if(text == "" || text == BUSINESS_TYPE_INITIAL_TEXT.trim().replace(/\n/g, ""))
			    {
					    // clear out selections so far
					    parent.removeAllFromList(businessTypePrefix+"selectedBusinessTypeList");   
					  	postBusinessTypeSelections();
					  	return;
			    }
			    
			    
			    if(doingValidate || SHOWING_PLEASE_WAIT_MESSAGE)
			    {  // can't validate right now as something else is being validated
			    	 return;
			    }
			    
			    doingValidate = true;
			    
			    // convert é to e
			    text = text.replace(/é/g, 'e');
			    
			    // remove | and ^ characters
				text = text.replace(/|/g, '');
				text = text.replace(/\^/g, '');
			    
			    var daURL = "my-business-1?cmd=find_business_type&text="+encodeURIComponent(text);
			    
			    document.getElementById("hiddenIFRAME").src = daURL;   
			    
			    showPleaseWait("Please wait while your Business Type(s) are validated."); 
           
  }
  
  function noBusinessTypeFound(searchText)
  {    
        hidePleaseWait();
        	  
			  if(displayingM2MSelector)
			  {
			  	// wait until user has stopped validating a different field
			  	return;
			  }  	
		  	
		  	showInfoMessage("Business type not found", "No business types were found for "+searchText+".<br/><br/>Please try again. Often a single word will produce better results e.g. try 'wine' instead of 'wine production'.");
		  	
		  	requestedNextPage = false; // abort moving to next page as the users input could not be validated
		  	    
		    // clear out selections so far
		    parent.removeAllFromList(businessTypePrefix+"selectedBusinessTypeList");   
		  	postBusinessTypeSelections();

 	 
  }
  
  function setBusinessTypeInputText()
  {
  	
  	        var text = "";
  	        
         	  // set the input box text
         	  var count = 0;
         	  var listObject = document.getElementById(businessTypePrefix+"selectedBusinessTypeList");
					  for(var i=0; i < listObject.childNodes.length; i++)
					  {
					  	if(listObject.childNodes[i].innerHTML)
					  	{
						    if(listObject.childNodes[i].tagName == "LI")
						    {   text += listObject.childNodes[i].innerHTML.trim().replace(/,/g, "")+",\n"; // got to remove commas as the search logic will assume they are spearate phrases!
						    	  count++;
						    }	  		
					  	}
					  } 
					  
					  // remove last comma
					  if( text.length > 0 )
					  {  text = text.substring(0, text.length-2).trim();
					  }  

					  document.getElementById(businessTypePrefix+"businessType").value = text;	
					  
					  lastValidatedBusinessTypeText = text;
					  
					  //requestedNextPage = requestedNextPage && (count > 0);
					  
					  expandTextboxHeightToFit( document.getElementById(businessTypePrefix+"businessType"), 50 );		  
					  
					  
					  doingValidate = false;
  	 
  }
  
  function postBusinessTypeSelections()
  {
		      if(document.getElementById("manyBusinessTypeMessage"))
				  {
							  if( countElementsInList(businessTypePrefix+"selectedBusinessTypeList") > 1 )
							  {  document.getElementById("manyBusinessTypeMessage").style.display = "";
								}
								else
								{  document.getElementById("manyBusinessTypeMessage").style.display = "none";
								}		  	
				  }	 
				  
				  setBusinessTypeInputText(); 
				  
				  //alert("postBusinessTypeSelections = requestedNextPage="+requestedNextPage); 
				  
				  if(requestedNextPage)
				  {
				  	  nextPage();
				  }  	
  	
  }
  
  //
  // sort by phrase a[2] then by name a[1]
  //
  function sortIdNamePhraseArray(a, b){
    //Compare "a" and "b" in some fashion, and return -1, 0, or 1
    
    if(a[2].toUpperCase() > b[2].toUpperCase())
    {  return 1;
    }
    else if(a[2].toUpperCase() < b[2].toUpperCase())
    {  return -1;
    }    
    
    if(a[1].toUpperCase() > b[1].toUpperCase())
    {  return 1;
    }
    else if(a[1].toUpperCase() < b[1].toUpperCase())
    {  return -1;
    }
    return 0;
  }
  
  function businessTypeM2MCheckboxClicked()
  {
    showHideManyBusinessTypeMessageInM2M();
  }
  
  function showHideManyBusinessTypeMessageInM2M()
  {
    var selectionCount = 0;
    
	  var table = document.getElementById("pop-upBUSINESS_TYPE_M2M_SELECTTable");
	  
	  for(var i=0; i < table.childNodes.length; i++)
	  {
		    if(table.childNodes[i].tagName == "TR")
		    {  
		    	var row = table.childNodes[i];
		    	for(var j=0; j <row.childNodes.length; j++)
	        {  
	        	  if(row.childNodes[j].tagName == "TD")
	        	  {  
	        	  	  var cell = row.childNodes[j];
	        	  	  for(var k=0; k < cell.childNodes.length; k++)
	                {
	                	  if(cell.childNodes[k].tagName == "INPUT")
	        	          {  
	        	          	var chkbox = cell.childNodes[k]; 
	        	          	if(chkbox.checked)
	  	                  {    selectionCount++;
	  	                  }
	        	          }
	                }  
	        	  }
	        }
		    	
		    }	  	
	  }
	  
	  
	  // Email from Chandra 20 May 2009: "Could we have the text that appears below the boxes, if the user has made multiple selections for business type, on the pop-up? 
	  // I know this is not in the original request so please advise if this is a significant effort."
	  if(selectionCount > 1)
	  {
	  	  document.getElementById("manyBusinessTypeMessageInM2M").style.display = "";
	  }
	  else
	  {  document.getElementById("manyBusinessTypeMessageInM2M").style.display = "none";
	  }  	
  }
  
  function setBusinessTypesFound(v_findNextArray, searchText, v_noMatchArray)
  {
      hidePleaseWait();  
  	
	  if(displayingM2MSelector)
	  {
	  	// wait until user has stopped validating a different field
	  	return;
	  } 	

      if(v_findNextArray.length > 200)
      {
      	  showInfoMessage("Business Type Too Broad", "Your business type has returned too many results ("+v_findNextArray.length+").<br/><br/>Please refine your business type keyword and try again.");
      	  return;
      }    
      

      //
      // If only one record matched per phrase then don't bother showing the M2M selector
      //
      
      var idNamePhraseArray = new Array();
      var phraseMatchCounts = new Object();
      for( var i=0; i < v_findNextArray.length; i++)
      {  
         var daId = v_findNextArray[i][v_findNextArray[i].length-1][0];
         var daName = v_findNextArray[i][v_findNextArray[i].length-1][2].trim();
         var daSearchPhrase = v_findNextArray[i][v_findNextArray[i].length-1][3].trim();
         
         if(!phraseMatchCounts[daSearchPhrase] || phraseMatchCounts[daSearchPhrase] == null || phraseMatchCounts[daSearchPhrase] == 0)
         {  
         	  phraseMatchCounts[daSearchPhrase] = 1;
         }
         else
         { phraseMatchCounts[daSearchPhrase] = phraseMatchCounts[daSearchPhrase]+1;
         }
         
         idNamePhraseArray[idNamePhraseArray.length] = [daId, daName, daSearchPhrase];
      }
      idNamePhraseArray.sort(sortIdNamePhraseArray);
      
      var maxCountForPhrase = 0;
      for(phrase in phraseMatchCounts)
      {  
      	if(maxCountForPhrase < phraseMatchCounts[phrase])
      	{  maxCountForPhrase = phraseMatchCounts[phrase];
      	}
      }
      
      
      if(maxCountForPhrase == 1)
      {
  	     // clear out selections so far
  	     parent.removeAllFromList(businessTypePrefix+"selectedBusinessTypeList");  
  	     
  	     for( var i=0; i < idNamePhraseArray.length; i++)
         {  
           var daId = idNamePhraseArray[i][0];
           var daName = idNamePhraseArray[i][1];
           var daSearchPhrase = idNamePhraseArray[i][2];
           
           // don't show M2M selector -> just add the ones we found
	      	 if(!isInList(businessTypePrefix+"selectedBusinessTypeList", daName) )
	         {  
	         	  addToList(businessTypePrefix+"selectedBusinessTypeList", daName, searchText, daId);
	         }
         }            
        	

   	     // ----------------------------------------------------------------
   	     // show message if some keywords had no matches
   	     if(v_noMatchArray.length > 0)
   	     {
   	     	  var msg = "No business types were found for ";
   	     	  for( var i=0; i < v_noMatchArray.length; i++)
   	     	  {  
   	     	  	 msg += v_noMatchArray[i];
   	     	  	 
   	     	  	 if(i < (v_noMatchArray.length - 2))
   	     	  	 {  msg += ", ";
   	     	  	 }
   	     	  	 else if(i < (v_noMatchArray.length - 1))
   	     	  	 {  msg += " & ";
   	     	  	 }   	     	  	 
   	     	  }
   	     	  msg += ".";
   	     	  
   	     	  doAfterCloseInfoPopup = function(){ postBusinessTypeSelections(); } // only move on after info popup is closed
   	     	  showInfoMessage("Warning: Not All Keywords Could Be Matched", msg);
   	     }
   	     else
   	     {  postBusinessTypeSelections();
   	     }
   	     // ----------------------------------------------------------------

      	 return;
      }      
      
      // show popup with checkboxes
			var table = document.getElementById("pop-upBUSINESS_TYPE_M2M_SELECTTable");
			
			// remove all rows
			for(var i=table.childNodes.length-1; i >= 0; i--)
			{
				  table.removeChild(table.childNodes[i]);
			}
			
			var tbody = document.createElement("TBODY"); // BC 04 Jun 2009 - need TBODY otherwise does not render in IE6
			
			var checkboxesToTick = new Array();
			var lastPhrase = "";
      for( var i=0; i < idNamePhraseArray.length; i++)
      {
         //alert(v_findNextArray[i][v_findNextArray[i].length-1]);
         
         // add checkbox
         // element is of type [id, node_type, name, search_phrase]
         var daId = idNamePhraseArray[i][0];
         var daName = idNamePhraseArray[i][1];
         var daSearchPhrase = idNamePhraseArray[i][2];
         
         //------------------------------------------------------
         // add row for keyword
         if(lastPhrase != daSearchPhrase)
         {
				         var phraseRow = document.createElement("TR");
							   var td1 = document.createElement("TD");
							   td1.style.valign="top";
							   td1.colSpan=2;
							   
							   var span = document.createElement("SPAN");
							   span.style.color = "#3333ab";
							   span.innerHTML = "Business types matching '"+daSearchPhrase+"'";
							   
							   td1.appendChild(span); 
				
							   phraseRow.appendChild(td1);
							   tbody.appendChild(phraseRow);         	  
         	
         	  lastPhrase = daSearchPhrase;
         }
         //------------------------------------------------------
         
         // add row
         
         var row = document.createElement("TR");
			   var td1 = document.createElement("TD");
			   td1.style.valign="top";
			   
			   var chkbox = document.createElement('input');    
			   chkbox.type = 'checkbox'; 
			   chkbox.id = daId; 
			   chkbox.name = 'chkbt' + daId;  
			   chkbox.value =  daName;  
			   chkbox.title = daSearchPhrase;
			   chkbox.onclick = businessTypeM2MCheckboxClicked;
			   
			   if((daSearchPhrase == daName.replace(/,/g, '')) || phraseMatchCounts[daSearchPhrase] == 1)  // if this was the only match for a search phrase then check by default
			   {  chkbox.checked = true;
			   	  checkboxesToTick[checkboxesToTick.length] = chkbox;
			   }
			   
			   td1.appendChild(chkbox); 

			   var td2 = document.createElement("TD");
			   td2.style.valign="top";
			   td2.appendChild (document.createTextNode(daName));
			   
			   row.appendChild(td1);
			   row.appendChild(td2);
			   tbody.appendChild(row);
			   
      }
      
      // --------------------------------------------------
      // add rows for keywords that had no matches
      for( var i=0; i < v_noMatchArray.length; i++)
      {
			        var phraseRow = document.createElement("TR");
					   var td1 = document.createElement("TD");
					   td1.style.valign="top";
					   td1.colSpan=2;
					   
					   var span = document.createElement("SPAN");
					   span.style.color = "red";
					   span.innerHTML = "No business types matched '"+v_noMatchArray[i]+"'";
					   
					   td1.appendChild(span); 
			
					   phraseRow.appendChild(td1);
					   tbody.appendChild(phraseRow);         	  
      }   
      // --------------------------------------------------   
      
      table.appendChild(tbody);

      
      openBusinessActivityM2M();
      
      // BC 26 June 2009 - workaround for IE6 and IE7 (they won't display the ticked checkboxes unless they're marked as checked AFTER the M2M popup is displayed)
      for(var i=0; i < checkboxesToTick.length; i++)
      {
      	 checkboxesToTick[i].checked = true;
      }
  }
  
  


function openBusinessActivityM2M()
{
	  if(displayingM2MSelector)
	  {
	  	// wait until user has stopped validating a different field
	  	return;
	  } 
	  
	  showHideManyBusinessTypeMessageInM2M();

    clearAllPopups();
		showPopup("BUSINESS_TYPE_M2M_SELECT");
		
		displayingM2MSelector = true;
		
		document.getElementById("btn-businessTypeM2MOK").focus();
		
		return false;	
}

function getBusinessTypeString(prefix)
{
  var listObject = document.getElementById(prefix+"selectedBusinessTypeList");

	var businessTypeString = "";  
	for(var i=0; i < listObject.childNodes.length; i++)
	{
	  if(listObject.childNodes[i].tagName == "LI")
	  {  businessTypeString += listObject.childNodes[i].innerHTML+"|"+listObject.childNodes[i].title+"|"+listObject.childNodes[i].id+"^";
	  }
	}
	return businessTypeString;
}

function businessTypeM2MSelectionsMade()
{
    var selectionArray = new Array();
    
	  var table = document.getElementById("pop-upBUSINESS_TYPE_M2M_SELECTTable");
	  var tableBody = table.childNodes[0];
	  
	  for(var i=0; i < tableBody.childNodes.length; i++)
	  {
		    if(tableBody.childNodes[i].tagName == "TR")
		    {  
		    	var row = tableBody.childNodes[i];
		    	for(var j=0; j <row.childNodes.length; j++)
	        {  
	        	  if(row.childNodes[j].tagName == "TD")
	        	  {  
	        	  	  var cell = row.childNodes[j];
	        	  	  for(var k=0; k < cell.childNodes.length; k++)
	                {
	                	  if(cell.childNodes[k].tagName == "INPUT")
	        	          {  
	        	          	var chkbox = cell.childNodes[k]; 
	        	          	if(chkbox.checked)
	  	                  {    //addToList(businessTypePrefix+"selectedBusinessTypeList", chkbox.value, chkbox.title, chkbox.id);
	  	                  	   selectionArray[selectionArray.length] = new Array(chkbox.id, chkbox.value, chkbox.title);
	  	                  }
	        	          }
	                }  
	        	  }
	        }
		    	
		    }	  	
	  }
	  
	  if(selectionArray.length == 0)
	  {   // If user makes no selection and clicks Continue then display error message 'At least one business type must be selected'
	  	  //alert("At least one location must be selected.");
	  	  //showInfoMessage("Selection Required", "At least one business type must be selected.");
	  	  //return;
	  }
	  	
    // clear out selections so far
    parent.removeAllFromList(businessTypePrefix+"selectedBusinessTypeList");  
    
    for(var i=0; i < selectionArray.length; i++)
    {   
    	  var daId = selectionArray[i][0];
    	  var daName = selectionArray[i][1];
    	  var daSearchPhrase = selectionArray[i][2];
    	
    	  addToList(businessTypePrefix+"selectedBusinessTypeList", daName, daSearchPhrase, daId);
    }		  
	  

	  displayingM2MSelector = false;
	  
	  
	  
	  
	  // remove the popup
		removeOverlay();
		$('#pop-up'+POPUP_ID).hide();
		
					// workaround for IE6 problem with infinite z indexes on dropdown boxes
					if( is_ie6 && document.getElementById("zIndexFixFrame"))
					{
						 document.getElementById("zIndexFixFrame").style.display = "none";
					}					
		
    removeLastPopupId();	
    showSelect();	
    
    postBusinessTypeSelections();
        	  
}

function businessTypeM2MSelectionsCancelled()
{
	
	  displayingM2MSelector = false;	
	  
	  requestedNextPage= false; // cancel moving to next page if hit cancel
	  
	  postBusinessTypeSelections();
}