home *** CD-ROM | disk | FTP | other *** search
/ Chip 2003 October / Chip Ekim 2003.iso / prog / code / contr / setup.exe / Disk1 / data1.cab / Configuration_En / Commands / Tabular Data.js < prev    next >
Encoding:
JavaScript  |  2003-07-18  |  14.1 KB  |  439 lines

  1. // Copyright 2000, 2001, 2002, 2003 Macromedia, Inc. All rights reserved
  2.  
  3. //---------------   GLOBAL VARIABLES   ---------------
  4.  
  5. var helpDoc = MM.HELP_objTabularData;
  6.  
  7. //---------------     API FUNCTIONS    ---------------
  8.  
  9. function isDOMRequired() { 
  10.     // Return false, indicating that this object is available in code view.
  11.     // This means this object/command is guaranteed to not use the DOM of the current document,
  12.     // except for dw.getDocumentDOM().source...
  13.     return false;
  14. }
  15.  
  16. function commandButtons(){
  17.    return new Array(MM.BTN_OK,         "createTableStr()",
  18.                     MM.BTN_Cancel,     "window.close()",
  19.                     MM.BTN_Help,       "displayHelp()" );
  20. }
  21.  
  22. //---------------    LOCAL FUNCTIONS   ---------------
  23.  
  24. function setTableFileToImport() {
  25.   var fName = dw.browseForFileURL('open','', false, true);
  26.   if (fName) {
  27.     document.forms[0].DataFile.value =  fName;
  28.     setDelimiter(fName);
  29.   }
  30. }
  31.  
  32. //function:setDelimiter
  33. //description: after choosing a file, set delimiter select menu
  34. //based on file type, e.g.: set it to Comma if a *.csv file is chosen
  35.  
  36. function setDelimiter(fileName){
  37.    var selDelimiter = document.forms[0].Delimiter;
  38.    var extension = fileName.substring(  fileName.indexOf(".")  );
  39.    
  40.    if (extension==".csv")   selDelimiter.selectedIndex = 1; //comma
  41.    if (extension==".xls")   alert( ERROR_Unsupported_Format + ERROR_Supported_Formats);
  42.    //if we support more formats in the future
  43.    //such as space-delimited (.csv), more checks may be added here
  44. }
  45.  
  46. //function:getDelimiter
  47. //description: returns user-chosen delimiter based on form parameters
  48.  
  49. function getDelimiter(theForm){
  50.    var retVal;
  51.    var selInd = theForm.Delimiter.selectedIndex;
  52.    
  53.    switch (selInd){
  54.       case 0:
  55.         retVal = "\t";   
  56.         break;
  57.      case 1:
  58.         retVal = ",";
  59.         break;
  60.      case 2:
  61.         retVal = ";";
  62.         break;
  63.      case 3:
  64.         retVal = ":";
  65.         break;
  66.      case 4:
  67.         retVal = theForm.CustomDelimiter.value;
  68.         break;
  69.    }
  70.    return retVal;
  71. }
  72.  
  73. //function: getNewLineChar
  74. //description: returns newline character
  75.  
  76. function getNewLineChar(dataStr){
  77.    var retVal;
  78.    
  79.    if (  dataStr.search("\r\n")!= -1)
  80.       retVal = "\r\n";
  81.    else if (  dataStr.search("\n")!= -1)
  82.       retVal="\n";
  83.    else
  84.       retVal="\r";
  85.      
  86.    return retVal;
  87.    
  88. }
  89.  
  90.  
  91. //function: getFormatTags
  92. //description: returns a two-item array representing opening and closing 
  93. //format tags to be used in the first row based on FormatTopRow form parameter
  94.  
  95. function getFormatTags(theForm){
  96.    var retVal = new Array("","");
  97.    var selInd = theForm.FormatTopRow.selectedIndex;
  98.    
  99.    switch (selInd){
  100.       case 1:
  101.         retVal[0] = "<b>";
  102.          retVal[1] = "</b>";
  103.        break;
  104.      case 2:
  105.         retVal[0] = "<i>";
  106.         retVal[1] = "</i>";
  107.        break;
  108.      case 3:
  109.         retVal[0] = "<b><i>";
  110.         retVal[1] = "</i></b>";
  111.        break;  
  112.    }
  113.    return retVal;
  114. }
  115.  
  116.  
  117. //function: createTableStr
  118. //description: creates the html table based on the form parameters
  119.  
  120. function createTableStr(){
  121.    var theForm = document.forms[0];
  122.    var delimiter = getDelimiter(theForm);
  123.    if (!delimiter){
  124.       alert(ERROR_No_Delimiter);
  125.      return;
  126.    }
  127.    if (delimiter.length>1){
  128.       alert(ERROR_Incorrect_Delimiter);
  129.      return;
  130.    }
  131.    var bAutoWidth = theForm.Width[0].checked;
  132.    if (!bAutoWidth){
  133.       var unitChoice = (theForm.WidthUnit.selectedIndex==0)?'%':'';
  134.      var width = theForm.WidthValue.value + unitChoice;
  135.    }
  136.    var cellSpacing = theForm.CellSpacing.value;
  137.    var cellPadding = theForm.CellPadding.value;
  138.    var border = theForm.Border.value;
  139.    var formatFirstRowArr = getFormatTags(theForm);   
  140.    var openTag = createOpenTableTag(width,border,cellSpacing,cellPadding);
  141.    
  142.    var dataFile = theForm.DataFile.value;
  143.    if ( dataFile && dataFile.substring(dataFile.lastIndexOf(".")) == ".xls"){
  144.       alert(ERROR_Unsupported_Format + ERROR_Supported_Formats);
  145.      return;
  146.    }
  147.    
  148.    var tableFileURL = getFullPath(dataFile);
  149.    if (  !verifyFilePath(tableFileURL)  )
  150.       return;
  151.      
  152.    MM.setBusyCursor();
  153.    var dataStr = DWfile.read(tableFileURL);
  154.    var newline = getNewLineChar(dataStr);
  155.    
  156.    if (dw.getFocus(true) == "html" || dw.getFocus() == "textView") {
  157.          selArray = dw.getDocumentDOM().source.getSelection();
  158.       dw.getDocumentDOM().source.replaceRange(selArray[0], selArray[1], 
  159.           openTag + createTableBody(dataStr,delimiter,newline,formatFirstRowArr) + 
  160.                "</TABLE>");
  161.    } else {    
  162.          dw.getDocumentDOM().insertHTML( openTag + createTableBody(dataStr,delimiter,newline,formatFirstRowArr) + 
  163.                "</TABLE>" );
  164.    }
  165.  
  166.    MM.clearBusyCursor();
  167.  
  168.    window.close();
  169.   
  170. }
  171.  
  172. //function: verifyFilePath
  173. //description: verify that file path is not null and is correct
  174. //and alert correct error message in each case
  175. //returns: true if valid, false if invalid
  176.  
  177. function verifyFilePath(fileURL){
  178.    retVal = true;
  179.    
  180.    //if no file path or incorrect file path, alert error message
  181.    if ( !fileURL ){
  182.       alert(ERROR_No_File)
  183.       retVal=false;
  184.    } else if (  !DWfile.exists( fileURL)  ){
  185.       alert(ERROR_Incorrect_File_Path)
  186.       retVal=false;
  187.    }
  188.    return retVal;
  189. }
  190.  
  191. //function: createOpenTableTag
  192. //description: creates an open table tag based on argument values
  193.  
  194.  function createOpenTableTag(width,border,cellSpacing,cellPadding){
  195.     var openTag = '<TABLE';
  196.    
  197.    if (width)         openTag +=' width="' + width + '"';
  198.    if (border)        openTag +=' border="' + border + '"';
  199.    if (cellSpacing)   openTag +=' cellspacing="' + cellSpacing + '"';
  200.    if (cellPadding)   openTag +=' cellpadding="' + cellPadding + '"';
  201.    
  202.    return openTag + '>';
  203.  
  204.  }
  205.  
  206. //function: getTableCells
  207. //description:returns an array of the table cell data.
  208. //Parses row data to take into account cases where
  209. //the delimiter is included in the cell.
  210. //For example, if the delimiter is a comma
  211. //ensures we don't divide the data at the comma in "Doe, Jane".
  212. //Note:Excel places double quotes around data with reserved characters
  213. //and surrounds double quotes with quotes.
  214. //Examples:
  215. //Excel (.xls file)  ->  Delimited file
  216. //Doe,Jane    ->       "Doe,Jane"
  217. //My name is "Jane" ->  "My name is ""Jane"""
  218. //
  219. //Arguments:
  220. //rowData - text string from original file that represents
  221. //one row of data
  222. //delimiter - character used to separate entries
  223.  
  224.  
  225.  function getTableCells(rowData,delimiter){
  226.     var retArr = new Array();
  227.    var startingOffset = 0;
  228.    var endingOffset = 0;
  229.    var cellData="";
  230.    var qualifier='"'; //qualifer is double quotes
  231.    var dataLen=0;
  232.    var rowDataLen = 0;
  233.    var qualifierCount = 0;
  234.    var i,j;
  235.    var lastInd;
  236.    
  237.    // Optimization
  238.    //if tab-delimited, just split data at tabs and return.
  239.    if (delimiter == "\t") {
  240.       retArr = rowData.split(delimiter);
  241.       return retArr;
  242.    }
  243.    
  244.    
  245.    //When we encounter a delimiter, we want to determine if the
  246.    //the delimiter is separating data: e.g: a,b,c, or
  247.    //if it included in the cell data: "Doe, Jane"
  248.    //To accomplish this goal, we count the number of double quotes
  249.    //between the beginning of the data and the delimiter character 
  250.    //that we find.
  251.    //If this number is even, we have completed getting the cell data.
  252.    //If it is odd, the cell data is not complete so we step
  253.    //through until reaching the next delimiter and repeat the 
  254.    //double-quote test.
  255.    
  256.    rowDataLen = rowData.length;
  257.    lastInd = rowDataLen - 1;
  258.    for (i=0;i<rowDataLen;i++){
  259.  
  260.       if (  rowData.charAt(i)==delimiter || i == lastInd ){
  261.          endingOffset = i;
  262.         if (  i!=lastInd || rowData.charAt(lastInd) == delimiter  ){
  263.            cellData = rowData.substring(startingOffset,endingOffset);
  264.         } else {
  265.            cellData = rowData.substring(startingOffset);
  266.         }       
  267.         //The way we are dividing the data, the delimiter character
  268.         //is the first character in all but the first data string
  269.         //We want to delete it.
  270.         if ( cellData[0] == delimiter ){
  271.            if (  cellData.charAt(1)  )
  272.              cellData = cellData.substring(1);
  273.            else
  274.              cellData = "";
  275.         }
  276.       
  277.         //Go through the cell data and count the number of double quotes
  278.         //I've assigned the double quotes to a qualifier variable
  279.         //to make it easy to allow custom qualifiers in future versions
  280.         if (cellData){
  281.            dataLen = cellData.length;
  282.            for (j=0;j<dataLen;j++){
  283.               if (cellData.charAt(j) == qualifier)
  284.                 qualifierCount++;
  285.            }
  286.         }
  287.  
  288.         //if this is the complete cell data, add it to the return array
  289.         //and reset start offset to the end of the cell data we have
  290.         //just processed
  291.         if (qualifierCount%2==0){ 
  292.            retArr[retArr.length] = cellData;  
  293.           startingOffset = endingOffset; 
  294.         } 
  295.       }
  296.       qualifierCount=0;
  297.    }
  298.    //if far right cell is blank, add last cell to return array:
  299.    if (  rowData.charAt( lastInd )==delimiter  )
  300.       retArr[retArr.length] = "";
  301.  
  302.    return retArr; // Note: optimization return at beginning of function.
  303. }
  304.  
  305.  
  306.  //function: createTable
  307.  //description: creates the body of the table based on the contents of the
  308.  //tabular data file. Parses contents of tabular data file.
  309.  
  310. function createTableBody(dataStr, colDelim, rowDelim, formatFirstRowArr) {
  311.   var openCellFormat = '<td>' + formatFirstRowArr[0];
  312.   var closeCellFormat = formatFirstRowArr[1] + '</td>';
  313.   var emptyFormat = '<td> </td>';
  314.   var escapeChar = '"';
  315.   var rtnArr = new Array();
  316.   var startLoc = 0, curRow = new Array();
  317.   var curRow = new Array();
  318.   var curChar, escapedStr = '';
  319.   var cellContents = '';
  320.   
  321.   // Collect rows of data.
  322.   for (var curLoc = 0; curLoc < dataStr.length; curLoc++) {
  323.     curChar = dataStr.charAt(curLoc);
  324.     if (curChar == escapeChar) {
  325.       escapedStr = '';
  326.       // Ignore everything until we get to the ending escape character.
  327.       for (curLoc++; curLoc < dataStr.length; curLoc++) {
  328.         curChar = dataStr.charAt(curLoc);
  329.         // Look for the ending escape character
  330.         if (curChar == escapeChar) { // Possibly ending escape character
  331.           if (dataStr.charAt(curLoc) == dataStr.charAt(curLoc+1)) {
  332.             // Nope, just the escaped escape character.
  333.             escapedStr += dataStr.substring(startLoc+1,curLoc+1);
  334.             // Save the string and keep looking.
  335.             curLoc++; // Throw away the extra escape character.
  336.             startLoc = curLoc;
  337.           } else {
  338.             // Found the terminating escape
  339.             escapedStr += dataStr.substring(startLoc+1,curLoc).replace(/(\r\n)|[\r\n]/g,'<br>');
  340.             startLoc = curLoc+1;
  341.             break; // Break out of inner for loop.
  342.           }
  343.         }
  344.       }
  345.     } else if (curChar == colDelim) {
  346.       cellContents = escapedStr + dataStr.substring(startLoc,curLoc);
  347.       if (cellContents) {
  348.          curRow.push(openCellFormat + cellContents + closeCellFormat);
  349.       } else {
  350.          curRow.push(emptyFormat);
  351.       }
  352.       escapedStr = '';
  353.       startLoc = curLoc+1;
  354.  
  355.     } else if (curChar == rowDelim.charAt(0)) {
  356.       cellContents = escapedStr + dataStr.substring(startLoc,curLoc);
  357.       if (cellContents) {
  358.          curRow.push(openCellFormat + cellContents + closeCellFormat);
  359.       } else {
  360.          curRow.push(emptyFormat);
  361.       }
  362.       openCellFormat = '<td>';
  363.       closeCellFormat = '</td>';
  364.       escapedStr = '';
  365.       startLoc = curLoc + rowDelim.length;
  366.       rtnArr.push('<tr>' + curRow.join('') + '</tr>');
  367.       curRow = new Array();
  368.     }
  369.   }
  370.   cellContents = escapedStr + dataStr.substring(startLoc,curLoc);
  371.   if (cellContents) {
  372.      curRow.push(openCellFormat + cellContents + closeCellFormat);
  373.   } else if (curRow.length > 0) {
  374.      curRow.push(emptyFormat);
  375.   }
  376.   if (curRow.length > 0) {
  377.     rtnArr.push('<tr>' + curRow.join('') + '</tr>');
  378.   }
  379.   return rtnArr.join('');
  380. }
  381.  
  382.  
  383. //function: toggleCustomField
  384. //description: if Other is chosen in the Delimiter Type select list,
  385. //this function makes a text entry field dynamically appear. Also
  386. //hides it if Other is not chosen
  387.  
  388. function toggleCustomField(optionText){
  389.    // Ignore OptionText because it is localized.
  390.    var theForm = document.forms[0];
  391.    // The "other" option is always last, check if the last option is selected.
  392.    if (theForm.Delimiter.options.length==(theForm.Delimiter.selectedIndex+1)){
  393.       findObject("DelimiterSpan").innerHTML = '<input type="text" maxlength="1" name="CustomDelimiter" size="7">';
  394.    } else {
  395.       findObject("DelimiterSpan").innerHTML = '';
  396.    }
  397. }
  398.  
  399.  
  400. //function: innitializeUI
  401. //description: loads the select menus with localized text strings
  402. //and performs other tasks relating to initializing the UI
  403.  
  404. function initializeUI(){
  405.  
  406.    var theForm = document.forms[0];
  407.  
  408.    //If "other" is chosen in the delimiter type select widget, a
  409.    //text field is dynamically added allowing the user to enter a
  410.    //custom delimiter.
  411.    //If this happens, the height of the table cell is re-calculated
  412.    //(which is visually jarring) unless we include a text field in the 
  413.    //table row when loading the file. the line below hides this field:
  414.    findObject("DelimiterSpan").innerHTML="";
  415.    
  416.    //put focus in data file name field
  417.    theForm.DataFile.focus();
  418.    
  419.    //place localized text strings in select widgets
  420.    //variable name note: variable names preceded by sel
  421.    //indicate a select widget object
  422.    
  423.    var selDelimiter = theForm.Delimiter;
  424.    var selFormatTopRow = theForm.FormatTopRow;
  425.    var selWidthUnit = theForm.WidthUnit;
  426.    
  427.    loadSelectList(selDelimiter,OPTIONS_Delimiters);
  428.    loadSelectList(selFormatTopRow,OPTIONS_Formatting);
  429.    loadSelectList(selWidthUnit,OPTIONS_Units);
  430.    enableBuddy("true")
  431. }
  432.  
  433. function enableBuddy(OnOff){
  434.    var theForm = document.forms[0];
  435.    var selWidthUnit = theForm.WidthUnit;
  436.  
  437.    selWidthUnit.setAttribute("disabled",OnOff);
  438.    theForm.WidthValue.setAttribute("disabled",OnOff);
  439. }