var ORGANISATION_INITIAL_TEXT = "Enter an Agency name e.g. Department of Justice.\nPlease use commas to separate multiple search terms.";

var findOrganisationPrefix = "";
var lastValidatedOrganisationText = "";              
              
function findOrganisations(prefix)
{
	  //alert("findOrganisations("+prefix+")");
	
  	findOrganisationPrefix = prefix;
  	
    var text = document.getElementById(findOrganisationPrefix+"findOrganisation").value.trim().replace(/\n/g, "").replace(/\\/g, "");
    
    if(text == lastValidatedOrganisationText.trim().replace(/\n/g, ""))
	{     // no change in text so do nothing
			    return;
	}
    else if(text == "" || text ==ORGANISATION_INITIAL_TEXT.trim().replace(/\n/g, ""))
    {
      // clear out selections so far
      parent.removeAllFromList(findOrganisationPrefix+"selectedOrganisationList");  
      postOrganisationSelections();
      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 = "advanced-search?cmd=find_organisation&text="+encodeURIComponent(text);
    document.getElementById("hiddenIFRAME").src = daURL;  
    
    showPleaseWait("Please wait while your Agency(s) are validated.");
  
}

function postOrganisationSelections()
{ 
			setOrganisationInputText();  
			
			if(requestedNextPage)
			{
				 nextPage();
			} 	
}

function setOrganisationInputText()
{
	          var text = "";
	  
         	  // set the input box text
         	  var count = 0;
         	  var listObject = document.getElementById(findOrganisationPrefix+"selectedOrganisationList");  
					  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(findOrganisationPrefix+"findOrganisation").value = text;	
					  
					  lastValidatedOrganisationText = text;
					  
					  //requestedNextPage = requestedNextPage && (count > 0);
					  
					  expandTextboxHeightToFit( document.getElementById(findOrganisationPrefix+"findOrganisation"), 50 );		  
					  					  
					  
					  doingValidate = false;  	  
}

						    
function noOrganisationFound(searchText)
{
      hidePleaseWait();
      
	  if(displayingM2MSelector)
	  {
	  	// wait until user has stopped validating a different field
	  	return;
	  } 
    
    showInfoMessage("Agency not found", "No Agencies were found for "+searchText+".<br/><br/>Please try again. Often a single word will produce better results e.g. try 'Justice' instead of 'Department of Justice'.")
    
    requestedNextPage = false; // abort moving to next page as the users input could not be validated
    
    // clear out selections so far
    parent.removeAllFromList(findOrganisationPrefix+"selectedOrganisationList");  
    postOrganisationSelections();  
  

}

//
// sort by searchPhrase, name
//
function sortIdTypeNameOrgArray(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(3) - (id, A/R, name, searchText)
  */
function setOrganisationsFound(v_foundArray, searchText, v_noMatchArray)
{
      hidePleaseWait();
	
	  if(displayingM2MSelector)
	  {
	  	// wait until user has stopped validating a different field
	  	return;
	  }  	

    if(v_foundArray.length > 200)
    {
    	  showInfoMessage("Find Agency", "Your search has returned too many results ("+v_foundArray.length+").<br/><br/>Please refine your Agency keyword and try again.")
    	  return;
    }
    
      var idTypeNameArray = new Array();
      var phraseMatchCounts = new Object();
      for( var i=0; i < v_foundArray.length; i++)
      {  
         var daId = v_foundArray[i][0];
         var daType = v_foundArray[i][1].trim();
         var daName = 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;
         }            
         
         idTypeNameArray[idTypeNameArray.length] = [daId, daType, daName, daSearchText];
      }
      idTypeNameArray.sort(sortIdTypeNameOrgArray);    
    
      var maxCountForPhrase = 0;
      for(phrase in phraseMatchCounts)
      {  
      	if(maxCountForPhrase < phraseMatchCounts[phrase])
      	{  maxCountForPhrase = phraseMatchCounts[phrase];
      	}
      }
      
		//
		// If only one record matched or simply removed a value then don't bother showing the M2M selector
		//
		if(maxCountForPhrase == 1) // || noNewValues)
		{
      // clear out selections so far
      parent.removeAllFromList(findOrganisationPrefix+"selectedOrganisationList");  			
			
			// don't show M2M selector -> just add the one we found
			for( var i=0; i < idTypeNameArray.length; i++)
			{
		      var daId = idTypeNameArray[i][0];
		      var daType = idTypeNameArray[i][1];
		      var daName = idTypeNameArray[i][2];   
		      var daSearchText = v_foundArray[i][3].trim();
		      
		      if(!isInList(findOrganisationPrefix+"selectedOrganisationList", daName) )
		      {  addToList(findOrganisationPrefix+"selectedOrganisationList", daName, "", daId);
		      }					
			}
			

   	     // ----------------------------------------------------------------
   	     // show message if some keywords had no matches
   	     if(v_noMatchArray.length > 0)
   	     {
   	     	  var msg = "No agencies 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(){ postOrganisationSelections(); } // only move on after info popup is closed
   	     	  showInfoMessage("Warning: Not All Keywords Could Be Matched", msg);
   	     }
   	     else
   	     {  postOrganisationSelections();
   	     }
   	     // ----------------------------------------------------------------         
						      	 
			return;
		}  
    
      // show popup with checkboxes
			var table = document.getElementById("pop-upORGANISATION_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 < idTypeNameArray.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 = idTypeNameArray[i][0];
         var daType = idTypeNameArray[i][1];
         var daName = idTypeNameArray[i][2];
         var daSearchText = idTypeNameArray[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 = "Agencies 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 chkbox = document.createElement('input');    
			   chkbox.type = 'checkbox'; 
			   chkbox.id = daId; 
			   chkbox.name = 'chkbt' + daId;  
			   chkbox.value =  daName;  			   
			   
			   if((daSearchText == daName.replace(/,/g, '')) || phraseMatchCounts[daSearchText] == 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 agencies matched '"+v_noMatchArray[i]+"'";
					   
					   td1.appendChild(span); 
			
					   phraseRow.appendChild(td1);
					   tbody.appendChild(phraseRow);         	  
      }   
      // --------------------------------------------------        
      
      table.appendChild(tbody);
      
      openOrganisationM2M();
      
      // 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 openOrganisationM2M()
{
	  if(displayingM2MSelector)
	  {
	  	// user is validating a different field
	  	return;
	  } 
	  
	  clearAllPopups();
	  showPopup("ORGANISATION_M2M_SELECT");
		
		displayingM2MSelector = true;
		
		document.getElementById("btn-ORGANISATIONM2MOK").focus();		
		
		return false;	
}

  
function getOrganisationString(prefix)
{
  var listObject = document.getElementById(prefix+"selectedOrganisationList");

	var organisationString = "";  
	for(var i=0; i < listObject.childNodes.length; i++)
	{
	  if(listObject.childNodes[i].tagName == "LI")
	  {   organisationString += listObject.childNodes[i].innerHTML+"|"+listObject.childNodes[i].title+"|"+listObject.childNodes[i].id+"^";
	  }
	}
	return organisationString;
}			  
						            
						            
						            
function ORGANISATIONM2MSelectionsMade()
{
	  var selectionArray = new Array();
	
	  var table = document.getElementById("pop-upORGANISATION_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)
	  	                  {    
	  	                  	  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'
	  	  //showInfoMessage("Selection Required", "At least one Agency must be selected.");
	  	  //return;	  	  
	  	  
	  }
	  	
    // clear out selections so far
    parent.removeAllFromList(findOrganisationPrefix+"selectedOrganisationList"); 
    
    for(var i=0; i < selectionArray.length; i++)
    {   
    	  var daId = selectionArray[i][0];
    	  var daName = selectionArray[i][1];
    	
    	  addToList(findOrganisationPrefix+"selectedOrganisationList", 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();	
    
    postOrganisationSelections();
        
}

function ORGANISATIONM2MSelectionsCancelled()
{
	  //alert("ORGANISATIONM2MSelectionsCancelled");
	
	  displayingM2MSelector = false;
	  
	  requestedNextPage= false; // cancel moving to next page if hit cancel
	  
	  postOrganisationSelections();
	  
	  //alert("ORGANISATIONM2MSelectionsCancelled END");
}