//PUBLIC: called from form before submitting form to retrieve selected object names
//and pack them up ready to be posted in the HTTP response.  True is returned
//if the names are found properly.  False is returned if there is a problem.
//The submit operation should be cancelled if False is return.
function validateTargetChooser()
{
   //get name of the form that the TC is in
   var f = document.forms[0];
   
   //get element to store packed info in to post                
   var controlForPost = eval("document.forms[0]."+controlName);
   if (controlForPost==null)
   {
      alert("Can't find specified form[0] control to return selected object(s) in. ControlName =  "+controlName);
      return false;     //can't find control to return value in
   }
   controlForPost.value = "PP";     //assume nothing selected

   //single select mode?
   if (document.getElementById("singleSelect") && document.getElementById("singleSelect").style.display=="block")
   {
      if (f.single.value.length > 0)
      {
         //get the selected object name
         var list = new Array();
         list[0] = f.single.value;
         
         //create a packed array with the name of the single selected object and store it in the post element             
         controlForPost.value = pack(list);  //create a packed array with the single name
      }
   }
   
   //simple selection (quickFind) mode
   else if (document.getElementById("quickFind") && document.getElementById("quickFind").style.display=="block")
   {
      var control = window.quickFindResults.document.getElementById("quickFindTarget");
      if (control==null)
      {
         //occurs if no search is done before calling validateTargetChooser() in TC.js
         return false;
      }

      var val = control.value;
      if (val==null)
      {
         return false;
      }
      else if (val.length>0)
      {
         //get the selected object names
         var list = new Array();
         list[0] = val;
         
         //create a packed array with the names of the selected objects and store it in the post element
         controlForPost.value = pack(list);
      }
   }
   
   //multi-selection mode
   else if (document.getElementById("multiSelect") && document.getElementById("multiSelect").style.display=="block")
   {
      if (f.multipleList.length>0)
      {
         //create a packed array with the names of the selected objects and store it in the post element
         controlForPost.value = packSelect(f.multipleList);
      }
      f.targetType.value = f.mooTargetType.value;
   }
   
   //advanced selection mode
   else if (document.getElementById("advancedSelection") && document.getElementById("advancedSelection").style.display=="block")
   {
      if (f.container.value==null || f.container.value.length<1)
      {
         //no container specified -- alert error message 
         alert(rc_mustEnterContainer);
         return false;
      }

      //create advanced selection criteria XML and store it in the post element
      controlForPost.value = buildQueryXML();
      f.targetType.value = f.asTargetType.value;
   }

   if (controlForPost.value==null || controlForPost.value=="" || controlForPost.value=="PP")
   {
      //no selected data -- alert error message (General.NeedsObjectName) Must enter an object name before submitting
      alert(rc_needObjectName);
      return false;
   }

   return true;
}

//PUBLIC:  call to see which menu pane is currently active
function getMode()
{
   var ret = "unknown";
   var el = null;
   
   // see if single select is active
   el = document.getElementById("singleSelect");
   if (el!=null && el.style.display=="block")
   {
      ret = "single";
      return ret;
   }
   
   // see if multiple select is active
   el = document.getElementById("multiSelect");
   if (el!=null && el.style.display=="block")
   {
      ret = "multiple";
      return ret;
   }
   
   // see if simple select (quickfind) is active
   el = document.getElementById("quickFind");
   if (el!=null && el.style.display=="block")
   {
      ret = "simple";
      return ret;
   }
   
   // see if advanced selection is active
   el = document.getElementById("advancedSelection");
   if (el!=null && el.style.display=="block")
   {
      ret = "advanced";
      return ret;
   }
   
   return ret;
}


//---------------------------------------------------------------------------------------------------------------------

// PRIVATE  The javascript methods below are private methods used to implement the
// dynamic UI of the Target Chooser.  They should never be used by a developer since they
// can and will change as different versions of iManager are developed.

//a setFocus() that won't generate javascript errors if it fails.
function safeFocus(obj)
{
   try
   {
      if (obj) obj.focus();
   }
   catch(e)
   {
      //ignore
   }
}

//see list functionality
//output the list of types used in the type filter
function showList()
{
   var list = unpack(packedObjectTypeNames);

   if (list!=null)
   {
      var strTypes = "";
      for (var i=0; i<list.length && i<15; i++)
      {
         strTypes += "-" + list[i] + (i+1<list.length ? "\n" : "");
      }
   
      if (list.length>15)
      {
         strTypes += "\n...";    //more than 15 types in filter
      }
   
      //display the list
      alert(rc_validObjectTypes + "\n" + strTypes);
   }
}

//retrieve the comma-delimited list of types for the advanced selection widget to use
function myASTypeFilterCallBack()
{
   var opts = document.forms[0].asTargetType.options;
   
   //find selected options
   var selectedOpts = new Array();
   for (var i=0; i<opts.length; i++)
   {
      if (opts[i].selected) selectedOpts[selectedOpts.length]=opts[i].value;
   }
   
   return iman.commaSepStr(selectedOpts);    //return comma-delimited list of selected types
}

// return from AS
function saveXML(controlName, type, xmlCriteria)
{
   if (xmlCriteria!=null && xmlCriteria.length>0)
   {
      eval("document.forms[0]."+controlName).value = xmlCriteria;
      document.getElementById("filterNo").style.display = "none";
      document.getElementById("filterYes").style.display = "inline";
   }
}

function clearAdvancedFilter()
{
   document.forms[0].advancedSelectionXML.value = "";
   document.getElementById("filterNo").style.display = "inline";
   document.getElementById("filterYes").style.display = "none";
}

//retrieve the Filter XML
function tcGetFilterXML(typeName)
{
   return document.forms[0].advancedSelectionXML.value;
}

//build a save query object representing the user's current query selections
function tcBuildSaveQuery()
{	
   var queryObject = null;
   var form = document.forms[0];
   if (form!=null)
   {
      queryObject                      = new QueryObject();
      queryObject.id                   = 'TC';
      queryObject.container            = form.container.value;
      queryObject.subcontainerSearch   = form.subContainerSearch.checked;
      queryObject.nameFilter           = "*";
      queryObject.typeFilter           = form.asTargetType.value;
      queryObject.subClasses           = ( (form.subClasses!=null) ? form.subClasses.checked : "false");
      queryObject.criteria             = new Array(1);
      queryObject.criteria[0]          = form.advancedSelectionXML.value;
      //dumpQueryObject("tcBuildSaveQuery", queryObject);
   }
   return queryObject;
}

//debug routine
function dumpQueryObject(title,obj)
{
   var s = "";
   s  = title+": query object = \n";
   s += "   id = "+obj.id+"\n";
   s += "   container = "+obj.container+"\n"; 
   s += "   subcontainerSearch = "+obj.subcontainerSearch+"\n"; 
   s += "   nameFilter = "+obj.nameFilter+"\n"; 
   s += "   typeFilter = "+obj.typeFilter+"\n"; 
   s += "   subClasses = "+obj.subClasses+"\n"; 
   for (var i=0; i<obj.criteria.length; i++)
   {
      s += "   criteria["+i+"] = "+obj.criteria[i]+"\n";
   }
   alert(s);
}

// returns advanced query string XML
function buildQueryXML()
{
   var form = document.forms[0];
   var searchFilter = form.advancedSelectionXML.value;
   var xml  = "<query>";
   xml += "<container>"+xmlEncode(form.container.value)+"</container>";
   xml += "<sub-container-search>"+form.subContainerSearch.checked+"</sub-container-search>";
   xml += "<nameFilter>*</nameFilter>";
   xml += "<objectTypeFilter>"+xmlEncode(form.asTargetType.value)+"</objectTypeFilter>";
   xml += "<subclasses>"+((form.subClasses!=null)?form.subClasses.checked:"false")+"</subclasses>";
   xml += searchFilter;
   xml += "</query>";
   return xml;
}

function load()
{
   window.open("frameservice?NPService=fw.LaunchService&NPAction=Launch&launch=fw.SaveAdvancedSelection&launcher=fw.LaunchService&lifecycle=new&nextState=load", "", "toolbar=no,location=no,directories=no,menubar=no,scrollbars=yes,resizable=yes,width=550,height=400");
}

function preview()
{
   var form = document.forms[0];
   if (form.container.value=="")
   {
      alert(rc_mustHaveContainer);
      return;
   }

   document.getElementById("nextButton").src = fw_modulesPath + "/dev/images/btnnext_palm_dis.gif";
   document.getElementById("backButton").src = fw_modulesPath + "/dev/images/btnback_palm_dis.gif";

   var doc = document.getElementById("previewFrame").contentWindow.document;
   doc.writeln("<HTML><HEAD><STYLE>body { font-family: 'Trebuchet MS', Arial }</STYLE></HEAD><BODY>"+rc_performingPreview+"</BODY></HTML>");

   // The traditional way to do the Preview was to write a URL into the IFRAME .src field.  However, with a long filter
   // (about 4 or more elements) it exceeds the IE max length and never returns results.  This was fixed by defining a
   // "previewForm" in the calling JSP and doing a submit, specifying that the results be returned to the previewFrame.
   // However, since the TargetChooser is publicly exposed there may be both internal and external plugins whose
   // JSP's don't define the previewForm.  Therefore, if we see it is not defined, we simply do it the old way.
   // TCFull_inc.jsp, DelObject.jsp, and MoveObject.jsp have been modified to take advantage of the new way.  dks 6/06.

   var pform = document.forms["previewForm"];
   if (pform==null)
   {
      var xml = urlEncode(form.advancedSelectionXML.value);
      var container = urlEncode(form.container.value);
      var queryString = urlEncode(buildQueryXML());
      document.getElementById("previewFrame").src = "webacc?taskId=fw.PreviewObjectFilter&nextState=initialState&merge=fw.TCPreviewFilter&query="+queryString+"&filter=" + xml + "&container=" + container + "&subContainerSearch=" + form.subContainerSearch.checked + "&subClasses=" + ((form.subClasses!=null)?form.subClasses.checked:"false");
   }
   else
   {
	   pform.nextState.value = "initialState";
	   pform.query.value = buildQueryXML()
	   pform.filter.value = form.advancedSelectionXML.value;  // Filter in XML
	   pform.container.value = form.container.value;
	   pform.subContainerSearch.value = form.subContainerSearch.checked;
	   pform.subClasses.value = (form.subClasses!=null) ? form.subClasses.checked : "false";
	   pform.submit();
	}
}

function movePreview(nextState, btn)
{
   if (btn.src.indexOf("_dis")>=0)
   {
      return;
   }

   // See notes in Preview() function.
   var form = document.forms[0];
   var count = document.getElementById("previewFrame").contentWindow.document.form.objectEntryCount.value;
   var pform = document.forms["previewForm"];
   if (pform==null)
   {
      var xml = urlEncode(form.advancedSelectionXML.value);
      var container = urlEncode(form.container.value);
      document.getElementById("previewFrame").src = "webacc?taskId=fw.PreviewObjectFilter&merge=fw.TCPreviewFilter&nextState="+ nextState + "&objectEntryCount=" + count;   // blockIndex="+blockIndex;
   }
   else
   {
	   pform.nextState.value = nextState;
	   pform.objectEntryCount.value = count;
	   pform.filter.value = form.advancedSelectionXML.value;  // Filter in XML
	   pform.container.value = form.container.value;
	   pform.subContainerSearch.value = form.subContainerSearch.checked;
	   pform.submit();
	}
}

function clearFilter()
{
   document.forms[0].advancedSelectionXML.value = "";
   document.getElementById("filterNo").style.display = "inline";
   document.getElementById("filterYes").style.display = "none";
}

function doQuickFind()
{
   var attr = document.getElementById("quickFindAttribute").value;
   if (attr==null || attr=="")
   {
      return;
   }
  	var sort; 
   if (document.getElementById("quickFindSortSelection").checked)
   {
   		sort = "true";
   }
   else
   {
   		sort = "false";
   }

   var op = document.getElementById("quickFindOp").value;
   var filter =  document.getElementById("quickFindFilter").value;
   var url = "frameservice?taskId=dev.Empty&merge=fw.TC_QuickFind&quickFindFilter=" + filter + "&op=" + op + "&quickFindAttribute="+attr + "&objectTypeName=" + window.singleObjectName+"&doSort="+sort;
   document.getElementById('quickFindResults').src = url;
}

function quickFindKeyPressed(event)
{
   if (!event) event = window.event; // Handle diff in IE and Mozilla event system

   if (event.keyCode==13)
   {
      doQuickFind();
      return false;
   }
}