var ACT_REGULATION_INITIAL_TEXT = "Enter an Act or Regulation title e.g. Food Act.\nPlease use commas to separate multiple search terms.";

var findActRegulationPrefix = "";
var lastValidatedActRegulationText = "";              
              
function findActRegulations(prefix)
{
	  //alert("findActRegulations("+prefix+")"); 
	
  	findActRegulationPrefix = prefix;
  	
    var text = document.getElementById(findActRegulationPrefix+"findActRegulation").value.trim().replace(/\n/g, "").replace(/\\/g, "");
    
    if(text == lastValidatedActRegulationText.trim().replace(/\n/g, ""))
	{     // no change in text so do nothing
			    return;
	}    
    else if(text == "" || text == ACT_REGULATION_INITIAL_TEXT.trim().replace(/\n/g, ""))
    {
      // clear out selections so far
      parent.removeAllFromList(findActRegulationPrefix+"selectedActRegulationList");  
      postActRegulationSelections();
      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_act_regulation&text="+encodeURIComponent(text);
    document.getElementById("hiddenIFRAME").src = daURL;  
    
    showPleaseWait("Please wait while your Act/ Regulation(s) are validated.");
  
}

function postActRegulationSelections()
{ 
			setActRegulationInputText();  
			
			if(requestedNextPage)
			{
				 nextPage();
			} 	
}

function setActRegulationInputText()
{
	          var text = "";
	  
         	  // set the input box text
         	  var count = 0;
         	  var listObject = document.getElementById(findActRegulationPrefix+"selectedActRegulationList");  
					  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(findActRegulationPrefix+"findActRegulation").value = text;	
					  
					  lastValidatedActRegulationText = text;
					  
					  //requestedNextPage = requestedNextPage && (count > 0);
					  
					  expandTextboxHeightToFit( document.getElementById(findActRegulationPrefix+"findActRegulation"), 50 );		  
					  
					  doingValidate = false;  	  
}

						    
function noActRegulationFound(searchText)
{
      hidePleaseWait();
      
  //alert("No matches for the act/regulation '"+searchText+"'");
  
	  if(displayingM2MSelector)
	  {
	  	// wait until user has stopped validating a different field
	  	return;
	  } 
    
    showInfoMessage("Act or Regulation not found", "No Acts or Regulations were found for "+searchText+".<br/><br/>Please try again. Often a single word will produce better results e.g. try 'Food' instead of 'Food Act'.")
    
    requestedNextPage = false; // abort moving to next page as the users input could not be validated
    
    // clear out selections so far
    parent.removeAllFromList(findActRegulationPrefix+"selectedActRegulationList");  
    postActRegulationSelections(); 
  

}

//
// sort by phrase a[3] then by name a[2]
//  
function sortIdTypeNameActRegArray(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 setActRegulationsFound(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 act/regulation '"+searchText+"'");
    if(v_foundArray.length > 200)
    {
    	  showInfoMessage("Find Act or Regulation", "Your search has returned too many results ("+v_foundArray.length+").<br/><br/>Please refine your Act or Regulation 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 daSearchPhrase = v_foundArray[i][3].trim();
         
         if(!phraseMatchCounts[daSearchPhrase] || phraseMatchCounts[daSearchPhrase] == null || phraseMatchCounts[daSearchPhrase] == 0)
         {  
         	  phraseMatchCounts[daSearchPhrase] = 1;
         }
         else
         { phraseMatchCounts[daSearchPhrase] = phraseMatchCounts[daSearchPhrase]+1;
         }         
         
         idTypeNameArray[idTypeNameArray.length] = [daId, daType, daName, daSearchPhrase];
      }
      idTypeNameArray.sort(sortIdTypeNameActRegArray);    
      
      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(findActRegulationPrefix+"selectedActRegulationList");  			
			
			// don't show M2M selector -> just add the ones 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];   
		      
		      if(!isInList(findActRegulationPrefix+"selectedActRegulationList", daName) )
		      {  addToList(findActRegulationPrefix+"selectedActRegulationList", daName, "", daId);
		      }					
			}
			

   	     // ----------------------------------------------------------------
   	     // show message if some keywords had no matches
   	     if(v_noMatchArray.length > 0)
   	     {
   	     	  var msg = "No acts or regulations 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(){ postActRegulationSelections(); } // only move on after info popup is closed
   	     	  showInfoMessage("Warning: Not All Keywords Could Be Matched", msg);
   	     }
   	     else
   	     {  postActRegulationSelections();
   	     }
   	     // ----------------------------------------------------------------        
						      	 
			return; 
		}  
    
      // show popup with checkboxes
			var table = document.getElementById("pop-upACT_REGULATION_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 daSearchPhrase = idTypeNameArray[i][3];
         
         //------------------------------------------------------
         // 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 = "Acts or Regulations 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; 
			   
			   
			   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 acts or regulations matched '"+v_noMatchArray[i]+"'";
					   
					   td1.appendChild(span); 
			
					   phraseRow.appendChild(td1);
					   tbody.appendChild(phraseRow);         	  
      }   
      // --------------------------------------------------        
      
      table.appendChild(tbody);
      
      openActRegulationM2M();
      
      // 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 openActRegulationM2M()
{
	  if(displayingM2MSelector)
	  {
	  	// user is validating a different field
	  	return;
	  } 
	  
	  clearAllPopups();
	  showPopup("ACT_REGULATION_M2M_SELECT");
		
		displayingM2MSelector = true;
		
		document.getElementById("btn-ACT_REGULATIONM2MOK").focus();		
		
		return false;	
}

/*
  function setActRegulationRightList()
  { removeAllFromList("rightActRegulationList");
  
	  var listObject = document.getElementById(findActRegulationPrefix+"selectedActRegulationList");
	  
	  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("rightActRegulationList", listObject.childNodes[i].innerHTML, listObject.childNodes[i].title, listObject.childNodes[i].id);
	    	 addToList("rightActRegulationList", listObject.childNodes[i].innerHTML, listObject.childNodes[i].innerHTML, listObject.childNodes[i].id);
	    }
	  }  
  } 	
  
  function editActRegulations(prefix)
  {   
  	findActRegulationPrefix = prefix;
  	
     // open up the popup which shows the selected 
     // FogBugz 9916 - don't clear out left list prior to edit - removeAllFromList("leftActRegulationList");
     
     setActRegulationRightList();
     
     if(countElementsInList("rightActRegulationList") == 0)
     {
       showInfoMessage("Edit Act or Regulation List", "You must select an act or regulation before you can edit your list.");
       return false;
     }
     
     openActRegulationM2M();
  }		
  */
  
function getActRegulationString(prefix)
{
  var listObject = document.getElementById(prefix+"selectedActRegulationList");

	var actRegulationsString = "";  
	for(var i=0; i < listObject.childNodes.length; i++)
	{
	  if(listObject.childNodes[i].tagName == "LI")
	  {   actRegulationsString += listObject.childNodes[i].innerHTML+"|"+listObject.childNodes[i].title+"|"+listObject.childNodes[i].id+"^";
	  }
	}
	return actRegulationsString;
}			  
						            
						            
						            
function ACT_REGULATIONM2MSelectionsMade()
{
	
	  var selectionArray = new Array();
	
	  var table = document.getElementById("pop-upACT_REGULATION_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'
	  	  //alert("At least one location must be selected.");
	  	  //showInfoMessage("Selection Required", "At least one Act or Regulation must be selected.");
	  	  //return;
	  }
	  	
    // clear out selections so far
    parent.removeAllFromList(findActRegulationPrefix+"selectedActRegulationList"); 
    
    for(var i=0; i < selectionArray.length; i++)
    {   
    	  var daId = selectionArray[i][0];
    	  var daName = selectionArray[i][1];
    	
    	  addToList(findActRegulationPrefix+"selectedActRegulationList", 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();	
    
    postActRegulationSelections();
        
}

function ACT_REGULATIONM2MSelectionsCancelled()
{
	  displayingM2MSelector = false;
	  
	  requestedNextPage= false; // cancel moving to next page if hit cancel
	  
	  postActRegulationSelections();
}