// Copyright 2005-2007 Adobe Systems Incorporated.  All rights reserved.

var HELP_DOC = MM.HELP_cmdSpryXMLDataSet;

var _dataSetName	= null;
var _xmlSource = null;
var _xmlSchemaTree = null;
var _dataSetTreeColList = null;
var _dataSetSortColList = null;
var _dataSetSortTypeList = null;
var _dataTypeList = null;
var _xPathExprTextField = null;
var _sampleDataPlaceHolder = null;
var _dataPreviewHolder = null;
var _distinctCheckBox   = null;
var _turnXMLCacheOffCheckBox = null;
var _autoRefreshCheckBox = null;
var _autoRefreshTextField = null;
var _designTimeFeedLink = null;

//design time ajax data set
var anAjaxDataSet = null;
var treeNodeContents = "";
var _schemaNameArray = "";
var _selfReferenceNode = null;

//edit mode
var _editMode = false;
var _origSpryDataSet = null;

//*************************API**************************

//--------------------------------------------------------------------
// FUNCTION:
//   commandButtons
//
// DESCRIPTION:
//   Returns the array of buttons that should be displayed on the
//   right hand side of the dialog.  The array is comprised
//   of name, handler function name pairs.
//
// ARGUMENTS:
//   none
//
// RETURNS:
//   array of strings - name, handler function name pairs
//--------------------------------------------------------------------

function commandButtons()
{                          
  return new Array(MM.BTN_OK,     "okClicked()",
                   MM.BTN_Cancel, "cancelClicked()",
                   MM.BTN_Help,   "displayHelp()" );
}


//--------------------------------------------------------------------
// FUNCTION:
//   localizeTypeToDataType
//
// DESCRIPTION:
//   for a localized string - get the corresponding data type
//
// ARGUMENTS:
//   display localized type
//
// RETURNS:
//   column data type
//--------------------------------------------------------------------
function localizeTypeToDataType(aDisplayType)
{
	//convert to lower case
	if (aDisplayType && aDisplayType.length)
	{
		aDisplayType = aDisplayType.toLowerCase(); 
	}

	var aColType = aDisplayType;
	if (aDisplayType && aDisplayType.length)
	{
		for (var i=0; i < MM.LABEL_SpryDataTypeCols.length; i++)
		{		
			var aDisplayLabelType = MM.LABEL_SpryDataTypeCols[i];
			//convert to lower case
			if (aDisplayLabelType && aDisplayLabelType.length)
			{
				aDisplayLabelType = aDisplayLabelType.toLowerCase(); 
			}
			if (aDisplayLabelType == aDisplayType)
			{
				//get the corresponding data type
				if (i < MM.VALUE_SpryDataTypeCols.length)
				{
					aColType = MM.VALUE_SpryDataTypeCols[i];				
				}
				break;
			}
		}
	}
	return aColType;
}

//--------------------------------------------------------------------
// FUNCTION:
//   dataTypeToLocalizeType
//
// DESCRIPTION:
//   for a data type string - get the corresponding localized string type
//
// ARGUMENTS:
//   column data type
//
// RETURNS:
//   display localized type
//--------------------------------------------------------------------
function dataTypeToLocalizeType(aColDataType)
{
	var aDisplayColType = aColDataType;
	if (aColDataType && aColDataType.length)
	{
		for (var i=0; i < MM.VALUE_SpryDataTypeCols.length; i++)
		{
			if (MM.VALUE_SpryDataTypeCols[i] == aColDataType)
			{
				//get the corresponding data type
				if (i < MM.LABEL_SpryDataTypeCols.length)
				{
					aDisplayColType = MM.LABEL_SpryDataTypeCols[i];				

				}
				break;
			}
		}
	}
	return aDisplayColType;
}



//--------------------------------------------------------------------
// FUNCTION:
//   okClicked
//
// DESCRIPTION:
//   Sets the return value to the selected DSN and closes the window.
//
// ARGUMENTS:
//   none
//
// RETURNS:
//   nothing
//--------------------------------------------------------------------

function okClicked()
{
  var retVal = new Array();
  var bValidData = 	validateDataAndChangedFields();
  if (bValidData)
  {
	  var ajaxJSName = _dataSetName.value;
  	  var xmlSource  = _xmlSource.value;
	  //var xPathRef		= _xmlSchemaTree.selectedNodes[0].getAttribute("xpath"); 
	  var xPathRef = _xPathExprTextField.value; 
	  if (xPathRef && xPathRef.length)
	  {
			var colList = new Array();
			var colListRows = _dataSetTreeColList.getRow('all');
			for (var i=0; i < colListRows.length; i++)
			{
				var currRowText  = colListRows[i];
				var rowTextTokens = dw.getTokens(currRowText,"|");
				//get the col val, is sortable, sortable
				var colVal	   = rowTextTokens[0];
				var displayColType    = rowTextTokens[1];
				var colType           = localizeTypeToDataType(displayColType);			

				//for string data types , make it text
				if (colType == "string")
				{
					colType = "text";
				}
				//set the data table columns list
				colList.push(new ajaxDSColNode(colVal,colType));
			}
			//set the colList
			var anAjaxDataSet = new ajaxDesignTimeDataSet(ajaxJSName,xmlSource,xPathRef);
			anAjaxDataSet.setColumnList(colList);
			
			//set the sort order options
			var sortColOnLoad = _dataSetSortColList.getValue();
			if ((sortColOnLoad) && (sortColOnLoad.length) && (sortColOnLoad != MM.LABEL_None))
			{
				anAjaxDataSet.setSortColOnLoad(sortColOnLoad);
				var sortOrderOnLoad = _dataSetSortTypeList.getValue();
				anAjaxDataSet.setOrderOnLoad(sortOrderOnLoad);
			}
			//set the other basic options
			anAjaxDataSet.setDistinct(_distinctCheckBox.getCheckedState());
			anAjaxDataSet.setUseCache(!(_turnXMLCacheOffCheckBox.getCheckedState())); //if it clicked on , turn off the cache by passing false
			if (_autoRefreshCheckBox.getCheckedState())
			{
				anAjaxDataSet.setAutoRefreshInterval(_autoRefreshTextField.value);
			}
			else
			{
				anAjaxDataSet.setAutoRefreshInterval(-1);
			}
			if (_editMode == true)
			{
			   //add js code for the ajax ds component
			   ajaxUtils.editAjaxDSJSCode(anAjaxDataSet,_origSpryDataSet);
			}
			else
			{
			   ajaxUtils.addAjaxDSJSCode(anAjaxDataSet);
			}
	  }
      window.close();
  }
}

//--------------------------------------------------------------------
// FUNCTION:
//   cancelClicked
//
// DESCRIPTION:
//   Closes the window and returns nothing
//
// ARGUMENTS:
//   none
//
// RETURNS:
//   nothing
//--------------------------------------------------------------------

function cancelClicked()
{
  dwscripts.setCommandReturnValue("");
  window.close();
}

//--------------------------------------------------------------------
// FUNCTION:
//   popUpDataPreviewDialog
//
// DESCRIPTION:
//   pop ups the data preview dialog
//
// ARGUMENTS:
//   none
//
// RETURNS:
//   nothing
//--------------------------------------------------------------------
function popUpDataPreviewDialog()
{
    var cmdArgs = new Array();
	var treeNodesList = _xmlSchemaTree.treeNodes;
	if (treeNodesList.length > 0)
	{
		if (_xmlSchemaTree.selectedNodes[0] != null)
		{
		  //var xPathRef = _xmlSchemaTree.selectedNodes[0].getAttribute("xpath"); 
		  //alert(_xPathExprTextField);
		  //alert(_xPathExprTextField.value);
		  var xPathRef = _xPathExprTextField.value; 
		  //alert("xPathRef:" + xPathRef);
		  if (xPathRef && xPathRef.length)
		  {
 			 var xmlSource = _xmlSource.value;
			 var dsName    = _dataSetName.value;
			 //set the command arguments
			 cmdArgs[0] = xmlSource;
			 cmdArgs[1] = xPathRef;
			 cmdArgs[2] = _schemaNameArray;
			 cmdArgs[3] = _selfReferenceNode;
			 cmdArgs[4] = dsName;
			 //call the spry test dialog
			dwscripts.callCommand("SpryXMLDataTest", cmdArgs);
		  }
		  else
		  {
			//please specify xpath before previewing.
			alert(MM.MSG_DefineASpryXPathBeforePreviewing);
		  }
		}
	}
	else
	{
		//please get schema before previewing.
		alert(MM.MSG_GetSchemaBeforePreviewing);
	}
}

//--------------------------------------------------------------------
// FUNCTION:
//   browseForXMLFile
//
// DESCRIPTION:
//   browse for the xml file
//
// ARGUMENTS:
//	 none
//
// RETURNS:
//   nothing
//--------------------------------------------------------------------
function browseForXMLFile()
{
	var LABEL_XMLFILTER = (navigator.platform == "Win32") ? "XML (*.xml)|*.xml|XML|" : "XML (*.xml)|*.xml|****|";
    var theXMLFilter	= new Array(LABEL_XMLFILTER, dw.loadString("General/all files filter"));
	var fileName = dw.browseForFileURL("select",dw.loadString("spry/data/SelectXMLSource"),false,false,theXMLFilter);
	if (fileName) 
	{
		_xmlSource.value = fileName;
	}
}

//--------------------------------------------------------------------
// FUNCTION:
//   onXMLSchema
//
// DESCRIPTION:
//   get xml schema tree and populates the tree control
//
// ARGUMENTS:
//	 none
//
// RETURNS:
//   nothing
//--------------------------------------------------------------------
function onXMLSchema()
{
	var bSuccess = getXMLSchema();
	if (bSuccess == false)
	{
		displayDesignTimeFeed();
	}
}



//--------------------------------------------------------------------
// FUNCTION:
//   getXMLSchema
//
// DESCRIPTION:
//   get xml schema tree and populates the tree control
//
// ARGUMENTS:
//	 none
//
// RETURNS:
//   nothing
//--------------------------------------------------------------------
function getXMLSchema()
{
	var bSuccess = false;
	var dsName    = _dataSetName.value;
	var xmlSource = _xmlSource.value;
	//get the schema xml
	var anAjaxDataSet = new ajaxDesignTimeDataSet(dsName,xmlSource,"");
	var xmlSchemaString = anAjaxDataSet.getSchemaString(true);//force a refresh
	if ((xmlSchemaString != null) && (xmlSchemaString.length))
	{
		var newDOM = dwscripts.getEmptyDOM(); 
		newDOM.documentElement.outerHTML = xmlSchemaString; 	
		var elementNodes = newDOM.getElementsByTagName("ELEMENT");
		if ((elementNodes != null) && (elementNodes.length))
		{
			var parentRootElement = elementNodes[0];		
			treeNodeContents = "";
			if (dwscripts.IS_MAC)
			{		
				//for mac create an empty column node
				treeNodeContents ="<mm:treecolumn width='300'>";
			}
			buildTreeContents(parentRootElement,"");
			//set the objects inner HTML
			_xmlSchemaTree.innerHTML = treeNodeContents;
			enableControls();
			buildColumnList();
			bSuccess  = true;
		}
		else
		{
			//look if we have error nodes
			var errorNodes = newDOM.getElementsByTagName("ERROR");
			treeNodeContents = "";
			if (dwscripts.IS_MAC)
			{		
				//for mac create an empty column node
				treeNodeContents ="<mm:treecolumn width='300'>";
			}
			buildErrorContents(errorNodes);
			//set the objects inner HTML
			_xmlSchemaTree.innerHTML = treeNodeContents;
			//disable controls
			disableControls();
		}
	}
	return bSuccess;
}

//--------------------------------------------------------------------
// FUNCTION:
//   buildTreeContents
//
// DESCRIPTION:
//   build tree contents of the xml schema tree
//
// ARGUMENTS:
//	 none
//
// RETURNS:
//   nothing
//--------------------------------------------------------------------
function buildTreeContents(aParentTreeNode,xpath)
{
	if (aParentTreeNode && ((aParentTreeNode.tagName == "ELEMENT") || (aParentTreeNode.tagName == "ATTRIBUTE")))
	{
		var xmlNodeName = "";
		var xmlNSName = aParentTreeNode.getAttribute("ns");
		if (xmlNSName.length)
		{
			xmlNodeName += xmlNSName;
			xmlNodeName += ":";
		}

    	xmlNodeName += aParentTreeNode.getAttribute("localName");
		var nodeXPath = "";
		
		var selected = "";
		if (xpath.length == 0)
		{
			nodeXPath = xmlNodeName;
			selected = " selected"; //select the root node by default
		}
		else
		{
			var attrPrefix = "";
			if (aParentTreeNode.tagName == "ATTRIBUTE")
			{
				//append the "@" 
	    		attrPrefix = "@";
			}
			nodeXPath = xpath + "/" + attrPrefix + xmlNodeName;
		}

		var iconVal = "tag";		
		var maxOccurs = aParentTreeNode.getAttribute("maxOccurs");
		if (maxOccurs == "unbounded")
		{
			iconVal = "tag-repeat";
		}		
		else if (aParentTreeNode.tagName == "ATTRIBUTE")
		{
			iconVal = "tag-attr";
		}
		treeNodeContents += '<MM:TREENODE state="expanded" xpath="' +  nodeXPath +  '" icon="' + iconVal  + '" value="' + xmlNodeName +  '"' + selected +'>';  
		//loop over its children
		if (aParentTreeNode.hasChildNodes())
		{
			for (var i=0; i < aParentTreeNode.childNodes.length ; i++)
			{
				buildTreeContents(aParentTreeNode.childNodes[i],nodeXPath);
			}
		}
		treeNodeContents += '</MM:TREENODE>'
	}
}

//--------------------------------------------------------------------
// FUNCTION:
//   buildErrorContents
//
// DESCRIPTION:
//   build error contents for error nodes
//
// ARGUMENTS:
//	 none
//
// RETURNS:
//   nothing
//--------------------------------------------------------------------
function buildErrorContents(errorList)
{
	var iconVal = "stop"; //stop icon
	for (var i=0; i < errorList.length ; i++)
	{
		var anErrorNode = errorList[i];
		if (anErrorNode && anErrorNode.getAttribute("errortype") == "fatalError")
		{
			var errorStr = anErrorNode.innerHTML;
			//remove the CDATA marker
			var cDataBeginIndex = errorStr.indexOf("<![CDATA[");
			var cDataEndIndex   = errorStr.lastIndexOf("]]>");
			if ((cDataBeginIndex != -1) && (cDataEndIndex != -1))
			{	
				cDataBeginIndex+=9; //size of <![CDATA[
				errorStr = errorStr.substring(cDataBeginIndex,cDataEndIndex);
			}
			var errorLineNum = anErrorNode.getAttribute("linenum");
			var errorColNum  = anErrorNode.getAttribute("colnum");
			if (errorLineNum.length && errorColNum.length)
			{
				errorStr += "(";
				errorStr += errorLineNum;
				errorStr += ",";
				errorStr += errorColNum;
				errorStr += ")";
			}
			treeNodeContents += '<MM:TREENODE state="expanded" ' + 'icon="' + iconVal  + '" value="' + errorStr +  '"' +'>';  
			treeNodeContents += '</MM:TREENODE>'
		}
	}
}


//--------------------------------------------------------------------
// FUNCTION:
//   buildColumnList
//
// DESCRIPTION:
//   build column list
//
// ARGUMENTS:
//	 none
//
// RETURNS:
//   nothing
//--------------------------------------------------------------------
function buildColumnList()
{
  if (_xmlSchemaTree.selectedNodes[0] != null)
  {
	  var xPathRef = _xmlSchemaTree.selectedNodes[0].getAttribute("xpath"); 
	  if (xPathRef && xPathRef.length)
	  {
		//set the value to xpath expression
		//_xPathExprTextField.innerHTML = xPathRef;		
		_xPathExprTextField.value = xPathRef;		
		var xmlSource = _xmlSource.value;
		var dsName    = _dataSetName.value;
		var anAjaxDataSet = new ajaxDesignTimeDataSet(dsName,xmlSource,xPathRef);
		var schemaArray   = anAjaxDataSet.getSchemaArray();
		var schemaNameArray  = new Array();
		var dsColList = new Array();				
		var dsColValList = new Array();
		for (var i=0; i < schemaArray.length; i++)
		{
			//add it to the binding arrays,add it to the list
			var aSchemaNode = schemaArray[i];
			var schemaNodeName = aSchemaNode.getFullNodeName();
			schemaNameArray.push(schemaNodeName);
			var colListParts = schemaNodeName + "|" + MM.LABEL_TypeString;
			dsColList.push(colListParts);
			dsColValList.push(new ajaxDSColNode(schemaNodeName,"text"));
			//var aDSBinding = new DataSourceBinding(schemaNodeName,AJAX_DATAFIELD_FILENAME,false,"AjaxDataSet.htm");
			//retVal.push(aDSBinding);
		}
		_dataSetTreeColList.setAllRows(dsColList, dsColValList);

		//set the value in global schema name array to be passed to test dialog
		_schemaNameArray = schemaNameArray;
		_selfReferenceNode = anAjaxDataSet.getSelfReferenceNode();

		//set the sort column list
		var colsWithNone = new Array(MM.LABEL_None)
		colsWithNone = colsWithNone.concat(schemaNameArray)
		_dataSetSortColList.setAll(colsWithNone, colsWithNone)

		if (_dataSetTreeColList.list.length)
		{
			//set it to first item in the list
			_dataTypeList.setIndex(0);
		}

		//generate the table for sample data
		/*var sampleDataContents = anAjaxDataSet.generateSampleDataHTMLTable(schemaNameArray);
		if (sampleDataContents && sampleDataContents.length)
		{
			_sampleDataPlaceHolder.innerHTML = sampleDataContents;
		}

		var dataPreviewContents = anAjaxDataSet.generateSampleDataTree(schemaNameArray);
		if (dataPreviewContents && dataPreviewContents.length)
		{
			_dataPreviewHolder.innerHTML = dataPreviewContents;
		}*/
	  }
	  else
	  {
			_xPathExprTextField.value = "";		
	  }
  }
}

//--------------------------------------------------------------------
// FUNCTION:
//   updateDataType
//
// DESCRIPTION:
//   update data type for ajax col
//
// ARGUMENTS:
//	 none
//
// RETURNS:
//   nothing
//--------------------------------------------------------------------
function updateDataType()
{
  var currRowText = _dataSetTreeColList.getRow();
  var currColName = currRowText.substring(0,currRowText.indexOf("|"));
  var newRowText  = currColName + "|" + _dataTypeList.get(); 
  _dataSetTreeColList.setRow(newRowText);
}

//--------------------------------------------------------------------
// FUNCTION:
//   setDataFormats
//
// DESCRIPTION:
//   set data formats
//
// ARGUMENTS:
//	 none
//
// RETURNS:
//   nothing
//--------------------------------------------------------------------
function setDataFormats()
{

	if (_dataSetTreeColList.list.length == 0)
	{
		return;
	}
	else
	{
	   var currRowText = _dataSetTreeColList.getRow();
       var rowTextTokens = dw.getTokens(currRowText,"|");
	   _dataTypeList.pick(rowTextTokens[1]); // update the display type
	}
}


//--------------------------------------------------------------------
// FUNCTION:
//   initializeUI
//
// DESCRIPTION:
//   This function is called in the onLoad event.  It is responsible
//   for initializing the UI.  If we are inserting a recordset, this
//   is a matter of populating the connection drop down.
//
//   If we are modifying a recordset, this is a matter of inspecting
//   the recordset tag and setting all the form elements.
//
// ARGUMENTS:
//   none
//
// RETURNS:
//   nothing
//--------------------------------------------------------------------

function initializeUI()
{
  // Initialize UI elements 
  _dataSetName = dwscripts.findDOMObject("dataSetName"); 
  _xmlSource   = dwscripts.findDOMObject("xmlSource"); 
  _xmlSchemaTree = dwscripts.findDOMObject("theSchemaTreeControl"); 

  //initialize the tree control
  _dataSetTreeColList = new TreeControl("dataSetColList");
  _dataSetTreeColList.setColumnNames(MM.LABEL_SpryColTypeGrid);

  _dataSetSortColList = new ListControl("dataSetSortColList");
  _dataTypeList = new ListControl("dataTypeList");
  _sortType = findObject("dataSetSortType")
  _dataSetSortTypeList = new ListControl("dataSetSortType");
  _dataSetSortTypeList.init();

  //_dataTypeList.init();
  _dataTypeList.setAll(MM.LABEL_SpryDataTypeCols,MM.VALUE_SpryDataTypeCols);
  _dataTypeList.setIndex(0); //set the index to first element

  _xPathExprTextField = dwscripts.findDOMObject("xpathExpr"); 
  //auto refresh interval
  _autoRefreshTextField = dwscripts.findDOMObject("autoRefreshInterval"); 
  _sampleDataPlaceHolder = dwscripts.findDOMObject("sampleData"); 
  _dataPreviewHolder = dwscripts.findDOMObject("dataPreview"); 
  _dataSetName.focus();
  //disable the sort type dd
  SetEnabled(_sortType, false);
	
  _distinctCheckBox = new CheckBox("","distinctOnLoad");
  _distinctCheckBox.initializeUI();

  _turnXMLCacheOffCheckBox = new CheckBox("","usecache");
  _turnXMLCacheOffCheckBox.initializeUI();

  _autoRefreshCheckBox = new CheckBox("","autoRefresh");
  _autoRefreshCheckBox.initializeUI();

  _designTimeFeedLink = dwscripts.findDOMObject("designTimeFeedLink"); 

  //disable the auto refresh interval field
  SetEnabled(_autoRefreshCheckBox.checkBox, false);
  SetEnabled(_autoRefreshTextField, false);

  //get the spry dataset
  var cmdArgs = dwscripts.getCommandArguments();
  if (cmdArgs && (cmdArgs.length > 0))
  {
	_editMode = true;
	_origSpryDataSet = cmdArgs[0];	
	//inspect the spry dataset	
	inspectSpryDataSet(_origSpryDataSet);
  }
  else
  {
	//in add mode auto generate the dataset name
	_dataSetName.value = ajaxUtils.getNextAvailableDataSetName();
	_xmlSource.focus();
  }
}


//--------------------------------------------------------------------
// FUNCTION:
//   disableControls
//
// DESCRIPTION:
//   disable UI Controls.
//
// ARGUMENTS:
//   none
//
// RETURNS:
//   nothing
//--------------------------------------------------------------------
function disableControls()
{
	//disable the dataSetSortList , and clear the column list
	var colsWithNone = new Array(MM.LABEL_None)
	_dataSetSortColList.setAll(colsWithNone, colsWithNone)
	SetEnabled(_dataSetSortColList.object,false);
	//disable the data type list
	SetEnabled(_dataTypeList.object,false);
	//disable the sort type
    SetEnabled(_sortType, false);
	//disable the column list
	var dsColList = new Array();				
	var dsColValList = new Array();
	_dataSetTreeColList.setAllRows(dsColList, dsColValList);
    SetEnabled(_dataSetTreeColList.object, false);	
}

//--------------------------------------------------------------------
// FUNCTION:
//   enableControls
//
// DESCRIPTION:
//   disable UI Controls.
//
// ARGUMENTS:
//   none
//
// RETURNS:
//   nothing
//--------------------------------------------------------------------
function enableControls()
{
	//enable the dataSetSortList
	SetEnabled(_dataSetSortColList.object,true);
	//disable the data type list
	SetEnabled(_dataTypeList.object,true);
	//enabble the sort type
    SetEnabled(_sortType, true);
	//disable the column list
    SetEnabled(_dataSetTreeColList.object, true);	

}


//--------------------------------------------------------------------
// FUNCTION:
//   inspectSpryDataSet
//
// DESCRIPTION:
//   inspects a spry data set
//
// ARGUMENTS:
//   none
//
// RETURNS:
//   nothing
//--------------------------------------------------------------------
function inspectSpryDataSet(aSpryDS)
{
	if (aSpryDS != null)
	{
		_dataSetName.value = aSpryDS.getJSVarName();
		_xmlSource.value  = aSpryDS.getDataSetURL();
		//get the xml schema.
		getXMLSchema();	
		//set the selected node
		var xPathValue = aSpryDS.getDataSetPath();
		//set the value for the selected node
		setXPathNode(xPathValue);
		//set the coltype for special type columns
		var colList = aSpryDS.getColumnList();
		if (colList && colList.length)
		{
			setColList(colList);
		}
		//in the tree
		_xPathExprTextField.value = xPathValue;
		//get the options array
		var optionsArr = aSpryDS.getOptions();
		//set the sort options
		if (optionsArr["sortOnLoad"].length)
		{
			_dataSetSortColList.pickValue(optionsArr["sortOnLoad"]);	
			if (optionsArr["sortOrderOnLoad"].length)
			{
				 SetEnabled(_sortType, true);
				_dataSetSortTypeList.pickValue(optionsArr["sortOrderOnLoad"]);	
			}
		}

		//set the simpler options
		if (optionsArr["distinctOnLoad"] == "true")
		{
			_distinctCheckBox.setCheckedState(true);
		}
		if (optionsArr["useCache"] == "false")
		{
			_turnXMLCacheOffCheckBox.setCheckedState(true);
		}

		//look for auto refresh -if cache is turned off
		if (_turnXMLCacheOffCheckBox.getCheckedState() == true)
		{
		    SetEnabled(_autoRefreshCheckBox.checkBox, true);
			if (optionsArr["loadInterval"] != -1)
			{
				_autoRefreshCheckBox.setCheckedState(true);	
				SetEnabled(_autoRefreshTextField, true);
				_autoRefreshTextField.value = optionsArr["loadInterval"];
			}
		}
		_xmlSchemaTree.focus();
		//display design time feed link
		displayDesignTimeFeedLink(aSpryDS.getJSVarName());
	}
}


//--------------------------------------------------------------------
// FUNCTION:
//   displayDesignTimeFeedLink
//
// DESCRIPTION:
//   display of design time feed link
//
// ARGUMENTS:
//   none
//
// RETURNS:
//   nothing
//--------------------------------------------------------------------
function displayDesignTimeFeedLink(dsName)
{
	var bHasDesignTimeFeed = false;
	var designTimeFeedURI = ajaxUtils.getDesignTimeSchemaURI(dsName);
	if (designTimeFeedURI && designTimeFeedURI.length)
	{
		//show the design time feed link
		//dwscripts.displayNode(_designTimeFeedLink,true);
		bHasDesignTimeFeed = true;
	}
	else
	{
		//dwscripts.displayNode(_designTimeFeedLink,false);
		bHasDesignTimeFeed = false;
	}

	return bHasDesignTimeFeed;
}


//--------------------------------------------------------------------
// FUNCTION:
//   setColList
//
// DESCRIPTION:
//   sets the column list
//
// ARGUMENTS:
//   none
//
// RETURNS:
//   nothing
//--------------------------------------------------------------------
function setColList(colList)
{
	if (colList && colList.length)
	{
		for (var i=0; i < colList.length; i++)
		{
			var aCol = colList[i];
			var colName = aCol.getColName();
			var colType = aCol.getDataType();
			//walk thru the ui col list and match up the column name and set the type
			for (var j = 0; j < _dataSetTreeColList.getRowLen(); j++)
			{
				var rowText = _dataSetTreeColList.getRow(j);
				var rowColName = rowText.substring(0,rowText.indexOf("|"));
				if (colName == rowColName)
				{
					//set the type
					var newRowText  = rowColName + "|" + dataTypeToLocalizeType(colType); 
					_dataSetTreeColList.setRow(newRowText,j);
					if (j == 0)
					{
						//set the data type 
						_dataTypeList.pickValue(colType);
					}
				}
			}
		}
	}
}


//--------------------------------------------------------------------
// FUNCTION:
//   setXPathNode
//
// DESCRIPTION:
//   sets the xpath node to be selected based on xpath value
//
// ARGUMENTS:
//   none
//
// RETURNS:
//   nothing
//--------------------------------------------------------------------
function setXPathNode(xPathValue)
{
	var treeNodesList = _xmlSchemaTree.treeNodes;
	if (xPathValue && xPathValue.length)
	{
		//trim the xPathRef
		xPathValue = ajaxUtils.trimXPath(xPathValue);
	}
	for (var i=0; i < treeNodesList.length; i++)
	{
		if (treeNodesList[i].getAttribute("xpath") == xPathValue)
		{
		     var selectedNodeArray = new Array();
			 selectedNodeArray.push(treeNodesList[i]);
			_xmlSchemaTree.selectedNodes = selectedNodeArray;
			//rebuild the column list
			buildColumnList();
			break;
		}
	}
}



//--------------------------------------------------------------------
// FUNCTION:
//   IsSortEnabled
//
// DESCRIPTION:
//   checks to see if we a column selected and it is not "None"
//
// ARGUMENTS:
//   none
//
// RETURNS:
//   nothing
//--------------------------------------------------------------------
function isSortEnabled()
{
  return (_dataSetSortColList.object.selectedIndex > 0)
}


//--------------------------------------------------------------------
// FUNCTION:
//   sortColChanged
//
// DESCRIPTION:
//   checks to see if we a column selected
//
// ARGUMENTS:
//   none
//
// RETURNS:
//   nothing
//--------------------------------------------------------------------
function sortColChanged()
{
  SetEnabled(_sortType, isSortEnabled())
}


//--------------------------------------------------------------------
// FUNCTION:
//   onAutoRefreshChange
//
// DESCRIPTION:
//   checks to see if we a column selected
//
// ARGUMENTS:
//   none
//
// RETURNS:
//   nothing
//--------------------------------------------------------------------
function onAutoRefreshChange()
{
  SetEnabled(_autoRefreshTextField, _autoRefreshCheckBox.getCheckedState());
}

//--------------------------------------------------------------------
// FUNCTION:
//   onUseCacheChange
//
// DESCRIPTION:
//   checks to see if we a column selected
//
// ARGUMENTS:
//   none
//
// RETURNS:
//   nothing
//--------------------------------------------------------------------
function onUseCacheChange()
{
   if (_turnXMLCacheOffCheckBox.getCheckedState() == false) //if cache is not off , disable auto refresh fields
   {      
     _autoRefreshCheckBox.setCheckedState(false);
	 onAutoRefreshChange();
	 SetEnabled(_autoRefreshCheckBox.checkBox, false);
	 _autoRefreshTextField.value = "";
   }
   else
   {
	 SetEnabled(_autoRefreshCheckBox.checkBox, true);
	 onAutoRefreshChange();
   }
}


//--------------------------------------------------------------------
// FUNCTION:
//   validateDataAndChangedFields
//
// DESCRIPTION:
//   validates the data
//
// ARGUMENTS:
//   none
//
// RETURNS:
//   nothing
//--------------------------------------------------------------------
function validateDataAndChangedFields()
{
	var bIsValid = validateData();
	if (bIsValid)
	{
		//check if the user edited the dataset name or the feed
		if (_editMode)
		{
			//still valid, check for if names of dataset differ
			var origDSName   = _origSpryDataSet.getJSVarName();
			var editedDSName = _dataSetName.value;
			if (origDSName != editedDSName)
			{
				if (confirm(MM.MSG_Spry_DSName_DataReferences) == false)
				{
					bIsValid = false;				
				}
				return bIsValid;
			}
			if (bIsValid)
			{
				//still valid, check for if feeds differ
				var origDSFeed   = _origSpryDataSet.getDataSetURL();
				var editedDSFeed = _xmlSource.value;
				if (origDSFeed != editedDSFeed)
				{
					if (confirm(MM.MSG_Spry_XMLFeed_DataReferences) == false)
					{
						bIsValid = false;				
					}
					return bIsValid;
				}
			}
			if (bIsValid)
			{
				//still valid, check for if xpath differ
				var origPathRef   = _origSpryDataSet.getDataSetPath();
				var editedPathRef = _xPathExprTextField.value;
				if (origPathRef != editedPathRef)
				{
					if (confirm(MM.MSG_Spry_XPath_DataReferences) == false)
					{
						bIsValid = false;				
					}
					return bIsValid;
				}
			}

		}
	}
	return bIsValid;
}


//--------------------------------------------------------------------
// FUNCTION:
//   validateData
//
// DESCRIPTION:
//   validates the data
//
// ARGUMENTS:
//   none
//
// RETURNS:
//   nothing
//--------------------------------------------------------------------
function validateData(bDesignTimeFeedOnly)
{
	var bIsValid = true;
	var dsName    = _dataSetName.value;
	if (dsName.length == 0)
	{
		bIsValid = false;
		alert(MM.MSG_DefineASpryDSName);
		return bIsValid;
	}	

	var aDOM = dw.getDocumentDOM();
	if ((aDOM && !aDOM.isValidIDValue(dsName)) || (dsName.indexOf(".") != -1) || (dsName.indexOf(":") != -1) || (dsName.indexOf("-") != -1))
	{
		bIsValid = false;
		alert(MM.MSG_InvalidCharsInSpryDSName);
		return bIsValid;
	}
	if (bDesignTimeFeedOnly && (bDesignTimeFeedOnly == true))
	{
		//don't validate further
		return bIsValid;
	}

	if (_editMode == false)
	{
		//if in the add mode , check for existing data set name
		if (ajaxUtils.isDataSetExisting(dsName))
		{
			bIsValid = false;
			alert(dwscripts.sprintf(MM.MSG_DataSetExisting,dsName));
			return bIsValid;
		}
	}

	var xmlSource = _xmlSource.value;
	if (xmlSource.length == 0)
	{
		bIsValid = false;
		alert(MM.MSG_DefineASpryXMLFeed);
		return bIsValid;
	}	
	var xPathFieldVal = _xPathExprTextField.value;
	if (xPathFieldVal.length == 0)
	{
		bIsValid = false;
		alert(MM.MSG_DefineASpryXPath);
		return bIsValid;
	}	

	if (_autoRefreshCheckBox.getCheckedState())
	{
		//get the auto refresh milliseconds and validate if it numeric 
		var autoRefreshValue = _autoRefreshTextField.value;
		if (autoRefreshValue.length == 0)
		{
			bIsValid = false;
			alert(MM.MSG_EnterAutoRefreshMilliSeconds);
			return bIsValid;
		}
		if (autoRefreshValue.search(/^(\d+)$/ig) == -1)
		{
			bIsValid = false;
			alert(MM.MSG_InvalidCharsInSpryAutoRefreshMS);
			return bIsValid;
		}
	}

	return bIsValid;
}


//--------------------------------------------------------------------
// FUNCTION:
//   displayDesignTimeFeed
//
// DESCRIPTION:
//   dsiplays design time feed
//
// ARGUMENTS:
//   none
//
// RETURNS:
//   nothing
//--------------------------------------------------------------------
function displayDesignTimeFeed()
{
	//launch the spry design time feed
	var bOkClicked = false;
	var bIsValid = validateData(true);
	if (bIsValid)
	{
		var dsName    = _dataSetName.value;
		var oldDesignTimeFeedURI = ajaxUtils.getDesignTimeSchemaURI(dsName);

		var xmlSource = _xmlSource.value;
		var cmdArgs = new Array();
		cmdArgs[0] = _dataSetName.value;
		cmdArgs[1] = xmlSource;
		var resArray = dwscripts.callCommand("SpryDesignTimeFeed", cmdArgs);
		if (resArray && resArray.length)
		{
			bOkClicked = (resArray == "true");
		}
		
		//show or hide the link	
		displayDesignTimeFeedLink(dsName);

		if (bOkClicked) 
		{
			//display design time feed link
			var newDesignTimeFeedURI = ajaxUtils.getDesignTimeSchemaURI(dsName);
			if (oldDesignTimeFeedURI != newDesignTimeFeedURI)
			{
				//try to get schema again since the user could have supplied
				//an updated copy of design time
				getXMLSchema();
			}
		}
	}

	return bOkClicked;
}



//--------------------------------------------------------------------
// FUNCTION:
//   displayHelp
//
// DESCRIPTION:
//   Displays the built-in Dreamweaver help.
//
// ARGUMENTS:
//   none
//
// RETURNS:
//   nothing
//--------------------------------------------------------------------

function displayHelp()
{
  // Replace the following call if you are modifying this file for your own use.
	dwscripts.displayDWHelp(HELP_DOC);
}
