//
// Copyright 1999, 2000, 2001, 2002, 2003 Macromedia, Inc. All rights reserved.
// ----------------------------------------------------
//
// ccTableOptions.js
//
// reads in the form in ccTableCommands.htm. and make a tablestr to insert into the document.
//
// Version 1.0
// Added functions...
// ----------------------------------------------------

//---------------   GLOBAL VARIABLES   ---------------
var helpDoc = MM.HELP_objTable;
var gDialogShown = false;
var targetDom = null;
var returnTag='';
var TBL_HDR;  //instance of iconSelectorClass, used for selecting table header icons

var DEFAULT_TR = '<tr valign="top">';  //by default, set vertical alignment to top

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

function isDOMRequired() {
	return false;
}

function commandButtons()
{
	return new Array( "PutButtonsOnBottom", "OkButton", MM.BTN_OK, "if (setTableStr()) window.close()",
					  "PutButtonOnLeft", MM.BTN_Help,    "displayHelp()",
					  "CancelButton", MM.BTN_Cancel,  "window.close()");
          
}

function setTableStr(){

  // read all the values out of the form.

  var cmdFile = dreamweaver.getConfigurationPath() + "/Commands/ccTableCommands.htm";
  var cmdDOM = dreamweaver.getDocumentDOM(cmdFile);

  var Columns = cmdDOM.theForm.Cols.value;
  var Rows = cmdDOM.theForm.Rows.value;
  var Border = cmdDOM.theForm.Border.value;
  var Width = cmdDOM.theForm.Width.value;
  var cellSpacing = cmdDOM.theForm.Cellspace.value;
  var cellPadding = cmdDOM.theForm.Cellpad.value;
  
  // unit choice is either 0 for pixels, or 1 for percent.
  var unitChoice = cmdDOM.theForm.Units.selectedIndex; 
  var useWidthInColumns = true;
  
  // width choice is the radio buttons. Either default, which makes each cell 100. Or specify size, 
  // which allows the user to specify the size of the table.
  var specifyWidth;
  var i;
  var cellWidth; 
  var alertString;
  
   //alert when the number of columns are not valid.
  if ( (!(parseInt(Columns)== Columns)) || (Columns < 1) || (Columns > 50))
  {
	alertString = dw.loadString ("ccTableOptions/numColumns");
  	alert (alertString);
	return false;
  }
  
  //alert when the number of rows are not valid.
  if ((!(parseInt(Rows)== Rows)) || (Rows < 1) || (Rows > 50))
  {
	alertString = dw.loadString ("ccTableOptions/numRows");
  	alert (alertString);
	return false;	
  }
  
  // alert when cellSpacing is invalid: non-blank & (non-number, or num<0 or num>50)
  if ((cellSpacing != "") && ((!(parseInt(cellSpacing)== cellSpacing)) || (cellSpacing < 0) || (cellSpacing > 50)))
  {
	  alertString = dw.loadString ("ccTableOptions/cellSpacing");
  	alert (alertString);
	  return false;	
  }

  // alert when cellPadding is invalid: non-blank, non-number, or num<0 or num>50
  if ((cellPadding != "") && ((!(parseInt(cellPadding)== cellPadding)) || (cellPadding < 0) || (cellPadding > 50)))
  {
	  alertString = dw.loadString ("ccTableOptions/cellPadding");
  	alert (alertString);
	  return false;	
  }

  // Display an error message if (#78375): 
  // 1. if it's not a number and the border is > 50 or < 0  OR 
  // 2. it's not a number but the border is not an empty string (which we now allow) 
  
  if ((dwscripts.isNumber(Border) && (Border > 50 || Border < 0)) || 
        (!dwscripts.isNumber(Border) && Border != "")) 
  {
    alertString = dw.loadString ("ccTableOptions/border");
    alert (alertString);
    return false;	
  }

  // alert when then width is not valid only if the user has selected the specify width radio button.
  if (!cmdDOM.theForm.RadioGroup1[0].checked && (!(parseInt(Width) == Width)) || (Width < 0))
  {
	alertString=dw.loadString ("ccTableOptions/width");
	alert (alertString);
	return false;
  }
  
  // figure out whether the user is specifying a width or just using the default width.
  for (i=0; i<cmdDOM.theForm.RadioGroup1.length;i++)
  {
	if (cmdDOM.theForm.RadioGroup1[i].checked)
		specifyWidth = cmdDOM.theForm.RadioGroup1[i].value;
  }
  
  if (specifyWidth == 'default')
  {
   	// cap the width at 1000% or 5000 pixels.
	cellWidth = 100;
  	Width = cellWidth * Columns;
  
  	// if width is pixels, then cap at 5000. otherwise, cap at 1000%.
  	if (unitChoice == 0)
	{
  		if (Width > 5000) Width = 5000;
		cellWidth = Math.round (Width / Columns);
    }	
  }
  
  // if the width is specified.
  else
  {
	// if the unit choice is %, then we dont want to set a width on the table columns.
  	if (unitChoice != 0) useWidthInColumns = false;
	else
  //		cellWidth = Math.round (Width / Columns);
  		useWidthInColumns = false;

	// cap the width at 1000% or 5000 pixels.
	if (unitChoice == 0)
	{
  		if (Width > 5000) Width = 5000;
		cellWidth = Math.round (Width / Columns);
    }	
	else
	{
		if (Width > 1000) Width = 1000;
		cellWidth = Math.round (Width/Columns);
	}
  }
  
  // header choice can be "none", "row", "column" or "both"
  var i = 0;
  var headerchoice;
  headerChoice = TBL_HDR.value;
	 
  //CREATE TABLE
  // there are 4 types of cells, Header cells with width, Header cells with no width, Regular cells with width, and Regular cells with 
  // no width.
   
  var tableHeaderColumnCellsWithWidth='<'+'th width="' + cellWidth + '" scope="row">' + dw.getDocumentDOM("document").getNBSPChar() + '<'+'/th>';
  var tableHeaderColumnCellsNoWidth='<th scope="row">'  + dw.getDocumentDOM("document").getNBSPChar() + '</th>';
  var tableHeaderRowCellsWithWidth='<'+'th width="' + cellWidth + '" scope="col">' + dw.getDocumentDOM("document").getNBSPChar() + '<'+'/th>';
  var tableHeaderRowCellsWithNoWidth='<th scope="col">' + dw.getDocumentDOM("document").getNBSPChar() + '</th>';
 
 
  var tableRegularCellsWithWidth = '<' + 'td width="' + cellWidth + '">' + dw.getDocumentDOM("document").getNBSPChar() + '</td>';
  var tableRegularCellsNoWidth ='<'+'td>' + dw.getDocumentDOM("document").getNBSPChar() + '<'+'/td>';
 
  //Calculate the table width, which is --
  //	width=table width in pixels
  //	n=number of columns
  //	border=table border width
  //	cellborder=(border > 0 ? 1 : 0)
  //	space=cell spacing
  //	x = sum of explicit column widths
  //	width = x + 2*border + (n+1)*space + 2*n*cellborder

  
  var tableWidth = -1;
  var cellBorder;

  if (Border!= "")
	cellBorder = 1;
  else
	cellBorder = 0;

  //if the table width was specified in pixels
 
  if (useWidthInColumns)
  {
    tableWidth = Width + 2*Border + (parseInt(Columns) + 1) * cellSpacing + 2*Columns*cellBorder;
  }

  // set the table opening tag. Thats the actual table tag
  var openTag= '<' + 'table';

  // see if we need to add a value to the open tag. If we didnt set width in the columns, that means we are setting a width on the
  // table tag itself. and then it is always a %.
 
  if ((!useWidthInColumns) && Width > 0) 
  {
	if (unitChoice != 0)
		openTag += ' width="' + Width + '%"';
	else
		openTag += ' width="' + Width + '"';
  
  }
  else
	if (tableWidth > -1) openTag += ' width="' + tableWidth + '"';
 
  // add cellSpacing and Padding
  if (cellSpacing != "") openTag += ' cellspacing="' + cellSpacing + '"';
  if (cellPadding != "") openTag += ' cellpadding="' + cellPadding + '"';

  // add the border if there is one.
  if (Border != "") openTag += ' border="' + Border + '"';

  //strip extra space from openTag, if it exists
  spaceIndex = openTag.length-1;
  if (escape(openTag.charAt(spaceIndex))=='%20')
    openTag = openTag.substring(0,spaceIndex);

  // close off the opening tag.
  openTag += '>';
  
 
 // make the first row. This is a special case because we sometimes set the width in the columns.
  var firstRow = DEFAULT_TR;
  
  // if we want row headers of both row and column headers, then we set the first row as headers.
 
  if (headerChoice == "row" || headerChoice == "both")
  {
	for (i = 0; i < Columns; i++)
	{
	    if (useWidthInColumns) firstRow += tableHeaderRowCellsWithWidth;
		else firstRow += tableHeaderRowCellsWithNoWidth;
	}	
  }

  // if the header choice is column, we want to set all the cells in the first column to be <th> 's.
  else if (headerChoice == "col")
  {
	for (i = 0; i < Columns; i++)
	{
	    // first cell in the row. set it to <th>... </th>
		if (i == 0)
		{
			if (useWidthInColumns) firstRow += tableHeaderColumnCellsWithWidth;
			else firstRow += tableHeaderColumnCellsNoWidth;
		}
		
		// not the first cell, so not part of the column of headers. so just set to <td>
		else
		{
			if (useWidthInColumns) firstRow += tableRegularCellsWithWidth;
			else firstRow += tableRegularCellsNoWidth;
		}
	}
  }

  else if (headerChoice == "none")
  {
    // no headers, so just put in regular cells.
	for (i = 0; i < Columns; i++)
	{
		if (useWidthInColumns) firstRow += tableRegularCellsWithWidth;
		else firstRow += tableRegularCellsNoWidth;
	}
  }
  
  firstRow += "</tr>"

  // make the rest of the table.

  var restOfTable = "";
  var i,j;

  if (headerChoice == "col" || headerChoice == "both")
  {
	// since the first row is already set, we start at 1 instead of 0.
	for (i = 1; i < Rows; i++)
	{
		for (j = 0; j < Columns; j ++)
		{
			// if its the first column, we want to put in header cells.
			if (j == 0) restOfTable += DEFAULT_TR + tableHeaderColumnCellsNoWidth;
			
			// otherwise, we're in the rest of the table, so we put in regular table cells.
			else
			{
				restOfTable += tableRegularCellsNoWidth;
				// last cell in a row, we need to close off the tr tag
				if (j == Columns - 1) restOfTable += "</tr>";
			}
		}
	 }
  }

  // we are not setting any headers, so just put in regular table cells.
  else
  {
	 for (i = 1; i < Rows; i++)
	 {
		for (j = 0; j < Columns; j++)
		{
			if (j == 0) restOfTable += DEFAULT_TR;
			restOfTable += tableRegularCellsNoWidth;
			if (j == Columns - 1) restOfTable += "</tr>";
		}
	 }
  }
 
  returnTag = openTag + firstRow + restOfTable + "</table>";
  return true;

}

function createTableStr()
{
	return returnTag;
}

//---------------    LOCAL FUNCTIONS   ---------------

function saveExtension(curDOM) {
  var curHTML = DWfile.read(curDOM.URL);
  var tempFilename = dw.getConfigurationPath() + '/Shared/MM/Cache/empty.htm';
  if (DWfile.exists(tempFilename)) {
    var tempDOM = dw.getDocumentDOM(tempFilename);
    tempDOM.documentElement.outerHTML = curHTML;
	var atrStr = DWfile.getAttributes(curDOM.URL);
    if (tempDOM.body.outerHTML != curDOM.body.outerHTML && (atrStr.indexOf('R') == -1)){
      tempDOM.body.outerHTML = curDOM.body.outerHTML;
      DWfile.write(curDOM.URL, tempDOM.documentElement.outerHTML);
	}
  }
}

// this function just sets the default text box to something reasonable when the user switches between units.
function onChangeUnits()
{
	var cmdFile = dreamweaver.getConfigurationPath() + "/Commands/ccTableCommands.htm";
    var cmdDOM = dreamweaver.getDocumentDOM(cmdFile);
	var unitChoice = cmdDOM.theForm.Units.selectedIndex; 
	// if it changed to pixels, set the default pixel value to like 500.
	if (unitChoice == 0)
		cmdDOM.theForm.Width.value = 500;
	else
		cmdDOM.theForm.Width.value = 100;
}

function toggleWidthControls()
{
	var cmdFile = dreamweaver.getConfigurationPath() + "/Commands/ccTableCommands.htm";
    var cmdDOM = dreamweaver.getDocumentDOM(cmdFile);
	var specifyWidthChoice;
	
	for (i=0; i<cmdDOM.theForm.RadioGroup1.length;i++)
	{
		if (cmdDOM.theForm.RadioGroup1[i].checked)
		{
			specifyWidthChoice = cmdDOM.theForm.RadioGroup1[i].value;
		}
	}
	// disable the text box and the units.dropdown.
	if (specifyWidthChoice == 'default')
	{
		cmdDOM.theForm.Width.disabled = true;
		cmdDOM.theForm.Units.disabled = true;
	}
	// enable the text box and the units dropdown.
	else
	{
		cmdDOM.theForm.Width.disabled = false;
		cmdDOM.theForm.Units.disabled = false;
	}
}





//////////////////////////////////////////////////////////////////
// Initialize UI:                                   //
// set default values for radio buttons, visibility for layers  //
// and values of caption and summary to blank.                  //
//////////////////////////////////////////////////////////////////

function initializeUI()
{	
      var cmdFile = dreamweaver.getConfigurationPath() + "/Commands/ccTableCommands.htm";
      var cmdDOM = dreamweaver.getDocumentDOM(cmdFile);

	  var headerChoice='both';
	  cmdDOM.theForm.Units.selectedIndex = 0;

    //initialize Table Header selector, default value "none"
    TBL_HDR = new IconSelectorClass(new Array("none","row","col","both"),"none");
	  
	  cmdDOM.theForm.Width.editText = "default";
	  cmdDOM.theForm.Width.selectedIndex = 0;


    cmdDOM.theForm.Rows.focus(); //set focus on textbox
    cmdDOM.theForm.Rows.select(); //set insertion point into textbox
	
//	  cmdDOM.theForm.Width.select(); //set insertion point into textbox


//	  cmdDOM.theForm.Rows.focus(); //set focus on textbox
//	  cmdDOM.theForm.Rows.select(); //set insertion point into textbox
	  gDialogShown = true;



} //initializeUI



///--------------------------------------------------------------------
// CLASS:
//   IconSelectorClass
//
// DESCRIPTION:
//   This class is used to provide radio-button functionality to images.
// When clicking images in table cells, their cells will highlight. To
// find out which image is selected, get the value property of the object.
//
// To set it up, place images in table cells, name the table cells uniquely,
// and add onMouse handlers to each image that call the update method and
// pass the name of their table cells.
//
// PUBLIC PROPERTIES:
//   value (read-only) - the name of the table cell currently selected.
//
// PUBLIC FUNCTIONS:
//   update(value) - passed by the click handler to select a new cell.
//
// CONSTRUCTOR:
//   tableCellNames - an array of all table cell names to be used
//   initialName (optional) - initial cell to select (otherwise 1st)
//
//--------------------------------------------------------------------

function IconSelectorClass(tableCellNames, initialName)
{
  //Private properties: set these to 
  this.selectedColor = "#716F64";   //background color for selected table cell
  this.unselectedColor = "";        //background color for unselected table cell (#9D9CA7 on table)
  this.selectedTextColor = "#FFFFFF";   //color for selected text (white)
  this.unselectedTextColor = "#000000"; //color for unselected text (black)

  //Clear out all selections
  for (var i=0; i<tableCellNames.length; i++)
  {
    document[tableCellNames[i]].bgColor = this.unselectedColor;
  }

  //determine initial value (use if passed in, otherwise 1st item)
  this.value = initialName;
  if (!this.value) this.value = tableCellNames[0];  //if now initial, use item 0

  this.update(this.value); //update, to select the default table cell
}
IconSelectorClass.prototype.update = IconSelectorClass_update;



//Update method. Pass in a new value, one of the table cell names.

function IconSelectorClass_update(newValue)
{
  document[this.value].bgColor = this.unselectedColor;  //unselect the prior table cell
  document[this.value].innerHTML = document[this.value].innerHTML.replace(RegExp(this.selectedTextColor),this.unselectedTextColor); //unset the prior text color

  this.value = newValue;                                //change the value to the new value
  document[this.value].bgColor = this.selectedColor;    //select the new table cell
  document[this.value].innerHTML = document[this.value].innerHTML.replace(RegExp(this.unselectedTextColor),this.selectedTextColor); //set the new text color
}

//----------- END IconSelectorClass --------------
