//
// Copyright 1999 Macromedia, Inc. All rights reserved. 
// --------------------------------------------------------------------------
//
// Export Table.js
//
// --------------------------------------------------------------------------

//****************** GLOBALS ********************

var helpDoc = MM.HELP_cmdExportTable;

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

function commandButtons(){
   return new Array(BTN_Export,     "exportTable();window.close()",
                    BTN_Cancel,     "window.close()",
                    BTN_Help,       "displayHelp()" );
}

function canAcceptCommand(){
   if (  !site.windowIsFrontmost() && findTable()  )
      return true;
   return false;
}

//LOCAL FUNCTIONS

//function: getLineBreak
//description: returns line break based on platform

function getLineBreak(theForm){
   var retVal;
   var selInd = theForm.WhichPlatform.selectedIndex;
   
   switch (selInd){
      case 0:
	     retVal = "\r\n";
		 break;
	  case 1:
	     retVal = "\r";
		 break;
	  case 2:
	     retVal = "\n";
		 break;
   }
   
   return retVal;

}

//function: getDelimiter
//description: returns delimiter based on form parameters

function getDelimiter(theForm){
   var retVal;
   var selInd = theForm.Delimiter.selectedIndex;
   
   switch (selInd){
      case 0:
	     retVal = "\t";
		 break;
	  case 1:
	     retVal = " ";
		 break;
	  case 2:
	     retVal = ",";
		 break;
	  case 3:
	     retVal = ";";
		 break;
	  case 4:
	     retVal = ":";
		 break;
   }
   
   return retVal; 

}

//function: findTable
//description: returns tableObject that insertion point is in
//returns an empty string if IP not in table

function findTable(){
  var tableObj="";
  var theDoc = dw.getDocumentDOM();
  
  if (!theDoc) return null;
  
  var selArr = theDoc.getSelection();
  // make sure we have a valid selection array
  if (selArr.length != 2) return null;
  // get the selected object
  var selObj = theDoc.offsetsToNode(selArr[0],selArr[1]);

  while (tableObj=="" && selObj.parentNode){
    if (selObj.nodeType == Node.ELEMENT_NODE && selObj.tagName=="TABLE")
	  tableObj=selObj;
	else
	  selObj = selObj.parentNode;
  }
  return tableObj;
}

//function:initializeUI
//description: sets default line breaks based on platform.
//Loads select lists with localized text strings.

function initializeUI(){
   var theForm = document.forms[0];
   var selPlatform = theForm.WhichPlatform;
   var selDelimiter = theForm.Delimiter;

   //load select widgets
   loadSelectList(selPlatform,OPTIONS_Platforms);
   loadSelectList(selDelimiter,OPTIONS_Delimiters);

   //change default line break type based on platform
   if (navigator.platform == "MacPPC")
      selPlatform.selectedIndex = 1;

}

//function: exportTable
//description: called from Export button
//exports tabular table based on html table

function exportTable(){
   var exportData = "";
   var theForm = document.forms[0];
   var currTable = findTable();
   var lineBreak = getLineBreak(theForm);
   var delimiter = getDelimiter(theForm);
   
   var tableRows = currTable.childNodes;
   var nRows = tableRows.length;
   var i,j;
   var tableCells;
   var nCells;
   var currRow;
   
   for (i=0;i<nRows;i++){
      if (tableRows.item(i).tagName!="TR")
	     continue;
	  currRow = tableRows.item(i);
	  tableCells = currRow.childNodes;
	  nCells = tableCells.length;
	  for (j=0;j<nCells;j++){
	     exportData+=addQualifiers(  getTextNode(tableCells.item(j)), delimiter);
		 exportData+=delimiter;
	  }
	  exportData=exportData.substring(0,exportData.length-1)+lineBreak;
   }
   writeToFile(exportData);
}


//function: writeToFile
//description: writes data to a user specified file
//Arguments:
//exportData = text string to write to a file
function writeToFile(exportData){
   
	 var index;
   var filePath = dw.browseForFileURL("save",LABEL_ExportAs); //determine file path
   
	 index = filePath.lastIndexOf(".")
   if (!filePath)
      alert(ERROR_No_Save_Path);
	 if (index == -1 || (filePath.length - index)!=4 )
	   filePath += ".csv"
   //save file     
   DWfile.write(filePath,exportData);
}


//function: addQualifiers
//description: In a delimited file, quotes should be wrapped
//around any data containing double quotes, commas, or a delimiter.
//This function is two fold: One, wrap quotes around any of the
//above listed items. Two, surround any double quotes with double quotes.
//Examples:
//text from table cell  ->  how it should appear in exported file
//Doe, Jane                  "Doe, Jane"
//My name is "Sue"           "My name is ""Sue"""
//Arguments:
//cellData - text string representing text content of table cell
//delimiter - character used to separate data

function addQualifiers(cellData,delimiter){
   
   var dataLen = cellData.length;
   var qualifier = '"'   //qualifier is double quotes
   var counter=0;
   var i; 
   var currChar;
   var bSurroundWithQualifier = false;
   
   //precede all double quotes (") with another, so:
   //  " --> ""
   cellData = cellData.replace(/"/g, '""'); 

   //surround any word containing comma,quotes,or delimiters with double quotes
   dataLen = cellData.length;
   
   for (i=0;i<dataLen;i++){
      if (  cellData.charAt( i ) == "," ||
	        cellData.charAt( i ) == qualifier  ||
			cellData.charAt( i ) == delimiter ){
	  
	           bSurroundWithQualifier = true;
		       break;
			}
   }
   
   if (bSurroundWithQualifier)
      cellData = qualifier + cellData + qualifier;
	  
   return cellData;
 
}

//function: getTextNode
//description: returns the text from a table cell
//returns only the text and not the html markup
//Arguments:
//tableCellObj - a TD object
//Returns:
//the text from that table cell

function getTextNode(tableCellObj){
  var iter=tableCellObj.childNodes;
  var counter=0;
  var child=iter.item(counter);
  var retVal="";

  while (child) {
    retVal+=getTextNode(child);
    child=iter.item(++counter);
  }

  if (tableCellObj.nodeType == Node.TEXT_NODE)
    retVal+=tableCellObj.data;

  // Replace white space 
  retVal = retVal.replace(/\s+/gi,' ');
  retVal = retVal.replace(/^\s+/,'');
  retVal = retVal.replace(/\s+$/,'');

  return retVal;
}

//GENERIC FUNCTIONS
//loadSelectList()
