var COUNCIL_INITIAL_TEXT = "Enter a postcode, address, or council name.\nPlease use commas to separate multiple search terms.\nDo not use commas if entering an address.";
var COUNCIL_INITIAL_TEXT2 = "Enter a postcode, address, or council name, then select Continue.\nPlease use commas to separate multiple search terms.\nDo not use commas if entering an address.";

var councilPrefix = "";
var lastValidatedCouncilText = "";

function openCouncilM2M()
{
	  if(displayingM2MSelector)
	  {
	  	// user is validating a different field
	  	return;
	  } 
	  
	  councilM2MCheckboxClicked();
	  
	  clearAllPopups();
	  showPopup("COUNCIL_M2M_SELECT");
		
		displayingM2MSelector = true;
		
		document.getElementById("btn-councilM2MOK").focus();		
		
		return false;	
} 
  
 /*
  function setCouncilRightList()
  { removeAllFromList("rightCouncilList");
  
	  var listObject = document.getElementById(councilPrefix+"selectedCouncilList");
	  
	  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("rightCouncilList", listObject.childNodes[i].innerHTML, listObject.childNodes[i].title, listObject.childNodes[i].id);
	    	  addToList("rightCouncilList", listObject.childNodes[i].innerHTML, listObject.childNodes[i].innerHTML, listObject.childNodes[i].id);
	    }
	  }  
  }
   

  
  function editCouncils(prefix)
  {   
  	councilPrefix = prefix;
  	
     // open up the popup which shows the selected 
     // FogBugz 9916 - don't clear out left list prior to edit - removeAllFromList("leftCouncilList");
     
     setCouncilRightList();
     
     if(countElementsInList("rightCouncilList") == 0)
     {
       showInfoMessage("Find Council", "You must select a council before you can edit your councils.");
       return false;
     }
     
     openCouncilM2M();
     
     return false;
  }
  
  
function browseCouncils(prefix)
{   councilPrefix = prefix;
	
    document.getElementById(councilPrefix+"businessLocation").value = ""; // so does not get recorded as search text for selected items
    document.getElementById(councilPrefix+"businessLocation").style.color = "#333333"; // Gemini issue 3654
    
    var daURL = "my-business-1?cmd=find_all_council";
    //alert(daURL);
    document.getElementById("hiddenIFRAME").src = daURL; 
    
    return false; 
} 
*/


  
  function findCouncil(prefix)
  {
  	councilPrefix = prefix;
  	
    var text = document.getElementById(councilPrefix+"businessLocation").value.trim().replace(/\n/g, "").replace(/\\/g, "");
    
    if(text == lastValidatedCouncilText.trim().replace(/\n/g, ""))
	{  // no change in text so do nothing
			    	 return;
	 }
    else if(text == "" || text == COUNCIL_INITIAL_TEXT.trim().replace(/\n/g, "") || text == COUNCIL_INITIAL_TEXT2.trim().replace(/\n/g, ""))
    {
      // clear out selections so far
      parent.removeAllFromList(councilPrefix+"selectedCouncilList");  
      postCouncilSelections();
      return;
    }
    
    
		if(doingValidate || SHOWING_PLEASE_WAIT_MESSAGE)
		{  // can't validate right now as something else is being validated
			 return;
		}
			    
		doingValidate = true;    
		
		// remove | and ^ characters
		text = text.replace(/|/g, '');
		text = text.replace(/\^/g, '');
  
    var daURL = "my-business-1?cmd=find_council&text="+encodeURIComponent(text);
    //alert(daURL);
    document.getElementById("hiddenIFRAME").src = daURL;  
    
    showPleaseWait("Please wait while your Location(s) are validated.");
  
  }
  
  

  
  function noCouncilFound(searchText)
  {
        hidePleaseWait();
        
	  if(displayingM2MSelector)
	  {
	  	// wait until user has stopped validating a different field
	  	return;
	  } 
    
    showInfoMessage("Location not found", "No locations were found for "+searchText+".<br/><br/>Please try again. Often a single word will produce better results e.g. try 'Blackburn' instead of 'Blackburn South' or enter a postcode.")
    
    requestedNextPage = false; // abort moving to next page as the users input could not be validated
    
    // clear out selections so far
    parent.removeAllFromList(councilPrefix+"selectedCouncilList");  
    postCouncilSelections();

    
  }
  
  function setCouncilInputText()
  {
  	        var text = "";
  	        
         	  // set the input box text
         	  var count = 0;
         	  var listObject = document.getElementById(councilPrefix+"selectedCouncilList");
					  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(councilPrefix+"businessLocation").value = text;	
					  
					  lastValidatedCouncilText = text;
					  
					  //requestedNextPage = requestedNextPage && (count > 0); requestedNextPage = requestedNextPage && (count > 0); this line is not relevant - may have chosen to cancel
					  
					  expandTextboxHeightToFit( document.getElementById(councilPrefix+"businessLocation"), 50 );		  
					  					  
					  
					  doingValidate = false;  
  	
  }  
  
  function postCouncilSelections()
  {
       var selectedCount = countElementsInList(councilPrefix+"selectedCouncilList");
       
      /* BC 15 Jan 2009: Never hide this message (Gemini issue 3754)
      if(document.getElementById("noCouncilMessage"))
			{
				  if( selectedCount == 0 )
					{ document.getElementById("noCouncilMessage").style.display = "";		 
					}
					else
				  {  document.getElementById("noCouncilMessage").style.display = "none";		 
					}
			}
			*/		
			if(document.getElementById("manyCouncilMessage"))
			{
					     if( selectedCount > 1 )
			         {  document.getElementById("manyCouncilMessage").style.display = "";
				       }
				       else
				       {  document.getElementById("manyCouncilMessage").style.display = "none";
				       }				 
			}	 
				  
			setCouncilInputText();  
			
			if(requestedNextPage)
			{
				 nextPage();
			}    	
  	
  }  
  
  function councilM2MCheckboxClicked()
  {
    showHideManyCouncilMessageInM2M();
  }
  
  function showHideManyCouncilMessageInM2M()
  {
    var selectionCount = 0;
    
	  var table = document.getElementById("pop-upCOUNCIL_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("manyCouncilMessageInM2M").style.display = "";
	  }
	  else
	  {  document.getElementById("manyCouncilMessageInM2M").style.display = "none";
	  }  	
  }  
  
  //
  // sort by phrase a[3] then by name a[2]
  //  
  function sortIdNameAddressArray(a, b){
    //Compare "a" and "b" in some fashion, and return -1, 0, or 1
    if(a[3].toUpperCase() > b[3].toUpperCase())
    {  return 1;
    }
    else if(a[3].toUpperCase() < b[3].toUpperCase())
    {  return -1;
    }    
    
    if(a[2].toUpperCase() > b[2].toUpperCase())
    {  return 1;
    }
    else if(a[2].toUpperCase() < b[2].toUpperCase())
    {  return -1;
    }
    return 0;
  }  
  
  /**
    *  v_foundArray = array of array(4) - (cspd_id, cspd_name,address_line,originalSearchText)
    */
  function setCouncilsFound(v_foundArray, searchText, v_noMatchArray)
  {
      hidePleaseWait();  
  	
	  if(displayingM2MSelector)
	  {
	  	// wait until user has stopped validating a different field
	  	return;
	  }  	
  	
      //alert(v_foundArray.length+" matches for the location '"+searchText+"'");
	  if(v_foundArray.length > 200)
	  {
			showInfoMessage("Location Too Broad", "Your location search has returned too many results ("+v_foundArray.length+").<br/><br/>Please refine your Location keyword and try again.")
			return;
	  }     
	  

      //
      // If only ony record matched per phrase then don't bother showing the M2M selector
      //
      
      var idNameAddressArray = new Array();
      var phraseMatchCounts = new Object();
      for( var i=0; i < v_foundArray.length; i++)
      {  
         var daId = v_foundArray[i][0];
         var daName = v_foundArray[i][1].trim();
         var daAddress = v_foundArray[i][2].trim();
         var daSearchText = v_foundArray[i][3].trim();
         
         if(!phraseMatchCounts[daSearchText] || phraseMatchCounts[daSearchText] == null || phraseMatchCounts[daSearchText] == 0)
         {  
         	  phraseMatchCounts[daSearchText] = 1;
         }
         else
         { phraseMatchCounts[daSearchText] = phraseMatchCounts[daSearchText]+1;
         }         
         
         idNameAddressArray[idNameAddressArray.length] = [daId, daName, daAddress, daSearchText];
      }
      idNameAddressArray.sort(sortIdNameAddressArray);
      
      
      var maxCountForPhrase = 0;
      for(phrase in phraseMatchCounts)
      {  
      	if(maxCountForPhrase < phraseMatchCounts[phrase])
      	{  maxCountForPhrase = phraseMatchCounts[phrase];
      	}
      }
      
		//
		// If only one record matched per search text then don't bother showing the M2M selector
		//      
      if(maxCountForPhrase == 1)
      {
  	     // clear out selections so far
  	     parent.removeAllFromList(councilPrefix+"selectedCouncilList"); 
  	     
  	     for( var i=0; i < idNameAddressArray.length; i++)
         {  
							      var daId = idNameAddressArray[i][0];
							      var daName = idNameAddressArray[i][1].trim();
							      var daAddress = idNameAddressArray[i][2].trim();
							      
										   
							      var addressLine = daAddress;
							      if(addressLine.length > 0)
							      {  addressLine += ", ";
							      }
							      addressLine += daName;	      
							      
							      if(!isInList(councilPrefix+"selectedCouncilList", addressLine) )
							      {  addToList(councilPrefix+"selectedCouncilList", addressLine, addressLine, daId);
							      }	
         }     

   	     // ----------------------------------------------------------------
   	     // show message if some keywords had no matches
   	     if(v_noMatchArray.length > 0)
   	     {
   	     	  var msg = "No locations 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(){ postCouncilSelections(); } // only move on after info popup is closed
   	     	  showInfoMessage("Warning: Not All Keywords Could Be Matched", msg);
   	     }
   	     else
   	     {  postCouncilSelections();
   	     }
   	     // ----------------------------------------------------------------   	     
   	     

      	 return;
      }         
      
      var extraAddressesToAutoCheck = new Array();
      var addressLinesSoFar = new Array(); 
      var idNameAddressArrayNoDuplicates = new Array();
      for( var i=0; i < idNameAddressArray.length; i++)
      {  
         var daId = idNameAddressArray[i][0];
         var daName = idNameAddressArray[i][1];
         var daAddress = idNameAddressArray[i][2];
         var daSearchText = idNameAddressArray[i][3];  
         
         var addressLine = daAddress;
         if(addressLine.length > 0)
         {  addressLine += ", ";
         }
         addressLine += daName;	             	
      	
      	  if(!addressLinesSoFar.contains(addressLine))
      	  {  
      	  	idNameAddressArrayNoDuplicates[idNameAddressArrayNoDuplicates.length] = idNameAddressArray[i];
      	  	
      	  	addressLinesSoFar[addressLinesSoFar.length] = addressLine;      	  	
      	  	
      	  }
      	  else if(phraseMatchCounts[daSearchText] == 1)
      	  {  
      	  	  // make a note that we should automatically check this addresses checkbox (eg. like if did a search on Preston, 3072)
      	  	  extraAddressesToAutoCheck[extraAddressesToAutoCheck.length] = addressLine;
      	  }
      	
      }
  
      
      // show popup with checkboxes
			var table = document.getElementById("pop-upCOUNCIL_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 < idNameAddressArrayNoDuplicates.length; i++)
      {
         // add to left hand list
         // element is of type [id, name]

         // add checkbox
         // element is of type [id, node_type, name]
         var daId = idNameAddressArrayNoDuplicates[i][0];
         var daName = idNameAddressArrayNoDuplicates[i][1];
         var daAddress = idNameAddressArrayNoDuplicates[i][2];
         var daSearchText = idNameAddressArrayNoDuplicates[i][3];
         
         //------------------------------------------------------
         // add row for keyword
         if(lastPhrase != daSearchText)
         {
				         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 = "Locations matching '"+daSearchText+"'";
							   
							   td1.appendChild(span); 
				
							   phraseRow.appendChild(td1);
							   tbody.appendChild(phraseRow);         	  
         	
         	  lastPhrase = daSearchText;
         }
         //------------------------------------------------------         
         
         
         // add row
         var row = document.createElement("TR");
			   var td1 = document.createElement("TD");
			   td1.style.valign="top";
			   
         var addressLine = daAddress;
         if(addressLine.length > 0)
         {  addressLine += ", ";
         }
         addressLine += daName;			   
			   
			   var chkbox = document.createElement('input');    
			   chkbox.type = 'checkbox'; 
			   chkbox.id = daId; 
			   chkbox.name = 'chkbt' + daId;  
			   chkbox.value =  addressLine;  
			   chkbox.onclick = councilM2MCheckboxClicked;
			   
			   if((daSearchText == addressLine.replace(/,/g, '')) || phraseMatchCounts[daSearchText] == 1 || extraAddressesToAutoCheck.contains(addressLine))  // 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(addressLine));
			   
			   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 locations matched '"+v_noMatchArray[i]+"'";
					   
					   td1.appendChild(span); 
			
					   phraseRow.appendChild(td1);
					   tbody.appendChild(phraseRow);         	  
      	
      }   
      // --------------------------------------------------         
      
      table.appendChild(tbody);
      
      openCouncilM2M();
      
      // 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;
      }
      
  }

// return [name|searchText|id^]  
function getCouncilString(prefix)
{
  var listObject = document.getElementById(prefix+"selectedCouncilList");

	var councilsString = "";  
	for(var i=0; i < listObject.childNodes.length; i++)
	{
	  if(listObject.childNodes[i].tagName == "LI")
	  {   councilsString += listObject.childNodes[i].innerHTML+"|"+listObject.childNodes[i].title+"|"+listObject.childNodes[i].id+"^";
	  }
	}
	return councilsString;
}   


function councilM2MSelectionsMade()
{
	
	  var selectionArray = new Array();
	
	  var table = document.getElementById("pop-upCOUNCIL_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(councilPrefix+"selectedCouncilList", chkbox.value, "", chkbox.id);
	  	                  	  selectionArray[selectionArray.length] = new Array(chkbox.id, chkbox.value);
	  	                  }
	        	          }
	                }  
	        	  }
	        }
		    	
		    }	  	
	  }

	  if(selectionArray.length == 0)
	  {   // If user makes no selection and clicks Continue then display error message 'At least one location must be selected'
	  	  //alert("At least one location must be selected.");
	  	  
	  	  // this message is not required - just continue
	  	  //showInfoMessage("Selection Required", "At least one location must be selected.");
	  	  //return;
	  }
	  	
    // clear out selections so far
    parent.removeAllFromList(councilPrefix+"selectedCouncilList");  
    
    for(var i=0; i < selectionArray.length; i++)
    {   
    	  var daId = selectionArray[i][0];
    	  var daName = selectionArray[i][1];
    	
    	  addToList(councilPrefix+"selectedCouncilList", daName, daName, 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();	
    
     postCouncilSelections();
        
}

function councilM2MSelectionsCancelled()
{
	  displayingM2MSelector = false;
	  
	  requestedNextPage= false; // cancel moving to next page if hit cancel
	  
	  postCouncilSelections();
}