var topicPrefix = "";
var topicBrowseIFRAMELoaded = false;

// BC 25 Mar 2009 - Gemini issue 3110
var topicBrowseChild = null;
function setTopicBrowseChild( daObject )
{   topicBrowseChild = daObject;
	  resetSelectionsInTopicBrowseChildIframe();
}

function resetSelectionsInTopicBrowseChildIframe()
{  //alert("TODO: resetSelectionsInTopicBrowseChildIframe");
	
	 
	 if(topicPrefix == null || topicPrefix == "")
	 {  //alert("resetSelectionsInTopicBrowseChildIframe: No topicPrefix set!");
	 	  return;
	 }	
	  
	 if(topicBrowseChild != null) 
	 {	 
		  try{ 
		  		 	
		 	  // BC 27 Feb 2009: Gemini 3110
		 	  // pre-populate it with selected ids
		 	  var idsToAdd = new Array();
			  var listObject = document.getElementById(topicPrefix+"selectedTopicList");
			  if(listObject != null)
			  {
					  for(var i=0; i < listObject.childNodes.length; i++)
					  {
						    if(listObject.childNodes[i].tagName == "LI")
						    {  idsToAdd[idsToAdd.length] = listObject.childNodes[i].id;
						    }
					  }				  	
			  }
			  //alert("idsToAdd.length="+idsToAdd.length);
 	
		 	
			  // remove all unselected
			  var currentBrowseSelections = topicBrowseChild.getAllSelectedIdsArray( );
			  //alert("currentBrowseSelections.length = "+currentBrowseSelections.length);
			  var currentlySelectedInBrowse = new Array();
			  for(var i=0; i < currentBrowseSelections.length; i++)
			  {       currentlySelectedInBrowse[currentlySelectedInBrowse.length] = currentBrowseSelections[i];
			  	    
  	
			  } 
			  for(var i=0; i < currentlySelectedInBrowse.length; i++)
			  {       var id = currentlySelectedInBrowse[i];
			  	
			  	      //alert(id+" is selcted = "+topicBrowseChild.isInAllSelectedIdsArray( id ));
			  	    
	              if( topicBrowseChild.document.getElementById(id+"-icon") && topicBrowseChild.isInAllSelectedIdsArray( id ))
				    	  {  
				    	  	  //alert("resetSelectionsInTopicBrowseChildIframe UNCHECKING "+id);
				    	  	  topicBrowseChild.webFXTreeHandler.checkOrUncheck( topicBrowseChild.document.getElementById(id+"-icon") );
				    	  }					  	   
			  }
				  	
		  

			  for(var i=0; i < idsToAdd.length; i++)
			  {
			        var id = idsToAdd[i];
			    	  
			    	  if( topicBrowseChild.document.getElementById(id+"-icon")  && !topicBrowseChild.isInAllSelectedIdsArray( id ))
			    	  {  
			    	  	  //alert("resetSelectionsInTopicBrowseChildIframe CHECKING "+id);
			    	  	  topicBrowseChild.webFXTreeHandler.checkOrUncheck( topicBrowseChild.document.getElementById(id+"-icon") );
			    	  }
			    	  else
			    	  {  topicBrowseChild.addToAllSelectedIdsArray( id );
			    	  }
			  } 
	
		  }catch(error)
		  {  alert("JS error: topic-m2m.js.resetSelectionsInTopicBrowseChildIframe, "+error.message+", topicPrefix="+topicPrefix);
		  }	 	  
      
	 }	 
	
}
  
  /*
   * Populate the right list with the selected topics
   */
  function setTopicRightList()
  { removeAllFromList("rightTopicList");
  
	  var listObject = document.getElementById(topicPrefix+"selectedTopicList");
	  
	  try{
	  	
		  for(var i=0; i < listObject.childNodes.length; i++)
		  {
		    if(listObject.childNodes[i].tagName == "LI")
		    {  
		    	 // Gemini issue 4464 - show full name as roll-over tooltip. We won't be able to keep the original search text in this case but not critical.
		    	 //addToList("rightTopicList", listObject.childNodes[i].innerHTML, listObject.childNodes[i].title, listObject.childNodes[i].id);
		    	 addToList("rightTopicList", listObject.childNodes[i].innerHTML, listObject.childNodes[i].innerHTML, listObject.childNodes[i].id);
		    	
		    	 // BC 25 Mar 2009 - make sure is not in left list
		    	 removeFromSelect("leftTopicList", listObject.childNodes[i].innerHTML);
		    }
		  } 	  	
	  	
	  }catch(error)
	  {  alert("JS error: topic-m2m.js.setTopicRightList, "+error.message+", topicPrefix="+topicPrefix);
	  }
	  

  } 
  
  function findTopic(prefix)
  {
  	topicPrefix = prefix;
  	
    var text = document.getElementById(topicPrefix+"topic").value.trim().replace(/\n/g, "").replace(/\\/g, "");
    
    if(text == "")
    {
      showInfoMessage("Find Topic", "Please type in the name of the topic and click 'Find'.");
      document.getElementById(topicPrefix+"topic").value = "";
      //document.getElementById(topicPrefix+"topic").focus(); // Gemini issue 3654
      document.getElementById(topicPrefix+"topic").style.color = "#333333"; // Gemini issue 3654
      return;
    }
    
    // remove | and ^ characters
		text = text.replace(/|/g, '');
		text = text.replace(/\^/g, '');
  
    var daURL = "my-business-1?cmd=find_topic&text="+encodeURIComponent(text);
    //alert(daURL);
    document.getElementById("hiddenIFRAME").src = daURL;
    
    showPleaseWait("Please wait while your Topic(s) are validated.");
    
  }
  
  function noTopicFound(searchText)
  {
      hidePleaseWait();  

        showInfoMessage("Find Topic", "No topics were found for "+searchText+". Please try again or use the Browse link to view a list of all topics to select from.")
 
  }
  
  function setTopicsFound(v_findNextArray, searchText)
  {
      hidePleaseWait();  
  
      //alert(v_findNextArray.length+" matches for the busines type '"+searchText+"'");
	  if(v_findNextArray.length > 200)
	  {
		  showInfoMessage("Find Topic", "Your search has returned too many results ("+v_findNextArray.length+").<br/><br/>Please refine your Topic keyword and try again.")
		  return;
	  }      

      //
      // If only one record matched then don't bother showing the M2M selector
      //
      if(v_findNextArray.length == 1)
      {
      	 // don't show M2M selector -> just add the one we found
         var daName = v_findNextArray[0][v_findNextArray[0].length-1][2];
				 if(!isInList(topicPrefix+"selectedTopicList", daName) )
				 {   addToList(topicPrefix+"selectedTopicList", daName, searchText, v_findNextArray[0][v_findNextArray[0].length-1][0]);
				 }
				 else
				 {  showInfoMessage("Find Topic", daName+" is already in your selected list.")
				 }	      	 
      	 
      	 return;
      }      
      
      setTopicRightList(); // Gemini 3600
      removeAllFromList("leftTopicList");
      
      for( var i=0; i < v_findNextArray.length; i++)
      {
         //alert(v_findNextArray[i][v_findNextArray[i].length-1]);
         
         // add to left hand list
         // element is of type [id, node_type, name]
         //addToList("leftTopicList", v_findNextArray[i][v_findNextArray[i].length-1][2], searchText, v_findNextArray[i][v_findNextArray[i].length-1][0]);
         
         var daId = v_findNextArray[i][v_findNextArray[i].length-1][0];
         var daName = v_findNextArray[i][v_findNextArray[i].length-1][2];
         if(!isInList("rightTopicList", daName))
         {  addToList("leftTopicList", daName, daName, daId);  // Gemini issue 4464
         }
      
      }
      
      openTopicM2M();
  }
  
  
  function editTopics(prefix)
  {
  	 topicPrefix = prefix;
  	
     // open up the popup which shows the selected
     // FogBugz 9916 - don't clear out left list prior to edit - removeAllFromList("leftTopicList");
     
     setTopicRightList();
     
     
     if(countElementsInList("rightTopicList") == 0)
     {
       showInfoMessage("Edit Topics", "You must select a topic before you can edit your topics.");
       return false;
     }     
     
     openTopicM2M();
  }    

function browseTopics(forFieldId)
{
	topicPrefix = forFieldId;

	if (topicPrefix != "" && document.getElementById(topicPrefix) != null)
	{
		document.getElementById(topicPrefix).value = ""; // so does not get recorded as search text for selected items
		document.getElementById(topicPrefix).style.color = "#333333"; // Gemini issue 3654
	}

	addNewPopupId("TOPIC_BROWSE");

	$('body').css({'height': '100%', 'width':'100%'});
	addOverlay();

	// center position the popup box
	var xcoord = Math.max(10, ($(window).width() - 730) / 2);
	var ycoord = Math.max(10, ($(window).height() - 283) / 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({'width': 750});
	$("#pop-up"+POPUP_ID).css({'visibility': 'visible'});
	$("#pop-up"+POPUP_ID).css({'z-index': (9000+OVERLAY_COUNT+1)});
	$("#pop-up"+POPUP_ID).removeClass('hide');
	$("#pop-up"+POPUP_ID).show();

	// got to do this here as get Firefox problems (Iframe does not render)
	if (!topicBrowseIFRAMELoaded) 
	{
		//document.getElementById("topicBrowseIFRAME").src = "topic-selector?width=730&height=310&mode=public";
		document.getElementById("topicBrowseIFRAME").src = "topic-selector?width=730&height=300&mode=public"; // Gemini issue 3621 - bit less height for Firefox
		topicBrowseIFRAMELoaded = true;
	}
	
	// BC 25 Mar 2009
	resetSelectionsInTopicBrowseChildIframe();

	return false;
}

function selectBrowsedTopic()
{
	// See Gemini 2911, 3110 & FogBugz 10191 for specifications

	if (selectedNode == null)
	{	// No Topic selected - report message
		showInfoMessage("Select Topic", "No topic selected. Please select a topic.");
		return false;
	}
	else if (/*selectedNode.text == "Topics" && */ selectedNode.action == "javascript:void(0);")
	{	// Root topic selected - report message
		showInfoMessage("Select Topic", "This is not a topic. Please select a topic.");
		return false;
	}

	// Report selected topic and add to selected topic list
	document.getElementById("topic-m2m-supportStatusDIV").innerHTML = "<strong>" + selectedNode.text + "</strong> has been added to your topics";
	parent.addToList(topicPrefix + "selectedTopicList", selectedNode.text, "", selectedNode.action);
}

// BC 25 mar 2009 - Gemini issue 3110
function addTopicToList(id, title)
{  parent.addToList(topicPrefix+"selectedTopicList", title, "", id);
}

function removeTopicFromList(id, title)
{  parent.removeFromList(topicPrefix+"selectedTopicList", title);
}
function removeAllTopicFromList()
{  parent.removeAllFromList(topicPrefix+"selectedTopicList");
}


function openTopicM2M()
{
	addNewPopupId("TOPIC_M2M_EDIT");

	$('body').css({'height': '100%', 'width':'100%'});
	addOverlay();

	// center position the popup box
	var xcoord = Math.max(10, ($(window).width() - 532) / 2);
	var ycoord = Math.max(10, ($(window).height() - 283) / 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;
}

function getTopicString(prefix)
{
  var listObject = document.getElementById(prefix+"selectedTopicList");

	var topicString = "";  
	for(var i=0; i < listObject.childNodes.length; i++)
	{
	  if(listObject.childNodes[i].tagName == "LI")
	  {  topicString += listObject.childNodes[i].innerHTML+"|"+listObject.childNodes[i].title+"|"+listObject.childNodes[i].id+"^";
	  }
	}
	return topicString;
}