// Copyright 2006 Adobe Macromedia Software LLC and its licensors. All rights reserved.
//---------------   GLOBAL VARIABLES   ---------------
var helpDoc = MM.HELP_objSpryDataTable;
var _LIST_AJAX_DATASETS = null;
var _TREELIST_AJAX_COLS	= null;
//var _SORTALBE_LIST	= null;
//var _SORTALBE_ORDER_LIST = null;
var _SORTALBE_CHECK_BOX = null;
var _sortOrderTypeCtrl = null;
var _ARR_COLS_TO_ADD = new Array();
var _LIST_SPRY_ODD_CLASSES = null;
var _LIST_SPRY_EVEN_CLASSES = null;
var _LIST_SPRY_HOVER_CLASSES = null;
var _LIST_SPRY_SELECT_CLASSES = null;
var _SET_CUR_BEHAVIOR_CHECKBOX = null;
var _bCalledFromDS = false;
var _dropOffsets = null;


var IsSortableList = new Array(MM.LABEL_SortNo,MM.LABEL_SortYes);
var IsSortableValueList = new Array(MM.VALUE_SortNo,MM.VALUE_SortYes);
//var SortOrderList  = new Array(MM.LABEL_None,MM.LABEL_SortAsc,MM.LABEL_SortDesc,MM.LABEL_SortToggle);
//var SortOrderValueList  = new Array(MM.LABEL_None,MM.VALUE_SortAsc,MM.VALUE_SortDesc,MM.VALUE_SortToggle);

//---------------     API FUNCTIONS    ---------------

function isDOMRequired()
{
	return true;
}

function commandButtons()
{
   return new Array( MM.BTN_OK,     "doInsertSpryDataTable()",
                     MM.BTN_Cancel, "window.close()",
                     MM.BTN_Help,   "displayHelp()");
}

//---------------    LOCAL FUNCTIONS   ---------------
function initializeUI()
{  
  _LIST_AJAX_DATASETS = new SpryDataSetList("spryDS");
  _TREELIST_AJAX_COLS = new TreeControlWithNavControls("ColumnList");
  //_SORTALBE_LIST	  = new ListControl("IsSortable");
  //_SORTALBE_ORDER_LIST = new ListControl("SortOrder");	
  _SORTALBE_CHECK_BOX = new CheckBox("","SortOrder");
  _SORTALBE_CHECK_BOX.initializeUI();

  _LIST_SPRY_ODD_CLASSES = new ListControl("spryOddRowClass");
  _LIST_SPRY_EVEN_CLASSES = new ListControl("spryEvenRowClass");
  _LIST_SPRY_HOVER_CLASSES = new ListControl("spryHoverClass");
  _LIST_SPRY_SELECT_CLASSES = new ListControl("sprySelectClass");
  _TREELIST_AJAX_COLS.setColumnNames(MM.LABEL_SpryColGrid);
  //_SORTALBE_LIST.setAll(IsSortableList,IsSortableList);
  //_SORTALBE_ORDER_LIST.setAll(SortOrderList,SortOrderList);
  _sortOrderTypeCtrl = findObject("SortOrder");

  //set the current behavior checkbox
  _SET_CUR_BEHAVIOR_CHECKBOX = new CheckBox("","setRowNum");
  _SET_CUR_BEHAVIOR_CHECKBOX.initializeUI();

  //disable the sort type dd
  //SetEnabled(_sortOrderTypeCtrl, false) 
   //get the list of classes available for this document
    populateSpryCSSClasses();

	//set the spry dataset
	_bCalledFromDS = false;
	var cmdArgs = dwscripts.getCommandArguments();
	if (cmdArgs && (cmdArgs.length > 0))
	{
		var dsName = cmdArgs[0];
		if (dsName && dsName.length)
		{
			_LIST_AJAX_DATASETS.setSelectedValue(dsName);
			_bCalledFromDS = true;
		}
	}
	//get the drop offsets
	if (cmdArgs && (cmdArgs.length > 1))
	{
		_dropOffsets = cmdArgs[1];
	}
	buildColList();	


}

//get the list of classes available for this document
function populateSpryCSSClasses()
{
    var dom = dw.getDocumentDOM();
	var allClasses = dom.getSelectorsDefinedInStylesheet('class');
	for (i = 0; i < allClasses.length; i++)
	{
		if (allClasses[i][0] == '.')
		{
			allClasses[i] = allClasses[i].slice(1);
		}
	}
	_LIST_SPRY_HOVER_CLASSES.setAll(allClasses,allClasses);
	_LIST_SPRY_SELECT_CLASSES.setAll(allClasses,allClasses);
	_LIST_SPRY_ODD_CLASSES.setAll(allClasses,allClasses);
	_LIST_SPRY_EVEN_CLASSES.setAll(allClasses,allClasses);
}

function buildColList()
{	
	//get the client side spry dataset name	
	var dsColList = new Array();				
	var dsColValList = new Array();
	var spryDSName		 = _LIST_AJAX_DATASETS.getSelectedValue();
	if (spryDSName.length != 0)
	{
		var dom = dw.getDocumentDOM();
		var ajaxDataSets = ajaxUtils.getAjaxDataSets(dom,spryDSName);
		if ((ajaxDataSets != null) && (ajaxDataSets.length > 0))
		{
			var anAjaxDataSet = ajaxDataSets[0];
			var schemaArray   = anAjaxDataSet.getSchemaArray();
			for (var i=0; i < schemaArray.length; i++)
			{
				//add it to the binding arrays,add it to the list
				var aSchemaNode = schemaArray[i];
				//append the @ sign for attribute schema elements
				var schemaNodeName = aSchemaNode.getFullNodeName();
				//default sort is off and default sort order is toggle
				var colListParts = schemaNodeName  + "|"  + MM.LABEL_SortNo;
				dsColList.push(colListParts);
				dsColValList.push(new ajaxDataTableColumn(schemaNodeName,false,"",anAjaxDataSet.getColType(schemaNodeName)));
			}
			//set the column names and value list
		 _TREELIST_AJAX_COLS.setAllRows(dsColList,dsColValList);
		 updateAdditionalColumnList('clear'); //clear the column list
		 displayColVals(); //sync to first column values
		}
	}
}


//--------------------------------------------------------------------
// FUNCTION:
//   displayColVals
//
// DESCRIPTION:
//   This function is called by the UI controls to handle UI updates
//
// ARGUMENTS:
//   control - string - the name of the control sending the event
//   event - string - the event which is being sent
//
// RETURNS:
//   nothing
//--------------------------------------------------------------------
function displayColVals()
{
	if (_TREELIST_AJAX_COLS.list.length == 0)
	{
		return;
	}
	else
	{
	   var currRowText = _TREELIST_AJAX_COLS.getRow();
	   var currRowVal  = _TREELIST_AJAX_COLS.getRowValue();
       var rowTextTokens = dw.getTokens(currRowText,"|");
	   //_SORTALBE_LIST.pickValue(rowTextTokens[1]); // update is sortable
	   if (rowTextTokens[1] == MM.LABEL_SortYes)
	   {
		_SORTALBE_CHECK_BOX.setCheckedState(true);
	   }
	   else
	   {
		_SORTALBE_CHECK_BOX.setCheckedState(false);
	   }
	   //_SORTALBE_ORDER_LIST.pickValue(rowTextTokens[1]); // update sort order list
	}
}


//--------------------------------------------------------------------
// FUNCTION:
//   updateCol
//
// DESCRIPTION:
//   This function is called by the UI controls to handle UI updates
//
// ARGUMENTS:
//   control - string - the name of the control sending the event
//   event - string - the event which is being sent
//
// RETURNS:
//   nothing
//--------------------------------------------------------------------
function updateCol(colName)
{
  var currRowObj  = _TREELIST_AJAX_COLS.getRowValue();
  var currRowText = _TREELIST_AJAX_COLS.getRow();
  var currColName = currRowText.substring(0,currRowText.indexOf("|"));
  var sortableText = MM.LABEL_SortNo;
  if (_SORTALBE_CHECK_BOX.getCheckedState())
  {
	sortableText = MM.LABEL_SortYes; 
  }
  var newRowText  = currColName + "|" + sortableText; 
  _TREELIST_AJAX_COLS.setRow(newRowText);
}


// function: updateAdditionalColumnList
// description: the + button calls up an Add Columns dialog, allowing
// the user to add additional columns to the list. When the Add Columns
// dialog is called, it is populated with the "additional columns list".
// This list is updated when a user adds or deletes a column from the UI.
// The action argument can be add, del, or clear

function updateAdditionalColumnList(action,col)
{
   var addColArr = _ARR_COLS_TO_ADD; 
   if (action == 'add')
   {
      addColArr.push(col);
   }
   else if ( action == 'clear')
   {
      _ARR_COLS_TO_ADD = new Array();
   }
   else 
   { 
		// delete an item from additional column list
		var nItems = addColArr.length,i;     
		for (i=0;i<nItems;i++)
		{
			if (addColArr[i] == col)
			{
				 addColArr.splice(i,1);
				 break;
			}
		}
   }
}




//--------------------------------------------------------------------
// FUNCTION:
//   updateUI
//
// DESCRIPTION:
//   This function is called by the UI controls to handle UI updates
//
// ARGUMENTS:
//   control - string - the name of the control sending the event
//   event - string - the event which is being sent
//
// RETURNS:
//   nothing
//--------------------------------------------------------------------
function updateUI(control, event)
{
  if (control == "AddDSCol")
  {
	// check to see if there are columns to add first
	if (_ARR_COLS_TO_ADD.length == 0)
	{
		alert(MM.MSG_NoMoreColumnsToAdd);
		return;
	}
    var colsToAdd = callCommand('Add Column.htm',_ARR_COLS_TO_ADD);
	if (!colsToAdd) return; // user clicked Cancel
	var nCols = colsToAdd.length,i, currCol, rowInfoArr;
	for (i=0;i<nCols;i++)
	{
		currCol = colsToAdd[i];
		//add the row
		var colListParts = currCol  + "|"  + MM.LABEL_SortNo;
		_TREELIST_AJAX_COLS.addRow(colListParts,new ajaxDataTableColumn(currCol,false));
		updateAdditionalColumnList('del',currCol);
	}
  }
  else if (control == "DeleteDSCol")
  {
	var currRow = _TREELIST_AJAX_COLS.getRow();
	var currCol = currRow.substring(0,currRow.indexOf("|") );
	var nRows = _TREELIST_AJAX_COLS.list.length;
	if (nRows > 1)
	{
		updateAdditionalColumnList('add',currCol);
		_TREELIST_AJAX_COLS.delRow();
		displayColVals(); 
	} 
	else 
	{
		alert(MM.MSG_NeedOneColumnInList);
	}
  }
  else if (control == "MoveDSColUp")
  {
    _TREELIST_AJAX_COLS.moveRowUp();
  }
  else if (control == "MoveDSColDown")
  {
    _TREELIST_AJAX_COLS.moveRowDown();
  }
  else if (control == "ColumnList")
  {
    displayColVals();
  }
  /*else if (control == "IsSortable")
  {	
    //if sort column is yes , then set the default sort order to be toggle
	if (_SORTALBE_LIST.getValue() == MM.LABEL_SortYes)
	{
		 SetEnabled(_sortOrderTypeCtrl, true);
		_SORTALBE_ORDER_LIST.pickValue(MM.LABEL_SortToggle);
	}
	else
	{
		 SetEnabled(_sortOrderTypeCtrl, false);
		_SORTALBE_ORDER_LIST.pickValue(MM.LABEL_None);
	}
	updateCol("IsSortable");
  }*/
  else if (control == "SortOrder")
  {	
	updateCol("SortOrder");
  }
}

function newCSSStyle()
{
	var dom = dw.getDocumentDOM();
	var selection;
	var oldLength = 0;
	
	//get the current selection
	selection = dom.getSelection();
	oldLength = dom.documentElement.outerHTML.length;

	//launch the css dialog
	dreamweaver.cssStylePalette.newStyle();
	var lengthDiff = dom.documentElement.outerHTML.length - oldLength;

	//restore the selection back
	if (lengthDiff > 0)
	{
		selection[0] += lengthDiff;
		selection[1] += lengthDiff;
	}
	dom.setSelection(selection[0], selection[1]);

	populateSpryCSSClasses();
}


function doInsertSpryDataTable()
{
	//get the client side spry dataset name					
	var spryDSName		 = _LIST_AJAX_DATASETS.getSelectedValue();
	if (spryDSName.length != 0)
	{
		var bIsInsideBody = ajaxUtils.isInsideBody(dom);
		if (bIsInsideBody)
		{
			//prompt for spry region if missing
			var bAddSpryRegion = ajaxUtils.promptForSpryRegion(_dropOffsets);		
			//TODO: ADD support for class names for alternating rows, hover , selection
			var anAjaxDataTable = new ajaxDataTable("",spryDSName,_LIST_SPRY_ODD_CLASSES.get(),_LIST_SPRY_EVEN_CLASSES.get(),_LIST_SPRY_HOVER_CLASSES.get(),_LIST_SPRY_SELECT_CLASSES.get());
			var colList = new Array();
			var colListRows = _TREELIST_AJAX_COLS.getRow('all');
			for (var i=0; i < colListRows.length; i++)
			{
				//get the column type
				var aColVal = _TREELIST_AJAX_COLS.getRowValue(i);
				var colType = aColVal.getColType();

				var currRowText  = colListRows[i];
				var rowTextTokens = dw.getTokens(currRowText,"|");
				//get the col val, is sortable, sortable
				var colVal	   = rowTextTokens[0];
				/*var IsSortableVal = rowTextTokens[1];
				var isSortable = false;
				if (IsSortableVal == MM.LABEL_SortYes)
				{
					isSortable = true;
				}*/
				var isSortable = false;
				var sortOrder  = rowTextTokens[1];
				if (sortOrder == MM.LABEL_SortYes)
				{
					sortOrder = MM.VALUE_SortToggle; //defaults to toggle sort
					isSortable = true;
				}
				/*else if (sortOrder == MM.LABEL_SortDesc)
				{
					sortOrder = MM.VALUE_SortDesc;
					isSortable = true;
				}
				else if (sortOrder == MM.LABEL_SortToggle)
				{
					sortOrder = MM.VALUE_SortToggle;
					isSortable = true;
				}*/
				//set the data table columns list
				colList.push(new ajaxDataTableColumn(colVal,isSortable,sortOrder,colType));
			}
			//set the current row behavior
			anAjaxDataTable.setColumnList(colList);
			anAjaxDataTable.setCurrentRowBehavior(_SET_CUR_BEHAVIOR_CHECKBOX.getCheckedState());
			var ajaxDTCode = ajaxUtils.getAjaxDataTableCode(anAjaxDataTable);
			if (bAddSpryRegion)
			{
				//add a spry region
				ajaxDTCode = ajaxUtils.wrapWithSpryRegion(ajaxDTCode,spryDSName);
			}

			var dom = dw.getDocumentDOM();
			if (_bCalledFromDS) //called from the data sources d&d
			{
				//set the return value
			  dwscripts.setCommandReturnValue(ajaxDTCode);
			}
			else
			{
				dom.insertHTML(ajaxDTCode);
			}
			//if added spry region ensure namespace is declared
			if (bAddSpryRegion)
			{
				ajaxUtils.initSpryNS();
			}
			window.close();
		}
		else
		{
			alert(MM.MSG_SpryRegionsNeedToBeInsideTheBody);
		}
	}
	else
	{
		alert(MM.MSG_DefineASpryDS);
	}
}

