]> CyberLeo.Net >> Repos - Github/sugarcrm.git/blob - modules/Import/views/view.step3.php
Release 6.4.0
[Github/sugarcrm.git] / modules / Import / views / view.step3.php
1 <?php
2 if(!defined('sugarEntry') || !sugarEntry) die('Not A Valid Entry Point');
3 /*********************************************************************************
4  * SugarCRM Community Edition is a customer relationship management program developed by
5  * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
6  * 
7  * This program is free software; you can redistribute it and/or modify it under
8  * the terms of the GNU Affero General Public License version 3 as published by the
9  * Free Software Foundation with the addition of the following permission added
10  * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
11  * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
12  * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
13  * 
14  * This program is distributed in the hope that it will be useful, but WITHOUT
15  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
16  * FOR A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more
17  * details.
18  * 
19  * You should have received a copy of the GNU Affero General Public License along with
20  * this program; if not, see http://www.gnu.org/licenses or write to the Free
21  * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
22  * 02110-1301 USA.
23  * 
24  * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
25  * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
26  * 
27  * The interactive user interfaces in modified source and object code versions
28  * of this program must display Appropriate Legal Notices, as required under
29  * Section 5 of the GNU Affero General Public License version 3.
30  * 
31  * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
32  * these Appropriate Legal Notices must retain the display of the "Powered by
33  * SugarCRM" logo. If the display of the logo is not reasonably feasible for
34  * technical reasons, the Appropriate Legal Notices must display the words
35  * "Powered by SugarCRM".
36  ********************************************************************************/
37
38 /*********************************************************************************
39
40  * Description: view handler for step 3 of the import process
41  * Portions created by SugarCRM are Copyright (C) SugarCRM, Inc.
42  * All Rights Reserved.
43  ********************************************************************************/
44 require_once('modules/Import/views/ImportView.php');
45 require_once('modules/Import/sources/ImportFile.php');
46 require_once('modules/Import/ImportFileSplitter.php');
47 require_once('modules/Import/ImportCacheFiles.php');
48 require_once('modules/Import/ImportDuplicateCheck.php');
49
50 require_once('include/upload_file.php');
51
52 class ImportViewStep3 extends ImportView
53 {
54
55     protected $pageTitleKey = 'LBL_STEP_3_TITLE';
56     protected $currentFormID = 'importstep3';
57     protected $previousAction = 'Confirm';
58     protected $nextAction = 'dupcheck';
59
60         /**
61      * @see SugarView::display()
62      */
63         public function display()
64     {
65         global $mod_strings, $app_strings, $current_user, $sugar_config, $app_list_strings, $locale;
66
67         $this->ss->assign("IMPORT_MODULE", $_REQUEST['import_module']);
68         $has_header = ( isset( $_REQUEST['has_header']) ? 1 : 0 );
69         $sugar_config['import_max_records_per_file'] = ( empty($sugar_config['import_max_records_per_file']) ? 1000 : $sugar_config['import_max_records_per_file'] );
70         $this->ss->assign("CURRENT_STEP", $this->currentStep);
71         // attempt to lookup a preexisting field map
72         // use the custom one if specfied to do so in step 1
73         $mapping_file = new ImportMap();
74         $field_map = $mapping_file->set_get_import_wizard_fields();
75         $default_values = array();
76                 $ignored_fields = array();
77
78         if ( !empty( $_REQUEST['source_id']))
79         {
80             $GLOBALS['log']->fatal("Loading import map properties.");
81             $mapping_file = new ImportMap();
82             $mapping_file->retrieve( $_REQUEST['source_id'],false);
83             $_REQUEST['source'] = $mapping_file->source;
84             $has_header = $mapping_file->has_header;
85             if (isset($mapping_file->delimiter))
86                 $_REQUEST['custom_delimiter'] = $mapping_file->delimiter;
87             if (isset($mapping_file->enclosure))
88                 $_REQUEST['custom_enclosure'] = htmlentities($mapping_file->enclosure);
89             $field_map = $mapping_file->getMapping();
90             //print_r($field_map);die();
91                         $default_values = $mapping_file->getDefaultValues();
92             $this->ss->assign("MAPNAME",$mapping_file->name);
93             $this->ss->assign("CHECKMAP",'checked="checked" value="on"');
94         }
95         else
96         {
97             // Try to see if we have a custom mapping we can use
98             // based upon the where the records are coming from
99             // and what module we are importing into
100             $classname = 'ImportMap' . ucfirst($_REQUEST['source']);
101             if ( file_exists("modules/Import/maps/{$classname}.php") )
102                 require_once("modules/Import/maps/{$classname}.php");
103             elseif ( file_exists("custom/modules/Import/maps/{$classname}.php") )
104                 require_once("custom/modules/Import/maps/{$classname}.php");
105             else {
106                 require_once("custom/modules/Import/maps/ImportMapOther.php");
107                 $classname = 'ImportMapOther';
108                 $_REQUEST['source'] = 'other';
109             }
110
111             if ( class_exists($classname) )
112             {
113                 $mapping_file = new $classname;
114                 $ignored_fields = $mapping_file->getIgnoredFields($_REQUEST['import_module']);
115                 $field_map2 = $mapping_file->getMapping($_REQUEST['import_module']);
116                 $field_map = array_merge($field_map,$field_map2);
117             }
118         }
119
120         $delimeter = $this->getRequestDelimiter();
121         
122         $this->ss->assign("CUSTOM_DELIMITER", $delimeter);
123         $this->ss->assign("CUSTOM_ENCLOSURE", ( !empty($_REQUEST['custom_enclosure']) ? $_REQUEST['custom_enclosure'] : "" ));
124
125        //populate import locale  values from import mapping if available, these values will be used througout the rest of the code path
126
127         $uploadFileName = $_REQUEST['file_name'];
128
129         // Now parse the file and look for errors
130         $importFile = new ImportFile( $uploadFileName, $delimeter, html_entity_decode($_REQUEST['custom_enclosure'],ENT_QUOTES), FALSE);
131
132         if ( !$importFile->fileExists() ) {
133             $this->_showImportError($mod_strings['LBL_CANNOT_OPEN'],$_REQUEST['import_module'],'Step2');
134             return;
135         }
136
137         $charset = $importFile->autoDetectCharacterSet();
138
139         // retrieve first 3 rows
140         $rows = array();
141
142         //Keep track of the largest row count found.
143         $maxFieldCount = 0;
144         for ( $i = 0; $i < 3; $i++ )
145         {
146             $rows[] = $importFile->getNextRow();
147             $maxFieldCount = $importFile->getFieldCount() > $maxFieldCount ?  $importFile->getFieldCount() : $maxFieldCount;
148         }
149         $ret_field_count = $maxFieldCount;
150
151         // Bug 14689 - Parse the first data row to make sure it has non-empty data in it
152         $isempty = true;
153         if ( $rows[(int)$has_header] != false ) {
154             foreach ( $rows[(int)$has_header] as $value ) {
155                 if ( strlen(trim($value)) > 0 ) {
156                     $isempty = false;
157                     break;
158                 }
159             }
160         }
161
162         if ($isempty || $rows[(int)$has_header] == false) {
163             $this->_showImportError($mod_strings['LBL_NO_LINES'],$_REQUEST['import_module'],'Step2');
164             return;
165         }
166
167         // save first row to send to step 4
168         $this->ss->assign("FIRSTROW", base64_encode(serialize($rows[0])));
169
170         // Now build template
171         $this->ss->assign("TMP_FILE", $uploadFileName );
172         $this->ss->assign("SOURCE", $_REQUEST['source'] );
173         $this->ss->assign("TYPE", $_REQUEST['type'] );
174         $this->ss->assign("DELETE_INLINE_PNG",  SugarThemeRegistry::current()->getImage('basic_search','align="absmiddle" alt="'.$app_strings['LNK_DELETE'].'" border="0"'));
175         $this->ss->assign("PUBLISH_INLINE_PNG",  SugarThemeRegistry::current()->getImage('advanced_search','align="absmiddle" alt="'.$mod_strings['LBL_PUBLISH'].'" border="0"'));
176
177         $this->instruction = 'LBL_SELECT_MAPPING_INSTRUCTION';
178         $this->ss->assign('INSTRUCTION', $this->getInstruction());
179
180         $this->ss->assign("MODULE_TITLE", $this->getModuleTitle(false));
181         $this->ss->assign("STEP4_TITLE",
182             strip_tags(str_replace("\n","",getClassicModuleTitle(
183                 $mod_strings['LBL_MODULE_NAME'],
184                 array($mod_strings['LBL_MODULE_NAME'],$mod_strings['LBL_STEP_4_TITLE']),
185                 false
186                 )))
187             );
188         $this->ss->assign("HEADER", $app_strings['LBL_IMPORT']." ". $mod_strings['LBL_MODULE_NAME']);
189
190         // we export it as email_address, but import as email1
191         $field_map['email_address'] = 'email1';
192
193         // build each row; row count is determined by the the number of fields in the import file
194         $columns = array();
195         $mappedFields = array();
196
197         // this should be populated if the request comes from a 'Back' button click
198         $importColumns = $this->getImportColumns();
199         $column_sel_from_req = false;
200         if (!empty($importColumns)) {
201             $column_sel_from_req = true;
202         }
203
204         for($field_count = 0; $field_count < $ret_field_count; $field_count++) {
205             // See if we have any field map matches
206             $defaultValue = "";
207             // Bug 31260 - If the data rows have more columns than the header row, then just add a new header column
208             if ( !isset($rows[0][$field_count]) )
209                 $rows[0][$field_count] = '';
210             // See if we can match the import row to a field in the list of fields to import
211             $firstrow_name = trim(str_replace(":","",$rows[0][$field_count]));
212             if ($has_header && isset( $field_map[$firstrow_name] ) ) {
213                 $defaultValue = $field_map[$firstrow_name];
214             }
215             elseif (isset($field_map[$field_count])) {
216                 $defaultValue = $field_map[$field_count];
217             }
218             elseif (empty( $_REQUEST['source_id'])) {
219                 $defaultValue = trim($rows[0][$field_count]);
220             }
221
222             // build string of options
223             $fields  = $this->bean->get_importable_fields();
224             $options = array();
225             $defaultField = '';
226             global $current_language;
227                     $moduleStrings = return_module_language($current_language, $this->bean->module_dir);
228
229             foreach ( $fields as $fieldname => $properties ) {
230                 // get field name
231                 if (!empty($moduleStrings['LBL_EXPORT_'.strtoupper($fieldname)]) )
232                 {
233                      $displayname = str_replace(":","", $moduleStrings['LBL_EXPORT_'.strtoupper($fieldname)] );
234                 }
235                 else if (!empty ($properties['vname']))
236                 {
237                     $displayname = str_replace(":","",translate($properties['vname'] ,$this->bean->module_dir));
238                 }
239                 else
240                     $displayname = str_replace(":","",translate($properties['name'] ,$this->bean->module_dir));
241                 // see if this is required
242                 $req_mark  = "";
243                 $req_class = "";
244                 if ( array_key_exists($fieldname, $this->bean->get_import_required_fields()) ) {
245                     $req_mark  = ' ' . $app_strings['LBL_REQUIRED_SYMBOL'];
246                     $req_class = ' class="required" ';
247                 }
248                 // see if we have a match
249                 $selected = '';
250                 if ($column_sel_from_req && isset($importColumns[$field_count])) {
251                     if ($fieldname == $importColumns[$field_count]) {
252                         $selected = ' selected="selected" ';
253                         $defaultField = $fieldname;
254                         $mappedFields[] = $fieldname;
255                     }
256                 } else {
257                     if ( !empty($defaultValue) && !in_array($fieldname,$mappedFields)
258                                                     && !in_array($fieldname,$ignored_fields) )
259                     {
260                         if ( strtolower($fieldname) == strtolower($defaultValue)
261                             || strtolower($fieldname) == str_replace(" ","_",strtolower($defaultValue))
262                             || strtolower($displayname) == strtolower($defaultValue)
263                             || strtolower($displayname) == str_replace(" ","_",strtolower($defaultValue)) )
264                         {
265                             $selected = ' selected="selected" ';
266                             $defaultField = $fieldname;
267                             $mappedFields[] = $fieldname;
268                         }
269                     }
270                 }
271                 // get field type information
272                 $fieldtype = '';
273                 if ( isset($properties['type'])
274                         && isset($mod_strings['LBL_IMPORT_FIELDDEF_' . strtoupper($properties['type'])]) )
275                     $fieldtype = ' [' . $mod_strings['LBL_IMPORT_FIELDDEF_' . strtoupper($properties['type'])] . '] ';
276                 if ( isset($properties['comment']) )
277                     $fieldtype .= ' - ' . $properties['comment'];
278                 $options[$displayname.$fieldname] = '<option value="'.$fieldname.'" title="'. $displayname . htmlentities($fieldtype) . '"'
279                     . $selected . $req_class . '>' . $displayname . $req_mark . '</option>\n';
280             }
281
282             // get default field value
283             $defaultFieldHTML = '';
284             if ( !empty($defaultField) ) {
285                 $defaultFieldHTML = getControl(
286                     $_REQUEST['import_module'],
287                     $defaultField,
288                     $fields[$defaultField],
289                     ( isset($default_values[$defaultField]) ? $default_values[$defaultField] : '' )
290                     );
291             }
292
293             if ( isset($default_values[$defaultField]) )
294                 unset($default_values[$defaultField]);
295
296             // Bug 27046 - Sort the column name picker alphabetically
297             ksort($options);
298
299             // to be displayed in UTF-8 format
300             if (!empty($charset) && $charset != 'UTF-8') {
301                 if (isset($rows[1][$field_count])) {
302                     $rows[1][$field_count] = $locale->translateCharset($rows[1][$field_count], $charset);
303                 }
304             }
305
306             $cellOneData = isset($rows[0][$field_count]) ? $rows[0][$field_count] : '';
307             $cellTwoData = isset($rows[1][$field_count]) ? $rows[1][$field_count] : '';
308             $cellThreeData = isset($rows[2][$field_count]) ? $rows[2][$field_count] : '';
309             $columns[] = array(
310                 'field_choices' => implode('',$options),
311                 'default_field' => $defaultFieldHTML,
312                 'cell1'         => str_replace("&quot;",'', htmlspecialchars($cellOneData)),
313                 'cell2'         => str_replace("&quot;",'', htmlspecialchars($cellTwoData)),
314                 'cell3'         => str_replace("&quot;",'', htmlspecialchars($cellThreeData)),
315                 'show_remove'   => false,
316                 );
317         }
318
319         // add in extra defaulted fields if they are in the mapping record
320         if ( count($default_values) > 0 ) {
321             foreach ( $default_values as $field_name => $default_value ) {
322                 // build string of options
323                 $fields  = $this->bean->get_importable_fields();
324                 $options = array();
325                 $defaultField = '';
326                 foreach ( $fields as $fieldname => $properties ) {
327                     // get field name
328                     if (!empty ($properties['vname']))
329                         $displayname = str_replace(":","",translate($properties['vname'] ,$this->bean->module_dir));
330                     else
331                         $displayname = str_replace(":","",translate($properties['name'] ,$this->bean->module_dir));
332                     // see if this is required
333                     $req_mark  = "";
334                     $req_class = "";
335                     if ( array_key_exists($fieldname, $this->bean->get_import_required_fields()) ) {
336                         $req_mark  = ' ' . $app_strings['LBL_REQUIRED_SYMBOL'];
337                         $req_class = ' class="required" ';
338                     }
339                     // see if we have a match
340                     $selected = '';
341                     if ( strtolower($fieldname) == strtolower($field_name)
342                                                         && !in_array($fieldname,$mappedFields)
343                                                         && !in_array($fieldname,$ignored_fields) ) {
344                         $selected = ' selected="selected" ';
345                         $defaultField = $fieldname;
346                         $mappedFields[] = $fieldname;
347                     }
348                     // get field type information
349                     $fieldtype = '';
350                     if ( isset($properties['type'])
351                             && isset($mod_strings['LBL_IMPORT_FIELDDEF_' . strtoupper($properties['type'])]) )
352                         $fieldtype = ' [' . $mod_strings['LBL_IMPORT_FIELDDEF_' . strtoupper($properties['type'])] . '] ';
353                     if ( isset($properties['comment']) )
354                         $fieldtype .= ' - ' . $properties['comment'];
355                     $options[$displayname.$fieldname] = '<option value="'.$fieldname.'" title="'. $displayname . $fieldtype . '"' . $selected . $req_class . '>'
356                         . $displayname . $req_mark . '</option>\n';
357                 }
358
359                 // get default field value
360                 $defaultFieldHTML = '';
361                 if ( !empty($defaultField) ) {
362                     $defaultFieldHTML = getControl(
363                         $_REQUEST['import_module'],
364                         $defaultField,
365                         $fields[$defaultField],
366                         $default_value
367                         );
368                 }
369
370                 // Bug 27046 - Sort the column name picker alphabetically
371                 ksort($options);
372
373                 $columns[] = array(
374                     'field_choices' => implode('',$options),
375                     'default_field' => $defaultFieldHTML,
376                     'show_remove'   => true,
377                     );
378
379                 $ret_field_count++;
380             }
381         }
382
383         $this->ss->assign("COLUMNCOUNT",$ret_field_count);
384         $this->ss->assign("rows",$columns);
385
386         $this->ss->assign('datetimeformat', $GLOBALS['timedate']->get_cal_date_time_format());
387
388         // handle building index selector
389         global $dictionary, $current_language;
390
391         // show notes
392         if ( $this->bean instanceof Person )
393             $module_key = "LBL_CONTACTS_NOTE_";
394         elseif ( $this->bean instanceof Company )
395             $module_key = "LBL_ACCOUNTS_NOTE_";
396         else
397             $module_key = "LBL_".strtoupper($_REQUEST['import_module'])."_NOTE_";
398         $notetext = '';
399         for ($i = 1;isset($mod_strings[$module_key.$i]);$i++) {
400             $notetext .= '<li>' . $mod_strings[$module_key.$i] . '</li>';
401         }
402         $this->ss->assign("NOTETEXT",$notetext);
403         $this->ss->assign("HAS_HEADER",($has_header ? 'on' : 'off' ));
404
405         // get list of required fields
406         $required = array();
407         foreach ( array_keys($this->bean->get_import_required_fields()) as $name ) {
408             $properties = $this->bean->getFieldDefinition($name);
409             if (!empty ($properties['vname']))
410                 $required[$name] = str_replace(":","",translate($properties['vname'] ,$this->bean->module_dir));
411             else
412                 $required[$name] = str_replace(":","",translate($properties['name'] ,$this->bean->module_dir));
413         }
414         // include anything needed for quicksearch to work
415         require_once("include/TemplateHandler/TemplateHandler.php");
416         $quicksearch_js = TemplateHandler::createQuickSearchCode($fields,$fields,'importstep3');
417
418         $this->ss->assign("QS_JS", $quicksearch_js);
419         $this->ss->assign("JAVASCRIPT", $this->_getJS($required));
420
421         $this->ss->assign('required_fields',implode(', ',$required));
422         $this->ss->assign('CSS', $this->_getCSS());
423
424         $content = $this->ss->fetch('modules/Import/tpls/step3.tpl');
425         $this->ss->assign("CONTENT",$content);
426         $this->ss->display('modules/Import/tpls/wizardWrapper.tpl');
427
428     }
429
430     protected function getRequestDelimiter()
431     {
432         $delimiter = !empty($_REQUEST['custom_delimiter']) ? $_REQUEST['custom_delimiter'] : ",";
433
434         switch ($delimiter)
435         {
436             case "other":
437                 $delimiter = $_REQUEST['custom_delimiter_other'];
438                 break;
439             case '\t':
440                 $delimiter = "\t";
441                 break;
442         }       
443         return $delimiter;
444     }
445
446     protected function getImportColumns()
447     {
448         $importColumns = array();
449         foreach ($_REQUEST as $name => $value)
450         {
451             // only look for var names that start with "fieldNum"
452             if (strncasecmp($name, "colnum_", 7) != 0)
453                 continue;
454
455             // pull out the column position for this field name
456             $pos = substr($name, 7);
457
458                 // now mark that we've seen this field
459             $importColumns[$pos] = $value;
460         }
461
462         return $importColumns;
463     }
464
465     protected function _getCSS()
466     {
467         return <<<EOCSS
468             <style>
469                 textarea { width: 20em }
470                                 .detail tr td[scope="row"] {
471                                         text-align:left
472                                 }
473                 span.collapse{
474                     background: transparent url('index.php?entryPoint=getImage&themeName=Sugar&themeName=Sugar&imageName=sugar-yui-sprites.png') no-repeat 0 -90px;
475                     padding-left: 10px;
476                     cursor: pointer;
477                 }
478
479                 span.expand{
480                     background: transparent url('index.php?entryPoint=getImage&themeName=Sugar&themeName=Sugar&imageName=sugar-yui-sprites.png') no-repeat -0 -110px;
481                     padding-left: 10px;
482                      cursor: pointer;
483                 }
484                 .removeButton{
485                     border: none !important;
486                     background-image: none !important;
487                     background-color: transparent;
488                     padding: 0px;
489                 }
490
491                 #importNotes ul{
492                         margin: 0px;
493                         margin-top: 10px;
494                         padding-left: 20px;
495                 }
496
497             </style>
498 EOCSS;
499
500     }
501     /**
502      * Returns JS used in this view
503      *
504      * @param  array $required fields that are required for the import
505      * @return string HTML output with JS code
506      */
507     protected function _getJS($required)
508     {
509         global $mod_strings;
510
511         $print_required_array = "";
512         foreach ($required as $name=>$display) {
513             $print_required_array .= "required['$name'] = '". $display . "';\n";
514         }
515         $sqsWaitImage = SugarThemeRegistry::current()->getImageURL('sqsWait.gif');
516
517         return <<<EOJAVASCRIPT
518     document.getElementById('goback').onclick = function()
519     {
520         document.getElementById('{$this->currentFormID}').action.value = '{$this->previousAction}';
521         //bug #48960: CSS didn't load when use click back in the step2 (external sources are selected for contacts)
522         //need to unset 'to_pdf' in extstep1.tpl 
523         if (document.getElementById('{$this->currentFormID}').to_pdf)
524         {
525             document.getElementById('{$this->currentFormID}').to_pdf.value = '';
526         }
527         return true;
528     }
529
530 ImportView = {
531
532     validateMappings : function()
533     {
534         // validate form
535         clear_all_errors();
536         var form = document.getElementById('{$this->currentFormID}');
537         var hash = new Object();
538         var required = new Object();
539         $print_required_array
540         var isError = false;
541         for ( i = 0; i < form.length; i++ ) {
542             if ( form.elements[i].name.indexOf("colnum",0) == 0) {
543                 if ( form.elements[i].value == "-1") {
544                     continue;
545                 }
546                 if ( hash[ form.elements[i].value ] == 1) {
547                     isError = true;
548                     add_error_style('{$this->currentFormID}',form.elements[i].name,"{$mod_strings['ERR_MULTIPLE']}");
549                 }
550                 hash[form.elements[i].value] = 1;
551             }
552         }
553
554         // check for required fields
555         for(var field_name in required) {
556             // contacts hack to bypass errors if full_name is set
557             if (field_name == 'last_name' &&
558                     hash['full_name'] == 1) {
559                 continue;
560             }
561             if ( hash[ field_name ] != 1 ) {
562                 isError = true;
563                 add_error_style('{$this->currentFormID}',form.colnum_0.name,
564                     "{$mod_strings['ERR_MISSING_REQUIRED_FIELDS']} " + required[field_name]);
565             }
566         }
567
568         // return false if we got errors
569         if (isError == true) {
570             return false;
571         }
572
573
574         return true;
575
576     }
577
578 }
579
580 if( document.getElementById('gonext') )
581 {
582     document.getElementById('gonext').onclick = function(){
583
584         if( ImportView.validateMappings() )
585         {
586             // Move on to next step
587             document.getElementById('{$this->currentFormID}').action.value = '{$this->nextAction}';
588             return true;
589         }
590         else
591             return false;
592     }
593 }
594
595 // handle adding new row
596 document.getElementById('addrow').onclick = function(){
597
598     toggleDefaultColumnVisibility(false);
599     rownum = document.getElementById('{$this->currentFormID}').columncount.value;
600     newrow = document.createElement("tr");
601
602     column0 = document.getElementById('row_0_col_0').cloneNode(true);
603     column0.id = 'row_' + rownum + '_col_0';
604     for ( i = 0; i < column0.childNodes.length; i++ ) {
605         if ( column0.childNodes[i].name == 'colnum_0' ) {
606             column0.childNodes[i].name = 'colnum_' + rownum;
607             column0.childNodes[i].onchange = function(){
608                 var module    = document.getElementById('{$this->currentFormID}').import_module.value;
609                 var fieldname = this.value;
610                 var matches   = /colnum_([0-9]+)/i.exec(this.name);
611                 var fieldnum  = matches[1];
612                 if ( fieldname == -1 ) {
613                     document.getElementById('defaultvaluepicker_'+fieldnum).innerHTML = '';
614                     return;
615                 }
616                 document.getElementById('defaultvaluepicker_'+fieldnum).innerHTML = '<img src="{$sqsWaitImage}" />'
617                 YAHOO.util.Connect.asyncRequest('GET', 'index.php?module=Import&action=GetControl&import_module='+module+'&field_name='+fieldname,
618                     {
619                         success: function(o)
620                         {
621                                 document.getElementById('defaultvaluepicker_'+fieldnum).innerHTML = o.responseText;
622                             SUGAR.util.evalScript(o.responseText);
623                             enableQS(true);
624                         },
625                         failure: function(o) {/*failure handler code*/}
626                     });
627             }
628         }
629     }
630
631     var removeButton = document.createElement("button");
632     removeButton.title = "{$mod_strings['LBL_REMOVE_ROW']}";
633     removeButton.id = 'deleterow_' + rownum;
634     removeButton.className = "removeButton";
635     var imgButton = document.createElement("img");
636     imgButton.src = "index.php?entryPoint=getImage&themeName=Sugar&imageName=id-ff-remove.png";
637     removeButton.appendChild(imgButton);
638
639
640     if ( document.getElementById('row_0_header') ) {
641         column1 = document.getElementById('row_0_header').cloneNode(true);
642         column1.innerHTML = '&nbsp;';
643         column1.style.textAlign = "right";
644         newrow.appendChild(column1);
645         column1.appendChild(removeButton);
646     }
647
648     newrow.appendChild(column0);
649
650
651
652     column3 = document.createElement('td');
653     column3.className = 'tabDetailViewDL';
654     if ( !document.getElementById('row_0_header') ) {
655         column3.colSpan = 2;
656     }
657
658     newrow.appendChild(column3);
659
660     column2 = document.getElementById('defaultvaluepicker_0').cloneNode(true);
661     column2.id = 'defaultvaluepicker_' + rownum;
662     newrow.appendChild(column2);
663
664     document.getElementById('{$this->currentFormID}').columncount.value = parseInt(document.getElementById('{$this->currentFormID}').columncount.value) + 1;
665
666     document.getElementById('row_0_col_0').parentNode.parentNode.insertBefore(newrow,this.parentNode.parentNode);
667
668     document.getElementById('deleterow_' + rownum).onclick = function(){
669         this.parentNode.parentNode.parentNode.removeChild(this.parentNode.parentNode);
670     }
671
672
673 }
674
675 function toggleDefaultColumnVisibility(hide)
676 {
677     if( typeof(hide) != 'undefined' && typeof(hide) == 'boolean')
678     {
679         var currentStyle = hide ? '' : 'none';
680     }
681     else
682     {
683         var currentStyle = YAHOO.util.Dom.getStyle('default_column_header_span', 'display');
684     }
685     if(currentStyle == 'none')
686     {
687         var newStyle = '';
688         var bgColor = '#eeeeee';
689         YAHOO.util.Dom.addClass('hide_default_link', 'collapse');
690         YAHOO.util.Dom.removeClass('hide_default_link', 'expand');
691         var col2Rowspan = "1";
692     }
693     else
694     {
695         var newStyle = 'none';
696         var bgColor = '#dddddd';
697         YAHOO.util.Dom.addClass('hide_default_link', 'expand');
698         YAHOO.util.Dom.removeClass('hide_default_link', 'collapse');
699         var col2Rowspan = "2";
700     }
701
702     YAHOO.util.Dom.setStyle('default_column_header_span', 'display', newStyle);
703     YAHOO.util.Dom.setStyle('default_column_header', 'backgroundColor', bgColor);
704
705     //Toggle all rows.
706     var columnCount = document.getElementById('{$this->currentFormID}').columncount.value;
707     for(i=0;i<columnCount;i++)
708     {
709         YAHOO.util.Dom.setStyle('defaultvaluepicker_' + i, 'display', newStyle);
710         YAHOO.util.Dom.setAttribute('row_'+i+'_col_2', 'colspan', col2Rowspan);
711     }
712 }
713
714 var notesEl = document.getElementById('toggleNotes');
715 if(notesEl)
716 {
717     notesEl.onclick = function() {
718         if (document.getElementById('importNotes').style.display == 'none'){
719             document.getElementById('importNotes').style.display = '';
720             document.getElementById('toggleNotes').value='{$mod_strings['LBL_HIDE_NOTES']}';
721         }
722         else {
723             document.getElementById('importNotes').style.display = 'none';
724             document.getElementById('toggleNotes').value='{$mod_strings['LBL_SHOW_NOTES']}';
725         }
726     }
727 }
728
729
730 YAHOO.util.Event.onDOMReady(function(){
731     toggleDefaultColumnVisibility();
732     YAHOO.util.Event.addListener('hide_default_link', "click", toggleDefaultColumnVisibility);
733
734     var selects = document.getElementsByTagName('select');
735     for (var i = 0; i < selects.length; ++i ){
736         if (selects[i].name.indexOf("colnum_") != -1 ) {
737             // fetch the field input control via ajax
738             selects[i].onchange = function(){
739                 var module    = document.getElementById('{$this->currentFormID}').import_module.value;
740                 var fieldname = this.value;
741                 var matches   = /colnum_([0-9]+)/i.exec(this.name);
742                 var fieldnum  = matches[1];
743                 if ( fieldname == -1 ) {
744                     document.getElementById('defaultvaluepicker_'+fieldnum).innerHTML = '';
745                     return;
746                 }
747
748                 document.getElementById('defaultvaluepicker_'+fieldnum).innerHTML = '<img src="{$sqsWaitImage}" />'
749                 YAHOO.util.Connect.asyncRequest('GET', 'index.php?module=Import&action=GetControl&import_module='+module+'&field_name='+fieldname,
750                     {
751                         success: function(o)
752                         {
753                             document.getElementById('defaultvaluepicker_'+fieldnum).innerHTML = o.responseText;
754                             SUGAR.util.evalScript(o.responseText);
755                             enableQS(true);
756                         },
757                         failure: function(o) {/*failure handler code*/}
758                     });
759             }
760         }
761     }
762     var inputs = document.getElementsByTagName('input');
763     for (var i = 0; i < inputs.length; ++i ){
764         if (inputs[i].id.indexOf("deleterow_") != -1 ) {
765             inputs[i].onclick = function(){
766                 this.parentNode.parentNode.parentNode.removeChild(this.parentNode.parentNode);
767             }
768         }
769     }
770 });
771
772 enableQS(false);
773
774
775 EOJAVASCRIPT;
776     }
777 }