// javascript for blis

var QUICK_SEARCH_INITIAL_TEXT = "Keywords for licences";

				
				var agt=navigator.userAgent.toLowerCase();
				var appVer = navigator.appVersion.toLowerCase();
				var is_minor = parseFloat(appVer);
				var is_major = parseInt(is_minor);
				var iePos = appVer.indexOf('msie');
				if (iePos !=-1) {
				is_minor = parseFloat(appVer.substring(iePos+5,appVer.indexOf(';',iePos)))
				is_major = parseInt(is_minor);
				}
				var is_getElementById = (document.getElementById) ? "true" : "false"; 
				var is_getElementsByTagName = (document.getElementsByTagName) ? "true" : "false";
				var is_documentElement = (document.documentElement) ? "true" : "false"; 
				var is_ie = ((iePos!=-1));
				var is_ie3 = (is_ie && (is_major < 4));
				var is_ie4 = (is_ie && is_major == 4);
				var is_ie4up = (is_ie && is_minor >= 4);
				var is_ie5 = (is_ie && is_major == 5);
				var is_ie5up = (is_ie && is_minor >= 5);
				var is_ie5_5 = (is_ie && (agt.indexOf("msie 5.5") !=-1)); 
				var is_ie5_5up =(is_ie && is_minor >= 5.5); 
				var is_ie6 = (is_ie && is_major == 6);
				var is_ie6up = (is_ie && is_minor >= 6);
				var is_ie7 = (is_ie && is_major == 7);
				var is_ie7up = (is_ie && is_minor >= 7);
				
				var is_ff = ( agt != null && agt.toUpperCase().indexOf( "FIREFOX/" ) != -1 );
				 
   
// ****************************************************
// String functions
// ****************************************************

if (!String.prototype.trim) {
		String.prototype.trim = function() {
			return this.replace(/(?:(?:^|\n)\s+|\s+(?:$|\n))/g,"");
		};
}

if (!String.prototype.escapeDoubleQuotes) {
		String.prototype.escapeDoubleQuotes = function() {
			return this.replace(/"/g,"\\\"");
		};
}

// ****************************************************

function showSaveMyWork(vCancelButtonIsPrevious){
		 
		setCancelButtonIsPrevious(vCancelButtonIsPrevious);
		 
		addNewPopupId("SAVE_WORK");
	
		$('body').css({'height': '100%', 'width':'100%'});
		hideSelect();
		addOverlay("showSaveMyWork");  
		
		// pre-populate the business name, activities, councils and potentially business structure
		var daSelect = document.getElementById("selected_business_id");
		if(daSelect)
	    {
	  	  if(daSelect.selectedIndex > -1)
	  	  {   document.getElementById("save_my_work_business_name").value = daSelect.options[daSelect.selectedIndex].text;
	  	  }
	    }
	    document.getElementById("save_my_work_business_name").style.color = "black";
	  
	  var listObject = document.getElementById("my-business-1-selectedBusinessTypeList");
	  if( listObject )
	  {
	  	  removeAllFromList("save-my-work-selectedBusinessTypeList");
	  	  
	  	  var baCount = 0;
			  for(var i=0; i < listObject.childNodes.length; i++)
			  {
			  	if(listObject.childNodes[i].tagName == "LI")
				  {  addToList("save-my-work-selectedBusinessTypeList", listObject.childNodes[i].innerHTML, listObject.childNodes[i].title, listObject.childNodes[i].id)
				  	 baCount++;
				  }	  		
			  }	  	    
			  if(baCount == 0)
			  {  document.getElementById("save-my-work-no-business-type-message").style.display = "";
			  }
			  else
			  {  document.getElementById("save-my-work-no-business-type-message").style.display = "none";
			  }
	  } 
	  
	  listObject = document.getElementById("my-business-1-selectedCouncilList");
	  if( listObject )
	  {
	  	  removeAllFromList("save-my-work-selectedCouncilList");
	  	  
	  	  var locCount = 0;
			  for(var i=0; i < listObject.childNodes.length; i++)
			  {
			  	if(listObject.childNodes[i].tagName == "LI")
				  {  addToList("save-my-work-selectedCouncilList", listObject.childNodes[i].innerHTML, listObject.childNodes[i].title, listObject.childNodes[i].id)
				  	 locCount++;
				  }	  		
			  }	  

			  if(locCount == 0)
			  {  document.getElementById("save-my-work-no-location-message").style.display = "";
			  }
			  else
			  {  document.getElementById("save-my-work-no-location-message").style.display = "none";
			  }			  	    
	  }	
	  
	  
	  var busStructDD = document.getElementById("business-structure-selector");
	  if( busStructDD )
	  {
	  	  var selectedValue = busStructDD.options[ busStructDD.selectedIndex ].value; 	
	  	  var selectedText = busStructDD.options[ busStructDD.selectedIndex ].text;
	  	  
	  	  // BC 03 Mar 2009 - update business structure if we need to   
	  	  var saveBusStructListItem = document.getElementById("save-my-work-businessStructureListItem");
	  	  if( saveBusStructListItem )
	  	  {  saveBusStructListItem.innerHTML = selectedText;
	  	  	 saveBusStructListItem.title = selectedText;
	  	  } 
	  	  
	  	  var saveBusStructDD = document.getElementById("save-my-work-businessStructure"); 
	  	  if(saveBusStructDD)
	  	  {
			  	  for(var i=0; i < saveBusStructDD.options.length; i++)
			  	  {
			  	  	  if( saveBusStructDD.options[i].value == selectedValue)
			  	  	  {  saveBusStructDD.selectedIndex = i;
			  	  	  }
			  	  }	  	  	
	  	  }

	  	  
	  }	
	  
	  
	  // save any existing data on this screen to BLIS
	  if( typeof(getSaveValuesURL) != "undefined" )
	  {
	  	  var daURL = getContextPath()+"/prod/my-business-1?cmd=save_search_values"+getSaveValuesURL();
	      document.getElementById("hiddenIFRAME").src = daURL;
	      //alert("SAVED! "+daURL);
	  }	
	  
		
		// center position the popup box
		var xcoord = Math.max(10, ($(window).width() - $("#pop-up"+POPUP_ID).width()) / 2);
		var ycoord = Math.max(10, ($(window).height() - $("#pop-up"+POPUP_ID).height()) / 2);
		$("#pop-up"+POPUP_ID).css({'left': xcoord, 'top': ycoord});
		$("#pop-up"+POPUP_ID).css({'z-index': (9000+OVERLAY_COUNT+1)});
		
		$("#pop-up"+POPUP_ID).show();
		
		// workaround for IE6 problem with infinite z indexes on dropdown boxes
		if( is_ie6 && document.getElementById("zIndexFixFrame"))
		{
			 document.getElementById("zIndexFixFrame").style.top = 0;
			 document.getElementById("zIndexFixFrame").style.left = 0;
			 document.getElementById("zIndexFixFrame").style.width = "100%";
			 document.getElementById("zIndexFixFrame").style.height = Math.min(1000, document.body.clientHeight);
			 
			 document.getElementById("zIndexFixFrame").style.zIndex = (9000+OVERLAY_COUNT);
			 document.getElementById("zIndexFixFrame").style.display = "inline";
		}					
		
		return false;
	}	
	


// ****************************************************

var POPUP_ID="";

var POPUP_IDS_ARRAY = new Array(); // keeps a LIFO (last-in, first out) list of the popups that are currently being displayed
var LAST_FOCUS_ARRAY = new Array(); // keeps a LIFO (last-in, first out) list of the objects that had focus before the popup was popped up

var OVERLAY_COUNT = 0;

function getOverlaySize()
{     
	  if (window.innerHeight && window.scrollMaxY) 
	  {  // Firefox       
	  	  yWithScroll = window.innerHeight + window.scrollMaxY;         
	  	  xWithScroll = window.innerWidth + window.scrollMaxX;    
	  } 
	  else if (document.body.scrollHeight > document.body.offsetHeight)
	  { // all but Explorer Mac       
	  	yWithScroll = document.body.scrollHeight;         
	  	xWithScroll = document.body.scrollWidth;     
	  } else 
	  { 
	        // works in Explorer 6 Strict, Mozilla (not FF) and Safari         
	  		//yWithScroll = document.body.offsetHeight;         
	  		//xWithScroll = document.body.offsetWidth;    
	  		
	  		xWithScroll = document.body.offsetWidth + document.body.offsetLeft; 
	  		yWithScroll = document.body.offsetHeight + document.body.offsetTop;   
	  		
	  }     
	  
	  // BC 04 Jun 2009
	  // add a bit on as IE does not give enough!
	  xWithScroll += 100;
	  yWithScroll += 100;
	  
	  var arrayPageSizeWithScroll = new Array(xWithScroll,yWithScroll);          
	  return arrayPageSizeWithScroll; 
} 
function addOverlay( debug )
{
	
	//alert("addOverlay() - FROM "+debug);
	

		     //if(OVERLAY_COUNT == 0)
		     //{
		     //	  // Gemini issue 3544 - make sure overlay is big enough to handle user incresing the screen size 
		     //	  //$('body').append('<div id="overlay" style="width:'+$(document).width()+'px; height:'+$(document).height()+'px;"></div>');
		     //	  $('body').append('<div id="overlay" style="width:'+screen.width+'px; height:'+screen.height+'px;"></div>');
		     //   $('#overlay').css({opacity : '0.8'});
		     //}
		     
		     OVERLAY_COUNT++;
		     var overlayWidth = screen.width;
         var overlayHeight = screen.height;
                                  
         //$('body').css({'height': '150%'}); // This screws things up in IE7                          
		     $('body').append('<div id="overlay'+OVERLAY_COUNT+'" class="overlay" style="width:'+screen.width+'px; height:'+screen.height+'px;"></div>');

		     $('#overlay'+OVERLAY_COUNT).css({'opacity': '0.8', 'z-index': (9000+OVERLAY_COUNT)});
		     
		        
		     // BC 25 Feb 2009 - Gemini issue 3725
		     var sizeArray = getOverlaySize();
		     var scrollWidth = sizeArray[0];
		     var scrollHeight = sizeArray[1];
		     
		     $('#overlay'+OVERLAY_COUNT).css({'height': (scrollHeight), 'width': (scrollWidth)});
		     
		     
		     
}

function removeOverlay()
{ 
		     //if(OVERLAY_COUNT == 1)
		     //{  $('#overlay').remove();
		     //}
		     
		     if( $('#overlay'+OVERLAY_COUNT) )
		     {  $('#overlay'+OVERLAY_COUNT).remove();	
		        OVERLAY_COUNT--;
		     }
		     
		     
}

function addNewPopupId( daId )
{
	  POPUP_ID = daId;
	  POPUP_IDS_ARRAY[POPUP_IDS_ARRAY.length] = daId;
	  LAST_FOCUS_ARRAY[LAST_FOCUS_ARRAY.length] = focusedElement;
}

function clearAllPopups()
{
	  //alert("removeLastPopupId POPUP_IDS_ARRAY.length = "+POPUP_IDS_ARRAY.length);
	  for(var i=POPUP_IDS_ARRAY.length-1; i >= 0; i--)
	  {
	  	 		removeOverlay();
		      $('#pop-up'+POPUP_ID).hide();
					
					removeLastPopupId();	
	  }
	  
		// workaround for IE6 problem with infinite z indexes on dropdown boxes
		if( is_ie6 && document.getElementById("zIndexFixFrame"))
		{
			 document.getElementById("zIndexFixFrame").style.display = "none";
		}			  
	  
	  showSelect();	
}	  

function removeLastPopupId()
{
	  //alert("removeLastPopupId POPUP_IDS_ARRAY.length = "+POPUP_IDS_ARRAY.length);
	  var daId = null;
	  if(POPUP_IDS_ARRAY.length > 0)
	  {
	  	  POPUP_IDS_ARRAY[POPUP_IDS_ARRAY.length-1];
	      POPUP_IDS_ARRAY.length = POPUP_IDS_ARRAY.length-1;
	  }
 
	  if(POPUP_IDS_ARRAY.length > 0)
	  {  POPUP_ID = POPUP_IDS_ARRAY[POPUP_IDS_ARRAY.length-1];
	  }
	  else
	  {  POPUP_ID = "";
	  }
	  
	  // return focus
	  if(LAST_FOCUS_ARRAY.length > 0)
	  {
			  var itemToFocus = LAST_FOCUS_ARRAY[LAST_FOCUS_ARRAY.length-1]
			  LAST_FOCUS_ARRAY.length = LAST_FOCUS_ARRAY.length-1;
			  if(itemToFocus != null)
			  {  try{
			       itemToFocus.focus();
			     }catch(error)
			     { // ignore - not focusing isn't the end of the world
			     }
			  }	  	
	  }

	  return daId;
}

 
/*
 * Only adds if doesn't already exist in list
 */
function addToList(listObjectId, daText, daTitle, daId)
{	  
	  //alert("addToList("+listObjectId+") "+document.getElementById(listObjectId));
	
	  if( document.getElementById(listObjectId).type && document.getElementById(listObjectId).type == "select-multiple" )
	  {  
	  	  //alert("addToList - "+listObjectId+" is a select");
	  	  addToSelect(listObjectId, daText, daTitle, daId);
	  	  return;
	  }
	
    if(isInList(listObjectId, daText))
    {  return;
    }	
    
	  var new_element = document.createElement('li');
	  new_element.title = daTitle;
	  new_element.id = daId;
    new_element.innerHTML = daText;
    
    //alert("addToList - "+listObjectId+" adding "+daText+" "+countItemsInList(listObjectId));
    
    //document.getElementById(listObjectId).insertBefore(new_element, document.getElementById("leftBusinessTypeList").firstChild);
    document.getElementById(listObjectId).appendChild(new_element);
    
    //alert("addToList - "+listObjectId+" added  "+daText+" "+countItemsInList(listObjectId));
    
    // mark that a change has been made
    isUnsavedChangesToBusinessProfile = true;
}

function addToSelect(listObjectId, daText, daTitle, daId)
{

    if(isInSelect(listObjectId, daText))
    {  return;
    }	
	
	var new_element = document.createElement('option');
	new_element.title = daTitle;
	new_element.id = daId;
    new_element.text = daText;
    
    //document.getElementById(listObjectId).insertBefore(new_element, document.getElementById("leftBusinessTypeList").firstChild);
    document.getElementById(listObjectId).options[document.getElementById(listObjectId).length] = new_element;
    
    // mark that a change has been made
    isUnsavedChangesToBusinessProfile = true;
    
    sortSelect(document.getElementById(listObjectId));
}

// sort function - ascending (case-insensitive)
function sortFuncAsc(record1, record2) {
    var value1 = record1.optText.toLowerCase();
    var value2 = record2.optText.toLowerCase();
    if (value1 > value2) return(1);
    if (value1 < value2) return(-1);
    return(0);
}

// sort function - descending (case-insensitive)
function sortFuncDesc(record1, record2) {
    var value1 = record1.optText.toLowerCase();
    var value2 = record2.optText.toLowerCase();
    if (value1 > value2) return(-1);
    if (value1 < value2) return(1);
    return(0);
}

function sortSelect(selectToSort) {
	
    //alert("Sorting: " + selectToSort.id);

    if (typeof(selectToSort.options) != "undefined") {
      
      // copy options into an array
      var myOptions = [];
      for (var loop=0; loop<selectToSort.options.length; loop++) {
          myOptions[loop] = { optText:selectToSort.options[loop].text, optValue:selectToSort.options[loop].value, optId:selectToSort.options[loop].id, optTitle:selectToSort.options[loop].title, optSelected:selectToSort.options[loop].selected };
      }
  
      myOptions.sort(sortFuncAsc);
  
      var daSelectedIndex = -1;
   
      // copy sorted options from array back to select box
      selectToSort.options.length = 0;
      for (var loop=0; loop<myOptions.length; loop++) {
          var optObj = document.createElement('option');
          optObj.text = myOptions[loop].optText;
          optObj.value = myOptions[loop].optValue;
          optObj.id = myOptions[loop].optId; // BC 02 Feb 2009: Must also keep ID
          optObj.title = myOptions[loop].optTitle; 
          optObj.selected = myOptions[loop].optSelected;  // BC 06 Apr 2009: Gemini 4475 - keep selection status
          
          if(myOptions[loop].optSelected)
          {  daSelectedIndex = loop;
          }
          
          selectToSort.options.add(optObj);
      }
      
      // Bug in IE6 where needs to be explicitly set
      if(is_ie6 && (daSelectedIndex > -1))
      {
      	 selectToSort.selectedIndex = daSelectedIndex;
      }
      
      
    }
    
}

function isInList(listObjectId, daText)
{
	
	  var listObject = document.getElementById(listObjectId);
	  
	  if(listObject == null)
	  {
	  	  //alert("Could not find object "+listObjectId);
	  	  return false;
	  }
	  
    if( listObject.type && listObject.type == "select-multiple" )
	  {  
	  	  //alert("isInList - "+listObjectId+" is a select");
	  	  return isInSelect(listObjectId, daText);
	  }	  
	  
	  
	  for(var i=0; i < listObject.childNodes.length; i++)
	  {
	  	if(listObject.childNodes[i].innerHTML && listObject.childNodes[i].innerHTML.trim() == daText.trim())
	  	{
		    if(listObject.childNodes[i].tagName == "LI")
		    {  return true;
		    }	  		
	  	}
	  }
	  return false;
}

function countItemsInList(listObjectId)
{
	  var listObject = document.getElementById(listObjectId);
	  
	  if(listObject == null)
	  {
	  	  //alert("Could not find object "+listObjectId);
	  	  return 0;
	  }
    
    var count = 0;
	  for(var i=0; i < listObject.childNodes.length; i++)
	  {
	  	if(listObject.childNodes[i].tagName == "LI")
		  {  count++;
		  }	  			  	
	  }
	  return count;
}

function getLIsFromList(listObjectId)
{
	  var listObject = document.getElementById(listObjectId);
	  
	  if(listObject == null)
	  {
	  	  //alert("Could not find object "+listObjectId);
	  	  return null;
	  }
	  
    if( listObject.type && listObject.type == "select-multiple" )
	  {  
	  	  alert("getLIsFromList - "+listObjectId+" is a select and not handled");
	  	  return null;
	  }	  
	  
	  var idsArray = new Array();
	  for(var i=0; i < listObject.childNodes.length; i++)
	  {
		    if(listObject.childNodes[i].tagName == "LI")
		    {  idsArray[idsArray.length] = listObject.childNodes[i];
		    }	  		
	  
	  }
	  return idsArray;
}


function isInSelect(listObjectId, daText)
{
	
	  var listObject = document.getElementById(listObjectId);
	  for(var i=0; i < listObject.options.length; i++)
	  {

	  	//alert("isInSelect("+listObjectId+") "+i+":'"+listObject.options[i].text+"' vs '"+daText+"' = "+(listObject.options[i].text.trim() == daText.trim()) );
	  	
	  	if(listObject.options[i].text && listObject.options[i].text.trim() == daText.trim())
	  	{
		    return true; 		
	  	}

	  }
	  return false;
}

function countElementsInList(listObjectId)
{
	  if( document.getElementById(listObjectId).type && document.getElementById(listObjectId).type == "select-multiple" )
	  {  
	  	  return countElementsInSelect(listObjectId);
	  }
		
	
	  var count=0;
	  var listObject = document.getElementById(listObjectId);
	  for(var i=0; i < listObject.childNodes.length; i++)
	  {
	  	if(listObject.childNodes[i].tagName == "LI")
		  {  count++;
		  }	  		
	  }
	  
	  return count;
}

function countElementsInSelect(selectObjectId)
{
  return document.getElementById(selectObjectId).options.length;
}

function removeAllFromList(listObjectId)
{
	  var listObject = document.getElementById(listObjectId);
	  
	  if(listObject.type && listObject.type == "select-multiple")
	  {  removeAllFromSelect(listObjectId);
	  	 return;
	  }

	  for(var i=listObject.childNodes.length-1; i >= 0; i--)
	  {
		    if(listObject.childNodes[i].tagName == "LI")
		    {  listObject.removeChild(listObject.childNodes[i]);
		    }	  	
	  }
	  
    // mark that a change has been made
    isUnsavedChangesToBusinessProfile = true;	  
}
function removeAllFromSelect(selectObjectId)
{
	  var selectObject = document.getElementById(selectObjectId);
	  selectObject.options.length = 0;
	  
    // mark that a change has been made
    isUnsavedChangesToBusinessProfile = true;	  
}
function removeFromList(listObjectId, daText)
{
	  var doneRemove = false;
	
	  var listObject = document.getElementById(listObjectId);
	  for(var i=0; i < listObject.childNodes.length && !doneRemove; i++)
	  {
	  	//alert("removeFromList "+listObject.childNodes[i].innerHTML+" vs "+daText +" = "+(listObject.childNodes[i].innerHTML == daText));
	  	
	  	if(listObject.childNodes[i].innerHTML == daText)
	  	{
		    if(listObject.childNodes[i].tagName == "LI")
		    {  listObject.removeChild(listObject.childNodes[i]);
	  		   doneRemove = true;
		    }	  		
	  	}
	  }
    // mark that a change has been made
    isUnsavedChangesToBusinessProfile = true;	
    
    //alert("removeFromList doneRemove="+doneRemove);  
	  
}


function removeFromSelect(listObjectId, daText)
{
	  var doneRemove = false;
	
	  var selectObject = document.getElementById(listObjectId);
	  for(var i=0; i < selectObject.options.length && !doneRemove; i++)
	  {
	  	if(selectObject.options[i].text == daText)
	  	{
		    selectObject.remove(i);
	  		doneRemove = true;  		
	  	}
	  }
    // mark that a change has been made
    isUnsavedChangesToBusinessProfile = true;	
    
    //alert("removeFromSelect doneRemove="+doneRemove);  
	  
}

function isPromptText(pText)
{
	  return (pText.trim() == ''
	     || pText.trim().replace(/\n/g, "") == BUSINESS_TYPE_INITIAL_TEXT.trim().replace(/\n/g, "")
	     || pText.trim().replace(/\n/g, "") == COUNCIL_INITIAL_TEXT.trim().replace(/\n/g, "")
	     || pText.trim().replace(/\n/g, "") == COUNCIL_INITIAL_TEXT2.trim().replace(/\n/g, "")
	     || pText.trim().replace(/\n/g, "") == ACT_REGULATION_INITIAL_TEXT.trim().replace(/\n/g, "")
	     || pText.trim().replace(/\n/g, "") == ORGANISATION_INITIAL_TEXT.trim().replace(/\n/g, "")
	     || pText.trim().replace(/\n/g, "") == QUICK_SEARCH_INITIAL_TEXT.trim().replace(/\n/g, "")
	     );
}


$(document).ready(function(){
	
	// clear out text fields onclick
	// BC 06 Jan 2009 - Changed by Reactive
	//$('input[@type="text"]').click(function(){
	//	$(this).val('');
	//});
	
	$('input[@type="text"]').each(function(){
		if( isPromptText( $(this).val() ) )
		{  $(this).css({'color':'#999999'});
		}
	});
	$('input[@type="text"]').focus(function(){
		if( isPromptText( $(this).val() ) )
		{   $(this).val('').css({'color':'black'});
		}
	});
	
	//BC 19 May 2009 - CR14 Added
	$('textarea').each(function(){
        if( isPromptText( $(this).val() ) )
        {  $(this).css({'color':'#999999'});
        }
    });
    $('textarea').focus(function(){
        if( isPromptText( $(this).val() ) )
        {   $(this).val('').css({'color':'black'});
        }
    }); 
	
	// when find button is clicked
	//$('.findButton').click(function(){
	//	openBusinessActivityM2M();
	//	return false;
	//});

	// when more info is clicked on step2
	$('.readMore').click(function(){
		$('body').css({'height': '100%', 'width':'100%'});
		hideSelect();
		addOverlay("readMore");
		
		// center position the popup box
		var xcoord = Math.max(10, ($(window).width() - $("#pop-up"+POPUP_ID).width()) / 2);
		var ycoord = Math.max(10, ($(window).height() - $("#pop-up"+POPUP_ID).height()) / 2);
		
		// BC 06 August 2008: show in middle of screen, even if user has scrolled down
		var topValue = document.documentElement.scrollTop + (document.documentElement.clientHeight - (document.documentElement.clientHeight-ycoord));
		
		$("#pop-up"+POPUP_ID).css({'left': xcoord, 'top': topValue});
		$("#pop-up"+POPUP_ID).css({'z-index': (9000+OVERLAY_COUNT+1)});
		$("#pop-up"+POPUP_ID).show();
						
		
		
		return false;
	});
	
	// when save button is pressed
	$('.saveButton').click(function (){ showSaveMyWork() });
	

	// adding
  // inline pop up boxes with multiple selection
	var tempArray = new Array();
	var tempIdArray = new Array();
	$('.addButton').click(function(){
		
			//$('#pop-up'+POPUP_ID+' li.highlight').remove();
			//$('.selections ul').append('<li id="'+tempId+'">' + temp + '</li>');
			

		var leftList = $(this).parent().children('div.results').children('select'); 
		var rightList = $(this).parent().children('div.selections').children('select'); 
		

		leftList.children('option').each(function(){
			if($(this).attr('selected')){

				tempArray[tempArray.length] = $(this).attr('text');
				tempIdArray[tempIdArray.length] = $(this).attr('id');
				$(this).remove();
			}
		});
		
		for(j=0;j<tempArray.length;j++){
			if(tempArray[j] != null){
				var temp = tempArray[j] ;
				var tempId = tempIdArray[j];
				
				//alert('<option id="'+tempIdArray[j]+'" value="'+ tempArray[j] +'">'+ tempArray[j] +'</option>');
				
				// only add to left list if name not already in left list
				var inRightList = false;
				rightList.children('option').each(function(){
						var name = $(this).attr('text');
						if(name == tempArray[j])
						{ inRightList = true;
						}
				});
				
				//alert("inRightList="+inRightList);
				
				if(!inRightList)
				{  
					  // BC 03 Mar 2009 - Gemini issue 4258 - not working in IE6 
					  //rightList.append('<option id="'+tempIdArray[j]+'" value="'+ tempArray[j] +'">'+ tempArray[j] +'</option>'); // doesn't work in IE6!
					  //alert( rightList.attr("id")+" "+document.getElementById(rightList.attr("id")) );
					  if(!is_ie6)
					  {  rightList.append('<option id="'+tempIdArray[j].escapeDoubleQuotes()+'" value="'+ tempArray[j].escapeDoubleQuotes() +'" title="'+tempArray[j].escapeDoubleQuotes()+'">'+ tempArray[j] +'</option>');					  	
					  }
					  else  // ie6
						{
								var rightListSelectObj = document.getElementById(rightList.attr("id"));
								var oOption = document.createElement("OPTION");
								oOption.text=tempArray[j];
								oOption.title=tempArray[j];
								oOption.value=tempIdArray[j];
								rightListSelectObj.add(oOption);							
						}

				}				

				tempArray[j] = null;
				tempIdArray[j] = null;
				
				// BC 12 Aug 2008: Also add to the YOUR BUSINESS TYPE section & to the hidden business_types field
				// save the search string as the title
				if(POPUP_ID == "COUNCIL_M2M_EDIT")
				{  
				     sortSelect(document.getElementById("rightCouncilList"));
				     addToList(councilPrefix+"selectedCouncilList", temp, document.getElementById(councilPrefix+"businessLocation").value, tempId);
					 if(document.getElementById("noCouncilMessage"))
					 {  
					    // BC 15 Jan 2009: Never hide this message (Gemini issue 3754)
					    //document.getElementById("noCouncilMessage").style.display = "none";
					 }
					 
					 if(document.getElementById("manyCouncilMessage"))
					 {
					   if( countElementsInList(councilPrefix+"selectedCouncilList") > 1 )
			           {  document.getElementById("manyCouncilMessage").style.display = "";
				       }
				       else
				       {  document.getElementById("manyCouncilMessage").style.display = "none";
				       }				 
					 }
					 
		 
			  }
			  else if(POPUP_ID == "BUSINESS_TYPE_M2M_EDIT" || POPUP_ID == "BUSINESS_TYPE_BROWSE")
			  {  
			  	sortSelect(document.getElementById("rightBusinessTypeList"));
			  	addToList(businessTypePrefix+"selectedBusinessTypeList", temp, document.getElementById(businessTypePrefix+"businessType").value, tempId);

			  	if(document.getElementById("manyBusinessTypeMessage"))
			  	{
					  if( countElementsInList(businessTypePrefix+"selectedBusinessTypeList") > 1 )
					  {   //alert("ITEMS IN LIST = "+countElementsInList(businessTypePrefix+"selectedBusinessTypeList"));
					  	  document.getElementById("manyBusinessTypeMessage").style.display = "";
						}
						else
						{  document.getElementById("manyBusinessTypeMessage").style.display = "none";
						}		  	
			  	}	
			  }
			  else if(POPUP_ID == "TOPIC_M2M_EDIT" || POPUP_ID == "TOPIC_BROWSE")
			  {  
			    sortSelect(document.getElementById("rightTopicList"));
			  	addToList(topicPrefix+"selectedTopicList", temp, document.getElementById(topicPrefix+"topic").value, tempId);
			  	
			  	if(document.getElementById("manyTopicMessage"))
			  	{
					  	if( countElementsInList(topicPrefix+"selectedTopicList") > 1 )
					    {  document.getElementById("manyTopicMessage").style.display = "";
						}
						else
						{  document.getElementById("manyTopicMessage").style.display = "none";
						}		  	
			  	}	
			  }
			  else if(POPUP_ID == "ACT_REGULATION_M2M_EDIT")
			  {  
			    sortSelect(document.getElementById("rightActRegulationList"));
			  	addToList(findActRegulationPrefix+"selectedActRegulationList", temp, document.getElementById(findActRegulationPrefix+"findActRegulation").value, tempId);
			  }
			  else if(POPUP_ID == "ORGANISATION_M2M_EDIT")
			  {  
			  	sortSelect(document.getElementById("rightOrganisationList"));
			  	addToList(findOrganisationPrefix+"selectedOrganisationList", temp, document.getElementById(findOrganisationPrefix+"findOrganisation").value, tempId);
			  }				
				
			
			}
		}

    tempArray.length = 0;
    tempIdArray.length = 0;
    
    if(POPUP_ID == "BUSINESS_TYPE_M2M_EDIT")
		{
				// BC 02 Mar 2009 - Gemini issue 3110
				resetSelectionsInBusinessTypeBrowseChildIframe();
    } 
    else if(POPUP_ID == "TOPIC_M2M_EDIT")
		{
				// BC 25 Mar 2009 - Gemini issue 3110
				resetSelectionsInTopicBrowseChildIframe();
    }   

		return false;
	});

	// removing
	$('.removeButton').click(function(){

			//$('#pop-up'+POPUP_ID+' li.highlight').remove();
			//$('.results ul').append('<li id="'+tempId+'">' + temp + '</li>');
			
			
		var leftList = $(this).parent().children('div.results').children('select'); 
		var rightList = $(this).parent().children('div.selections').children('select'); 
		
		rightList.children('option').each(function(){
			if($(this).attr('selected')){
				tempArray[tempArray.length] = $(this).attr('text');
				tempIdArray[tempIdArray.length] = $(this).attr('id');
				$(this).remove();
			}
		});
		
		for(j=0;j<tempArray.length;j++){
			if(tempArray[j] != null){
				var temp = tempArray[j] ;
				var tempId = tempIdArray[j];
				
				// only add to left list if name not already in left list
				var inLeftList = false;
				leftList.children('option').each(function(){
						var name = $(this).attr('text');
						if(name == tempArray[j])
						{ inLeftList = true;
						}
				});
				if(!inLeftList)
				{  
					
					  // BC 03 Mar 2009 - Gemini issue 4258 - not working in IE6 
					  //leftList.append('<option id="'+tempIdArray[j]+'" value="'+ tempArray[j] +'">'+ tempArray[j] +'</option>'); // doesn't work in IE6!
					  
					  if(!is_ie6)
					  {  leftList.append('<option id="'+tempIdArray[j]+'" value="'+ tempArray[j] +'">'+ tempArray[j] +'</option>');
					  }
					  else  // ie6
						{
							var leftListSelectObj = document.getElementById(leftList.attr("id"));
							var oOption = document.createElement("OPTION");
							oOption.text=tempArray[j];
							oOption.value=tempIdArray[j];
							leftListSelectObj.add(oOption);									
						}					  

			
				}

				tempArray[j] = null;
				tempIdArray[j] = null;
				
					// BC 12 Aug 2008: Also remove from the YOUR BUSINESS TYPE section
						
						if(POPUP_ID == "COUNCIL_M2M_EDIT")
						{    
							sortSelect(document.getElementById("leftCouncilList"));
							removeFromList(councilPrefix+"selectedCouncilList", temp);
							 if( countElementsInList(councilPrefix+"selectedCouncilList") == 0)
							 {  if(document.getElementById("noCouncilMessage")){document.getElementById("noCouncilMessage").style.display = "";}
							 }
							 else
							 {  // BC 15 Jan 2009: Never hide this message (Gemini issue 3754)
							    //if(document.getElementById("noCouncilMessage")){document.getElementById("noCouncilMessage").style.display = "none";}
							 }
							 
							 if(document.getElementById("manyCouncilMessage"))
							 {
							   if( countElementsInList(councilPrefix+"selectedCouncilList") > 1 )
					           {  document.getElementById("manyCouncilMessage").style.display = "";
						       }
						       else
						       {  document.getElementById("manyCouncilMessage").style.display = "none";
						       }					 
							 }
							 
						 
					  }
					  else if(POPUP_ID == "BUSINESS_TYPE_M2M_EDIT")
					  {
					  	 sortSelect(document.getElementById("leftBusinessTypeList"));
					  	 removeFromList(businessTypePrefix+"selectedBusinessTypeList", temp);
					  	 
					  	 if(document.getElementById("manyBusinessTypeMessage"))
					  	 {
						  	 if( countElementsInList(businessTypePrefix+"selectedBusinessTypeList") > 1 )
								 {  document.getElementById("manyBusinessTypeMessage").style.display = "";
								 }
								 else
								 {  document.getElementById("manyBusinessTypeMessage").style.display = "none";
						     }			  	 	
					  	 }
					  }	
					  else if(POPUP_ID == "TOPIC_M2M_EDIT")
					  {  
					     sortSelect(document.getElementById("leftTopicList"));
					     removeFromList(topicPrefix+"selectedTopicList", temp);
					  	 if(document.getElementById("manyTopicMessage"))
					  	 {
							  	 if( countElementsInList(topicPrefix+"selectedTopicList") > 1 )
								   {  document.getElementById("manyTopicMessage").style.display = "";
								   }
								   else
								   {  document.getElementById("manyTopicMessage").style.display = "none";
							     }		  	 	
					  	 }
					  }			
					  else if(POPUP_ID == "ACT_REGULATION_M2M_EDIT")
					  {
					  	 sortSelect(document.getElementById("leftActRegulationList"));
					  	 removeFromList(findActRegulationPrefix+"selectedActRegulationList", temp);
					  }	
					  else if(POPUP_ID == "ORGANISATION_M2M_EDIT")
					  {
					  	 sortSelect(document.getElementById("leftOrganisationList"));
					  	 removeFromList(findOrganisationPrefix+"selectedOrganisationList", temp);
					  }							
				
				
			}
		}		
		
    tempArray.length = 0;
    tempIdArray.length = 0;
    
    
    if(POPUP_ID == "BUSINESS_TYPE_M2M_EDIT")
		{
				// BC 02 Mar 2009 - Gemini issue 3110
				resetSelectionsInBusinessTypeBrowseChildIframe();
    }
    else if(POPUP_ID == "TOPIC_M2M_EDIT")
		{
				// BC 25 Mar 2009 - Gemini issue 3110
				resetSelectionsInTopicBrowseChildIframe();
    }
    
		return false;			
			
	

	});
	
	// done
	// NOTE: Removed , .saveToAccount as need to prevent div hiding if user hasn't entered mandatory criteria
	$('.doneButton, .cancelButton, .closeButton, .closeIcon, .saveCancelButton').click(function(){
		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();	
		return false;
	});
	
	// set priority to center align
	$('#myResults table tr').each(function(){
		$(this).find('td:eq(2)').css({'text-align': 'center'});
	});
	// set select to center align
	$('#myResults table tr').each(function(){
		$(this).find('td:eq(3)').css({'text-align': 'right', 'padding-right': '27px'});
	});
	
	$('#myResults table tr').each(function(){
		$('td:eq(1) div', this).addClass('hide');
	});
	
	// toggling myresults
	$('#myResults td strong').click(function(){
		var getClasses = $(this).siblings('div').attr('class');
		if(getClasses.match(/hide/)){
			$(this).siblings('div').removeClass('hide');
			$(this).parents('tr').children('td:eq(0)').children('span').css({background: 'url(\'../skin/' + getSkin() + '/images/icons/collapseIcon.gif\')', 'background-repeat':'no-repeat', 'background-position':'0 50%'});
		}
		else{
			$(this).siblings('div').addClass('hide');
			$(this).parents('tr').children('td:eq(0)').children('span').css({background: 'url(\'../skin/' + getSkin() + '/images/icons/expandIcon.gif\')', 'background-repeat':'no-repeat', 'background-position':'0 50%'});
		}
	});
	$('#myResults tr').each(function(){
		$('td:eq(0)').css({'cursor':'pointer'});
		$('td:eq(0)', this).click(function(){
			var getClasses = $(this).siblings('td').children('div').attr('class');
			if(getClasses.match(/hide/)){
				$(this).siblings('td').children('div').removeClass('hide');
				$(this).children('span').css({background: 'url(\'../skin/' + getSkin() + '/images/icons/collapseIcon.gif\')', 'background-repeat':'no-repeat', 'background-position':'0 50%'});
			}
			else{
				$(this).siblings('td').children('div').addClass('hide');
				$(this).children('span').css({background: 'url(\'../skin/' + getSkin() + '/images/icons/expandIcon.gif\')', 'background-repeat':'no-repeat', 'background-position':'0 50%'});
			}
		});
	});
	
	// check if icons are expanded
	$('#myResults table tr').each(function(){
		$('td:eq(0) span', this).css({background: 'url(\'../skin/' + getSkin() + '/images/icons/expandIcon.gif\')', 'background-position': '0 50%', 'background-repeat': 'no-repeat', 'padding-left':'24px'});
		
		// Added by Reactive: 05 Jan 2009
		// if the first td (Topic column) has no text, insert a non-breaking space to create a line-height space. This enables the +/- signs
		if( !$('td:eq(0) span', this).text()){
			$('td:eq(0) span', this).html('&nbsp;');
		}		
		
	});
	$('.expandAll').toggle(function(){
		$('img', this).css({top:'-8px'});  // Added by Reactive: 05 Jan 2009
		$('#myResults tr').each(function(){
			$('.details', this).removeClass('hide');
			$(this).children('td:eq(0)').children('span').css({background: 'url(\'../skin/' + getSkin() + '/images/icons/collapseIcon.gif\')', 'background-repeat':'no-repeat', 'background-position':'0 50%'});
		});
	}, function(){
		$('img', this).css({top:'0px'});  // Added by Reactive: 05 Jan 2009
		$('#myResults tr').each(function(){
			$('.details', this).addClass('hide');
			$(this).children('td:eq(0)').children('span').css({background: 'url(\'../skin/' + getSkin() + '/images/icons/expandIcon.gif\')', 'background-repeat':'no-repeat', 'background-position':'0 50%'});
		});
	});
	
	// BC 11 Feb 2009 - Gemini issue 3650
  $('.showSelectedOrAllLink').toggle(function(){
		$('#myResults tr').each(function(){
			if($(this).children('th:eq(0)').children('a').attr("title") != "Expand/ Collapse All")  // dont hide the title
			{
					if($(this).children('td:eq(3)').children('input').attr("checked"))
					{
						  //$('.details', this).removeClass('hide');
						  $(this).css({'display':''});
					    //$(this).children('td:eq(0)').children('span').css({background: 'url(\'../skin/' + getSkin() + '/images/icons/collapseIcon.gif\')', 'background-repeat':'no-repeat', 'background-position':'0 50%'});
					}
					else
					{   
						  //$('.details', this).addClass('hide');
						  $(this).css({'display':'none'}); // Gemini issue 3650 - really hide (just not unexpand)
					    //$(this).children('td:eq(0)').children('span').css({background: 'url(\'../skin/' + getSkin() + '/images/icons/expandIcon.gif\')', 'background-repeat':'no-repeat', 'background-position':'0 50%'});
					}				
			}

		}		
		);
		$(this).attr({'innerHTML':'Show All'});
	}, function(){
		$('#myResults tr').each(function(){
			//$('.details', this).removeClass('hide');
			$(this).css({'display':''});
			//$(this).children('td:eq(0)').children('span').css({background: 'url(\'../skin/' + getSkin() + '/images/icons/collapseIcon.gif\')', 'background-repeat':'no-repeat', 'background-position':'0 50%'});
		});
		$(this).attr({'innerHTML':'Show Selected'});
	});				
	
	
	//when selectAll checkbox clicked
	
	$('.selectAll').click(function(){
		
		 //alert("selectAll click "+ $(this).attr("title"));
		 
		 if( $(this).attr("title") == "Unselect All")
		 {
		     $(this).css({'background-position':'0 -14px'});
				 $(this).attr({'title':'Select All'});
				 $('#myResults tr').each(function(){
				 		$('td:eq(3)', this).children('input').removeAttr('checked');
						// check if compliance req has any input checkbox
						if('td:eq(1):contains("input")', this){
							$('td:eq(1) input', this).each(function(){
								$(this).removeAttr('checked');
							});
						}
				 });		 	  
		 }
		 else
		 {
		 	
				 $(this).css({'background-position':'0 0px'});
				 $(this).attr({'title':'Unselect All'});
				 $('#myResults tr').each(function(){
				 		$('td:eq(3)', this).children('input').attr({'checked':'checked'});
						// check if compliance req has any input checkbox
						if('td:eq(1):contains("input")', this){
							$('td:eq(1) input', this).each(function(){
								$(this).attr({'checked':'checked'});
							});
						}
				 });		 	
		 }
		 
	});
	
		
	// step3 - arrow to position depending on packageOption selected
	$('#packageOption input').click(function(){
	//  SB 19 May 2009 -> removed this for CR14
	//	if($(this).attr('id') == 'fullpack'){ $('#packageOptionArrow').show().css({left:'29px'}); }
	//	else if($(this).attr('id') == 'summarypack'){ $('#packageOptionArrow').show().css({left:'270px'}); }
	//	else if($(this).attr('id') == 'customise'){ $('#packageOptionArrow').show().css({left:'509px'}); }
	});
	
	// expand all for customReviewIframe
	$('.customReviewIframe tr').each(function(){
	    // BC 12 Nov 2008 -> removed this as was not working properly with the expand all functions
		//$('td:eq(1) div', this).removeClass('hide');
	});

	// test
	var iframeSize = $('#customReviewIframe').width();
	$('.customReviewIframe').attr({css: iframeSize});
	
	// tool tip
	$('img[@src="../skin/" + getSkin() + "/images/icons/priority.gif"]').hover(function(){
		$(this).parent('td').append('<div class="toolTip">Tool tip instruction text here.</div>');
	}, function(){
		$('div', $(this).parent('td')).remove();
	});
	
});
 

function hideSelect(){
	// goes through all select boxes in #contentcenter div and hides them
	$('#contentcenter select').hide();
}
function showSelect(){
	// goes through all select boxes in #contentcenter div and hides them
	$('#contentcenter select').show();
}

