Ejemplo n.º 1
0
 /**
  * Return the Indicia form code
  * @param array $args Input parameters.
  * @param array $node Drupal node object
  * @param array $response Response from Indicia services after posting.
  * @return HTML string
  */
 public static function get_form($args, $node, $response)
 {
     iform_load_helpers(array('report_helper', 'map_helper'));
     $auth = report_helper::get_read_auth($args['website_id'], $args['password']);
     $reportOptions = iform_report_get_report_options($args, $auth);
     $r = '<div class="ui-helper-clearfix">';
     $reportOptions['geoserverLayer'] = $args['geoserver_layer'];
     $reportOptions['geoserverLayerStyle'] = $args['geoserver_layer_style'];
     $reportOptions['cqlTemplate'] = $args['cql_template'];
     $reportOptions['clickable'] = $args['click_on_map_mode'] != 'none';
     $reportOptions['clickableLayersOutputDiv'] = $args['click_on_map_div'];
     if (!empty($args['click_on_map_columns'])) {
         $reportOptions['clickableLayersOutputColumns'] = helper_base::explode_lines_key_value_pairs($args['click_on_map_columns']);
     }
     if ($args['click_on_map_mode'] != 'none') {
         $reportOptions['clickableLayersOutputMode'] = $args['click_on_map_mode'];
     }
     // Use the proxy module if enabled, to get round limitations in URL length for
     // filtered WMS requests.
     if (defined('DRUPAL_BOOTSTRAP_CONFIGURATION') && module_exists('iform_proxy')) {
         global $base_url;
         $reportOptions['proxy'] = $base_url . '/?q=' . variable_get('iform_proxy_path', 'proxy') . '&url=';
     }
     $r .= '<br/>' . report_helper::report_map($reportOptions);
     $options = iform_map_get_map_options($args, $readAuth);
     $olOptions = iform_map_get_ol_options($args);
     // This is used for drawing, so need an editlayer, but not used for input
     $options['editLayer'] = true;
     $options['editLayerInSwitcher'] = true;
     $options['clickForSpatialRef'] = false;
     if ($args['layer_picker'] != 'none') {
         $picker = array('id' => 'map-layer-picker', 'includeIcons' => false, 'includeSwitchers' => true, 'includeHiddenLayers' => true);
         if ($args['layer_picker'] == 'before') {
             $r .= map_helper::layer_list($picker);
         }
         // as we have a layer picker, we can drop the layerSwitcher from the OL map.
         if (array_search('layerSwitcher', $options['standardControls']) !== false) {
             unset($options['standardControls'][array_search('layerSwitcher', $options['standardControls'])]);
         }
     }
     if ($args['legend'] != 'none') {
         $legend = array('id' => 'map-legend', 'includeIcons' => true, 'includeSwitchers' => false, 'includeHiddenLayers' => false);
         if ($args['legend'] == 'before') {
             $r .= map_helper::layer_list($legend);
         }
     }
     if (isset($args['map_toolbar_pos'])) {
         $options['toolbarDiv'] = $args['map_toolbar_pos'];
     }
     $r .= map_helper::map_panel($options, $olOptions);
     if ($args['layer_picker'] == 'after') {
         $r .= map_helper::layer_list($picker);
     }
     if ($args['legend'] == 'after') {
         $r .= map_helper::layer_list($legend);
     }
     $r .= '</div>';
     return $r;
 }
Ejemplo n.º 2
0
 /**
  * Return the generated form output.
  * @return Form HTML.
  * @todo: Implement this method
  */
 public static function get_form($args)
 {
     global $user;
     $lang = isset($user) ? iform_lang_iso_639_2($user->lang) : 'eng';
     if (function_exists('iform_load_helpers')) {
         iform_load_helpers(array('map_helper'));
     } else {
         require_once dirname(dirname(__FILE__)) . '/map_helper.php';
     }
     $readAuth = data_entry_helper::get_read_auth($args['website_id'], $args['password']);
     $r = '';
     // setup the map options
     $options = iform_map_get_map_options($args, $readAuth);
     $olOptions = iform_map_get_ol_options($args);
     if (array_key_exists('table', $_GET) && $_GET['table'] == 'sample') {
         // Use a cUrl request to get the data from Indicia which contains the value we need to filter against
         // Read the record that was just posted.
         $fetchOpts = array('dataSource' => 'reports_for_prebuilt_forms/my_dot_map/occurrences_list', 'mode' => 'report', 'readAuth' => $readAuth, 'extraParams' => array('sample_id' => $_GET['id'], 'language' => $lang));
         // @todo Error handling on the response
         $occurrence = data_entry_helper::get_report_data($fetchOpts);
         self::prepare_layer_titles($args, $occurrence);
         // Add the 3 distribution layers if present. Reverse the order so 1st layer is topmost
         $layerName = self::build_distribution_layer(3, $args, $occurrence);
         if ($layerName) {
             $options['layers'][] = $layerName;
         }
         $layerName = self::build_distribution_layer(2, $args, $occurrence);
         if ($layerName) {
             $options['layers'][] = $layerName;
         }
         $layerName = self::build_distribution_layer(1, $args, $occurrence);
         if ($layerName) {
             $options['layers'][] = $layerName;
         }
         if ($layerName) {
             $options['layers'][] = $layerName;
         }
         // This is not a map used for input
         $options['editLayer'] = false;
         if ($args['hide_grid'] == false) {
             // Now output a grid of the occurrences that were just saved.
             $r .= "<table class=\"submission\"><thead><tr><th>" . lang::get('Species') . "</th><th>" . lang::get('Latin Name') . "</th><th>" . lang::get('Date') . "</th><th>" . lang::get('Spatial Ref') . "</th></tr></thead>\n";
             $r .= "<tbody>\n";
             foreach ($occurrence as $record) {
                 $r .= '<tr class="biota"><td>' . $record['lt4_taxon'] . '</td><td class="binomial"><em>' . $record['lt7_taxon'] . '</em></td><td>' . $record['lt0_date_start'] . '</td><td>' . $record['lt0_entered_sref'] . "</td></tr>\n";
             }
             $r .= "</tbody></table>\n";
         }
     }
     $r .= '<div id="mapandlegend">';
     $r .= map_helper::layer_list(array('id' => 'legend', 'includeSwitchers' => false, 'includeHiddenLayers' => false, 'includeIcons' => true, 'layerTypes' => array('overlay')));
     $r .= map_helper::map_panel($options, $olOptions);
     $r .= '</div>';
     return $r;
 }
 /**
  * Return the generated form output.
  * @return Form HTML.
  */
 public static function get_form($args)
 {
     iform_load_helpers(array('map_helper'));
     $readAuth = map_helper::get_read_auth($args['website_id'], $args['password']);
     // setup the map options
     $options = iform_map_get_map_options($args, $readAuth);
     $olOptions = iform_map_get_ol_options($args);
     for ($layer = 1; $layer <= 3; $layer++) {
         $argTitle = $args["layer_title_{$layer}"];
         if (isset($argTitle) && !empty($argTitle)) {
             //if there is no title then ignore the layer
             $meaningId = self::get_meaning_id($layer, $args, $readAuth);
             $taxon = self::get_taxon($meaningId, $readAuth);
             $layerTitle = str_replace('{species}', $taxon, $argTitle);
             $layerTitle = str_replace("'", "\\'", $layerTitle);
             $url = map_helper::$geoserver_url . 'wms';
             $argFeature = $args["wms_feature_type_{$layer}"];
             $layers = "layers: '{$argFeature}'";
             $argStyle = $args["wms_style_{$layer}"];
             $style = $argStyle ? ", styles: '{$argStyle}'" : '';
             $argWebsite = $args["website_id"];
             $filter = ", CQL_FILTER: 'website_id={$argWebsite} AND taxon_meaning_id={$meaningId}";
             $argCql = $args["cql_filter_{$layer}"];
             if ($argCql) {
                 $arg = str_replace("'", "\\'", $argCql);
                 $filter .= " AND({$argCql})'";
             } else {
                 $filter .= "'";
             }
             $script = "  var distLayer{$layer} = new OpenLayers.Layer.WMS(";
             $script .= "'{$layerTitle}', '{$url}',";
             $script .= "{" . "{$layers}, transparent: true {$filter} {$style}},";
             $script .= "{isBaseLayer: false, sphericalMercator: true, singleTile: true}";
             $script .= ");\n";
             map_helper::$onload_javascript .= $script;
             $options['layers'][] = "distLayer{$layer}";
         }
     }
     // This is not a map used for input
     $options['editLayer'] = false;
     // output a legend
     $r .= map_helper::layer_list(array('includeSwitchers' => true, 'includeHiddenLayers' => true));
     // output a map
     $r .= map_helper::map_panel($options, $olOptions);
     // Set up a page refresh for dynamic update of the map at set intervals
     if ($args['refresh_timer'] !== 0 && is_numeric($args['refresh_timer'])) {
         // is_int prevents injection
         if (isset($args['load_on_refresh']) && !empty($args['load_on_refresh'])) {
             map_helper::$javascript .= "setTimeout('window.location=\"" . $args['load_on_refresh'] . "\";', " . $args['refresh_timer'] . "*1000 );\n";
         } else {
             map_helper::$javascript .= "setTimeout('window.location.reload( false );', " . $args['refresh_timer'] . "*1000 );\n";
         }
     }
     return $r;
 }
Ejemplo n.º 4
0
 /**
  * Return the generated form output.
  * @return Form HTML.
  * @todo: Implement this method
  */
 public static function get_form($args)
 {
     global $user;
     $readAuth = data_entry_helper::get_read_auth($args['website_id'], $args['password']);
     // setup the map options
     $options = iform_map_get_map_options($args, $readAuth);
     $olOptions = iform_map_get_ol_options($args);
     if (array_key_exists('table', $_GET) && $_GET['table'] == 'sample') {
         // Use a cUrl request to get the data from Indicia which contains the value we need to filter against
         // Read the record that was just posted.
         $fetchOpts = array('dataSource' => 'reports_for_prebuilt_forms/my_dot_map/occurrences_list', 'mode' => 'report', 'readAuth' => $readAuth, 'extraParams' => array('sample_id' => $_GET['id'], 'language' => iform_lang_iso_639_2($user->lang)));
         // @todo Error handling on the response
         $occurrence = data_entry_helper::get_report_data($fetchOpts);
         $legend = '';
         self::prepare_layer_titles($args, $occurrence);
         // Add the 3 distribution layers if present. Reverse the order so 1st layer is topmost
         $layerName = self::build_distribution_layer(3, $args, $occurrence);
         if ($layerName) {
             $options['layers'][] = $layerName;
             $legend = '<div><img src="' . data_entry_helper::$geoserver_url . 'wms?SERVICE=WMS&VERSION=1.1.1&REQUEST=GetLegendGraphic&LAYER=detail_occurrences&Format=image/jpeg' . '&STYLE=' . $args["wms_dist_3_style"] . '" alt=""/>' . $args["wms_dist_3_title"] . '</div>' . $legend;
         }
         $layerName = self::build_distribution_layer(2, $args, $occurrence);
         if ($layerName) {
             $options['layers'][] = $layerName;
             $legend = '<div><img src="' . data_entry_helper::$geoserver_url . 'wms?SERVICE=WMS&VERSION=1.1.1&REQUEST=GetLegendGraphic&LAYER=detail_occurrences&Format=image/jpeg' . '&STYLE=' . $args["wms_dist_2_style"] . '" alt=""/>' . $args["wms_dist_2_title"] . '</div>' . $legend;
         }
         $layerName = self::build_distribution_layer(1, $args, $occurrence);
         if ($layerName) {
             $options['layers'][] = $layerName;
             $legend = '<div><img src="' . data_entry_helper::$geoserver_url . 'wms?SERVICE=WMS&VERSION=1.1.1&REQUEST=GetLegendGraphic&LAYER=detail_occurrences&Format=image/png' . '&STYLE=' . $args["wms_dist_1_style"] . '" alt=""/>' . $args["wms_dist_1_title"] . '</div>' . $legend;
         }
         if ($layerName) {
             $options['layers'][] = $layerName;
         }
         // This is not a map used for input
         $options['editLayer'] = false;
         // Now output a grid of the occurrences that were just saved.
         $r .= "<table class=\"submission\"><thead><tr><th>" . lang::get('Species') . "</th><th>" . lang::get('Latin Name') . "</th><th>" . lang::get('Date') . "</th><th>" . lang::get('Spatial Ref') . "</th></tr></thead>\n";
         $r .= "<tbody>\n";
         foreach ($occurrence as $record) {
             $r .= '<tr class="biota"><td>' . $record['lt4_taxon'] . '</td><td class="binomial"><em>' . $record['lt7_taxon'] . '</em></td><td>' . $record['lt0_date_start'] . '</td><td>' . $record['lt0_entered_sref'] . "</td></tr>\n";
         }
         $r .= "</tbody></table>\n";
         $r .= '<div id="legend" class="ui-widget ui-widget-content ui-corner-all">' . $legend . '</div>';
     }
     $r .= data_entry_helper::map_panel($options, $olOptions);
     return $r;
 }
Ejemplo n.º 5
0
 /**
  * Outputs a map with an overlay of regions, showing a count for each. Default is to count records, but can
  * be configured to count taxa.
  *
  * @param array $auth Authorisation tokens.
  * @param array $args Form arguments (the settings on the form edit tab).
  * @param string $tabalias The alias of the tab this is being loaded onto.
  * @param array $options The options passed to this control using @option=value settings in the form structure.
  * Options supported are those which can be passed to the report_helper::report_map method. In addition
  * set @output=species to configure the report to show a species counts map.   
  * @param string $path The page reload path, in case it is required for the building of links.
  * @return string HTML to insert into the page for the location map. JavaScript is added to the variables in helper_base.
  *
  * @link http://www.biodiverseit.co.uk/indicia/dev/docs/classes/report_helper.html#method_report_map API docs for report_helper::report_map
  */
 public static function count_by_location_map($auth, $args, $tabalias, $options, $path)
 {
     iform_load_helpers(array('map_helper', 'report_helper'));
     require_once iform_client_helpers_path() . 'prebuilt_forms/includes/map.php';
     $mapOptions = iform_map_get_map_options($args, $auth['read']);
     $olOptions = iform_map_get_ol_options($args);
     $mapOptions['clickForSpatialRef'] = false;
     $r = map_helper::map_panel($mapOptions, $olOptions);
     if (!empty($options['output']) && $options['output'] === 'species') {
         $type = 'species';
     } else {
         $type = 'occurrence';
     }
     $reportOptions = array_merge(iform_report_get_report_options($args, $auth['read']), array('dataSource' => "library/locations/{$type}_counts_mappable_for_event", 'featureDoubleOutlineColour' => '#f7f7f7', 'rowId' => 'id'), $options);
     $r .= report_helper::report_map($reportOptions);
     return $r;
 }
Ejemplo n.º 6
0
 /**
  * Outputs a map with an overlay of regions, showing a count for each. Default is to count records, but can
  * be configured to count taxa.
  *
  * @param array $auth Authorisation tokens.
  * @param array $args Form arguments (the settings on the form edit tab).
  * @param string $tabalias The alias of the tab this is being loaded onto.
  * @param array $options The options passed to this control using @option=value settings in the form structure.
  * Options supported are those which can be passed to the report_helper::report_map method. In addition
  * set @output=species to configure the report to show a species counts map and set @title=... to 
  * include a heading in the output.   
  * @param string $path The page reload path, in case it is required for the building of links.
  * @return string HTML to insert into the page for the location map. JavaScript is added to the variables in helper_base.
  *
  * @link http://www.biodiverseit.co.uk/indicia/dev/docs/classes/report_helper.html#method_report_map API docs for report_helper::report_map
  */
 public static function count_by_location_map($auth, $args, $tabalias, $options, $path)
 {
     iform_load_helpers(array('map_helper', 'report_helper'));
     require_once iform_client_helpers_path() . 'prebuilt_forms/includes/map.php';
     $mapOptions = iform_map_get_map_options($args, $auth['read']);
     $olOptions = iform_map_get_ol_options($args);
     $mapOptions['clickForSpatialRef'] = false;
     if ($args['interface'] !== 'one_page') {
         $mapOptions['tabDiv'] = $tabalias;
     }
     $r = self::output_title($options);
     $r .= map_helper::map_panel($mapOptions, $olOptions);
     if (!empty($options['output']) && $options['output'] === 'species') {
         $type = 'species';
     } else {
         $type = 'occurrence';
     }
     $subtype = empty($options['linked']) || $options['linked'] === false ? '' : '_linked';
     $reportOptions = array_merge(iform_report_get_report_options($args, $auth['read']), array('dataSource' => "library/locations/filterable_{$type}_counts_mappable{$subtype}", 'featureDoubleOutlineColour' => '#f7f7f7', 'rowId' => 'id', 'caching' => true, 'cachePerUser' => false), $options);
     $r .= report_helper::report_map($reportOptions);
     return $r;
 }
Ejemplo n.º 7
0
 /**
  * Return the generated form output.
  * @return Form HTML.
  * @todo: Implement this method
  */
 public static function get_form($args)
 {
     $readAuth = data_entry_helper::get_read_auth($args['website_id'], $args['password']);
     // setup the map options
     $options = iform_map_get_map_options($args, $readAuth);
     $olOptions = iform_map_get_ol_options($args);
     if (array_key_exists('table', $_GET) && $_GET['table'] == 'sample') {
         // Use a cUrl request to get the data from Indicia which contains the value we need to filter against
         // Read the record that was just posted.
         $fetchOpts = array('table' => 'occurrence', 'extraParams' => $readAuth + array('sample_id' => $_GET['id'], 'view' => 'detail'));
         // @todo Error handling on the response
         $occurrence = data_entry_helper::get_population_data($fetchOpts);
     }
     // Add the 3 distribution layers if present. Reverse the order so 1st layer is topmost
     $layerName = self::build_distribution_layer(3, $args, $occurrence);
     if ($layerName) {
         $options['layers'][] = $layerName;
     }
     $layerName = self::build_distribution_layer(2, $args, $occurrence);
     if ($layerName) {
         $options['layers'][] = $layerName;
     }
     $layerName = self::build_distribution_layer(1, $args, $occurrence);
     if ($layerName) {
         $options['layers'][] = $layerName;
     }
     // Now output a grid of the occurrences that were just saved.
     if (isset($occurrence)) {
         $r .= "<table class=\"submission\"><thead><tr><th>Species</th><th>Date</th><th>Spatial Reference</th></tr></thead>\n";
         $r .= "<tbody>\n";
         foreach ($occurrence as $record) {
             $r .= "<tr><td>" . $record['taxon'] . "</td><td>" . $record['date_start'] . "</td><td>" . $record['entered_sref'] . "</td></tr>\n";
         }
         $r .= "</tbody></table>\n";
     }
     $r .= data_entry_helper::map_panel($options, $olOptions);
     return $r;
 }
 /** 
  * Get the map control.
  */
 protected static function get_control_map($auth, $args, $tabalias, $options)
 {
     $options = array_merge(iform_map_get_map_options($args, $auth['read']), $options);
     if (isset(data_entry_helper::$entity_to_load['sample:geom'])) {
         $options['initialFeatureWkt'] = data_entry_helper::$entity_to_load['sample:wkt'];
     }
     if ($args['interface'] !== 'one_page') {
         $options['tabDiv'] = $tabalias;
     }
     $olOptions = iform_map_get_ol_options($args);
     if (!isset($options['standardControls'])) {
         $options['standardControls'] = array('layerSwitcher', 'panZoom');
     }
     return data_entry_helper::map_panel($options, $olOptions);
 }
Ejemplo n.º 9
0
 private static function get_template_with_map($args, $readAuth, $extraParams, $paramDefaults)
 {
     $r = '<div id="outer-with-map" class="ui-helper-clearfix">';
     $r .= '<div id="grid" class="left" style="width:65%">{paramsForm}{grid}';
     // Insert a button to verify all visible, only available if viewing the clean records.
     if (isset($_POST['verification-rule']) && $_POST['verification-rule'] === 'none' && empty($_POST['verification-id'])) {
         $r .= '<button type="button" id="btn-verify-all">' . lang::get('Verify all visible') . '</button>';
     }
     $r .= '</div>';
     $r .= '<div id="map-and-record" class="right" style="width: 34%"><div id="summary-map">';
     $options = iform_map_get_map_options($args, $readAuth);
     $olOptions = iform_map_get_ol_options($args);
     // This is used for drawing, so need an editlayer, but not used for input
     $options['editLayer'] = true;
     $options['editLayerInSwitcher'] = true;
     $options['clickForSpatialRef'] = false;
     $options['featureIdField'] = 'occurrence_id';
     $r .= map_helper::map_panel($options, $olOptions);
     $reportMapOpts = array('dataSource' => !empty($args['mapping_report_name']) ? $args['mapping_report_name'] : $args['report_name'], 'mode' => 'report', 'readAuth' => $readAuth, 'autoParamsForm' => false, 'extraParams' => $extraParams, 'paramDefaults' => $paramDefaults, 'reportGroup' => 'verification', 'clickableLayersOutputMode' => 'report', 'rowId' => 'occurrence_id', 'sharing' => 'verification', 'ajax' => TRUE);
     if (!empty($args['mapping_report_name_lores'])) {
         $reportMapOpts['dataSourceLoRes'] = $args['mapping_report_name_lores'];
     }
     $r .= report_helper::report_map($reportMapOpts);
     $r .= '</div>';
     global $user;
     if (function_exists('hostsite_get_user_field') && ($locationId = hostsite_get_user_field('location_expertise', false))) {
         iform_map_zoom_to_location($locationId, $readAuth);
     }
     $r .= '<div id="record-details-wrap" class="ui-widget ui-widget-content">';
     $r .= self::instructions('grid on the left');
     $r .= '<div id="record-details-content" style="display: none">';
     $r .= '<div id="record-details-toolbar">';
     $r .= '<label>Set status:</label>';
     $r .= '<button type="button" id="btn-verify">' . lang::get('Verify') . '</button>';
     $r .= '<button type="button" id="btn-reject">' . lang::get('Reject') . '</button>';
     $r .= '<button type="button" id="btn-query">' . lang::get('Query') . '</button>';
     $r .= '<button type="button" id="btn-multiple" title="' . lang::get('Select this tool to tick off a list of records and action all of the ticked records in one go') . '">' . lang::get('Select records') . '</button>';
     $r .= '<br/><label>Contact:</label>';
     $r .= '<button type="button" id="btn-email-expert" class="default-button">' . lang::get('Another expert') . '</button>';
     $r .= '<button type="button" id="btn-email-recorder" class="default-button">' . lang::get('Recorder') . '</button>';
     $r .= '</div>';
     $r .= '<div id="record-details-tabs">';
     // note - there is a dependency in the JS that comments is the last tab and images the 2nd to last.
     $r .= data_entry_helper::tab_header(array('tabs' => array('#details-tab' => lang::get('Details'), '#experience-tab' => lang::get('Experience'), '#phenology-tab' => lang::get('Phenology'), '#images-tab' => lang::get('Images'), '#comments-tab' => lang::get('Comments'))));
     data_entry_helper::$javascript .= "indiciaData.detailsTabs = ['details','experience','phenology','images','comments'];\n";
     data_entry_helper::enable_tabs(array('divId' => 'record-details-tabs'));
     $r .= '<div id="details-tab"></div>';
     $r .= self::other_tab_html();
     $r .= '</div></div></div></div></div>';
     return $r;
 }
Ejemplo n.º 10
0
    /**
     * Return the generated form output.
     * @return Form HTML.
     */
    public static function get_form($args, $node)
    {
        global $user;
        // There is a language entry in the args parameter list: this is derived from the $language DRUPAL global.
        // It holds the 2 letter code, used to pick the language file from the lang subdirectory of prebuilt_forms.
        // There should be no explicitly output text in this file.
        // We must translate any field names and ensure that the termlists and taxonlists use the correct language.
        // For attributes, the caption is automatically translated by data_entry_helper.
        $logged_in = $user->uid > 0;
        $uid = $user->uid;
        $email = $user->mail;
        $username = $user->name;
        if (!user_access('IForm n' . $node->nid . ' access')) {
            return "<p>" . lang::get('LANG_Insufficient_Privileges') . "</p>";
        }
        $r = '';
        // Get authorisation tokens to update and read from the Warehouse.
        $readAuth = data_entry_helper::get_read_auth($args['website_id'], $args['password']);
        $svcUrl = data_entry_helper::$base_url . '/index.php/services';
        $language = iform_lang_iso_639_2($args['language']);
        drupal_add_js(drupal_get_path('module', 'iform') . '/media/js/jquery.form.js', 'module');
        data_entry_helper::link_default_stylesheet();
        data_entry_helper::add_resource('jquery_ui');
        if ($args['language'] != 'en') {
            data_entry_helper::add_resource('jquery_ui_' . $args['language']);
        }
        data_entry_helper::enable_validation('new-comments-form');
        // don't care about ID itself, just want resources
        $occID = '';
        $smpID = '';
        $userID = '';
        $mode = 'FILTER';
        if (array_key_exists('insect_id', $_GET)) {
            $occID = $_GET['insect_id'];
            $mode = 'INSECT';
        } else {
            if (array_key_exists('insect', $_GET)) {
                $occID = $_GET['insect'];
                $mode = 'INSECT';
            } else {
                if (array_key_exists('flower_id', $_GET)) {
                    $occID = $_GET['flower_id'];
                    $mode = 'FLOWER';
                } else {
                    if (array_key_exists('flower', $_GET)) {
                        $occID = $_GET['flower'];
                        $mode = 'FLOWER';
                    } else {
                        if (array_key_exists('collection_id', $_GET)) {
                            $smpID = $_GET['collection_id'];
                            $mode = 'COLLECTION';
                        } else {
                            if (array_key_exists('collection', $_GET)) {
                                $smpID = $_GET['collection'];
                                $mode = 'COLLECTION';
                            } else {
                                if (array_key_exists('user_id', $_GET)) {
                                    $userID = $_GET['user_id'];
                                } else {
                                    if (array_key_exists('user', $_GET)) {
                                        $userID = $_GET['user'];
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
        //	data_entry_helper::enable_validation('cc-1-collection-details'); // don't care about ID itself, just want resources
        // The only things that will be editable after the collection is saved will be the identifiaction of the flower/insects.
        // no id - just getting the attributes, rest will be filled in using AJAX
        $sample_attributes = data_entry_helper::getAttributes(array('valuetable' => 'sample_attribute_value', 'attrtable' => 'sample_attribute', 'key' => 'sample_id', 'fieldprefix' => 'smpAttr', 'extraParams' => $readAuth, 'survey_id' => $args['survey_id']));
        $occurrence_attributes = data_entry_helper::getAttributes(array('valuetable' => 'occurrence_attribute_value', 'attrtable' => 'occurrence_attribute', 'key' => 'occurrence_id', 'fieldprefix' => 'occAttr', 'extraParams' => $readAuth, 'survey_id' => $args['survey_id']));
        $location_attributes = data_entry_helper::getAttributes(array('valuetable' => 'location_attribute_value', 'attrtable' => 'location_attribute', 'key' => 'location_id', 'fieldprefix' => 'locAttr', 'extraParams' => $readAuth, 'survey_id' => $args['survey_id']));
        $defAttrOptions = array('extraParams' => $readAuth + array('orderby' => 'id'), 'lookUpListCtrl' => 'checkbox_group', 'lookUpKey' => 'meaning_id', 'booleanCtrl' => 'checkbox_group', 'sep' => ' &nbsp; ', 'language' => $language, 'suffixTemplate' => 'nosuffix', 'default' => '-1');
        // note we have to proxy the post. Every time a write transaction is carried out, the write nonce is trashed.
        // For security reasons we don't want to give the user the ability to generate their own nonce, so we use
        // the fact that the user is logged in to drupal as the main authentication/authorisation/identification
        // process for the user. The proxy also packages the post into the correct format
        // the controls for the filter include all taxa, not just the ones allowed for data entry, as does the one for checking the tool, just to be on the safe side.
        $flower_ctrl_args = array('label' => lang::get('LANG_Flower_Species'), 'fieldname' => 'flower:taxa_taxon_list_id', 'table' => 'taxa_taxon_list', 'captionField' => 'taxon', 'valueField' => 'id', 'columns' => 2, 'blankText' => lang::get('LANG_Choose_Taxon'), 'extraParams' => $readAuth + array('taxon_list_id' => $args['flower_list_id'], 'view' => 'detail', 'orderby' => 'taxonomic_sort_order'), 'suffixTemplate' => 'nosuffix');
        $focus_flower_ctrl_args = $flower_ctrl_args;
        $focus_flower_ctrl_args['fieldname'] = 'determination:taxa_taxon_list_id';
        $focus_flower_ctrl_args['extraParams'] = $readAuth + array('taxon_list_id' => $args['flower_list_id'], 'view' => 'detail', 'orderby' => 'taxonomic_sort_order', 'allow_data_entry' => 't');
        $insect_ctrl_args = array('label' => lang::get('LANG_Insect_Species'), 'fieldname' => 'insect:taxa_taxon_list_id', 'table' => 'taxa_taxon_list', 'captionField' => 'taxon', 'valueField' => 'id', 'columns' => 2, 'blankText' => lang::get('LANG_Choose_Taxon'), 'extraParams' => $readAuth + array('taxon_list_id' => $args['insect_list_id'], 'view' => 'detail', 'orderby' => 'taxonomic_sort_order'), 'suffixTemplate' => 'nosuffix');
        $focus_insect_ctrl_args = $insect_ctrl_args;
        $focus_insect_ctrl_args['fieldname'] = 'determination:taxa_taxon_list_id';
        $focus_insect_ctrl_args['extraParams'] = $readAuth + array('taxon_list_id' => $args['insect_list_id'], 'view' => 'detail', 'orderby' => 'taxonomic_sort_order', 'allow_data_entry' => 't');
        $options = iform_map_get_map_options($args, $readAuth);
        $olOptions = iform_map_get_ol_options($args);
        // The maps internal projection will be left at its default of 900913.
        $options['initialFeatureWkt'] = null;
        $options['proxy'] = '';
        $options['suffixTemplate'] = 'nosuffix';
        if (lang::get('msgGeorefSelectPlace') != 'msgGeorefSelectPlace') {
            $options['msgGeorefSelectPlace'] = lang::get('msgGeorefSelectPlace');
        }
        if (lang::get('msgGeorefNothingFound') != 'msgGeorefNothingFound') {
            $options['msgGeorefNothingFound'] = lang::get('msgGeorefNothingFound');
        }
        $options2 = $options;
        $options['searchLayer'] = 'true';
        $options['editLayer'] = 'false';
        $options['layers'] = array('polygonLayer');
        $options2['divId'] = "map2";
        $options2['layers'] = array('locationLayer');
        $options2['height'] = $args['2nd_map_height'];
        data_entry_helper::$javascript .= "var flowerTaxa = [";
        $extraParams = $readAuth + array('taxon_list_id' => $args['flower_list_id'], 'view' => 'list');
        $species_data_def = array('table' => 'taxa_taxon_list', 'extraParams' => $extraParams);
        $taxa = data_entry_helper::get_population_data($species_data_def);
        $first = true;
        foreach ($taxa as $taxon) {
            data_entry_helper::$javascript .= ($first ? '' : ',') . "{id: " . $taxon['id'] . ", taxon: \"" . htmlSpecialChars($taxon['taxon']) . "\"}\n";
            $first = false;
        }
        data_entry_helper::$javascript .= "];\nvar insectTaxa = [";
        $extraParams['taxon_list_id'] = $args['insect_list_id'];
        $species_data_def['extraParams'] = $extraParams;
        $taxa = data_entry_helper::get_population_data($species_data_def);
        $first = true;
        foreach ($taxa as $taxon) {
            data_entry_helper::$javascript .= ($first ? '' : ',') . "{id: " . $taxon['id'] . ", taxon: \"" . htmlSpecialChars($taxon['taxon']) . "\"}\n";
            $first = false;
        }
        data_entry_helper::$javascript .= "];";
        // TBD Breadcrumb
        $r .= '<h1 id="poll-banner">' . lang::get('LANG_Main_Title') . '</h1>
<div id="refresh-message" style="display:none" ><p>' . lang::get('LANG_Please_Refresh_Page') . '</p></div>
<div id="filter" class="ui-accordion ui-widget ui-helper-reset">
	<div id="filter-header" class="ui-accordion-header ui-helper-reset ui-state-active ui-accordion-content-active ui-corner-top">
	  	<div id="results-collections-title">
	  		<span>' . lang::get('LANG_Filter_Title') . '</span>
    	</div>
	</div>';
        if (user_access('IForm n' . $node->nid . ' save filter')) {
            $r .= '<div id="filter-save" class="ui-accordion-content ui-helper-reset ui-widget-content ui-accordion-content-active"><div id="gallery-filter-retrieve-wrapper">
<div id="gallery-filter-retrieve-image"><img
src="/' . path_to_theme() . '/css/gallery_filter.png" 
alt="Mes filtres" title="Mes filtres" /></div> <div id="gallery-filter-retrieve"></div>
</div>
   <input value="' . lang::get('LANG_Enter_Filter_Name') . '" type="text" id="gallery-filter-save-name" /><input value="' . lang::get('LANG_Save_Filter_Button') . '" type="button" id="gallery-filter-save-button" /></div>';
        }
        $r .= '<div id="filter-spec" class="ui-accordion-content ui-helper-reset ui-widget-content ui-accordion-content-active">
	  <div class="ui-accordion ui-widget ui-helper-reset">
		<div id="name-filter-header" class="ui-accordion-header ui-helper-reset ui-state-default ui-corner-all">
	  		<div id="fold-name-button" class="ui-state-default ui-corner-all fold-button fold-button-folded">&nbsp;</div>
	  		<div id="reset-name-button" class="ui-state-default ui-corner-all reset-button">' . lang::get('LANG_Reset_Filter') . '</div>
	  		<div id="general-filter-title">
		  		<span>' . lang::get('LANG_Name_Filter_Title') . '</span>
      		</div>
		</div>
	    <div id="name-filter-body" class="ui-accordion-content ui-helper-reset ui-widget-content ui-corner-all">
	        ' . data_entry_helper::text_input(array('label' => lang::get('LANG_Name'), 'fieldname' => 'username', 'suffixTemplate' => 'nosuffix')) . '
  		</div>
		<div id="date-filter-header" class="ui-accordion-header ui-helper-reset ui-state-default ui-corner-all">
	  		<div id="fold-date-button" class="ui-state-default ui-corner-all fold-button fold-button-folded">&nbsp;</div>
	  		<div id="reset-date-button" class="ui-state-default ui-corner-all reset-button">' . lang::get('LANG_Reset_Filter') . '</div>
	  		<div id="general-filter-title">
		  		<span>' . lang::get('LANG_Date_Filter_Title') . '</span>
      		</div>
		</div>
	    <div id="date-filter-body" class="ui-accordion-content ui-helper-reset ui-widget-content ui-corner-all">
        	<label for="start_date" >' . lang::get('LANG_Created_Between') . ':</label>
  			<input type="text" size="10" id="start_date" name="start_date" value="' . lang::get('click here') . '" />
  			<input type="hidden" id="real_start_date" name="real_start_date" />
  			<label for="end_date" >' . lang::get('LANG_And') . ':</label>
  			<input type="text" size="10" id="end_date" name="end_date" value="' . lang::get('click here') . '" />
  			<input type="hidden" id="real_end_date" name="real_end_date" />
  		</div>
  		<div id="flower-filter-header" class="ui-accordion-header ui-helper-reset ui-state-default ui-corner-all">
	  		<div id="fold-flower-button" class="ui-state-default ui-corner-all fold-button fold-button-folded">&nbsp;</div>
	  		<div id="reset-flower-button" class="ui-state-default ui-corner-all reset-button">' . lang::get('LANG_Reset_Filter') . '</div>
	  		<div id="flower-filter-title">
		  		<span>' . lang::get('LANG_Flower_Filter_Title') . '</span>
      		</div>
		</div>
		<div id="flower-filter-body" class="ui-accordion-content ui-helper-reset ui-widget-content ui-corner-all">
		  ' . data_entry_helper::select($flower_ctrl_args) . '
 		  <input type="text" name="flower:taxon_extra_info" class="taxon-info" value="' . lang::get('LANG_More_Precise') . '"
	 		onclick="if(this.value==\'' . lang::get('LANG_More_Precise') . '\'){this.value=\'\'; this.style.color=\'#000\'}"  
            onblur="if(this.value==\'\'){this.value=\'' . lang::get('LANG_More_Precise') . '\'; this.style.color=\'#555\'}" />
		  ' . str_replace("\n", "", data_entry_helper::outputAttribute($occurrence_attributes[$args['flower_type_attr_id']], $defAttrOptions)) . str_replace("\n", "", data_entry_helper::outputAttribute($location_attributes[$args['habitat_attr_id']], $defAttrOptions)) . '
    	</div>
		<div id="insect-filter-header" class="ui-accordion-header ui-helper-reset ui-state-default ui-corner-all">
	  		<div id="fold-insect-button" class="ui-state-default ui-corner-all fold-button fold-button-folded">&nbsp;</div>
			<div id="reset-insect-button" class="ui-state-default ui-corner-all reset-button">' . lang::get('LANG_Reset_Filter') . '</div>
	  		<div id="insect-filter-title">
		  		<span>' . lang::get('LANG_Insect_Filter_Title') . '</span>
      		</div>
		</div>
		<div id="insect-filter-body" class="ui-accordion-content ui-helper-reset ui-widget-content ui-corner-all">
		  ' . data_entry_helper::select($insect_ctrl_args) . '
 		  <input type="text" name="insect:taxon_extra_info" class="taxon-info" value="' . lang::get('LANG_More_Precise') . '"
	 		onclick="if(this.value==\'' . lang::get('LANG_More_Precise') . '\'){this.value=\'\'; this.style.color=\'#000\'}"  
            onblur="if(this.value==\'\'){this.value=\'' . lang::get('LANG_More_Precise') . '\'; this.style.color=\'#555\'}" />
		</div>
		<div id="conditions-filter-header" class="ui-accordion-header ui-helper-reset ui-state-default ui-corner-all">
	  		<div id="fold-conditions-button" class="ui-state-default ui-corner-all fold-button fold-button-folded">&nbsp;</div>
			<div id="reset-conditions-button" class="ui-state-default ui-corner-all reset-button">' . lang::get('LANG_Reset_Filter') . '</div>
	  		<div id="conditions-filter-title">
		  		<span>' . lang::get('LANG_Conditions_Filter_Title') . '</span>
      		</div>
		</div>
		<div id="conditions-filter-body" class="ui-accordion-content ui-helper-reset ui-widget-content ui-corner-all">
    	  ' . str_replace("\n", "", data_entry_helper::outputAttribute($sample_attributes[$args['sky_state_attr_id']], $defAttrOptions)) . str_replace("\n", "", data_entry_helper::outputAttribute($sample_attributes[$args['temperature_attr_id']], $defAttrOptions)) . str_replace("\n", "", data_entry_helper::outputAttribute($sample_attributes[$args['wind_attr_id']], $defAttrOptions)) . str_replace("\n", "", data_entry_helper::outputAttribute($sample_attributes[$args['shade_attr_id']], $defAttrOptions)) . '
		</div>
		<div id="location-filter-header" class="ui-accordion-header ui-helper-reset ui-state-active ui-corner-all">
	  		<div id="fold-location-button" class="ui-state-default ui-corner-all fold-button">&nbsp;</div>
			<div id="reset-location-button" class="ui-state-default ui-corner-all reset-button">' . lang::get('LANG_Reset_Filter') . '</div>
			<div id="location-filter-title">
		  		<span>' . lang::get('LANG_Location_Filter_Title') . '</span>
      		</div>
		</div>
		<div id="location-filter-body" class="ui-accordion-content ui-helper-reset ui-widget-content ui-accordion-content-active ui-corner-all">
		  <div id="location-entry">
		    ' . data_entry_helper::georeference_lookup(iform_map_get_georef_options($args)) . '
    		<span id="location-georef-notes" >' . lang::get('LANG_Georef_Notes') . '</span>
    		<label for="place:INSEE">' . lang::get('LANG_Or') . '</label>
 		    <input type="text" id="place:INSEE" name="place:INSEE" value="' . lang::get('LANG_INSEE') . '"
	 		  onclick="if(this.value==\'' . lang::get('LANG_INSEE') . '\'){this.value=\'\'; this.style.color=\'#000\'}"  
              onblur="if(this.value==\'\'){this.value=\'' . lang::get('LANG_INSEE') . '\'; this.style.color=\'#555\'}" />
    	    <input type="button" id="search-insee-button" class="ui-corner-all ui-widget-content ui-state-default search-button" value="' . lang::get('search') . '" />
 	      </div>';
        // this is a bit of a hack, because the apply_template method is not public in data entry helper.
        $tempScript = data_entry_helper::$onload_javascript;
        data_entry_helper::$onload_javascript = '';
        $r .= data_entry_helper::map_panel($options, $olOptions);
        $map1JS = data_entry_helper::$onload_javascript;
        data_entry_helper::$onload_javascript = $tempScript;
        $r .= '
		</div>
      </div>
    </div>
    <div id="filter-footer" class="ui-accordion-content ui-helper-reset ui-widget-content ui-accordion-content-active ui-corner-bottom">
	  <div id="search-insects-button" class="ui-state-default ui-corner-all search-button">' . lang::get('LANG_Search_Insects') . '</div>
      <div id="search-collections-button" class="ui-state-default ui-corner-all search-button">' . lang::get('LANG_Search_Collections') . '</div>
    </div>
	<div id="results-collections-header" class="ui-accordion-header ui-helper-reset ui-state-active ui-corner-top">
	  <div id="results-collections-title">
	  	<span>' . lang::get('LANG_Collections_Search_Results') . '</span>
      </div>
	</div>
	<div id="results-collections-results" class="ui-accordion-content ui-helper-reset ui-widget-content ui-accordion-content-active ui-corner-bottom">
    </div>
	<div id="results-insects-header" class="ui-accordion-header ui-helper-reset ui-state-active ui-corner-top">
	  <div id="results-insects-title">
	  	<span>' . lang::get('LANG_Insects_Search_Results') . '</span>
      </div>
	</div>
	<div id="results-insects-results" class="ui-accordion-content ui-helper-reset ui-widget-content ui-accordion-content-active ui-corner-bottom">
    </div>
</div>
<div id="focus-collection" class="ui-accordion ui-widget ui-helper-reset">
	<div id="fc-header" class="ui-accordion-content ui-helper-reset ui-state-active ui-corner-top ui-accordion-content-active">
	  <div id="fc-header-buttons">';
        if (user_access('IForm n' . $node->nid . ' add preferred collection')) {
            $r .= '<span id="fc-add-preferred" class="ui-state-default ui-corner-all preferred-button">' . lang::get('LANG_Add_Preferred_Collection') . '</span>';
        }
        $r .= '  
	    <span id="fc-prev-button" class="ui-state-default ui-corner-all previous-button">' . lang::get('LANG_Previous') . '</span>
	    <span id="fc-next-button" class="ui-state-default ui-corner-all next-button">' . lang::get('LANG_Next') . '</span>
	  	<span id="fc-filter-button" class="ui-state-default ui-corner-all collection-button">' . lang::get('LANG_List') . '</span>
	  </div>
	</div>
	<div id="collection-details" class="ui-accordion-content ui-helper-reset ui-widget-content ui-accordion-content-active ui-corner-bottom">
	  <div id="flower-image-container" ><div id="flower-image" class="flower-image"></div>
        <div id="show-flower-button" class="ui-state-default ui-corner-all display-button">' . lang::get('LANG_Display') . '</div>
      </div>
      <div id="environment-image" class="environment-image"></div>
      <div id="collection-description">
	    <p id="collection-date"></p>
	    <p id="collection-flower-name"></p>
	    <p>' . lang::get($occurrence_attributes[$args['flower_type_attr_id']]['caption']) . ': <span id="collection-flower-type" class=\\"collection-value\\"></span></p>
	    <p>' . lang::get($location_attributes[$args['habitat_attr_id']]['caption']) . ': <span id="collection-habitat" class=\\"collection-value\\"></span></p>
	    <p id="collection-locality"></p>
	    <p id="collection-user-name"></p>
	    <a id="collection-user-link">' . lang::get('LANG_User_Link') . '</a>
	  </div>
      <div id="map2_container">';
        // this is a bit of a hack, because the apply_template method is not public in data entry helper.
        $tempScript = data_entry_helper::$onload_javascript;
        data_entry_helper::$onload_javascript = '';
        $r .= data_entry_helper::map_panel($options2, $olOptions);
        $map2JS = data_entry_helper::$onload_javascript;
        data_entry_helper::$onload_javascript = $tempScript;
        $r .= '</div>
    </div>
	<div id="collection-insects">
    </div>
	<div id="fc-comments-header" class="ui-accordion-header ui-helper-reset ui-state-active ui-corner-top">
	    <div id="fc-new-comment-button" class="ui-state-default ui-corner-all new-comment-button">' . lang::get('LANG_New_Comment') . '</div>
		<span>' . lang::get('LANG_Comments_Title') . '</span>
	</div>
	<div id="fc-new-comment" class="ui-accordion-content ui-helper-reset ui-widget-content">
		<form id="fc-new-comment-form" action="' . iform_ajaxproxy_url($node, 'smp-comment') . '" method="POST">
		    <input type="hidden" name="website_id" value="' . $args['website_id'] . '" />
    		<input type="hidden" name="sample_comment:sample_id" value="" />
    		<label for="sample_comment:person_name">' . lang::get('LANG_Username') . ':</label>
		    <input type="text" name="sample_comment:person_name" value="' . $username . '" readonly="readonly" />  
    		<label for="sample_comment:email_address">' . lang::get('LANG_Email') . ':</label>
		    <input type="text" name="sample_comment:email_address" value="' . $email . '" readonly="readonly" />
		    ' . data_entry_helper::textarea(array('label' => lang::get('LANG_Comment'), 'fieldname' => 'sample_comment:comment', 'class' => 'required', 'suffixTemplate' => 'nosuffix')) . '
    		<input type="submit" id="fc_comment_submit_button" class="ui-state-default ui-corner-all submit-button" value="' . lang::get('LANG_Submit_Comment') . '" />
    	</form>
	</div>
	<div id="fc-comment-list" class="ui-accordion-content ui-helper-reset ui-widget-content ui-corner-bottom ui-accordion-content-active">
	</div>
</div>
<div id="focus-occurrence" class="ui-accordion ui-widget ui-helper-reset">
	<div id="fo-header" class="ui-accordion-content ui-helper-reset ui-state-active ui-corner-top ui-accordion-content-active">
	  <div id="fo-header-buttons">
 	    <span id="fo-collection-button" class="ui-state-default ui-corner-all collection-button">' . lang::get('LANG_Collection') . '</span>
	    <span id="fo-prev-button" class="ui-state-default ui-corner-all previous-button">' . lang::get('LANG_Previous') . '</span>
	    <span id="fo-next-button" class="ui-state-default ui-corner-all next-button">' . lang::get('LANG_Next') . '</span>
	  	<span id="fo-filter-button" class="ui-state-default ui-corner-all collection-button">' . lang::get('LANG_List') . '</span>
	  </div>
	</div>
	<div id="fo-picture" class="ui-accordion-content ui-helper-reset ui-widget-content ui-corner-bottom ui-accordion-content-active">
	  <div id="fo-warning"></div>
	  <div id="fo-image">
      </div>
    </div>
	<div id="fo-identification" class="ui-accordion-header ui-helper-reset ui-corner-top ui-state-active">
	  <div id="fo-id-title">
	  	<span>' . lang::get('LANG_Indentification_Title') . '</span>
      </div>
    </div>
	<div id="fo-current-id" class="ui-accordion-content ui-helper-reset ui-widget-content ui-accordion-content-active">
	</div>
	<div id="fo-new-insect-id" class="ui-accordion-content ui-helper-reset ui-widget-content">
	  <form id="fo-new-insect-id-form" action="' . iform_ajaxproxy_url($node, 'determination') . '" method="POST">
		<input type="hidden" name="website_id" value="' . $args['website_id'] . '" />
    	<input type="hidden" name="determination:occurrence_id" value="" />
		<input type="hidden" name="determination:cms_ref" value="' . $uid . '" />  
    	<input type="hidden" name="determination:person_name" value="' . $username . '" />  
		<input type="hidden" name="determination:email_address" value="' . $email . '" />';
        if (user_access('IForm n' . $node->nid . ' insect expert')) {
            $r .= '		<select name="determination:determination_type" />
			<option value="C" selected>' . lang::get('LANG_Det_Type_C') . '</option>
			<option value="X">' . lang::get('LANG_Det_Type_X') . '</option>
		</select>';
        } else {
            $r .= '		<input type="hidden" name="determination:determination_type" value="A" />';
        }
        $r .= '		<div class="id-tool-group">
          <input type="hidden" name="determination:taxon_details" />
          <span id="insect-id-button" class="ui-state-default ui-corner-all poll-id-button" >' . lang::get('LANG_Launch_ID_Key') . '</span>
		  <span id="insect-id-cancel" class="ui-state-default ui-corner-all poll-id-cancel" >' . lang::get('LANG_Cancel_ID') . '</span>
 	      <p id="insect_taxa_list"></p>
 	    </div>
 	    <div class="id-specified-group">
 	      ' . data_entry_helper::select($focus_insect_ctrl_args) . '
          <label for="insect:taxon_extra_info" class="follow-on">' . lang::get('LANG_More_Precise') . ' </label> 
          <input type="text" id="insect:taxon_extra_info" name="determination:taxon_extra_info" class="taxon-info" />
        </div>
 	    <div class="id-comment">
          <label for="insect:comment" class="follow-on">' . lang::get('LANG_ID_Comment') . ' </label>
          <textarea id="insect:comment" name="determination:comment" class="taxon-comment" rows="5" ></textarea>
        </div>
        <input type="submit" id="insect_id_submit_button" class="ui-state-default ui-corner-all submit-button" value="' . lang::get('LANG_Validate') . '" />
      </form>
	</div>
    <div id="fo-new-flower-id" class="ui-accordion-content ui-helper-reset ui-widget-content">
	  <form id="fo-new-flower-id-form" action="' . iform_ajaxproxy_url($node, 'determination') . '" method="POST">
		<input type="hidden" name="website_id" value="' . $args['website_id'] . '" />
    	<input type="hidden" name="determination:occurrence_id" value="" />
		<input type="hidden" name="determination:cms_ref" value="' . $uid . '" />  
    	<input type="hidden" name="determination:person_name" value="' . $username . '" />  
		<input type="hidden" name="determination:email_address" value="' . $email . '" />';
        if (user_access('IForm n' . $node->nid . ' flower expert')) {
            $r .= '		<select name="determination:determination_type" />
			<option value="C" selected>' . lang::get('LANG_Det_Type_C') . '</option>
			<option value="X">' . lang::get('LANG_Det_Type_X') . '</option>
		</select>';
        } else {
            $r .= '		<input type="hidden" name="determination:determination_type" value="A" />';
        }
        $r .= '		<div class="id-tool-group">
          <input type="hidden" name="determination:taxon_details" />
          <span id="flower-id-button" class="ui-state-default ui-corner-all poll-id-button" >' . lang::get('LANG_Launch_ID_Key') . '</span>
		  <span id="flower-id-cancel" class="ui-state-default ui-corner-all poll-id-cancel" >' . lang::get('LANG_Cancel_ID') . '</span>
 	      <p id="flower_taxa_list" class="taxa_list" ></p>
 	    </div>
 	    <div class="id-specified-group">
 	      ' . data_entry_helper::select($focus_flower_ctrl_args) . '
          <label for="flower:taxon_extra_info" class="follow-on">' . lang::get('LANG_More_Precise') . ' </label> 
          <input type="text" id="flower:taxon_extra_info" name="determination:taxon_extra_info" class="taxon-info" />
        </div>
 	    <div class="id-comment">
          <label for="flower:comment" class="follow-on">' . lang::get('LANG_ID_Comment') . ' </label>
          <textarea id="flower:comment" name="determination:comment" class="taxon-comment" rows="5" ></textarea>
        </div>
        <input type="submit" id="flower_id_submit_button" class="ui-state-default ui-corner-all submit-button" value="' . lang::get('LANG_Validate') . '" />
      </form>
	</div>
	<div id="fo-express-doubt" class="ui-accordion-content ui-helper-reset ui-widget-content">
	  <form id="fo-express-doubt-form" action="' . iform_ajaxproxy_url($node, 'determination') . '" method="POST">
		<input type="hidden" name="website_id" value="' . $args['website_id'] . '" />
    	<input type="hidden" name="determination:occurrence_id" value="" />
		<input type="hidden" name="determination:cms_ref" value="' . $uid . '" />  
    	<input type="hidden" name="determination:person_name" value="' . $username . '" />  
		<input type="hidden" name="determination:email_address" value="' . $email . '" />
    	<input type="hidden" name="determination:determination_type" value="B" />
        <input type="hidden" name="determination:taxon_extra_info" />
        <input type="hidden" name="determination:taxa_taxon_list_id" />
 	    <div class="doubt-comment">
          <label for="determination:comment" class="follow-on">' . lang::get('LANG_Doubt_Comment') . ' </label>
          <textarea id="determination:comment" name="determination:comment" class="taxon-comment" rows="5" ></textarea>
        </div>
        <input type="submit" id="doubt_submit_button" class="ui-state-default ui-corner-all submit-button" value="' . lang::get('LANG_Validate') . '" />
      </form>
	</div>
	
	<div id="fo-id-history" class="ui-accordion-content ui-helper-reset ui-widget-content ui-accordion-content-active"></div>
	<div id="fo-id-buttons" class="ui-accordion-content ui-helper-reset ui-widget-content ui-accordion-content-active">
		<div id="fo-new-insect-id-button" class="ui-state-default ui-corner-all new-id-button">' . lang::get('LANG_New_ID') . '</div>
		<div id="fo-new-flower-id-button" class="ui-state-default ui-corner-all new-id-button">' . lang::get('LANG_New_ID') . '</div>
		<div id="fo-doubt-button" class="ui-state-default ui-corner-all doubt-button">' . lang::get('LANG_Doubt') . '</div>
    </div>	
	<div id="fo-insect-addn-info" class="ui-accordion-content ui-helper-reset ui-widget-content ui-corner-bottom ui-accordion-content-active">
	    <span class="addn-info-title">' . lang::get('LANG_Additional_Info_Title') . '</span>
	    <p>' . lang::get('LANG_Date') . ': <span id="fo-insect-date"></span></p>
	    <p>' . lang::get('LANG_Time') . ': <span id="fo-insect-start-time"></span> ' . lang::get('LANG_To') . ' <span id="fo-insect-end-time"></span></p>
	    <p>' . $sample_attributes[$args['sky_state_attr_id']]['caption'] . ': <span id="fo-insect-sky"></span></p>
	    <p>' . $sample_attributes[$args['temperature_attr_id']]['caption'] . ': <span id="fo-insect-temp"></span></p>
	    <p>' . $sample_attributes[$args['wind_attr_id']]['caption'] . ': <span id="fo-insect-wind"></span></p>
	    <p>' . $sample_attributes[$args['shade_attr_id']]['caption'] . ': <span id="fo-insect-shade"></span></p>
	</div>
	<div id="fo-flower-addn-info" class="ui-accordion-content ui-helper-reset ui-widget-content ui-corner-bottom ui-accordion-content-active">
	    <p>' . $occurrence_attributes[$args['flower_type_attr_id']]['caption'] . ': <span id="focus-flower-type"></span></p>
	    <p>' . $location_attributes[$args['habitat_attr_id']]['caption'] . ': <span id="focus-habitat"></span></p>
	</div>
	<div id="fo-comments-header" class="ui-accordion-header ui-helper-reset ui-state-active ui-corner-top">
	    <div id="fo-new-comment-button" class="ui-state-default ui-corner-all new-comment-button">' . lang::get('LANG_New_Comment') . '</div>
		<span>' . lang::get('LANG_Comments_Title') . '</span>
	</div>
	<div id="fo-new-comment" class="ui-accordion-content ui-helper-reset ui-widget-content">
		<form id="fo-new-comment-form" action="' . iform_ajaxproxy_url($node, 'occ-comment') . '" method="POST">
		    <input type="hidden" name="website_id" value="' . $args['website_id'] . '" />
    		<input type="hidden" name="occurrence_comment:occurrence_id" value="" />
    		<label for="occurrence_comment:person_name">' . lang::get('LANG_Username') . ':</label>
		    <input type="text" name="occurrence_comment:person_name" value="' . $username . '" readonly="readonly" />  
    		<label for="occurrence_comment:email_address">' . lang::get('LANG_Email') . ':</label>
		    <input type="text" name="occurrence_comment:email_address" value="' . $email . '" readonly="readonly" />
		    ' . data_entry_helper::textarea(array('label' => lang::get('LANG_Comment'), 'fieldname' => 'occurrence_comment:comment', 'class' => 'required', 'suffixTemplate' => 'nosuffix')) . '
    		<input type="submit" id="comment_submit_button" class="ui-state-default ui-corner-all submit-button" value="' . lang::get('LANG_Submit_Comment') . '" />
    	</form>
	</div>
	<div id="fo-comment-list" class="ui-accordion-content ui-helper-reset ui-widget-content ui-corner-bottom ui-accordion-content-active">
	</div>
</div>
';
        data_entry_helper::$javascript .= "\n// We need to leave the AJAX calls for the search alone, but abort other focus-on calls,\n// so we put a dummy REMOVEABLEJSONP in the URL, and search on that. This is ignored by the service call itself.\najaxStack = [];\nabortAjax = function()\n{\n\tjQuery('script').each(function(){\n\t\tif(this.src.indexOf('REMOVEABLEJSONP')>0){\n\t\t\tvar test = this.src.match(/jsonp\\d*/);\n\t\t\twindow[test] = function(){};\n\t\t\tjQuery(this).remove();\n\t\t}\n\t});\n\t// This deals with any non cross domain calls.\n\twhile(ajaxStack.length > 0){\n\t\tvar request = ajaxStack.shift();\n\t\tif(!(typeof request == 'undefined')) request.abort();\n\t}\n}\n\n\nalertIndiciaError = function(data){\n\tvar errorString = \"" . lang::get('LANG_Indicia_Warehouse_Error') . "\";\n\tif(data.error){\terrorString = errorString + ' : ' + data.error;\t}\n\tif(data.errors){\n\t\tfor (var i in data.errors){\n\t\t\terrorString = errorString + ' : ' + data.errors[i];\n\t\t}\t\t\t\t\n\t}\n\talert(errorString);\n\t// the most likely cause is authentication failure - eg the read authentication has timed out.\n\t// prevent further use of the form:\n\tjQuery('#filter,#focus-occurrence,#focus-collection').hide();\n\tjQuery('#refresh-message').show();\n};\n\njQuery('#imp-georef-search-btn').removeClass('indicia-button').addClass('search-button');\n\$.validator.messages.required = \"" . lang::get('validation_required') . "\";\n\n// remove the (don't know) entry from flower type filter.\njQuery('[name=occAttr\\:" . $args['flower_type_attr_id'] . "]').filter('[value=" . $args['flower_type_dont_know'] . "]').parent().remove();\n \njQuery('#start_date').datepicker({\n  dateFormat : 'dd/mm/yy',\n  constrainInput: false,\n  maxDate: '0',\n  altField : '#real_start_date',\n  altFormat : 'yy-mm-dd'\n});\njQuery('#end_date').datepicker({\n  dateFormat : 'dd/mm/yy',\n  constrainInput: false,\n  maxDate: '0',\n  altField : '#real_end_date',\n  altFormat : 'yy-mm-dd'\n});\n\nmyScrollTo = function(selector){\n\tjQuery(selector).filter(':visible').each(function(){\n\t\twindow.scroll(0, jQuery(this).offset().top);\n\t});\n};\n\njQuery('#reset-name-button').click(function(){\n\tjQuery('[name=username]').val('');\n});\njQuery('#fold-name-button').click(function(){\n\tjQuery('#name-filter-header').toggleClass('ui-state-active').toggleClass('ui-state-default');\n\tjQuery('#fold-name-button').toggleClass('fold-button-folded');\n\tjQuery('#name-filter-body').toggleClass('ui-accordion-content-active');\n});\njQuery('#reset-date-button').click(function(){\n\tjQuery('[name=start_date]').val('" . lang::get('click here') . "');\n\tjQuery('[name=real_start_date]').val('');\n\tjQuery('[name=end_date]').val('" . lang::get('click here') . "');\n\tjQuery('[name=real_end_date]').val('');\n});\njQuery('#fold-date-button').click(function(){\n\tjQuery('#date-filter-header').toggleClass('ui-state-active').toggleClass('ui-state-default');\n\tjQuery('#fold-date-button').toggleClass('fold-button-folded');\n\tjQuery('#date-filter-body').toggleClass('ui-accordion-content-active');\n});\n\njQuery('#reset-flower-button').click(function(){\n\tjQuery('[name=flower\\:taxa_taxon_list_id]').val('');\n\tjQuery('[name=flower\\:taxon_extra_info]').val(\"" . lang::get('LANG_More_Precise') . "\");\n\tjQuery('#flower-filter-body').find(':checkbox').removeAttr('checked');\n});\njQuery('#fold-flower-button').click(function(){\n\tjQuery('#flower-filter-header').toggleClass('ui-state-active').toggleClass('ui-state-default');\n\tjQuery('#fold-flower-button').toggleClass('fold-button-folded');\n\tjQuery('#flower-filter-body').toggleClass('ui-accordion-content-active');\n});\n\njQuery('#reset-insect-button').click(function(){\n\tjQuery('[name=insect\\:taxa_taxon_list_id]').val('');\n\tjQuery('[name=insect\\:taxon_extra_info]').val(\"" . lang::get('LANG_More_Precise') . "\");\n\tjQuery('#insect-filter-body').find(':checkbox').removeAttr('checked');\n});\n\njQuery('#fold-insect-button').click(function(){\n\tjQuery('#insect-filter-header').toggleClass('ui-state-active').toggleClass('ui-state-default');\n\tjQuery('#fold-insect-button').toggleClass('fold-button-folded');\n\tjQuery('#insect-filter-body').toggleClass('ui-accordion-content-active');\n});\n\njQuery('#reset-conditions-button').click(function(){\n\tjQuery('#conditions-filter-body').find(':checkbox').removeAttr('checked');\n});\n\njQuery('#fold-conditions-button').click(function(){\n\tjQuery('#conditions-filter-header').toggleClass('ui-state-active').toggleClass('ui-state-default');\n\tjQuery('#fold-conditions-button').toggleClass('fold-button-folded');\n\tjQuery('#conditions-filter-body').toggleClass('ui-accordion-content-active');\n});\n\njQuery('#reset-location-button').click(function(){\n\tpolygonLayer.destroyFeatures();\n\tpolygonLayer.map.searchLayer.destroyFeatures();\n\tif(inseeLayer != null)\n\t\tinseeLayer.destroyFeatures();\n\tjQuery('#imp-georef-search').val('');\n\tjQuery('[name=place\\:INSEE]').val('" . lang::get('LANG_INSEE') . "');\n\tvar div = jQuery('#map')[0];\n\tvar center = new OpenLayers.LonLat(" . $args['map_centroid_long'] . ", " . $args['map_centroid_lat'] . ");\n\tcenter.transform(div.map.displayProjection, div.map.projection);\n\tdiv.map.setCenter(center, " . (int) $args['map_zoom'] . ");\n});\njQuery('#fold-location-button').click(function(){\n\tjQuery('#location-filter-header').toggleClass('ui-state-active').toggleClass('ui-state-default');\n\tjQuery('#fold-location-button').toggleClass('fold-button-folded');\n\tjQuery('#location-filter-body').toggleClass('ui-accordion-content-active');\n});\n\njQuery('#flower-image').click(function(){\n\tif(jQuery('#flower-image').data('occID') != 'none'){\n\t\tloadFlower(jQuery('#flower-image').data('occID'), jQuery('#flower-image').data('collectionIndex'));\n\t}\n});\njQuery('#show-flower-button').click(function(){\n\tif(jQuery('#flower-image').data('occID') != 'none'){\n\t\tloadFlower(jQuery('#flower-image').data('occID'), jQuery('#flower-image').data('collectionIndex'));\n\t}\n});\n\njQuery('#fo-doubt-button').click(function(){\n\tjQuery('#fo-new-insect-id,#fo-new-flower-id').removeClass('ui-accordion-content-active');\n\tjQuery('#fo-express-doubt [name=determination\\:comment]').val(\"" . lang::get('LANG_Default_Doubt_Comment') . "\");\n\tjQuery('#fo-express-doubt').toggleClass('ui-accordion-content-active');\n});\n\njQuery('#fc-next-button,#fc-prev-button').click(function(){\n\tvar index = jQuery(this).data('index');\n\tvar id = searchResults.features[index].attributes.collection_id;\n\tloadCollection(id, index);\n});\n\njQuery('#fc-filter-button,#fo-filter-button').click(function(){\n    jQuery('#filter').show();\n\tjQuery('#focus-occurrence,#focus-collection,#results-insects-header,#results-collections-header,#results-insects-results,#results-collections-results').hide();\n    loadFilter();\n    if(searchResults != null){\n    \tif(searchResults.type == 'C')\n    \t\tjQuery('#results-collections-header,#results-collections-results').show();\n    \telse \n    \t\tjQuery('#results-insects-header,#results-insects-results').show();\n\t}\n});\n\nhtmlspecialchars = function(value){\n\treturn value.replace(/[<>\"'&]/g, function(m){return replacechar(m)})\n};\n\nreplacechar = function(match){\n\tif (match==\"<\") return \"&lt;\"\n\telse if (match==\">\") return \"&gt;\"\n\telse if (match=='\"') return \"&quot;\"\n\telse if (match==\"'\") return \"&#039;\"\n\telse if (match==\"&\") return \"&amp;\"\n};\n\nconvertDate = function(dateStr, incTime){\n\tvar retDate = '';\n\t// assume date is in in YYYY/MM/DD[+Time] format.\n\t// if language is french convert to DD/MM/YYYY[+Time] format.\n\tif('" . $args['language'] . "' == 'fr'){\n\t\tretDate = dateStr.slice(8,10)+'-'+dateStr.slice(5,7)+'-'+dateStr.slice(0,4);\n\t\tif(incTime) retDate = retDate+dateStr.slice(10);\n\t} else if(incTime)\n\t\tretDate = dateStr;\n\telse\n\t\tretDate = dateStr.slice(0,10);\n\treturn retDate;\n} \n\nloadCollection = function(id, index){\n\tabortAjax();\n    jQuery('[name=sample_comment\\:sample_id]').val(id);\n\tjQuery('#fc-add-preferred').attr('smpID', id);\n\tcollection_preferred_object.collection_id = id;\n\tjQuery('#fc-new-comment-button')." . (user_access('IForm n' . $node->nid . ' create collection comment') ? "show()" : "hide()") . ";\n    jQuery('#focus-occurrence,#filter,#fc-next-button,#fc-prev-button').hide();\n    jQuery('#focus-collection').show();\n    if(index != null){\n    \tif(index < (searchResults.features.length-1) )\n    \t\tjQuery('#fc-next-button').show().data('index', index+1);\n    \tif(index > 0)\n    \t\tjQuery('#fc-prev-button').show().data('index', index-1);\n    }\n    if(jQuery('#map2').children().length == 0) {\n    \tlocationLayer = new OpenLayers.Layer.Vector('Location Layer',{displayInLayerSwitcher: false});\n    \t" . $map2JS . "\n \t};\n    locationLayer.destroyFeatures();\n \tjQuery('#map2').width('auto');\n\tjQuery('#flower-image').data('occID', 'none').data('collectionIndex', index);\n\tjQuery('#collection-insects,#collection-date,#collection-flower-name,#collection-flower-type,#collection-habitat,#collection-user-name').empty();\n\tloadComments(id, '#fc-comment-list', 'sample_comment', 'sample_id', 'sample-comment-block', 'sample-comment-body', true);\n\t// only need to reset the timeout on the first fetch as rest follow on quickly.\n\tajaxStack.push(\$.getJSON(\"" . $svcUrl . "/data/occurrence\" +\n\t\t\t\"?mode=json&view=detail&nonce=" . $readAuth['nonce'] . "&auth_token=" . $readAuth['auth_token'] . "\" +\n\t\t\t\"&sample_id=\"+id+\"&deleted=f&REMOVEABLEJSONP&callback=?\", function(flowerData) {\n   \t\tif(!(flowerData instanceof Array)){\n   \t\t\talertIndiciaError(flowerData);\n   \t\t} else if (flowerData.length>0) {\n   \t\t\tloadImage('occurrence_image', 'occurrence_id', flowerData[0].id, '#flower-image', " . $args['Flower_Image_Ratio'] . ", function(imageRecord){collection_preferred_object.flower_image_path = imageRecord.path}, 'med-', false);\n\t\t\tjQuery('#flower-image').data('occID', flowerData[0].id);\n\t\t\tcollection_preferred_object.flower_id = flowerData[0].id;\n\t\t\tajaxStack.push(\$.getJSON(\"" . $svcUrl . "/data/determination\" + \n\t\t\t\t\t\"?mode=json&view=list&nonce=" . $readAuth['nonce'] . "&auth_token=" . $readAuth['auth_token'] . "\" + \n\t\t\t\t\t\"&occurrence_id=\" + flowerData[0].id + \"&deleted=f&orderby=id&REMOVEABLEJSONP&callback=?\", function(detData) {\n   \t\t\t\tif(!(detData instanceof Array)){\n   \t\t\t\t\talertIndiciaError(detData);\n   \t\t\t\t} else if (detData.length>0) {\n   \t\t\t\t\tvar i = detData.length-1;\n\t\t\t\t\tvar string = '';\n\t\t\t\t\tif(detData[i].taxon != '' && detData[i].taxon != null){\n\t\t\t\t\t\tstring = detData[i].taxon;\n\t\t  \t\t\t}\n\t\t\t\t\tif(detData[i].taxa_taxon_list_id_list != '' && detData[i].taxa_taxon_list_id_list != null){\n\t\t\t\t\t\tdetData[i].taxa_taxon_list_id_list;\n\t\t\t  \t\t\tvar resultsIDs = detData[i].taxa_taxon_list_id_list.substring(1, detData[i].taxa_taxon_list_id_list.length - 1).split(',');\n\t\t\t\t\t\tif(resultsIDs[0] != '') {\n\t\t\t\t\t\t\tfor(var j=0; j < resultsIDs.length; j++){\n\t\t\t\t\t\t\t\tfor(k = 0; k< flowerTaxa.length; k++){\n\t\t\t\t\t\t\t\t\tif(flowerTaxa[k].id == resultsIDs[j]){\n\t\t\t\t\t\t\t\t\t\tstring = (string == '' ? '' : string + ', ') + flowerTaxa[k].taxon;\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t};\n\t\t\t\t\t  \t\t}\n\t\t\t\t\t  \t}\n\t\t\t\t\t}\n\t\t  \t\t\tif(detData[i].taxon_extra_info != '' && detData[i].taxon_extra_info != null){\n\t\t\t\t\t\tstring = (string == '' ? '' : string + ' ') + '('+detData[i].taxon_extra_info+')';\n\t\t\t\t\t}\n\t\t\t\t\tjQuery('<span>" . lang::get('LANG_Flower_Name') . ": <span class=\"collection-value\">'+htmlspecialchars(string)+'</span></span>').appendTo('#collection-flower-name');\n\t\t\t\t}}));\n\t\t\tajaxStack.push(\$.getJSON(\"" . $svcUrl . "/data/occurrence_attribute_value\"  +\n   \t\t\t\t\t\"?mode=json&view=list&nonce=" . $readAuth['nonce'] . "&auth_token=" . $readAuth['auth_token'] . "\" +\n   \t\t\t\t\t\"&occurrence_id=\" + flowerData[0].id + \"&iso=" . $language . "&REMOVEABLEJSONP&callback=?\", function(attrdata) {\n\t\t\t\tif(!(attrdata instanceof Array)){\n   \t\t\t\t\talertIndiciaError(attrdata);\n   \t\t\t\t} else if (attrdata.length>0) {\n   \t\t\t\t\tfor(i=0; i< attrdata.length; i++){\n\t\t\t\t\t\tif (attrdata[i].id){\n\t\t\t\t\t\t\tswitch(parseInt(attrdata[i].occurrence_attribute_id)){\n\t\t\t\t\t\t\t\tcase " . $args['flower_type_attr_id'] . ":\n\t\t\t\t\t\t\t\t\tjQuery('<span>'+attrdata[i].value+'</span>').appendTo('#collection-flower-type');\n\t\t\t\t\t\t\t\t\tbreak;\n  \t\t\t}}}}}));\n\t\t\t\t\n\t\t}\n\t}));\n\tajaxStack.push(\$.getJSON(\"" . $svcUrl . "/data/sample_attribute_value\"  +\n   \t\t\t\"?mode=json&view=list&nonce=" . $readAuth['nonce'] . "&auth_token=" . $readAuth['auth_token'] . "\" +\n   \t\t\t\"&sample_id=\" + id + \"&REMOVEABLEJSONP&callback=?\", function(attrdata) {\n\t\tif(!(attrdata instanceof Array)){\n   \t\t\talertIndiciaError(attrdata);\n   \t\t} else if (attrdata.length>0) {\n\t\t\tfor(i=0; i< attrdata.length; i++){\n\t\t\t\tif (attrdata[i].id){\n\t\t\t\t\tswitch(parseInt(attrdata[i].sample_attribute_id)){\n\t\t\t\t\t\tcase " . $args['username_attr_id'] . ":\n\t\t\t\t\t\t\tjQuery('<span>" . lang::get('LANG_Comment_By') . "'+attrdata[i].value+'</span>').appendTo('#collection-user-name');\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tcase " . $args['uid_attr_id'] . ":\n\t\t\t\t\t\t\tcollection_preferred_object.user_id = attrdata[i].value\n\t\t\t       \t\t    jQuery('#collection-user-link').attr('href', '" . url('node/' . $node->nid) . "?user_id='+attrdata[i].value);\n\t\t\t\t\t\t\tbreak;\n    }}}}}));\n\tajaxStack.push(\$.getJSON(\"" . $svcUrl . "/data/sample/\" +id+\n\t\t\t\"?mode=json&view=detail&nonce=" . $readAuth['nonce'] . "&auth_token=" . $readAuth['auth_token'] . "\" +\n\t\t\t\"&REMOVEABLEJSONP&callback=?\", function(collectionData) {\n   \t\tif(!(collectionData instanceof Array)){\n   \t\t\talertIndiciaError(collectionData);\n   \t\t} else if (collectionData.length>0) {\n\t\t\tif(collectionData[0].date_start == collectionData[0].date_end){\n\t\t\t\tcollection_preferred_object.date = collectionData[0].date_start.slice(0,10);\n\t\t\t\tjQuery('<span>'+convertDate(collectionData[0].date_start, false)+'</span>').appendTo('#collection-date');\n\t\t\t} else {\n\t\t\t\tcollection_preferred_object.date = collectionData[0].date_start.slice(0,10)+' - '+collectionData[0].date_end.slice(0,10);\n\t\t\t\tjQuery('<span>'+convertDate(collectionData[0].date_start, false)+' - '+convertDate(collectionData[0].date_end, false)+'</span>').appendTo('#collection-date');\n\t\t\t}\n\t\t\tjQuery('#poll-banner').empty().append(collectionData[0].location_name);\n\t  \t\tcollection_preferred_object.collection_name = collectionData[0].location_name;\n\t        ajaxStack.push(\$.getJSON(\"" . $svcUrl . "/data/location/\" +collectionData[0].location_id +\n\t\t\t\t\t\"?mode=json&view=detail&nonce=" . $readAuth['nonce'] . "&auth_token=" . $readAuth['auth_token'] . "\" +\n\t\t\t\t\t\"&REMOVEABLEJSONP&callback=?\", function(locationData) {\n   \t\t\t\tif(!(locationData instanceof Array)){\n   \t\t\t\t\talertIndiciaError(locationData);\n   \t\t\t\t} else if (locationData.length>0) {\n\t\t\t\t\tloadImage('location_image', 'location_id', locationData[0].id, '#environment-image', " . $args['Environment_Image_Ratio'] . ", function(imageRecord){collection_preferred_object.environment_image_path = imageRecord.path}, 'med-', false);\n\t\t\t\t\tvar parser = new OpenLayers.Format.WKT();\n\t\t\t\t\tvar feature = parser.read(locationData[0].centroid_geom);\n\t\t\t\t\tlocationLayer.addFeatures([feature]);\n\t\t\t\t\tvar bounds=locationLayer.getDataExtent();\n\t\t\t\t\tlocationLayer.map.setCenter(bounds.getCenterLonLat(), 13);\n\t\t\t        var filter = new OpenLayers.Filter.Spatial({\n  \t\t\t\t\t\ttype: OpenLayers.Filter.Spatial.CONTAINS ,\n    \t\t\t\t\tproperty: 'the_geom',\n    \t\t\t\t\tvalue: feature.geometry\n\t\t\t\t  \t});\n\t\t\t\t\tvar locality = jQuery('#collection-locality');\n\t\t\t\t  \tvar scope = {target: locality};\n\t\t\t\t\tinseeProtocol.read({filter: filter, callback: fillLocationDetails, scope: scope});\n\t\t\t\t}\n\t\t\t}));\n\t        ajaxStack.push(\$.getJSON(\"" . $svcUrl . "/data/location_attribute_value\"  +\n   \t\t\t\t\t\"?mode=json&view=list&nonce=" . $readAuth['nonce'] . "&auth_token=" . $readAuth['auth_token'] . "\" +\n   \t\t\t\t\t\"&location_id=\" + collectionData[0].location_id + \"&iso=" . $language . "&REMOVEABLEJSONP&callback=?\", function(attrdata) {\n\t\t\t\tif(!(attrdata instanceof Array)){\n   \t\t\t\t\talertIndiciaError(attrdata);\n   \t\t\t\t} else if (attrdata.length>0) {\n\t\t\t\t\tfor(i=0; i< attrdata.length; i++){\n\t\t\t\t\t\tif (attrdata[i].id){\n\t\t\t\t\t\t\tswitch(parseInt(attrdata[i].location_attribute_id)){\n\t\t\t\t\t\t\t\tcase " . $args['habitat_attr_id'] . ":\n\t\t\t\t\t\t\t\t\tjQuery('<span>'+attrdata[i].value+' / </span>').appendTo('#collection-habitat');\n\t\t\t\t\t\t\t\t\tbreak;\n  \t\t\t}}}}}));\n\t\t}\n\t}));\n\t// we want to tag end of row pictuure, so we need to keep track of its position in list.\n\tcollection_preferred_object.insects = [];\n\tajaxStack.push(jQuery.ajax({\n\t\turl: \"" . $svcUrl . "/data/sample?mode=json&view=detail&nonce=" . $readAuth['nonce'] . "&auth_token=" . $readAuth['auth_token'] . "&REMOVEABLEJSONP&callback=?&parent_id=\"+id,\n\t\tdataType: 'json',\n\t\tmyIndex: index,\n\t\tsuccess: function(sessiondata) {\n          if(!(sessiondata instanceof Array)){\n   \t\t\talertIndiciaError(sessiondata);\n   \t\t  } else if (sessiondata.length>0) {\n   \t\t\tvar sessList=[];\n   \t\t\t// code has been changed to fetch all insects at once, so we can now go async\n\t\t\tfor (var i=0;i<sessiondata.length;i++)\n\t\t\t\tsessList.push(sessiondata[i].id);\n\t\t\t\tajaxStack.push(jQuery.ajax({\n\t\t\t\t\turl: \"" . $svcUrl . "/data/occurrence?mode=json&view=detail&nonce=" . $readAuth['nonce'] . "&auth_token=" . $readAuth['auth_token'] . "&deleted=f&orderby=id&REMOVEABLEJSONP&callback=?&query=\"+escape(JSON.stringify({'in': ['sample_id', sessList]})),\n\t\t\t\t\tdataType: 'json',\n\t\t\t\t\tmyIndex: this.myIndex,\n\t\t\t\t\tsuccess: function(insectData) {\n\t\t\t\t\t  if(!(insectData instanceof Array)){\n   \t\t\t\t\t\talertIndiciaError(insectData);\n   \t\t  \t\t\t  } else if (insectData.length>0) {\n\t\t\t\t\t\tfor (var j=0;j<insectData.length;j++){\n\t\t\t\t\t\t\tvar insect=jQuery('<div class=\"ui-widget-content ui-corner-all collection-insect\" />').attr('occID', insectData[j].id).appendTo('#collection-insects');\n\t\t\t\t\t\t\tif((j+1)/" . $args['insectsPerRow'] . " == parseInt((j+1)/" . $args['insectsPerRow'] . "))\n\t\t\t\t\t\t\t\tinsect.addClass('end-of-row');\n\t\t\t\t\t\t\tjQuery('<p class=\"insect-tag insect-unknown\" />').appendTo(insect);\n\t\t\t\t\t\t\tvar image = jQuery('<div class=\"insect-image empty\" />').appendTo(insect).data('occID',insectData[j].id)\n\t\t\t\t\t\t\t\t\t.data('collectionIndex',this.myIndex).click(function(){\n\t\t\t\t\t\t\t\tloadInsect(jQuery(this).data('occID'),jQuery(this).data('collectionIndex'),null,'C');\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\tjQuery('<p class=\"insect-determination empty\" />').appendTo(insect);\n\t\t\t\t\t\t\tjQuery('<div class=\"ui-state-default ui-corner-all display-button\">" . lang::get('LANG_Display') . "</div>')\n\t\t\t\t\t\t\t\t\t.appendTo(insect).attr('occID',insectData[j].id).data('collectionIndex',this.myIndex).data('collectionInsectIndex',j).click(function(){\n\t\t\t\t\t\t\t\tloadInsect(jQuery(this).attr('occID'),jQuery(this).data('collectionIndex'),null,'C');\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\tloadImage('occurrence_image', 'occurrence_id', insectData[j].id, image, " . $args['Insect_Image_Ratio'] . ", function(imageRecord){collection_preferred_object.insects.push({insect_id: imageRecord.occurrence_id, insect_image_path: imageRecord.path})}, 'med-',\n\t\t\t\t\t\t\t\tfunction(img){\n\t\t\t\t\t\t\t\t\tvar group = jQuery('#collection-insects').find('.collection-insect');\n\t\t\t\t\t\t\t\t\tjQuery(img).parent().removeClass('empty');\n\t\t\t\t\t\t\t\t\tif(group.find('.empty').length == 0){\n\t\t\t\t\t\t\t\t\t\tvar tallest = 0;\n\t\t\t\t\t\t\t\t\t\tgroup.each(function(){ tallest = Math.max(\$(this).height(), tallest); });\n\t\t\t\t\t\t\t\t\t\tgroup.each(function(){ \$(this).height(Math.max(\$(this).height(), tallest)); }); // have synchronicity problems.\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\tajaxStack.push(jQuery.ajax({\n\t\t\t\t\t\t\t\turl: \"" . $svcUrl . "/data/determination\" + \n\t\t\t\t\t    \t\t\t\"?mode=json&view=list&nonce=" . $readAuth['nonce'] . "&auth_token=" . $readAuth['auth_token'] . "\" + \n\t\t\t\t\t    \t\t\t\"&occurrence_id=\" + insectData[j].id + \"&deleted=f&orderby=id&REMOVEABLEJSONP&callback=?\",\n\t\t\t\t\t\t\t\tdataType: 'json',\n\t\t\t\t\t\t\t\tmyID: insectData[j].id,\n\t\t\t\t\t\t\t\tsuccess: function(detData) {\n   \t\t\t\t\t\t\t\t  if(!(detData instanceof Array)){\n   \t\t\t\t\t\t\t\t\talertIndiciaError(detData);\n   \t\t  \t\t\t  \t\t\t  } else {\n   \t\t  \t\t\t  \t\t\t   if (detData.length>0) {\n\t\t\t\t\t    \t\t\tvar insect = jQuery('.collection-insect').filter('[occID='+detData[0].occurrence_id+']');\n\t\t\t\t\t    \t\t\tvar tag = insect.find('.insect-tag');\n\t\t\t\t\t    \t\t\tvar det = insect.find('.insect-determination');\n\t\t\t\t\t\t\t\t\tvar i = detData.length-1;\n\t\t\t\t\t\t\t\t\tvar string = '';\n\t\t\t\t\t\t\t\t\tif(detData[i].taxon != '' && detData[i].taxon != null){\n\t\t\t\t\t\t\t\t\t\tstring = detData[i].taxon;\n\t\t\t\t\t\t  \t\t\t}\n\t\t\t\t\t\t\t\t\tif(detData[i].taxa_taxon_list_id_list != '' && detData[i].taxa_taxon_list_id_list != null){\n\t\t\t\t\t\t\t\t\t\tdetData[i].taxa_taxon_list_id_list;\n\t\t\t\t\t\t\t\t\t  \tvar resultsIDs = detData[i].taxa_taxon_list_id_list.substring(1, detData[i].taxa_taxon_list_id_list.length - 1).split(',');\n\t\t\t\t\t\t\t\t\t\tif(resultsIDs[0] != '') {\n\t\t\t\t\t\t\t\t\t\t\tfor(var j=0; j < resultsIDs.length; j++){\n\t\t\t\t\t\t\t\t\t\t\t\tfor(var k = 0; k< insectTaxa.length; k++){\n\t\t\t\t\t\t\t\t\t\t\t\t\tif(insectTaxa[k].id == resultsIDs[j]){\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tstring = (string == '' ? '' : string + ', ') + insectTaxa[k].taxon;\n\t\t\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t\t\t};\n\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t  \t\t}\n\t\t\t\t\t\t\t\t\t}\t\n\t\t\t\t\t\t\t\t\tif(string != '')\n\t\t\t\t\t\t\t\t\t\tjQuery('<div><p>" . lang::get('LANG_Last_ID') . ":</p><p><strong>'+string+'</strong></p></div>').addClass('insect-id').appendTo(det);\n\t\t\t\t\t\t\t\t\tif(detData[i].determination_type == 'B' || detData[i].determination_type == 'I' || detData[i].determination_type == 'U'){\n\t\t\t\t\t\t\t\t\t\ttag.removeClass('insect-unknown').addClass('insect-dubious');\n\t\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\t\ttag.removeClass('insect-unknown').addClass('insect-ok');\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t   }\n\t\t\t\t\t\t\t\t\tvar group = jQuery('#collection-insects').find('.collection-insect');\n\t\t\t\t\t\t\t\t\tgroup.filter('[occID='+this.myID+']').find('.insect-determination').removeClass('empty');\n\t\t\t\t\t\t\t\t\tif(group.find('.empty').length == 0){\n\t\t\t\t\t\t\t\t\t\tvar tallest = 0;\n\t\t\t\t\t\t\t\t\t\tgroup.each(function(){ tallest = Math.max(\$(this).height(), tallest); });\n\t\t\t\t\t\t\t\t\t\tgroup.each(function(){ \$(this).height(Math.max(\$(this).height(), tallest)); }); // have synchronicity problems.\n\t\t\t\t\t\t\t}}}}));\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t  }})); \n\t\t\t}}\n\t    }));\n\tmyScrollTo('#poll-banner');\n};\nfillLocationDetails = function(a1)\n{\n\tjQuery(this.target).empty();\n\tcollection_preferred_object.location_description = '';\n\tif(a1.features.length > 0) {\n\t   \tvar text = a1.features[0].attributes.NOM+' ('+a1.features[0].attributes.INSEE_NEW+'), '+a1.features[0].attributes.DEPT_NOM+' ('+a1.features[0].attributes.DEPT_NUM+'), '+a1.features[0].attributes.REG_NOM+' ('+a1.features[0].attributes.REG_NUM+')';\n\t\tcollection_preferred_object.location_description = text;\n\t   \tjQuery('<span>'+text+'</span>').appendTo(this.target);\n  }\n}\naddCollection = function(index, attributes, geom, first){\n\t// first the text, then the flower and environment picture, then the small insect pictures, then the afficher button\n\tvar collection=jQuery('<div class=\"ui-widget-content ui-corner-all filter-collection\" />').appendTo('#results-collections-results');\n\tvar details = jQuery('<div class=\"collection-details\" />').appendTo(collection); \n\tvar flower = jQuery('<div class=\"collection-image collection-flower\" />').data('occID', attributes.flower_id).\n\t\tdata('collectionIndex', index).click(function(){\n\t\t\tloadFlower(jQuery(this).data('occID'), jQuery(this).data('collectionIndex'));\n\t});\n\tvar filter = new OpenLayers.Filter.Spatial({\n  \t\t\ttype: OpenLayers.Filter.Spatial.CONTAINS ,\n    \t\tproperty: 'the_geom',\n    \t\tvalue: geom\n  \t});\n\tflower.appendTo(collection);\n\tinsertImage('med-'+attributes.image_de_la_fleur, flower, " . $args['Flower_Image_Ratio'] . ", false);\n\tvar location = jQuery('<div class=\"collection-image collection-environment\" />').appendTo(collection);\n\tinsertImage('med-'+attributes.image_de_environment, location, " . $args['Environment_Image_Ratio'] . ", false);\n\tjQuery('<div class=\"collection-photoreel\"></div>').attr('collID', attributes.collection_id).appendTo(collection);\n\tvar displayButtonContainer = jQuery('<div class=\"collection-buttons\"></div>').appendTo(collection);\n\tjQuery('<div class=\"ui-state-default ui-corner-all display-button\">" . lang::get('LANG_Display') . "</div>').click(function(){\n\t\tloadCollection(jQuery(this).data('value'), jQuery(this).data('index'));\n\t}).appendTo(displayButtonContainer).data('value',attributes.collection_id).data('index',index);\n\tif(attributes.datedebut == attributes.datefin){\n\t  jQuery('<p class=\"collection-date\">'+convertDate(attributes.datedebut,false)+'</p>').appendTo(details);\n    } else {\n\t  jQuery('<p class=\"collection-date\">'+convertDate(attributes.datedebut,false)+' - '+convertDate(attributes.datefin,false)+'</p>').appendTo(details);\n    }\n\tjQuery('<p class=\"collection-name\">'+attributes.nom+'</p>').appendTo(details);\n\tvar locality = jQuery('<p  class=\"collection-locality\"></p>').appendTo(details);\n\tvar scope = {target: locality};\n\tinseeProtocol.read({filter: filter, callback: fillLocationDetails, scope: scope});\n\tjQuery.getJSON(\"" . $svcUrl . "/data/sample?mode=json&view=detail&nonce=" . $readAuth['nonce'] . "&auth_token=" . $readAuth['auth_token'] . "\" + (first ? \"&reset_timeout=true\" : \"\") + \"&callback=?&parent_id=\"+attributes.collection_id,\n        function(sessiondata) {\n\t\t  if(!(sessiondata instanceof Array)){\n   \t\t\talertIndiciaError(sessiondata);\n   \t\t  } else for (var i=0;i<sessiondata.length;i++){\n   \t\t  \tvar photoreel = jQuery('.collection-photoreel').filter('[collID='+sessiondata[i].parent_id+']');\n   \t\t  \tjQuery('<span class=\"photoreel-session\"></span>').attr('sessID', sessiondata[i].id).appendTo(photoreel);\n\t\t\t\$.getJSON(\"" . $svcUrl . "/data/occurrence/\" +\n\t\t\t\t\t\"?mode=json&view=detail&nonce=" . $readAuth['nonce'] . "&auth_token=" . $readAuth['auth_token'] . "&orderby=id\" +\n\t\t\t\t\t\"&sample_id=\"+sessiondata[i].id+\"&deleted=f&callback=?\", function(insectData) {\n\t\t    \tif(!(insectData instanceof Array)){\n   \t\t\t\t\talertIndiciaError(insectData);\n   \t\t\t\t} else if (insectData.length>0) {\n \t\t\t\t\tfor (var j=0;j<insectData.length;j++){\n\t\t\t\t\t\tvar container = jQuery('<div/>').addClass('thumb').attr('occID', insectData[j].id.toString()).data('collectionIndex',index).click(function () {\n\t\t\t\t\t\t\tloadInsect(jQuery(this).attr('occID'),jQuery(this).data('collectionIndex'),null,'P');\n\t\t\t\t\t\t});\n\t\t\t\t\t\tjQuery('<span>" . lang::get('LANG_Unknown') . "</span>').addClass('thumb-text').appendTo(container);\n\t\t\t\t\t\tjQuery('.photoreel-session').filter('[sessID='+insectData[j].sample_id+']').append(container);\n\t\t\t\t\t\t\$.getJSON(\"" . $svcUrl . "/data/occurrence_image\" +\n\t\t\t\t\t   \t\t\t\"?mode=json&view=list&nonce=" . $readAuth['nonce'] . "&auth_token=" . $readAuth['auth_token'] . "\" +\n   \t\t\t\t\t\t\t\t\"&occurrence_id=\" + insectData[j].id + \"&callback=?\", function(imageData) {\n\t\t\t\t\t\t\t  if(!(imageData instanceof Array)){\n   \t\t\t\t\t\t\t\talertIndiciaError(imageData);\n   \t\t\t\t\t\t\t  } else if (imageData.length>0) {\n\t\t\t\t\t\t      \tvar container = jQuery('.thumb').filter('[occID='+imageData[0].occurrence_id.toString()+']');\n\t\t\t\t\t\t\t    var img = new Image();\n\t\t\t\t\t\t\t    // thumbs are fixed in size, and small - dont worry about ratios\n\t\t\t\t\t\t\t\tjQuery(img).attr('src', '" . data_entry_helper::$base_url . data_entry_helper::$indicia_upload_path . "thumb-'+imageData[0].path)\n\t\t\t    \t\t\t\t\t.attr('width', container.width()).attr('height', container.height()).addClass('thumb-image').appendTo(container);\n\t\t\t\t\t\t\t  }}); \n\t\t\t\t\t\t\$.getJSON(\"" . $svcUrl . "/data/determination\" + \n\t\t\t\t\t    \t\t\"?mode=json&view=list&nonce=" . $readAuth['nonce'] . "&auth_token=" . $readAuth['auth_token'] . "\" + \n\t\t\t\t\t    \t\t\"&occurrence_id=\" + insectData[j].id + \"&orderby=id&deleted=f&callback=?\", function(detData) {\n\t\t\t\t\t\t      if(!(detData instanceof Array)){\n   \t\t\t\t\t\t\t\talertIndiciaError(detData);\n   \t\t\t\t\t\t\t  } else if (detData.length>0) {\n\t\t\t\t\t\t        var container = jQuery('.thumb').filter('[occID='+detData[0].occurrence_id.toString()+']');\n\t\t\t\t\t\t        if(detData[detData.length-1].determination_type == 'B' || detData[detData.length-1].determination_type == 'I' || detData[detData.length-1].determination_type == 'U'){\n\t\t\t\t\t\t        \tcontainer.find('.thumb-text').remove();\n\t\t\t\t\t\t        \tjQuery('<span>" . lang::get('LANG_Dubious') . "</span>').addClass('thumb-text').appendTo(container);\n\t\t\t\t\t\t\t  \t} else {\n\t\t\t\t\t\t\t\t\tcontainer.find('.thumb-text').remove();\n\t\t\t\t\t\t\t  \t}\n  \t\t\t\t\t\t}});  \t\t\t\t\t\n\t\t\t\t\t}\n\t\t\t\t}});\n\t\t}});\n};\naddInsect = function(index, attributes, endOfRow, first){\n\tvar container=jQuery('<div class=\"ui-widget-content ui-corner-all filter-insect\" />').attr('occID',attributes.insect_id).appendTo('#results-insects-results');\n\tif(endOfRow) container.addClass('end-of-row');\n\tjQuery('<div />').addClass('insect-unknown').appendTo(container); // flag\n\tvar insect = jQuery('<div class=\"insect-image empty\" />').data('occID',attributes.insect_id).data('insectIndex',index).click(function(){\n\t\tloadInsect(jQuery(this).data('occID'), null, jQuery(this).data('insectIndex'), 'S');\n\t});\n\tinsect.appendTo(container);\n\tjQuery('<div class=\"insect-determinationX empty\" />').attr('occID',attributes.insect_id).appendTo(container).append(\"<p>" . lang::get('LANG_No_Determinations') . "</p>\");\n\tinsertImage('med-'+attributes.image_d_insecte, insect, " . $args['Insect_Image_Ratio'] . ", function(img){\n\t\t\tvar group = jQuery('#results-insects-results').find('.filter-insect');\n\t\t\tjQuery(img).parent().removeClass('empty');\n\t\t\tif(group.find('.empty').length == 0){\n\t\t\t\tvar tallest = 0;\n\t\t\t\tgroup.each(function(){ tallest = Math.max(\$(this).height(), tallest); });\n\t\t\t\tgroup.each(function(){ \$(this).height(Math.max(\$(this).height(), tallest)); }); // have synchronicity problems.\n\t\t\t}\n\t\t});\n\tjQuery.ajax({\n\t\turl: \"" . $svcUrl . "/data/determination?mode=json&view=list&nonce=" . $readAuth['nonce'] . "&auth_token=" . $readAuth['auth_token'] . "\" + (first ? \"&reset_timeout=true\" : \"\") + \"&orderby=id&callback=?&occurrence_id=\" + attributes.insect_id,\n\t\tdataType: 'json',\n\t\tmyID: attributes.insect_id,\n\t\tsuccess: function(detData) {\n   \t\t  if(!(detData instanceof Array)){\n   \t\t\talertIndiciaError(detData);\n   \t\t  } else {\n   \t\t   if (detData.length>0) {\n\t\t\tvar i = detData.length-1;\n   \t\t\tvar string = '';\n\t\t\tvar determination = jQuery('.insect-determinationX').filter('[occID='+detData[i].occurrence_id+']').empty();\n\t\t\tvar flag = determination.parent().find('.insect-unknown');\n\t\t\tif(detData[i].taxon != '' && detData[i].taxon != null){\n\t\t\t\tstring = detData[i].taxon;\n\t\t\t}\n\t\t\tif(detData[i].taxa_taxon_list_id_list != '' && detData[i].taxa_taxon_list_id_list != null && detData[i].taxa_taxon_list_id_list != '{}'){\n\t\t\t\tdetData[i].taxa_taxon_list_id_list;\n\t\t\t\tvar resultsIDs = detData[i].taxa_taxon_list_id_list.substring(1, detData[i].taxa_taxon_list_id_list.length - 1).split(',');\n\t\t\t\tif(resultsIDs[0] != '') {\n\t\t\t\t\tfor(var j=0; j < resultsIDs.length; j++){\n\t\t\t\t\t\tfor(var k = 0; k< insectTaxa.length; k++){\n\t\t\t\t\t\t\tif(insectTaxa[k].id == resultsIDs[j]){\n\t\t\t\t\t\t\t\tstring = (string == '' ? '' : string + ', ') + insectTaxa[k].taxon;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t};\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tjQuery('<p>'+string+'</p>').appendTo(determination)\n\t\t\tif(detData[i].determination_type == 'B' || detData[i].determination_type == 'I' || detData[i].determination_type == 'U'){\n\t\t\t\tflag.removeClass('insect-unknown').addClass('insect-dubious');\n\t\t\t} else \n\t\t\t\tflag.removeClass('insect-unknown').addClass('insect-ok');\n\t\t   }\n\t\t   var group = jQuery('#results-insects-results').find('.filter-insect');\n\t\t   group.filter('[occID='+this.myID+']').find('.insect-determinationX').removeClass('empty');\n\t\t   if(group.find('.empty').length == 0){\n\t\t\t\tvar tallest = 0;\n\t\t\t\tgroup.each(function(){ tallest = Math.max(\$(this).height(), tallest); });\n\t\t\t\tgroup.each(function(){ \$(this).height(Math.max(\$(this).height(), tallest)); }); // have synchronicity problems.\n\t\t   \n  \t\t  }}\n\t}});\n\tjQuery('<div class=\"ui-state-default ui-corner-all display-button\">" . lang::get('LANG_Display') . "</div>').click(function(){\n\t\tloadInsect(jQuery(this).attr('occID'), null, jQuery(this).data('insectIndex'), 'S');\n\t}).appendTo(container).attr('occID',attributes.insect_id).data('insectIndex',index);\n};\n\n\nsetCollectionPage = function(pageNum){\n\tvar no_units = 4;\n\tvar no_tens = 2;\n\tvar no_hundreds = 1;\n\tjQuery('#results-collections-results').empty();\n\tvar numPages = Math.ceil(searchResults.features.length/" . $args['collectionsPerPage'] . ");\n\tif(numPages > 1) {\n\t\tvar item;\n\t\tvar itemList = jQuery('<div class=\"item-list\"></div>').appendTo('#results-collections-results');\n\t\tvar pageCtrl = jQuery('<ul>').addClass('pager').appendTo(itemList);\n\t\tfor (var j = pageNum - no_units; j<= pageNum + no_units; j++){\n\t\t\tif(j <= numPages && j >= 1){\n\t\t\t\tif(j == pageNum)\n\t\t\t\t\tjQuery('<li class=\"pager-current\">'+pageNum+'</li>').appendTo(pageCtrl);\n\t\t\t\telse {\n\t\t\t\t\titem = jQuery('<li class=\"pager-item\"></li>').attr('value',j).click(function(){setCollectionPage(jQuery(this).attr('value'))}).appendTo(pageCtrl);\n\t\t\t\t\tjQuery('<a class=\"active\">'+j+'</a>').appendTo(item);\n\t\t\t\t}\n  \t\t\t}\n\t\t}\n\t\tvar start = Math.ceil(j/10)*10;\n\t\tfor (j = start; j< start + no_tens*10; j=j+10){\n\t\t\tif(j <= numPages){\n\t\t\t\titem = jQuery('<li class=\"pager-item\"></li>').attr('value',j).click(function(){setCollectionPage(jQuery(this).attr('value'))}).appendTo(pageCtrl);\n\t\t\t\tjQuery('<a class=\"active\">'+j+'</a>').appendTo(item);\n\t\t\t}\n\t\t}\n\t\tstart = Math.ceil(j/100)*100;\n\t\tfor (j = start; j< start + no_hundreds*100; j=j+100){\n\t\t\tif(j <= numPages){\n\t\t\t\titem = jQuery('<li class=\"pager-item\"></li>').attr('value',j).click(function(){setCollectionPage(jQuery(this).attr('value'))}).appendTo(pageCtrl);\n\t\t\t\tjQuery('<a class=\"active\">'+j+'</a>').appendTo(item);\n\t\t\t}\n\t\t}\n\t\tif(pageNum != numPages){\n\t\t\titem = jQuery('<li class=\"pager-next\"></li>').attr('value',pageNum+1).click(function(){setCollectionPage(jQuery(this).attr('value'))}).appendTo(pageCtrl);\n\t\t\tjQuery('<a class=\"active\">&nbsp;</a>').appendTo(item);\n  \t\t\titem = jQuery('<li class=\"pager-last\"></li>').attr('value',numPages).click(function(){setCollectionPage(jQuery(this).attr('value'))}).appendTo(pageCtrl);\n\t\t\tjQuery('<a class=\"active\">'+numPages+'</a>').appendTo(item);\n  \t\t}\n\t\tstart = Math.floor((pageNum - no_units -1)/10)*10;\n\t\tfor (j = start; j> start - no_tens*10; j=j-10){\n\t\t\tif(j >= 1){\n\t\t\t\titem = jQuery('<li class=\"pager-item\"></li>').attr('value',j).click(function(){setCollectionPage(jQuery(this).attr('value'))}).prependTo(pageCtrl);\n\t\t\t\tjQuery('<a class=\"active\">'+j+'</a>').appendTo(item);\n\t\t\t}\n\t\t}\n\t\tstart = Math.floor(j/100)*100;\n\t\tfor (j = start; j> start - no_hundreds*100; j=j-100){\n\t\t\tif(j >= 1){\n\t\t\t\titem = jQuery('<li class=\"pager-item\"></li>').attr('value',j).click(function(){setCollectionPage(jQuery(this).attr('value'))}).prependTo(pageCtrl);\n\t\t\t\tjQuery('<a class=\"active\">'+j+'</a>').appendTo(item);\n\t\t\t}\n\t\t}\n\t\tif(pageNum != 1){\n\t\t\titem = jQuery('<li class=\"pager-previous\"></li>').attr('value',pageNum-1).click(function(){setCollectionPage(jQuery(this).attr('value'))}).prependTo(pageCtrl);\n\t\t\tjQuery('<a class=\"active\">&nbsp;</a>').appendTo(item);\n  \t\t\titem = jQuery('<li class=\"pager-first\"></li>').click(function(){setCollectionPage(1)}).prependTo(pageCtrl);\n\t\t\tjQuery('<a class=\"active\">&nbsp;</a>').appendTo(item);\n  \t\t}\n  \t\tpageCtrl.find('li').filter(':first').addClass('first');\n  \t\tpageCtrl.find('li').filter(':last').addClass('last');\n\t}\n    for (var i = (pageNum-1)*" . $args['collectionsPerPage'] . ", first = true; i < searchResults.features.length && i < pageNum*" . $args['collectionsPerPage'] . "; i++, first = false){\n\t\taddCollection(i, searchResults.features[i].attributes,searchResults.features[i].geometry, first);\n\t}\n\tif(numPages > 1) {\n\t\titemList.clone(true).appendTo('#results-collections-results');\n\t}\n}\nsetInsectPage = function(pageNum){\n\tjQuery('#results-insects-results').empty();\n\tvar numPages = Math.ceil(searchResults.features.length/(" . $args['insectsRowsPerPage'] . "*" . $args['insectsPerRow'] . "));\n\tvar no_units = 4;\n\tvar no_tens = 2;\n\tvar no_hundreds = 1;\n\tif(numPages > 1) {\n\t\tvar item;\n\t\tvar itemList = jQuery('<div class=\"item-list\"></div>').appendTo('#results-insects-results');\n\t\tvar pageCtrl = jQuery('<ul>').addClass('pager').appendTo(itemList);\n\t\tfor (var j = pageNum - no_units; j<= pageNum + no_units; j++){\n\t\t\tif(j <= numPages && j >= 1){\n\t\t\t\tif(j == pageNum)\n\t\t\t\t\tjQuery('<li class=\"pager-current\">'+pageNum+'</li>').appendTo(pageCtrl);\n\t\t\t\telse {\n\t\t\t\t\titem = jQuery('<li class=\"pager-item\"></li>').attr('value',j).click(function(){setInsectPage(jQuery(this).attr('value'))}).appendTo(pageCtrl);\n\t\t\t\t\tjQuery('<a class=\"active\">'+j+'</a>').appendTo(item);\n\t\t\t\t}\n  \t\t\t}\n\t\t}\n\t\tvar start = Math.ceil(j/10)*10;\n\t\tfor (j = start; j< start + no_tens*10; j=j+10){\n\t\t\tif(j <= numPages){\n\t\t\t\titem = jQuery('<li class=\"pager-item\"></li>').attr('value',j).click(function(){setInsectPage(jQuery(this).attr('value'))}).appendTo(pageCtrl);\n\t\t\t\tjQuery('<a class=\"active\">'+j+'</a>').appendTo(item);\n\t\t\t}\n\t\t}\n\t\tstart = Math.ceil(j/100)*100;\n\t\tfor (j = start; j< start + no_hundreds*100; j=j+100){\n\t\t\tif(j <= numPages){\n\t\t\t\titem = jQuery('<li class=\"pager-item\"></li>').attr('value',j).click(function(){setInsectPage(jQuery(this).attr('value'))}).appendTo(pageCtrl);\n\t\t\t\tjQuery('<a class=\"active\">'+j+'</a>').appendTo(item);\n\t\t\t}\n\t\t}\n\t\tif(pageNum != numPages){\n\t\t\titem = jQuery('<li class=\"pager-next\"></li>').attr('value',pageNum+1).click(function(){setInsectPage(jQuery(this).attr('value'))}).appendTo(pageCtrl);\n\t\t\tjQuery('<a class=\"active\">&nbsp;</a>').appendTo(item);\n  \t\t\titem = jQuery('<li class=\"pager-last\"></li>').attr('value',numPages).click(function(){setInsectPage(jQuery(this).attr('value'))}).appendTo(pageCtrl);\n\t\t\tjQuery('<a class=\"active\">'+numPages+'</a>').appendTo(item);\n  \t\t}\n\t\tstart = Math.floor((pageNum - no_units -1)/10)*10;\n\t\tfor (j = start; j> start - no_tens*10; j=j-10){\n\t\t\tif(j >= 1){\n\t\t\t\titem = jQuery('<li class=\"pager-item\"></li>').attr('value',j).click(function(){setInsectPage(jQuery(this).attr('value'))}).prependTo(pageCtrl);\n\t\t\t\tjQuery('<a class=\"active\">'+j+'</a>').appendTo(item);\n\t\t\t}\n\t\t}\n\t\tstart = Math.floor(j/100)*100;\n\t\tfor (j = start; j> start - no_hundreds*100; j=j-100){\n\t\t\tif(j >= 1){\n\t\t\t\titem = jQuery('<li class=\"pager-item\"></li>').attr('value',j).click(function(){setInsectPage(jQuery(this).attr('value'))}).prependTo(pageCtrl);\n\t\t\t\tjQuery('<a class=\"active\">'+j+'</a>').appendTo(item);\n\t\t\t}\n\t\t}\n\t\tif(pageNum != 1){\n\t\t\titem = jQuery('<li class=\"pager-previous\"></li>').attr('value',pageNum-1).click(function(){setInsectPage(jQuery(this).attr('value'))}).prependTo(pageCtrl);\n\t\t\tjQuery('<a class=\"active\">&nbsp;</a>').appendTo(item);\n  \t\t\titem = jQuery('<li class=\"pager-first\"></li>').click(function(){setInsectPage(1)}).prependTo(pageCtrl);\n\t\t\tjQuery('<a class=\"active\">&nbsp;</a>').appendTo(item);\n  \t\t}\n  \t\tpageCtrl.find('li').filter(':first').addClass('first');\n  \t\tpageCtrl.find('li').filter(':last').addClass('last');\n\t}\n    for (var i = (pageNum-1)*" . $args['insectsRowsPerPage'] . "*" . $args['insectsPerRow'] . ", first = true; i < searchResults.features.length && i < pageNum*" . $args['insectsRowsPerPage'] . "*" . $args['insectsPerRow'] . "; i++, first = false){\n\t\taddInsect(i, searchResults.features[i].attributes, (i+1)/" . $args['insectsPerRow'] . " == parseInt((i+1)/" . $args['insectsPerRow'] . "), first);\n\t}\n\tif(numPages > 1) {\n\t\titemList.clone(true).appendTo('#results-insects-results');\n\t}\n}\n\n// searchLayer in map is used for georeferencing.\n// map editLayer is switched off. TODO: need to switch off click control\nsearchLayer = null;\ninseeLayer = null;\npolygonLayer = null;     \nlocationLayer = null;\ninseeProtocol = new OpenLayers.Protocol.WFS({\n              url:  '" . str_replace("{HOST}", $_SERVER['HTTP_HOST'], $args['INSEE_url']) . "',\n              featurePrefix: '" . $args['INSEE_prefix'] . "',\n              featureType: '" . $args['INSEE_type'] . "',\n              geometryName:'the_geom',\n              featureNS: '" . $args['INSEE_ns'] . "',\n              srsName: 'EPSG:900913',\n              version: '1.1.0'                  \n      \t\t  ,propertyNames: ['NOM', 'INSEE_NEW', 'DEPT_NUM', 'DEPT_NOM', 'REG_NUM', 'REG_NOM']\n});\n\n\nflowerIDstruc = {\n\ttype: 'flower',\n\tmainForm: 'form#fo-new-flower-id-form',\n\ttimeOutTimer: null,\n\tpollTimer: null,\n\tpollFile: '',\n\tinvokeURL: '" . $args['ID_tool_flower_url'] . "',\n\tpollURL: '" . str_replace("{HOST}", $_SERVER['HTTP_HOST'], $args['ID_tool_flower_poll_dir']) . "',\n\tname: 'flowerIDstruc',\n\tdeterminationType: '" . (user_access('IForm n' . $node->nid . ' flower expert') ? 'C' : 'A') . "',\n\ttaxaList: flowerTaxa\n};\n\ntoolPoller = function(toolStruct){\n\tif(toolStruct.pollFile == '') return;\n\ttoolStruct.pollTimer = setTimeout('toolPoller('+toolStruct.name+');', " . $args['ID_tool_poll_interval'] . ");\n\tjQuery.ajax({\n\t url: toolStruct.pollURL+toolStruct.pollFile,\n\t toolStruct: toolStruct,\n\t success: function(data){\n\t  pollReset(this.toolStruct);\n\t  var da = data.split('\\n');\n      jQuery(this.toolStruct.mainForm+' [name=determination\\:taxon_details]').val(da[2]); // Stores the state of identification, which details how the identification was arrived at within the tool.\n\t  da[1] = da[1].replace(/\\\\\\\\i\\{\\}/g, '').replace(/\\\\\\\\i0\\{\\}/g, '').replace(/\\\\/g, '');\n\t  var items = da[1].split(':');\n\t  var count = items.length;\n\t  if(items[count-1] == '') count--;\n\t  if(items[count-1] == '') count--;\n\t  if(count <= 0){\n\t  \t// no valid stuff so blank it all out.\n\t  \tjQuery('#'+this.toolStruct.type+'_taxa_list').append(\"" . lang::get('LANG_Taxa_Unknown_In_Tool') . "\");\n\t  \tjQuery(this.toolStruct.mainForm+' [name=determination\\:determination_type]').val('X'); // Unidentified.\n      } else {\n      \tvar resultsIDs = [];\n      \tvar resultsText = \"" . lang::get('LANG_Taxa_Returned') . "<br />{ \";\n      \tvar notFound = '';\n\t\tfor(var j=0; j < count; j++){\n\t\t\tvar found = false;\n\t\t\titemText = items[j].replace(/</g, '&lt;').replace(/>/g, '&gt;');\n\t\t\tfor(i = 0; i< this.toolStruct.taxaList.length; i++){\n\t\t\t\tif(this.toolStruct.taxaList[i].taxon == itemText){\n\t\t\t\t\tresultsIDs.push(this.toolStruct.taxaList[i].id);\n\t\t\t\t\tresultsText = resultsText + (j == 0 ? '' : '<br />&nbsp;&nbsp;') + itemText;\n\t\t\t\t\tfound = true;\n  \t\t\t\t}\n  \t\t\t};\n  \t\t\tif(!found){\n  \t\t\t\tnotFound = (notFound == '' ? '' : notFound + ', ') + itemText;\n  \t\t\t}\n  \t\t}\n\t\tjQuery('#'+this.toolStruct.type+'_taxa_list').append(resultsText+ ' }');\n\t\tjQuery('#'+this.toolStruct.type+'-id-button').data('toolRetValues', resultsIDs);\n\t  \tif(notFound != ''){\n\t\t\tvar comment = jQuery(this.toolStruct.mainForm+' [name=determination\\:comment]');\n\t\t\tcomment.val('" . lang::get('LANG_ID_Unrecognised') . " '+notFound+' '+comment.val());\n\t\t}\n  \t  }\n  \t }\n    });\n};\n\npollReset = function(toolStruct){\n\tclearTimeout(toolStruct.timeOutTimer);\n\tclearTimeout(toolStruct.pollTimer);\n\tjQuery('#'+toolStruct.type+'-id-cancel').hide();\n\tjQuery('#'+toolStruct.type+'-id-button').show();\n\ttoolStruct.pollFile='';\n\ttoolStruct.timeOutTimer = null;\n\ttoolStruct.pollTimer = null;\n};\n\nidButtonPressed = function(toolStruct){\n\tjQuery(toolStruct.mainForm+' [name=determination\\:determination_type]').val(toolStruct.determinationType);\n\tjQuery('#'+toolStruct.type+'-id-button').data('toolRetValues', []);\n\tjQuery(toolStruct.mainForm+' [name=determination\\:taxon_details]').val('');\n\tjQuery('#'+toolStruct.type+'_taxa_list').empty();\n\tjQuery(toolStruct.mainForm+' [name=determination\\:taxa_taxon_list_id]').val('');\n\tjQuery('#'+toolStruct.type+'-id-cancel').show();\n\tjQuery('#'+toolStruct.type+'-id-button').hide();\n\tvar d = new Date;\n\tvar s = d.getTime();\n\ttoolStruct.pollFile = '" . session_id() . "_'+s.toString()\n\tclearTimeout(toolStruct.timeOutTimer);\n\tclearTimeout(toolStruct.pollTimer);\n\twindow.open(toolStruct.invokeURL+toolStruct.pollFile,'','');\n\ttoolStruct.pollTimer = setTimeout('toolPoller('+toolStruct.name+');', " . $args['ID_tool_poll_interval'] . ");\n\ttoolStruct.timeOutTimer = setTimeout('toolReset('+toolStruct.name+');', " . $args['ID_tool_poll_timeout'] . ");\n};\njQuery('#flower-id-button').click(function(){\n\tidButtonPressed(flowerIDstruc);\n});\njQuery('#flower-id-cancel').click(function(){\n\tpollReset(flowerIDstruc);\n});\n\njQuery('#flower-id-cancel').hide();\n\ntaxonChosen = function(toolStruct){\n\tjQuery('#'+toolStruct.type+'-id-button').data('toolRetValues', []);\n\tjQuery(toolStruct.mainForm+' [name=determination\\:taxon_details]').val('');\n\tjQuery('#'+toolStruct.type+'_taxa_list').empty();\n\tjQuery(toolStruct.mainForm+' [name=determination\\:comment]').val('');\n  \tjQuery(toolStruct.mainForm+' [name=determination\\:determination_type]').val(toolStruct.determinationType);\n};\njQuery('form#fo-new-flower-id-form select[name=determination\\:taxa_taxon_list_id]').change(function(){\n\tpollReset(flowerIDstruc);\n\ttaxonChosen(flowerIDstruc);\n});\n\ninsectIDstruc = {\n\ttype: 'insect',\n\tmainForm: 'form#fo-new-insect-id-form',\n\ttimeOutTimer: null,\n\tpollTimer: null,\n\tpollFile: '',\n\tinvokeURL: '" . $args['ID_tool_insect_url'] . "',\n\tpollURL: '" . str_replace("{HOST}", $_SERVER['HTTP_HOST'], $args['ID_tool_insect_poll_dir']) . "',\n\tname: 'insectIDstruc',\n\tdeterminationType: '" . (user_access('IForm n' . $node->nid . ' insect expert') ? 'C' : 'A') . "',\n\ttaxaList: insectTaxa\n};\n\njQuery('#insect-id-button').click(function(){\n\tidButtonPressed(insectIDstruc);\n});\njQuery('#insect-id-cancel').click(function(){\n\tpollReset(insectIDstruc);\n});\njQuery('#insect-id-cancel').hide();\njQuery('form#fo-new-insect-id-form select[name=determination\\:taxa_taxon_list_id]').change(function(){\n\tpollReset(insectIDstruc);\n\ttaxonChosen(insectIDstruc);\n});\n\njQuery('#search-insee-button').click(function(){\n\tif(inseeLayer != null)\n\t\tinseeLayer.destroy();\n\tpolygonLayer.map.searchLayer.destroyFeatures();\n\tpolygonLayer.destroyFeatures();\n\tvar filters = [];\n  \tvar place = jQuery('input[name=place\\:INSEE]').val();\n  \tif(place == '" . lang::get('LANG_INSEE') . "') return;\n  \tfilters.push(new OpenLayers.Filter.Comparison({\n  \t\t\ttype: OpenLayers.Filter.Comparison.EQUAL_TO ,\n    \t\tproperty: 'INSEE_NEW',\n    \t\tvalue: place\n  \t\t}));\n  \tfilters.push(new OpenLayers.Filter.Comparison({\n  \t\t\ttype: OpenLayers.Filter.Comparison.EQUAL_TO ,\n    \t\tproperty: 'INSEE_OLD',\n    \t\tvalue: place\n  \t\t}));\n\n\tvar strategy = new OpenLayers.Strategy.Fixed({preload: false, autoActivate: false});\n\tvar styleMap = new OpenLayers.StyleMap({\n                \"default\": new OpenLayers.Style({\n                    fillColor: \"Red\",\n                    strokeColor: \"Red\",\n                    fillOpacity: 0,\n                    strokeWidth: 1\n                  })\n\t});\n\tinseeLayer = new OpenLayers.Layer.Vector('INSEE Layer', {\n\t\t  styleMap: styleMap,\n          strategies: [strategy],\n          displayInLayerSwitcher: false,\n\t      protocol: new OpenLayers.Protocol.WFS({\n              url:  '" . str_replace("{HOST}", $_SERVER['HTTP_HOST'], $args['INSEE_url']) . "',\n\t          featurePrefix: '" . $args['INSEE_prefix'] . "',\n              featureType: '" . $args['INSEE_type'] . "',\n              geometryName:'the_geom',\n              featureNS: '" . $args['INSEE_ns'] . "',\n              srsName: 'EPSG:900913',\n              version: '1.1.0'                  \n      \t\t  ,propertyNames: ['the_geom']\n  \t\t\t})\n    });\n\tinseeLayer.events.register('featuresadded', {}, function(a1){\n\t\tvar div = jQuery('#map')[0];\n\t\tdiv.map.searchLayer.destroyFeatures();\n\t\tvar bounds=inseeLayer.getDataExtent();\n    \tvar dy = (bounds.top-bounds.bottom)/10;\n    \tvar dx = (bounds.right-bounds.left)/10;\n    \tbounds.top = bounds.top + dy;\n    \tbounds.bottom = bounds.bottom - dy;\n    \tbounds.right = bounds.right + dx;\n    \tbounds.left = bounds.left - dx;\n    \t// if showing a point, don't zoom in too far\n    \tif (dy===0 && dx===0) {\n    \t\tdiv.map.setCenter(bounds.getCenterLonLat(), div.settings.maxZoom);\n    \t} else {\n    \t\tdiv.map.zoomToExtent(bounds);\n    \t}\n    });\n\tinseeLayer.events.register('loadend', {}, function(){\n\t\tif(inseeLayer.features.length == 0){\n\t\t\talert(\"" . lang::get('LANG_NO_INSEE') . "\");\n\t\t}\n    });\n    jQuery('#map')[0].map.addLayer(inseeLayer);\n\tstrategy.load({filter: new OpenLayers.Filter.Logical({\n\t\t\t      type: OpenLayers.Filter.Logical.OR,\n\t\t\t      filters: filters\n\t\t  \t  })});\n});\n\njQuery('#search-collections-button').click(function(){\n\tjQuery('#results-insects-header,#results-insects-results').hide();\n\tjQuery('#results-collections-header,#results-collections-results').show();\n\tjQuery('#results-collections-header').addClass('ui-state-active').removeClass('ui-state-default');\n\trunSearch(true);\n});\njQuery('#search-insects-button').click(function(){\n\tjQuery('#results-collections-header,#results-collections-results').hide();\n\tjQuery('#results-insects-header,#results-insects-results').show();\n\tjQuery('#results-insects-header').addClass('ui-state-active').removeClass('ui-state-default');\n\trunSearch(false);\n});\n\ncombineOR = function(ORgroup){\n\tif(ORgroup.length > 1){\n\t\treturn new OpenLayers.Filter.Logical({\n\t\t\t\ttype: OpenLayers.Filter.Logical.OR,\n\t\t\t\tfilters: ORgroup\n\t\t\t});\n\t}\n\treturn ORgroup[0];\n};\n\nencodeMap = function(){\n\tvar features = [];\n\tif(inseeLayer != null && inseeLayer.features.length > 0)\n\t\tfeatures = inseeLayer.features;\n\telse if(polygonLayer != null && polygonLayer.features.length > 0)\n\t\tfeatures = polygonLayer.features\n\telse {\n\t\tvar mapBounds = jQuery('#map')[0].map.getExtent();\n\t\tvar feature = new OpenLayers.Feature.Vector(mapBounds.toGeometry());\n\t\tfeatures = [feature];\n\t}\n      var format=new OpenLayers.Format.GML.v2({featureName: 'user', featureType: 'user',\n          featureNS: 'user', featurePrefix: 'user'});\n      return format.write(features);\n    }\n\ndecodeMap = function(string){\n      var format=new OpenLayers.Format.GML.v2({featureName: 'user', featureType: 'user',\n          featureNS: 'user', featurePrefix: 'user'});\n      var features=format.read(string);\n\tif(inseeLayer != null) inseeLayer.destroyFeatures();\n\tif(polygonLayer!= null) polygonLayer.destroyFeatures();\n\tvar div = jQuery('#map')[0];\n\tdiv.map.searchLayer.destroyFeatures();\n\tpolygonLayer.addFeatures(features, {});\n\tvar bounds= polygonLayer.getDataExtent();\n    div.map.zoomToExtent(bounds);\n\n}\n    \nrunSearch = function(forCollections){\n  \tvar ORgroup = [];\n  \tif(searchLayer != null)\n\t\tsearchLayer.destroy();\n    jQuery('#results-collections-results,#results-insects-results').empty();\n\tjQuery('#focus-occurrence,#focus-collection').hide();\n\tvar filters = [];\n\n\t// By default restrict selection to area displayed on map. When using the georeferencing system the map searchLayer\n\t// will contain a single point zoomed in appropriately.\n\tvar mapBounds = jQuery('#map')[0].map.getExtent();\n\tif (mapBounds != null) filters.push(new OpenLayers.Filter.Spatial({type: OpenLayers.Filter.Spatial.BBOX, property: 'geom', value: mapBounds}));\n\t// should only be one entry in the inseeLayer\n\tif(inseeLayer != null)\n  \t\tif(inseeLayer.features.length > 0)\n\t\t\tfilters.push(new OpenLayers.Filter.Spatial({type: OpenLayers.Filter.Spatial.WITHIN, property: 'geom',value: inseeLayer.features[0].geometry}));\n\tif(polygonLayer != null)\n  \t\tif(polygonLayer.features.length > 0){\n  \t\t\tORgroup = [];\n  \t\t\tfor(i=0; i< polygonLayer.features.length; i++)\n\t\t\t\tORgroup.push(new OpenLayers.Filter.Spatial({type: OpenLayers.Filter.Spatial.WITHIN, property: 'geom', value: polygonLayer.features[i].geometry}));\n\t\t  \tif(ORgroup.length >= 1) filters.push(combineOR(ORgroup));\n\t\t}\n\n  \t// filters.push(new OpenLayers.Filter.Comparison({type: OpenLayers.Filter.Comparison.EQUAL_TO, property: 'survey_id', value: '" . $args['survey_id'] . "' }));\n\n  \tvar user = jQuery('input[name=username]').val();\n  \tif(user != '') filters.push(new OpenLayers.Filter.Comparison({type: OpenLayers.Filter.Comparison.LIKE, property: 'username', value: user}));\n  \tvar start_date = jQuery('input[name=real_start_date]').val();\n  \tvar end_date = jQuery('input[name=real_end_date]').val();\n  \tif(start_date != '" . lang::get('click here') . "' && start_date != '')\n  \t\tfilters.push(new OpenLayers.Filter.Comparison({type: OpenLayers.Filter.Comparison.GREATER_THAN_OR_EQUAL_TO, property: 'datefin', value: start_date}));\n  \tif(end_date != '" . lang::get('click here') . "' && end_date != '')\n  \t\tfilters.push(new OpenLayers.Filter.Comparison({type: OpenLayers.Filter.Comparison.LESS_THAN_OR_EQUAL_TO, property: 'datedebut', value: end_date}));\n \t\n  \tvar flower = jQuery('select[name=flower\\:taxa_taxon_list_id]').val();\n  \tif(flower != '') filters.push(new OpenLayers.Filter.Comparison({type: OpenLayers.Filter.Comparison.LIKE, property: 'flower_taxon_ids', value: '*|'+flower+'|*'}));\n  \tflower = jQuery('[name=flower\\:taxon_extra_info]').val();\n  \tif(flower != '' && flower != '" . lang::get('LANG_More_Precise') . "')\n  \t\tfilters.push(new OpenLayers.Filter.Comparison({type: OpenLayers.Filter.Comparison.LIKE, property: 'taxons_fleur_precise', value: '*'+flower+'*' }));\n\n  \tORgroup = [];\n  \tjQuery('#flower-filter-body').find('[name^=occAttr:" . $args['flower_type_attr_id'] . "]').filter('[checked]').each(function(index, elem){\n  \t\tORgroup.push(new OpenLayers.Filter.Comparison({type: OpenLayers.Filter.Comparison.EQUAL_TO, property: 'flower_type_id', value: elem.value}));\n  \t});\n  \tif(ORgroup.length >= 1) filters.push(combineOR(ORgroup));\n  \tORgroup = [];\n  \tjQuery('#flower-filter-body').find('[name^=locAttr:" . $args['habitat_attr_id'] . "]').filter('[checked]').each(function(index, elem){\n  \t\tORgroup.push(new OpenLayers.Filter.Comparison({type: OpenLayers.Filter.Comparison.LIKE, property: 'habitat_ids', value: '*|'+elem.value+'|*'}));\n  \t});\n  \tif(ORgroup.length >= 1) filters.push(combineOR(ORgroup));\n\n  \tvar insect = jQuery('select[name=insect\\:taxa_taxon_list_id]').val();\n  \tif(insect != '') filters.push(new OpenLayers.Filter.Comparison({type: OpenLayers.Filter.Comparison.LIKE, property: 'insect_taxon_ids', value: '*|'+insect+'|*'}));\n  \tinsect = jQuery('[name=insect\\:taxon_extra_info]').val();\n  \tif(insect != '' && insect != '" . lang::get('LANG_More_Precise') . "')\n  \t\tfilters.push(new OpenLayers.Filter.Comparison({type: OpenLayers.Filter.Comparison.LIKE, property: 'taxons_insecte_precise', value: '*'+insect+'*'}));\n\n  \tORgroup = [];\n  \tjQuery('#conditions-filter-body').find('[name^=smpAttr:" . $args['sky_state_attr_id'] . "]').filter('[checked]').each(function(index, elem){\n  \t\tORgroup.push(new OpenLayers.Filter.Comparison({type: OpenLayers.Filter.Comparison.LIKE, property: 'sky_ids', value: '*|'+elem.value+'|*'}));\n  \t});\n  \tif(ORgroup.length >= 1) filters.push(combineOR(ORgroup));\n  \t\n  \tORgroup = [];\n  \tjQuery('#conditions-filter-body').find('[name^=smpAttr:" . $args['temperature_attr_id'] . "]').filter('[checked]').each(function(index, elem){\n  \t\tORgroup.push(new OpenLayers.Filter.Comparison({type: OpenLayers.Filter.Comparison.LIKE, property: 'temp_ids', value: '*|'+elem.value+'|*'}));\n  \t});\n  \tif(ORgroup.length >= 1) filters.push(combineOR(ORgroup));\n  \t\n  \tORgroup = [];\n  \tjQuery('#conditions-filter-body').find('[name^=smpAttr:" . $args['wind_attr_id'] . "]').filter('[checked]').each(function(index, elem){\n  \t\tORgroup.push(new OpenLayers.Filter.Comparison({type: OpenLayers.Filter.Comparison.LIKE, property: 'wind_ids', value: '*|'+elem.value+'|*'}));\n  \t});\n  \tif(ORgroup.length >= 1) filters.push(combineOR(ORgroup));\n  \t\n  \tORgroup = [];\n  \tjQuery('#conditions-filter-body').find('[name^=smpAttr:" . $args['shade_attr_id'] . "]').filter('[checked]').each(function(index, elem){\n  \t\tORgroup.push(new OpenLayers.Filter.Comparison({type: OpenLayers.Filter.Comparison.LIKE, property: 'shade_ids', value: '*|'+elem.value+'|*'}));\n  \t});\n  \tif(ORgroup.length >= 1) filters.push(combineOR(ORgroup));\n  \tif(forCollections){\n\t\tproperties = ['collection_id','datedebut','datefin','geom','nom','image_de_environment','image_de_la_fleur','flower_id']\n\t\tfeature = 'spipoll_collections_cache_view';\n  \t} else {\n  \t\tfeature = 'spipoll_insects_cache_view';\n  \t\tproperties = ['insect_id','collection_id','geom','image_d_insecte'];\n  \t}\n\tvar strategy = new OpenLayers.Strategy.Fixed({preload: false, autoActivate: false});\n\tsearchLayer = new OpenLayers.Layer.Vector('Search Layer', {\n          strategies: [strategy],\n          displayInLayerSwitcher: false,\n\t      protocol: new OpenLayers.Protocol.WFS({\n              url: '" . str_replace("{HOST}", $_SERVER['HTTP_HOST'], $args['search_url']) . "',\n              featurePrefix: '" . $args['search_prefix'] . "',\n              featureType: feature,\n              geometryName:'geom',\n              featureNS: '" . $args['search_ns'] . "',\n              srsName: 'EPSG:900913',\n              version: '1.1.0',   \n              maxFeatures: " . $args['max_features'] . ",\n              propertyNames: properties,\n              sortBy: 'datedebut' // not supported by Openlayers, so have to use orderby in a DB view.\n\t\t  })\n\t});\n\tif(forCollections) {\n\t\tjQuery('#results-collections-results').empty().append('<div class=\"collection-loading-panel\" ><img src=\"" . helper_config::$base_url . "media/images/ajax-loader2.gif\" />" . lang::get('loading') . "...</div>');\n\t\tsearchLayer.events.register('featuresadded', {}, function(a1){\n\t\t\tsearchResults = a1;\n\t\t\tsearchResults.type = 'C';\n\t\t\tif(searchResults.features.length >= " . $args['max_features'] . "){\n\t\t\t\talert(\"" . lang::get('LANG_Max_Features_Reached') . "\");\n\t\t\t}\n\t\t\tsetCollectionPage(1);\n\t\t});\n\t\tsearchLayer.events.register('loadend', {}, function(){\n\t\t\tif(searchLayer.features.length == 0){\n\t\t\t\tjQuery('#results-collections-results').empty().text('" . lang::get('LANG_No_Collection_Results') . "');\n\t\t\t}\n\t\t});\n\t} else {\n\t\tjQuery('#results-insects-results').empty().append('<div class=\"insect-loading-panel\" ><img src=\"" . helper_config::$base_url . "media/images/ajax-loader2.gif\" />" . lang::get('loading') . "...</div>');\n\t\tsearchLayer.events.register('featuresadded', {}, function(a1){\n\t\t\tsearchResults = a1;\n\t\t\tsearchResults.type = 'I';\n\t\t\tif(searchResults.features.length >= " . $args['max_features'] . "){\n\t\t\t\talert(\"" . lang::get('LANG_Max_Features_Reached') . "\");\n\t\t\t}\n\t\t\tsetInsectPage(1);\n\t\t});\n\t\tsearchLayer.events.register('loadend', {}, function(){\n\t\t\tif(searchLayer.features.length == 0){\n\t\t\t\tjQuery('#results-insects-results').empty().text('" . lang::get('LANG_No_Insect_Results') . "');\n\t\t\t}\n\t\t});\n\t}\n\tjQuery('#map')[0].map.addLayer(searchLayer);\n\tstrategy.load({filter: new OpenLayers.Filter.Logical({\n\t\t\t      type: OpenLayers.Filter.Logical.AND,\n\t\t\t      filters: filters\n\t\t  \t  })});\n};\n\nsearchResults = null;  \ncollection = '';\n\nerrorPos = null;\nclearErrors = function(formSel) {\n\tjQuery(formSel).find('.inline-error').remove();\n\terrorPos = null;\n};\n\nmyScrollToError = function(){\n\tjQuery('.inline-error,.error').filter(':visible').prev().each(function(){\n\t\tif(errorPos == null || jQuery(this).offset().top < errorPos){\n\t\t\terrorPos = jQuery(this).offset().top;\n\t\t\twindow.scroll(0,errorPos);\n\t\t}\n\t});\n};\n\nvalidateRequiredField = function(name, formSel){\n    var control = jQuery(formSel).find('[name='+name+']');\n    if(control.val() == '') {\n        var label = \$('<p/>')\n\t\t\t\t.attr({'for': name})\n\t\t\t\t.addClass('inline-error')\n\t\t\t\t.html(\$.validator.messages.required);\n\t\tlabel.insertBefore(control);\n\t\treturn false;\n    }\n    return true;\n}\n\nvar insect_alert_object = {\n\tinsect_id: null,\n\tinsect_image_path: null,\n\tdate: null,\n\tuser_id: null,\n\tcollection_user_id: null,\n\tdetails: []\n};\nvar flower_alert_object = {\n\tflower_id: null,\n\tflower_image_path: null,\n\tdate: null,\n\tuser_id: null,\n\tcollection_user_id: null,\n\tdetails: []\n};\n\nvar collection_preferred_object = {\n\tcollection_id: null,\n\tcollection_name: null,\n\tflower_id: null,\n\tflower_image_path: null,\n\tenvironment_image_path: null,\n\tdate: null,\n\tlocation_description: null,\n\tuser_id: null,\n\tinsects: []\n};\n\njQuery('form#fo-express-doubt-form').ajaxForm({\n\tasync: false,\n\tdataType:  'json', \n\tbeforeSubmit:   function(data, obj, options){\n\t\tif(!confirm(\"" . lang::get('LANG_Confirm_Express_Doubt') . "\")){\n\t\t\treturn FALSE;\n\t\t}\t\n\t\tvar toolValues = jQuery('#fo-doubt-button').data('toolRetValues');\n\t\tif(toolValues.length == 0)\n\t\t\tdata.push({name: 'determination\\:taxa_taxon_list_id_list[]', value: ''});\n\t\telse {\n\t\t\tfor(var i = 0; i<toolValues.length; i++){\n\t\t\t\tdata.push({name: 'determination\\:taxa_taxon_list_id_list[]', value: toolValues[i]});\n\t\t\t}\n\t\t}\n  \t\tjQuery('#doubt_submit_button').addClass('loading-button');\n   \t\treturn true;\n\t},\n\tsuccess:   function(data){\n\t\tif(data.error == undefined){\n\t\t\tjQuery('#fo-express-doubt').removeClass('ui-accordion-content-active');\n\t\t\tloadDeterminations(jQuery('[name=determination\\:occurrence_id]').val(), '#fo-id-history', '#fo-current-id', insect_alert_object.insect_id == null ? 'form#fo-new-flower-id-form' : 'form#fo-new-insect-id-form', function(args, type){\n\t\t\t";
        if ($args['alert_js_function'] != '') {
            data_entry_helper::$javascript .= "\n\t\t\t\tif(type == 'F'){\n\t\t\t\t\tflower_alert_object.details = [];\n\t\t\t\t\tfor(i=0; i< args.length && i < 5; i++){\n\t\t\t\t\t\tflower_alert_object.details.push({flower_taxa: args[i].taxa, date: args[i].date, user_id: args[i].user_id});\n\t\t\t\t\t\tflower_alert_object.date = flower_alert_object.details[0].date;\n\t\t\t\t\t}\n\t\t\t\t\tflower_alert_object.details = JSON.stringify(flower_alert_object.details);\n\t\t\t\t\t" . $args['alert_js_function'] . "({alert_type: 'D', type: 'F', flower: flower_alert_object});\n\t\t\t\t} else {\n\t\t\t\t\tinsect_alert_object.details = [];\n\t\t\t\t\tfor(i=0; i< args.length && i < 5; i++){\n\t\t\t\t\t\tinsect_alert_object.details.push({insect_taxa: args[i].taxa, date: args[i].date, user_id: args[i].user_id});\n\t\t\t\t\t\tinsect_alert_object.date = insect_alert_object.details[0].date;\n\t\t\t\t\t}\n\t\t\t\t\tinsect_alert_object.details = JSON.stringify(insect_alert_object.details);\n\t\t\t\t\t" . $args['alert_js_function'] . "({alert_type: 'D', type: 'I', insect: insect_alert_object});\n\t\t\t\t}";
        }
        data_entry_helper::$javascript .= "\n\t\t\t}, insect_alert_object.insect_id == null ? " . (user_access('IForm n' . $node->nid . ' flower expert') ? '1' : '0') . " : " . (user_access('IForm n' . $node->nid . ' insect expert') ? '1' : '0') . ",\n\t\t\tinsect_alert_object.insect_id == null ? " . (user_access('IForm n' . $node->nid . ' flag dubious flower') ? '1' : '0') . " : " . (user_access('IForm n' . $node->nid . ' flag dubious insect') ? '1' : '0') . ",\n\t\t\tinsect_alert_object.insect_id == null ? flowerTaxa : insectTaxa,\n\t\t\tinsect_alert_object.insect_id == null ? 'F' : 'I');\n\t\t} else {\n\t\t\talert(data.error);\n\t\t}\n\t},\n\tcomplete: function (){\n  \t\tjQuery('.loading-button').removeClass('loading-button');\n  \t} \n});\n\njQuery('form#fo-new-insect-id-form').ajaxForm({ \n\tasync: false,\n\tdataType:  'json', \n\tbeforeSubmit:   function(data, obj, options){\n\t\tvar valid = true;\n\t\tclearErrors('form#fo-new-insect-id-form');\n\t\tif (!jQuery('form#fo-new-insect-id-form input').valid()) { valid = false; }\n\t\tif (jQuery('form#fo-new-insect-id-form [name=determination\\:taxon_details]').val() == ''){\n\t\t\tif (!validateRequiredField('determination\\:taxa_taxon_list_id', '#fo-new-insect-id-form')) {\n\t\t\t\tvalid = false;\n  \t\t\t} else {\n\t\t\t\tdata.push({name: 'determination\\:taxa_taxon_list_id_list[]', value: ''});\n  \t\t\t}\n\t\t} else {\n\t\t\tvar toolValues = jQuery('#insect-id-button').data('toolRetValues');\n\t\t\tfor(var i = 0; i<toolValues.length; i++){\n\t\t\t\tdata.push({name: 'determination\\:taxa_taxon_list_id_list[]', value: toolValues[i]});\n\t\t\t}\t\t\t\n\t\t}\n   \t\tif ( valid == false ) {\n\t\t\tmyScrollToError();\n\t\t\treturn false;\n\t\t};\n  \t\tjQuery('#insect_id_submit_button').addClass('loading-button');\n   \t\treturn true;\n\t},\n\tsuccess:   function(data){\n\t\tif(data.error == undefined){\n\t\t\tjQuery(insectIDstruc.mainForm+' [name=determination\\:determination_type]').val(insectIDstruc.determinationType);\n\t\t\tjQuery(insectIDstruc.mainForm+' [name=determination\\:taxa_taxon_list_id],[name=determination\\:comment],[name=determination\\:taxon_details],[name=determination\\:taxon_extra_info]').val('');\n\t\t\tjQuery('#insect_taxa_list').empty();\n\t\t\tjQuery('#fo-new-insect-id').removeClass('ui-accordion-content-active');\n\t\t\tloadDeterminations(jQuery('[name=determination\\:occurrence_id]').val(), '#fo-id-history', '#fo-current-id', 'form#fo-new-insect-id-form', function(args, type){\n\t\t\t";
        if ($args['alert_js_function'] != '') {
            data_entry_helper::$javascript .= "\n\t\t\t\tinsect_alert_object.details = [];\n\t\t\t\tfor(i=0; i< args.length && i < 5; i++){\n\t\t\t\t\tinsect_alert_object.details.push({insect_taxa: args[i].taxa, date: args[i].date, user_id: args[i].user_id});\n\t\t\t\t\tinsect_alert_object.date = insect_alert_object.details[0].date;\n\t\t\t\t}\n\t\t\t\tinsect_alert_object.details = JSON.stringify(insect_alert_object.details);\n\t\t\t\t" . $args['alert_js_function'] . "({alert_type: 'R', type: 'I', insect: insect_alert_object});";
        }
        data_entry_helper::$javascript .= "\n\t\t\t  \t\t\t}, " . (user_access('IForm n' . $node->nid . ' insect expert') ? '1' : '0') . ", " . (user_access('IForm n' . $node->nid . ' flag dubious insect') ? '1' : '0') . ", insectTaxa, 'I');\n\t\t} else {\n\t\t\talert(data.error);\n\t\t}\n\t},\n\tcomplete: function (){\n  \t\tjQuery('.loading-button').removeClass('loading-button');\n  \t}\n\t\n});\njQuery('form#fo-new-flower-id-form').ajaxForm({ \n\tasync: false,\n\tdataType:  'json', \n\tbeforeSubmit:   function(data, obj, options){\n\t\tvar valid = true;\n\t\tclearErrors('form#fo-new-flower-id-form');\n\t\tif (!jQuery('form#fo-new-flower-id-form input').valid()) { valid = false; }\n\t\tif (jQuery('form#fo-new-flower-id-form [name=determination\\:taxon_details]').val() == ''){\n\t\t\tif (!validateRequiredField('determination\\:taxa_taxon_list_id', '#fo-new-flower-id-form')) {\n\t\t\t\tvalid = false;\n  \t\t\t} else {\n\t\t\t\tdata.push({name: 'determination\\:taxa_taxon_list_id_list[]', value: ''});\n  \t\t\t}\n\t\t} else {\n\t\t\tvar toolValues = jQuery('#flower-id-button').data('toolRetValues');\n\t\t\tfor(var i = 0; i<toolValues.length; i++){\n\t\t\t\tdata.push({name: 'determination\\:taxa_taxon_list_id_list[]', value: toolValues[i]});\n\t\t\t}\t\t\t\n\t\t}\n   \t\tif ( valid == false ) {\n\t\t\tmyScrollToError();\n\t\t\treturn false;\n\t\t};\n  \t\tjQuery('#flower_id_submit_button').addClass('loading-button');\n   \t\treturn true;\n\t},\n\tsuccess:   function(data){\n\t\tif(data.error == undefined){\n\t\t\tjQuery(flowerIDstruc.mainForm+' [name=determination\\:determination_type]').val(flowerIDstruc.determinationType);\n\t\t\tjQuery(flowerIDstruc.mainForm+' [name=determination\\:taxa_taxon_list_id],[name=determination\\:comment],[name=determination\\:taxon_details],[name=determination\\:taxon_extra_info]').val('');\n\t\t\tjQuery('#flower_taxa_list').empty();\n\t\t\tjQuery('#fo-new-flower-id').removeClass('ui-accordion-content-active');\n\t\t\tloadDeterminations(jQuery('[name=determination\\:occurrence_id]').val(), '#fo-id-history', '#fo-current-id', 'form#fo-new-flower-id-form', function(args, type){\n\t\t\t";
        if ($args['alert_js_function'] != '') {
            data_entry_helper::$javascript .= "\n\t\t\t\tflower_alert_object.details = [];\n\t\t\t\tfor(i=0; i< args.length && i < 5; i++) {\n\t\t\t\t\tflower_alert_object.details.push({flower_taxa: args[i].taxa, date: args[i].date, user_id: args[i].user_id});\n\t\t\t\t\tflower_alert_object.date = flower_alert_object.details[0].date;\n\t\t\t\t}\n\t\t\t\tflower_alert_object.details = JSON.stringify(flower_alert_object.details);\n\t\t\t\t" . $args['alert_js_function'] . "({alert_type: 'R', type: 'F', flower: flower_alert_object});";
        }
        data_entry_helper::$javascript .= "\n\t\t\t  \t\t\t}, " . (user_access('IForm n' . $node->nid . ' flower expert') ? '1' : '0') . ", " . (user_access('IForm n' . $node->nid . ' flag dubious flower') ? '1' : '0') . ", flowerTaxa, 'F');\n\t\t} else {\n\t\t\talert(data.error);\n\t\t}\n\t},\n\tcomplete: function (){\n  \t\tjQuery('.loading-button').removeClass('loading-button');\n  \t}\n\t\n});\njQuery('#fo-new-comment-form').ajaxForm({ \n\tasync: false,\n\tdataType:  'json', \n\t// success identifies the function to invoke when the server response \n\t// has been received \n\tbeforeSubmit:   function(data, obj, options){\n\t\tif (!jQuery('form#fo-new-comment-form').valid()) { return false; }\n\t\treturn true;\n\t},\n\tsuccess:   function(data){\n\t\tif(data.error == undefined){\n\t\t\tjQuery('[name=occurrence_comment\\:comment]').val('');\n\t\t\tjQuery('#fo-new-comment').removeClass('ui-accordion-content-active');\n\t\t\tloadComments(jQuery('[name=occurrence_comment\\:occurrence_id]').val(), '#fo-comment-list', 'occurrence_comment', 'occurrence_id', 'occurrence-comment-block', 'occurrence-comment-body', true);\n  \t\t} else {\n\t\t\talert(data.error);\n\t\t}\n\t} \n});\njQuery('#fc-new-comment-form').ajaxForm({ \n\tasync: false,\n\tdataType:  'json', \n\tbeforeSubmit:   function(data, obj, options){\n\t\tif (!jQuery('form#fc-new-comment-form').valid()) { return false; }\n\t\treturn true;\n\t},\n\tsuccess:   function(data){\n\t\tif(data.error == undefined){\n\t\t\tjQuery('[name=sample_comment\\:comment]').val('');\n\t\t\tjQuery('#fc-new-comment').removeClass('ui-accordion-content-active');\n\t\t\tloadComments(jQuery('[name=sample_comment\\:sample_id]').val(), '#fc-comment-list', 'sample_comment', 'sample_id', 'sample-comment-block', 'sample-comment-body', true);\n  \t\t} else {\n\t\t\talert(data.error);\n\t\t}\n\t} \n});\n\nloadSampleAttributes = function(keyValue){\n    jQuery('#fo-insect-start-time,#fo-insect-end-time,#fo-insect-sky,#fo-insect-temp,#fo-insect-wind,#fo-insect-shade').empty();\n\tajaxStack.push(\$.getJSON(\"" . $svcUrl . "/data/sample_attribute_value\"  +\n   \t\t\t\"?mode=json&view=list&nonce=" . $readAuth['nonce'] . "&auth_token=" . $readAuth['auth_token'] . "\" +\n   \t\t\t\"&sample_id=\" + keyValue + \"&REMOVEABLEJSONP&callback=?\", function(attrdata) {\n\t\tif(!(attrdata instanceof Array)){\n   \t\t\talertIndiciaError(attrdata);\n   \t\t} else if (attrdata.length>0) {\n\t\t\tfor(i=0; i< attrdata.length; i++){\n\t\t\t\tif (attrdata[i].id && (attrdata[i].iso == null || attrdata[i].iso == '' || attrdata[i].iso == '" . $language . "')){\n\t\t\t\t\tswitch(parseInt(attrdata[i].sample_attribute_id)){\n\t\t\t\t\t\tcase " . $args['start_time_attr_id'] . ":\n\t\t\t\t\t\t\tjQuery('#fo-insect-start-time').append(attrdata[i].value);\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tcase " . $args['end_time_attr_id'] . ":\n\t\t\t\t\t\t\tjQuery('#fo-insect-end-time').append(attrdata[i].value);\n\t\t\t\t\t\t\tbreak;\n  \t\t\t\t\t\tcase " . $args['sky_state_attr_id'] . ":\n\t\t\t\t\t\t\tjQuery('#fo-insect-sky').append(attrdata[i].value);\n\t\t\t\t\t\t\tbreak;\n  \t\t\t\t\t\tcase " . $args['temperature_attr_id'] . ":\n\t\t\t\t\t\t\tjQuery('#fo-insect-temp').append(attrdata[i].value);\n\t\t\t\t\t\t\tbreak;\n  \t\t\t\t\t\tcase " . $args['wind_attr_id'] . ":\n\t\t\t\t\t\t\tjQuery('#fo-insect-wind').append(attrdata[i].value);\n\t\t\t\t\t\t\tbreak;\n  \t\t\t\t\t\tcase " . $args['shade_attr_id'] . ":\n  \t\t\t\t\t\t\tif(attrdata[i].value == '1'){\n\t\t\t\t\t\t\t\tjQuery('#fo-insect-shade').append(\"" . lang::get('Yes') . "\");\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\tjQuery('#fo-insect-shade').append(\"" . lang::get('No') . "\");\n  \t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tbreak;\n  \t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}));\n}\nloadOccurrenceAttributes = function(keyValue){\n    jQuery('#focus-flower-type').empty();\n\tajaxStack.push(\$.getJSON(\"" . $svcUrl . "/data/occurrence_attribute_value\"  +\n\t\t\t\"?mode=json&view=list&nonce=" . $readAuth['nonce'] . "&auth_token=" . $readAuth['auth_token'] . "\" +\n   \t\t\t\"&occurrence_id=\" + keyValue + \"&iso=" . $language . "&REMOVEABLEJSONP&callback=?\", function(attrdata) {\n\t\tif(!(attrdata instanceof Array)){\n   \t\t\talertIndiciaError(attrdata);\n   \t\t} else if (attrdata.length>0) {\n\t\t\tfor(i=0; i< attrdata.length; i++){\n\t\t\t\tif (attrdata[i].id){\n\t\t\t\t\tswitch(parseInt(attrdata[i].occurrence_attribute_id)){\n\t\t\t\t\t\tcase " . $args['flower_type_attr_id'] . ":\n\t\t\t\t\t\t\tjQuery('<span>'+attrdata[i].value+'</span>').appendTo('#focus-flower-type');\n\t\t\t\t\t\t\tbreak;\n  \t}}}}}));\n}\nloadLocationAttributes = function(keyValue){\n    jQuery('#focus-habitat').empty();\n\tajaxStack.push(\$.getJSON(\"" . $svcUrl . "/data/location_attribute_value\"  +\n\t\t\t\"?mode=json&view=list&nonce=" . $readAuth['nonce'] . "&auth_token=" . $readAuth['auth_token'] . "\" +\n   \t\t\t\"&location_id=\" + keyValue + \"&iso=" . $language . "&REMOVEABLEJSONP&callback=?\", function(attrdata) {\n\t\tif(!(attrdata instanceof Array)){\n   \t\t\talertIndiciaError(attrdata);\n   \t\t} else if (attrdata.length>0) {\n   \t\t\tvar habitat_string = '';\n\t\t\tfor(i=0; i< attrdata.length; i++){\n\t\t\t\tif (attrdata[i].id){\n\t\t\t\t\tswitch(parseInt(attrdata[i].location_attribute_id)){\n\t\t\t\t\t\tcase " . $args['habitat_attr_id'] . ":\n\t\t\t\t\t\t\thabitat_string = (habitat_string == '' ? attrdata[i].value : (habitat_string + ' | ' + attrdata[i].value));\n\t\t\t\t\t\t\tbreak;\n\t\t\t}}}\n\t\t\tjQuery('<span>'+habitat_string+'</span>').appendTo('#focus-habitat');\n  }}));\n}\n\ninsertImage = function(path, target, ratio, callback){\n    var img = new Image();\n\tjQuery(img).load(function () {\n        target.append(this);\n        if(this.width/this.height > ratio){\n\t    \tjQuery(this).css('width', '100%').css('height', 'auto').css('vertical-align', 'middle').css('margin-left', 'auto').css('margin-right', 'auto').css('display', 'block');\n  \t\t} else {\n\t        jQuery(this).css('width', (100*this.width/(this.height*ratio))+'%').css('height', 'auto').css('vertical-align', 'middle').css('margin-left', 'auto').css('margin-right', 'auto').css('display', 'block');\n  \t\t}\n  \t\tif(callback)\n  \t\t\tcallback(this);\n\t}).attr('src', '" . data_entry_helper::$base_url . data_entry_helper::$indicia_upload_path . "'+path);\n}\n\nloadImage = function(imageTable, key, keyValue, target, imageRatio, callback, prepend, imgCallback){\n    jQuery(target).empty();\n    ajaxStack.push(jQuery.ajax({ \n        type: \"GET\",\n        myTarget: target,\n        myCallback: callback,\n        myPrepend: prepend,\n        myImgCallback: imgCallback,\n        url: \"" . $svcUrl . "/data/\" + imageTable +\n   \t\t\t\"?mode=json&view=list&nonce=" . $readAuth['nonce'] . "&auth_token=" . $readAuth['auth_token'] . "\" +\n   \t\t\t\"&\" + key + \"=\" + keyValue + \"&REMOVEABLEJSONP&callback=?\", \n        success: function(imageData) {\n\t\t  if(!(imageData instanceof Array)){\n   \t\t\talertIndiciaError(imageData);\n   \t\t  } else if (imageData.length>0) {\n \t\t\tinsertImage(this.myPrepend+imageData[0].path, jQuery(this.myTarget), imageRatio, this.myImgCallback);\n\t\t\tif(this.myCallback) this.myCallback(imageData[0]);\n\t\t  }},\n\t\tdataType: 'json'\n\t}));\n}\n\nloadDeterminations = function(keyValue, historyID, currentID, lookup, callback, expert, can_doubt, taxaList, type){\n    jQuery(historyID).empty().append('<strong>" . lang::get('LANG_History_Title') . "</strong>');\n\tjQuery(currentID).empty();\n\tjQuery('#poll-banner').empty();\n\tjQuery('#fo-doubt-button').hide();\n\tjQuery('#fo-express-doubt-form').find('[name=determination:taxon_extra_info]').val('');\n\tjQuery('#fo-express-doubt-form').find('[name=determination:taxa_taxon_list_id]').val('');\n\tjQuery('#fo-doubt-button').data('toolRetValues',[]);\n\tjQuery('.poll-id-button').data('toolRetValues',[]);\n\tjQuery('#fo-warning').addClass('occurrence-ok').removeClass('occurrence-dubious').removeClass('occurrence-unknown');\n\tjQuery('.taxa_list').empty();\n    ajaxStack.push(jQuery.ajax({ \n        type: \"GET\", \n        url: \"" . $svcUrl . "/data/determination?mode=json&view=list&nonce=" . $readAuth['nonce'] . "&auth_token=" . $readAuth['auth_token'] . "&reset_timeout=true&orderby=id&REMOVEABLEJSONP&callback=?&occurrence_id=\" + keyValue,\n        myCurrentID: currentID,\n        myHistoryID: historyID,\n        myCallback: callback,\n        myLookup: lookup,\n\t\tdataType: 'json',\n        success: function(detData) {\n   \t\t  var callbackArgs = [];\n   \t\t  if(!(detData instanceof Array)){\n   \t\t\talertIndiciaError(detData);\n   \t\t  } else if (detData.length>0) {\n\t\t\tvar i = detData.length-1;\n\t\t\tvar callbackEntry = {date: detData[i].updated_on, user_id: detData[i].cms_ref, taxa: []};\n   \t\t\tjQuery('#fo-express-doubt-form').find('[name=determination\\:occurrence_id]').val(detData[i].occurrence_id);\n   \t\t\tvar string = '';\n   \t\t\tvar resultsText = \"" . lang::get('LANG_Taxa_Returned') . "<br />{ \";\n\t\t\tif(detData[i].taxon != '' && detData[i].taxon != null){\n\t\t\t\tstring = detData[i].taxon;\n\t\t\t\tcallbackEntry.taxa.push(detData[i].taxon);\n  \t\t\t}\n\t\t\tjQuery('#fo-express-doubt-form').find('[name=determination\\:taxa_taxon_list_id]').val(detData[i].taxa_taxon_list_id);\n\t\t\tjQuery(this.myLookup).find('[name=determination:taxa_taxon_list_id]').val(detData[i].taxa_taxon_list_id);\n\t\t\tif(detData[i].taxa_taxon_list_id_list != null && detData[i].taxa_taxon_list_id_list != '' && detData[i].taxa_taxon_list_id_list != '{}'){\n\t\t\t  \tresultsIDs = detData[i].taxa_taxon_list_id_list.substring(1, detData[i].taxa_taxon_list_id_list.length - 1).split(',');\n\t\t\t  \tfor(j=0; j < resultsIDs.length; j++){\n\t\t\t\t\tfor(k = 0; k< taxaList.length; k++)\n\t\t\t\t\t\tif(taxaList[k].id == resultsIDs[j]) {\n\t\t\t\t\t\t\tstring = (string == '' ? '' : string + ', ') + taxaList[k].taxon;\n\t\t\t\t\t\t\tcallbackEntry.taxa.push(taxaList[k].taxon);\n\t\t\t\t\t\t\tresultsText = resultsText + (j == 0 ? '' : '<br />&nbsp;&nbsp;') + taxaList[k].taxon;\n  \t\t\t\t\t\t}\n\t\t  \t\t}\n\t  \t\t\tif(resultsIDs.length>1 || resultsIDs[0] != '') {\n\t\t\t\t\tjQuery('#fo-doubt-button').data('toolRetValues',resultsIDs);\n\t\t\t\t\tjQuery('.poll-id-button').data('toolRetValues',resultsIDs);\n\t\t\t\t\tjQuery('.taxa_list').append(resultsText+ ' }');\n\t\t\t\t}\n\t\t\t}\n\t\t\tcallbackArgs.push(callbackEntry);\n\t\t\tjQuery('#poll-banner').append(string);\n\t\t\tif(detData[i].taxon_extra_info != '' && detData[i].taxon_extra_info != null){\n\t\t\t\tstring = (string == '' ? '' : string + ' ') + '('+detData[i].taxon_extra_info+')';\n\t\t\t}\n\t\t\tjQuery('#fo-express-doubt-form').find('[name=determination\\:taxon_extra_info]').val(detData[i].taxon_extra_info);\n\t\t\tjQuery(this.myLookup).find('[name=determination:taxon_extra_info]').val(detData[i].taxon_extra_info);\n\t\t\tif(string != '')\n\t\t\t\tjQuery('<p><strong>'+string+ '</strong> " . lang::get('LANG_Comment_By') . "' + detData[i].person_name + ' ' + convertDate(detData[i].updated_on,false) + '</p>').appendTo(this.myCurrentID)\n\t\t\telse\n\t\t\t\tjQuery('<p>" . lang::get('LANG_Comment_By') . "' + detData[i].person_name + ' ' + convertDate(detData[i].updated_on,false) + '</p>').appendTo(this.myCurrentID)\n\t\t\tif(detData[i].determination_type == 'A' && (expert || can_doubt)){\n\t\t\t\tjQuery('#fo-doubt-button').show();\n\t\t\t} else if(detData[i].determination_type == 'B'){\n\t\t\t\tjQuery(\"<p>" . lang::get('LANG_Doubt_Expressed') . "</p>\").appendTo(this.myCurrentID);\n\t\t\t\tjQuery('#fo-warning').removeClass('occurrence-ok').addClass('occurrence-dubious');\n\t\t\t} else if(detData[i].determination_type == 'C'){\n\t\t\t\tjQuery(\"<p>" . lang::get('LANG_Determination_Valid') . "</p>\").appendTo(this.myCurrentID);\n\t\t\t\tif(!expert)\n\t\t\t\t\tjQuery('.new-id-button').hide();\n\t\t\t} else if(detData[i].determination_type == 'I'){\n\t\t\t\tjQuery(\"<p>" . lang::get('LANG_Determination_Incorrect') . "</p>\").appendTo(this.myCurrentID);\n\t\t\t\tjQuery('#fo-warning').removeClass('occurrence-ok').addClass('occurrence-dubious');\n\t\t\t} else if(detData[i].determination_type == 'U'){\n\t\t\t\tjQuery(\"<p>" . lang::get('LANG_Determination_Unconfirmed') . "</p>\").appendTo(this.myCurrentID);\n\t\t\t\tjQuery('#fo-warning').removeClass('occurrence-ok').addClass('occurrence-dubious');\n\t\t\t} else if(detData[i].determination_type == 'X'){\n\t\t\t\tjQuery(\"<p>" . lang::get('LANG_Determination_Unknown') . "</p>\").appendTo(this.myCurrentID);\n//\t\t\t\tjQuery('#fo-warning').removeClass('occurrence-ok').addClass('occurrence-unknown');\n\t\t\t}\n\t\t\tif(detData[i].comment != '' && detData[i].comment != null){\n\t\t\t\tjQuery('<p>'+detData[i].comment+'</p>').appendTo(this.myCurrentID);\n\t\t\t}\n\t\t\t\n\t\t\tfor(i=detData.length - 2; i >= 0; i--){ // deliberately miss last one, in reverse order\n\t\t\t\tcallbackEntry = {date: detData[i].updated_on, user_id: detData[i].cms_ref, taxa: []};\n\t\t\t\tstring = '';\n\t\t\t\tvar item = jQuery('<div></div>').addClass('history-item').appendTo(this.myHistoryID);\n\t\t\t\tif(detData[i].taxon != '' && detData[i].taxon != null){\n\t\t\t\t\tstring = detData[i].taxon;\n\t\t  \t\t\tcallbackEntry.taxa.push(detData[i].taxon);\n  \t\t\t\t}\n\t\t\t\tif(detData[i].taxa_taxon_list_id_list != '' && detData[i].taxa_taxon_list_id_list != null && detData[i].taxa_taxon_list_id_list != '{}'){\n\t\t\t\t\tvar resultsIDs = detData[i].taxa_taxon_list_id_list.substring(1, detData[i].taxa_taxon_list_id_list.length - 1).split(',');\n\t\t\t\t\tfor(j=0; j < resultsIDs.length; j++){\n\t\t\t\t\t\tfor(k = 0; k< taxaList.length; k++)\n\t\t\t\t\t\t\tif(taxaList[k].id == resultsIDs[j]) {\n\t\t\t\t\t\t\t\tstring = (string == '' ? '' : string + ', ') + taxaList[k].taxon;\n\t\t\t\t\t\t\t\tcallbackEntry.taxa.push(taxaList[k].taxon);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif(detData[i].taxon_extra_info != '' && detData[i].taxon_extra_info != null){\n\t\t\t\t\tstring = (string == '' ? '' : string + ' ') + '('+detData[i].taxon_extra_info+')' ;\n\t\t\t\t}\n\t\t\t\tstring = convertDate(detData[i].updated_on,false) + ' : ' + string;\n\t\t\t\tjQuery('<p><strong>'+string+ '</strong> " . lang::get('LANG_Comment_By') . "' + detData[i].person_name+'</p>').appendTo(item)\n\t\t\t\tif(detData[i].determination_type == 'B'){\n\t\t\t\t\tjQuery(\"<p>" . lang::get('LANG_Doubt_Expressed') . "</p>\").appendTo(item)\n\t\t\t\t} else if(detData[i].determination_type == 'I'){\n\t\t\t\t\tjQuery(\"<p>" . lang::get('LANG_Determination_Incorrect') . "</p>\").appendTo(item)\n\t\t\t\t} else if(detData[i].determination_type == 'U'){\n\t\t\t\t\tjQuery(\"<p>" . lang::get('LANG_Determination_Unconfirmed') . "</p>\").appendTo(item)\n\t\t\t\t} else if(detData[i].determination_type == 'X'){\n\t\t\t\t\tjQuery(\"<p>" . lang::get('LANG_Determination_Unknown') . "</p>\").appendTo(item)\n\t\t\t\t}\n\t\t\t\tif(detData[i].comment != '' && detData[i].comment != null){\n\t\t\t\t\tjQuery('<p>'+detData[i].comment+'</p>').appendTo(item);\n\t\t\t\t}\n\t\t\t\tcallbackArgs.push(callbackEntry);\n  \t\t\t}\n\t\t\t\n\t\t  } else {\n\t\t\tjQuery('#fo-doubt-button').hide();\n\t\t\tjQuery('#fo-warning').removeClass('occurrence-ok').addClass('occurrence-unknown');\n\t\t\tjQuery('<p>" . lang::get('LANG_No_Determinations') . "</p>')\n\t\t\t\t\t.appendTo(this.myHistoryID);\n\t\t\tjQuery('<p>" . lang::get('LANG_No_Determinations') . "</p>')\n\t\t\t\t\t.appendTo(this.myCurrentID);\n\t\t  }\n\t\t  if(this.myCallback) this.myCallback(callbackArgs, type);\n\t\t}  \n\t}));\n\t// when the occurrence is loaded (eg in loadInsect) all determination:occurrence_ids are set.\n\tjQuery(lookup).find('[name=determination\\:determination_type]').val(expert ? 'C' : 'A');\n};\n\nloadComments = function(keyValue, block, table, key, blockClass, bodyClass, reset_timeout){\n    jQuery(block).empty();\n    ajaxStack.push(jQuery.ajax({ \n        type: \"GET\",\n        url: \"" . $svcUrl . "/data/\" + table + \"?mode=json&view=list\" +\n        \t(reset_timeout ? \"&reset_timeout=true\" : \"\") + \"&nonce=" . $readAuth['nonce'] . "&auth_token=" . $readAuth['auth_token'] . "\" +\n   \t\t\t\"&\" + key + \"=\" + keyValue + \"&REMOVEABLEJSONP&callback=?\", \n        myBlock: block,\n        myBlockClass: blockClass,\n        myBodyClass: bodyClass,\n\t\tdataType: 'json',\n        success: function(commentData) {\n   \t\t  if(!(commentData instanceof Array)){\n   \t\t\talertIndiciaError(commentData);\n   \t\t  } else if (commentData.length>0) {\n   \t\t\tfor(i=commentData.length - 1; i >= 0; i--){\n\t   \t\t\tvar newCommentDetails = jQuery('<div class=\"'+this.myBlockClass+'\"/>')\n\t\t\t\t\t.appendTo(block);\n\t\t\t\tjQuery('<span>" . lang::get('LANG_Comment_By') . "' + commentData[i].person_name + ' ' + convertDate(commentData[i].updated_on,false) + '</span>')\n\t\t\t\t\t.appendTo(newCommentDetails);\n\t   \t\t\tvar newComment = jQuery('<div class=\"'+bodyClass+'\"/>')\n\t\t\t\t\t.appendTo(this.myBlock);\n\t\t\t\tjQuery('<p>' + commentData[i].comment + '</p>')\n\t\t\t\t\t.appendTo(newComment);\n\t\t\t}\n\t\t  } else {\n\t\t\tjQuery('<p>" . lang::get('LANG_No_Comments') . "</p>')\n\t\t\t\t\t.appendTo(this.myBlock);\n\t\t  }\n\t\t}\n    }));\n};\n\ncollectionProcessing = function(keyValue, expert){\n    ajaxStack.push(\$.getJSON(\"" . $svcUrl . "/data/sample_attribute_value\"  +\n   \t\t\t\"?mode=json&view=list&nonce=" . $readAuth['nonce'] . "&auth_token=" . $readAuth['auth_token'] . "\" +\n   \t\t\t\"&sample_id=\" + keyValue + \"&REMOVEABLEJSONP&callback=?\", function(attrdata) {\n\t\tif(!(attrdata instanceof Array)){\n   \t\t\talertIndiciaError(attrdata);\n   \t\t} else if (attrdata.length>0) {\n\t\t\tfor(i=0; i< attrdata.length; i++){\n\t\t\t\tif (attrdata[i].id){\n\t\t\t\t\tswitch(parseInt(attrdata[i].sample_attribute_id)){\n\t\t\t\t\t\tcase " . $args['uid_attr_id'] . ":\n\t\t\t\t\t\t\tinsect_alert_object.collection_user_id = attrdata[i].value;\n\t\t\t\t\t\t\tflower_alert_object.collection_user_id = attrdata[i].value;\n\t\t\t\t\t\t\tif(!expert && parseInt(attrdata[i].value) != " . $uid . ")\n\t\t\t\t\t\t\t\tjQuery('.new-id-button').hide();\n\t\t\t\t\t\t\tbreak;\n  \t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n    }));\n}\n\nloadInsectAddnInfo = function(keyValue, collectionIndex){\n    // TODO convert buttons into thumbnails\n\tcollection = '';\t\n\t// fetch occurrence details first to get the sample_id.\n\t// Get the sample to get the parent_id.\n\t// get all the samples (sessions) with the same parent_id;\n\t// fetch all the occurrences of the sessions.\n    ajaxStack.push(\$.getJSON(\"" . $svcUrl . "/data/occurrence/\" + keyValue +\n   \t\t\t\"?mode=json&view=detail&nonce=" . $readAuth['nonce'] . "&auth_token=" . $readAuth['auth_token'] . "\" +\n   \t\t\t\"&REMOVEABLEJSONP&callback=?\", function(occData) {\n   \t\tif(!(occData instanceof Array)){\n   \t\t\talertIndiciaError(occData);\n   \t\t} else if (occData.length > 0) {\n            ajaxStack.push(\$.getJSON(\"" . $svcUrl . "/data/sample/\" + occData[0].sample_id +\n   \t\t\t\t\t\"?mode=json&view=detail&nonce=" . $readAuth['nonce'] . "&auth_token=" . $readAuth['auth_token'] . "\" +\n   \t\t\t\t\t\"&REMOVEABLEJSONP&callback=?\", function(smpData) {\n   \t\t\t\tif(!(smpData instanceof Array)){\n   \t\t\t\t\talertIndiciaError(smpData);\n   \t\t\t\t} else if (smpData.length > 0) {\n   \t\t\t\t\tcollection = smpData[0].parent_id;\n\t\t\t\t\tcollectionProcessing(collection, " . (user_access('IForm n' . $node->nid . ' insect expert') ? "true" : "false") . ");\n\t\t\t\t\tjQuery('#fo-insect-date').empty().append(convertDate(smpData[0].date_start,false));\n\t\t\t\t\tloadSampleAttributes(smpData[0].id);\n\t\t\t\t\tjQuery('#fo-collection-button').data('smpID',smpData[0].parent_id).data('collectionIndex', collectionIndex).show();\n  \t\t\t\t}\n   \t\t   \t  }));\n   \t\t}\n    }));\n}\nloadFlowerAddnInfo = function(keyValue, collectionIndex){\n    // fetch occurrence details first to get the collection id.\n    loadOccurrenceAttributes(keyValue);\n    ajaxStack.push(\$.getJSON(\"" . $svcUrl . "/data/occurrence/\" + keyValue +\n   \t\t\t\"?mode=json&view=detail&nonce=" . $readAuth['nonce'] . "&auth_token=" . $readAuth['auth_token'] . "\" +\n   \t\t\t\"&REMOVEABLEJSONP&callback=?\", function(occData) {\n   \t\tif(!(occData instanceof Array)){\n   \t\t\talertIndiciaError(occData);\n   \t\t} else if (occData.length > 0) {\n\t\t\tjQuery('#fo-collection-button').data('smpID',occData[0].sample_id).data('collectionIndex',collectionIndex).show();\n\t\t\tcollectionProcessing(occData[0].sample_id, " . (user_access('IForm n' . $node->nid . ' flower expert') ? "true" : "false") . ");\n            ajaxStack.push(\$.getJSON(\"" . $svcUrl . "/data/sample/\" + occData[0].sample_id +\n   \t\t\t\t\t\"?mode=json&view=detail&nonce=" . $readAuth['nonce'] . "&auth_token=" . $readAuth['auth_token'] . "\" +\n   \t\t\t\t\t\"&REMOVEABLEJSONP&callback=?\", function(collection) {\n   \t\t\t\tif(!(collection instanceof Array)){\n   \t\t\t\t\talertIndiciaError(collection);\n   \t\t\t\t} else if (collection.length > 0) {\n\t\t\t\t\tloadLocationAttributes(collection[0].location_id);\n  \t\t\t\t}\n   \t\t   \t  }));\n   \t\t}\n    }));\n}\n\nloadInsect = function(insectID, collectionIndex, insectIndex, type){\n    abortAjax();\n\tjQuery('#fo-prev-button,#fo-next-button').hide();\n\tjQuery('#fo-filter-button').show();\n\tif(type == 'S'){ // called from search\n\t\tif(insectIndex > 0)\n\t\t\tjQuery('#fo-prev-button').show().data('occID', searchResults.features[insectIndex-1].attributes.insect_id).data('collectionIndex', null).data('insectIndex', insectIndex-1).data('type', 'S');\n\t\tif(insectIndex < searchResults.features.length-1)\n\t\t\tjQuery('#fo-next-button').show().data('occID', searchResults.features[insectIndex+1].attributes.insect_id).data('collectionIndex', null).data('insectIndex', insectIndex+1).data('type', 'S');\n\t} else if(type == 'C'){ // called from collection\n\t\tjQuery('#fo-filter-button').hide();\n\t\tvar myThumb = jQuery('.collection-insect').filter('[occID='+insectID+']').prev();\n\t\tif(myThumb.length > 0)\n\t\t\tjQuery('#fo-prev-button').show().data('occID', myThumb.attr('occID')).data('collectionIndex', collectionIndex).data('insectIndex', null).data('type', 'C');\n\t\tmyThumb = jQuery('.collection-insect').filter('[occID='+insectID+']').next();\n\t\tif(myThumb.length > 0)\n\t\t\tjQuery('#fo-next-button').show().data('occID', myThumb.attr('occID')).data('collectionIndex', collectionIndex).data('insectIndex', null).data('type', 'C');\t\t\n  \t} else if(type == 'P'){ // called from photoreel\n\t\tvar myThumb = jQuery('.thumb').filter('[occID='+insectID+']').prev();\n\t\tif(myThumb.length > 0)\n\t\t\tjQuery('#fo-prev-button').show().data('occID', myThumb.attr('occID')).data('collectionIndex', collectionIndex).data('insectIndex', null).data('type', 'P');\n\t\tmyThumb = jQuery('.thumb').filter('[occID='+insectID+']').next();\n\t\tif(myThumb.length > 0)\n\t\t\tjQuery('#fo-next-button').show().data('occID', myThumb.attr('occID')).data('collectionIndex', collectionIndex).data('insectIndex', null).data('type', 'P');\t\t\n\t}\n\tinsect_alert_object.insect_id = insectID;\n\tinsect_alert_object.user_id = \"" . $uid . "\";\n\tflower_alert_object.flower_id = null;\n\tjQuery('#focus-collection,#filter,#fo-flower-addn-info').hide();\n    jQuery('#focus-occurrence,#fo-addn-info-header,#fo-insect-addn-info').show();\n\tjQuery('[name=determination\\:occurrence_id]').val(insectID);\n\tjQuery('[name=occurrence_comment\\:occurrence_id]').val(insectID);\n\tjQuery('#fo-new-comment,#fo-new-insect-id,#fo-new-flower-id,#fo-express-doubt').removeClass('ui-accordion-content-active');\n\tjQuery('#fo-new-insect-id-button').show();\n\tjQuery('#fo-new-flower-id-button').hide();\n\tjQuery('#fo-new-comment-button')." . (user_access('IForm n' . $node->nid . ' insect expert') || user_access('IForm n' . $node->nid . ' create insect comment') ? "show()" : "hide()") . ";\n\tloadDeterminations(insectID, '#fo-id-history', '#fo-current-id', 'form#fo-new-insect-id-form', null, " . (user_access('IForm n' . $node->nid . ' insect expert') ? '1' : '0') . ", " . (user_access('IForm n' . $node->nid . ' flag dubious insect') ? '1' : '0') . ", insectTaxa, 'I');\n\tloadImage('occurrence_image', 'occurrence_id', insectID, '#fo-image', " . $args['Insect_Image_Ratio'] . ", function(imageRecord){insect_alert_object.insect_image_path = imageRecord.path}, '', false);\n\tloadInsectAddnInfo(insectID, collectionIndex);\n\tloadComments(insectID, '#fo-comment-list', 'occurrence_comment', 'occurrence_id', 'occurrence-comment-block', 'occurrence-comment-body', false);\n\tmyScrollTo('#poll-banner');\n}\nloadFlower = function(flowerID, collectionIndex){\n    abortAjax();\n\tinsect_alert_object.insect_id = null;\n\tflower_alert_object.flower_id = flowerID;\n\tflower_alert_object.user_id = \"" . $uid . "\";\n\tjQuery('#fo-filter-button').show();\n\tjQuery('#fo-prev-button,#fo-next-button').hide(); // only one flower per collection, and don't search flowers: no next or prev buttons.\n\tjQuery('#focus-collection,#filter,#fo-insect-addn-info').hide();\n\tjQuery('#focus-occurrence,#fo-addn-info-header,#fo-flower-addn-info').show();\n\tjQuery('#fo-new-comment,#fo-new-insect-id,#fo-new-flower-id,#fo-express-doubt').removeClass('ui-accordion-content-active');\n\tjQuery('[name=determination\\:occurrence_id]').val(flowerID);\n\tjQuery('[name=occurrence_comment\\:occurrence_id]').val(flowerID);\n\tjQuery('#fo-new-flower-id-button').show();\n\tjQuery('#fo-new-insect-id-button').hide();\n\tjQuery('#fo-new-comment-button')." . (user_access('IForm n' . $node->nid . ' flower expert') || user_access('IForm n' . $node->nid . ' create flower comment') ? "show()" : "hide()") . ";\n\tloadDeterminations(flowerID, '#fo-id-history', '#fo-current-id', 'form#fo-new-flower-id-form', null, " . (user_access('IForm n' . $node->nid . ' flower expert') ? '1' : '0') . ", " . (user_access('IForm n' . $node->nid . ' flag dubious flower') ? '1' : '0') . ", flowerTaxa, 'F');\n\tloadImage('occurrence_image', 'occurrence_id', flowerID, '#fo-image', " . $args['Flower_Image_Ratio'] . ", function(imageRecord){flower_alert_object.flower_image_path = imageRecord.path}, '', false);\n\tloadFlowerAddnInfo(flowerID, collectionIndex);\n\tloadComments(flowerID, '#fo-comment-list', 'occurrence_comment', 'occurrence_id', 'occurrence-comment-block', 'occurrence-comment-body', false);\n\tmyScrollTo('#poll-banner');\n}\n\naddDrawnGeomToSelection = function(geometry) {\n   \t// Create the polygon as drawn\n   \tvar feature = new OpenLayers.Feature.Vector(geometry, {});\n   \tpolygonLayer.addFeatures([feature]);\n};\n\nMyEditingToolbar=OpenLayers.Class(\n\t\tOpenLayers.Control.Panel,{\n\t\t\tinitialize:function(layer,options){\n\t\t\t\tOpenLayers.Control.Panel.prototype.initialize.apply(this,[options]);\n\t\t\t\tthis.addControls([new OpenLayers.Control.Navigation()]);\n\t\t\t\tvar controls=[new OpenLayers.Control.DrawFeature(layer,OpenLayers.Handler.Polygon,{'displayClass':'olControlDrawFeaturePolygon', drawFeature: addDrawnGeomToSelection})];\n\t\t\t\tthis.addControls(controls);\n\t\t\t},\n\t\t\tdraw:function(){\n\t\t\t\tvar div=OpenLayers.Control.Panel.prototype.draw.apply(this,arguments);\n\t\t\t\tthis.activateControl(this.controls[0]);\n\t\t\t\treturn div;\n\t\t\t},\n\tCLASS_NAME:\"MyEditingToolbar\"});\n\nloadFilter = function(){\n    if(jQuery('#map').children().length == 0) {\n    \tpolygonLayer = new OpenLayers.Layer.Vector('Polygon Layer', {\n\t\t\tstyleMap: new OpenLayers.StyleMap({\n                \t\t\"default\": new OpenLayers.Style({\n                    \t\tfillColor: \"Red\",\n        \t\t            strokeColor: \"Red\",\n\t\t                    fillOpacity: 0,\n                \t\t    strokeWidth: 1\n        \t\t          })\n\t\t\t}),\n\t\t\tdisplayInLayerSwitcher: false\n\t\t});\n\t\tpolygonLayer.events.register('featuresadded', {}, function(a1){\n\t\t\tpolygonLayer.map.searchLayer.destroyFeatures();\n\t\t\tif(inseeLayer != null)\n\t\t\t\tinseeLayer.destroyFeatures();\n\t\t});\n    \t" . $map1JS . "\n    \teditControl = new MyEditingToolbar(polygonLayer, {'displayClass':'olControlEditingToolbar'});\n\t\tpolygonLayer.map.addControl(this.editControl);\n\t\teditControl.activate();\n\t\tpolygonLayer.map.searchLayer.events.register('featuresadded', {}, function(a1){\n\t\t\tif(inseeLayer != null)\n\t\t\t\tinseeLayer.destroyFeatures();\n\t\t\tpolygonLayer.destroyFeatures();\n\t\t});\n\t}\n}\n\njQuery('#fc-add-preferred').click(function(){\n\tif(collection_preferred_object.collection_id == null) return;\n\tvar newObj = {};\n\tfor (i in collection_preferred_object) {\n\t\tnewObj[i] = collection_preferred_object[i]\n\t};\n\tnewObj.insects = JSON.stringify(newObj.insects);";
        if ($args['preferred_js_function'] != '') {
            data_entry_helper::$javascript .= "\n\t\t" . $args['preferred_js_function'] . "({type: 'C', collection: newObj});";
        }
        data_entry_helper::$javascript .= "\n});\njQuery('#fc-new-comment-button').click(function(){ \n\tjQuery('#fc-new-comment').toggleClass('ui-accordion-content-active');\n});\njQuery('#fo-new-comment-button').click(function(){ \n\tjQuery('#fo-new-comment').toggleClass('ui-accordion-content-active');\n});\njQuery('#fo-new-insect-id-button').click(function(){ \n\tjQuery('#fo-express-doubt').removeClass('ui-accordion-content-active');\n\tjQuery('#fo-new-insect-id [name=determination\\:comment]').val(\"" . lang::get('LANG_Default_ID_Comment') . "\");\n\tjQuery('#fo-new-insect-id').toggleClass('ui-accordion-content-active');\n});\njQuery('#fo-new-flower-id-button').click(function(){ \n\tjQuery('#fo-express-doubt').removeClass('ui-accordion-content-active');\n\tjQuery('#fo-new-flower-id [name=determination\\:comment]').val(\"" . lang::get('LANG_Default_ID_Comment') . "\");\n\tjQuery('#fo-new-flower-id').toggleClass('ui-accordion-content-active');\n});\njQuery('#fo-collection-button').click(function(){\n\tloadCollection(jQuery(this).data('smpID'), jQuery(this).data('collectionIndex'));\n});\njQuery('#fo-prev-button,#fo-next-button').click(function(){\n\tloadInsect(jQuery(this).data('occID'), // my occurrence id.\n\t\tjQuery(this).data('collectionIndex'), // index of my collection within search results. Used when called from a focus on collection or from search collection photoreel thumbnail\n\t\tjQuery(this).data('insectIndex'), // index of me within search results. Used when called from search\n\t\tjQuery(this).data('type') // type: 'P' from photoreel, 'S' from search, 'C' from collection, 'X' NA\n\t);\n});\n  ";
        switch ($mode) {
            case 'INSECT':
                data_entry_helper::$onload_javascript .= "loadInsect(" . $occID . ", null, null, 'X');";
                break;
            case 'FLOWER':
                data_entry_helper::$onload_javascript .= "loadFlower(" . $occID . ", null);";
                break;
            case 'COLLECTION':
                data_entry_helper::$onload_javascript .= "loadCollection(" . $smpID . ", null);";
                break;
            default:
                data_entry_helper::$onload_javascript .= "\n    \t\tjQuery('#focus-occurrence,#focus-collection,#results-insects-header,#results-collections-header,#results-insects-results,#results-collections-results').hide();\n    \t\tloadFilter();";
                if ($userID != '') {
                    $thisuser = user_load($userID);
                    data_entry_helper::$onload_javascript .= "jQuery('[name=username]').val('" . $thisuser->name . "');\n    \t\t\tjQuery('#fold-name-button').click();";
                }
                data_entry_helper::$onload_javascript .= "jQuery('#search-collections-button').click();";
                break;
        }
        return $r;
    }
 private static function get_site_tab($auth, $args, $settings)
 {
     $r = '<div id="site-details" class="ui-helper-clearfix">';
     $r .= '<form method="post" id="input-form">';
     $r .= $auth['write'];
     $r .= '<div id="cols" class="ui-helper-clearfix"><div class="left" style="width: 54%">';
     $r .= '<fieldset><legend>' . lang::get('Site Details') . '</legend>';
     $r .= "<input type=\"hidden\" name=\"website_id\" value=\"" . $args['website_id'] . "\" />\n";
     $typeTerms = array();
     if (!empty($args['main_type_term_1'])) {
         $typeTerms[] = $args['main_type_term_1'];
     }
     if (!empty($args['main_type_term_2'])) {
         $typeTerms[] = $args['main_type_term_2'];
     }
     if (!empty($args['main_type_term_3'])) {
         $typeTerms[] = $args['main_type_term_3'];
     }
     $typeTermIDs = helper_base::get_termlist_terms($auth, 'indicia:location_types', $typeTerms);
     $lookUpValues = array('' => '<' . lang::get('please select') . '>');
     foreach ($typeTermIDs as $termDetails) {
         $lookUpValues[$termDetails['id']] = $termDetails['term'];
     }
     // if location is predefined, can not change unless a 'managerPermission'
     $canEditType = !$settings['locationId'] || isset($args['managerPermission']) && $args['managerPermission'] != '' && function_exists('user_access') && user_access($args['managerPermission']);
     if ($canEditType) {
         $r .= data_entry_helper::select(array('label' => lang::get('Site Type'), 'id' => 'location_type_id', 'fieldname' => 'location:location_type_id', 'lookupValues' => $lookUpValues));
         data_entry_helper::$javascript .= "\$('#location_type_id').change(function(){\r\n  switch(\$(this).val()){\n";
         for ($i = 1; $i < 4; $i++) {
             if (!empty($args['main_type_term_' . $i])) {
                 $type = helper_base::get_termlist_terms($auth, 'indicia:location_types', array($args['main_type_term_' . $i]));
                 data_entry_helper::$javascript .= "    case \"" . $type[0]['id'] . "\":\n";
                 if (!isset($args['can_change_section_number_' . $i]) || !$args['can_change_section_number_' . $i]) {
                     if ($settings['locationId']) {
                         // not saved yet, so no sections yet created, hence no need to worry about existing value. make number attribute readonly. set value. min value will be 1.
                         data_entry_helper::$javascript .= "      var minValue = \$('[name=" . str_replace(':', '\\\\:', $settings['numSectionsAttr']) . "]').attr('min');\r\n      if(minValue > " . $args['section_number_' . $i] . ") { // existing value is greater than one we want to set\r\n        alert('You are reducing the number of sections below that already existing. Please use the Remove Section button on the Your Route tab to reduce the number of sections to " . $args['section_number_' . $i] . " before changing the Site type');\r\n        return false;\r\n      }\r\n      \$('[name=" . str_replace(':', '\\\\:', $settings['numSectionsAttr']) . "]').val(" . $args['section_number_' . $i] . ").attr('readonly','readonly').css('color','graytext');\n";
                     } else {
                         // not saved yet, so no sections yet created, hence no need to worry about existing value. make number attribute readonly. set value. min value will be 1.
                         data_entry_helper::$javascript .= "      \$('[name=" . str_replace(':', '\\\\:', $settings['numSectionsAttr']) . "]').val(" . $args['section_number_' . $i] . ").attr('readonly','readonly').css('color','graytext');\n";
                     }
                 } else {
                     // user modifiable number of sections. value of attribute is left alone: don't have to worry att his point whether existing data.
                     data_entry_helper::$javascript .= "      \$('[name=" . str_replace(':', '\\\\:', $settings['numSectionsAttr']) . "]').removeAttr('readonly').css('color','');\n";
                 }
                 data_entry_helper::$javascript .= "      break;\n";
             }
         }
         data_entry_helper::$javascript .= "    default: break;\r\n  };\r\n  return true;\r\n});\n";
     }
     if ($settings['locationId']) {
         $r .= '<input type="hidden" name="location:id" id="location:id" value="' . $settings['locationId'] . "\" />\n";
     }
     $r .= data_entry_helper::text_input(array('fieldname' => 'location:name', 'label' => lang::get('Site Name'), 'class' => 'control-width-4 required', 'disabled' => $settings['canEditBody'] ? '' : ' disabled="disabled" '));
     if (!$settings['canEditBody']) {
         $r .= '<p>' . lang::get('This site cannot be edited because there are walks recorded on it. Please contact the site administrator if you think there are details which need changing.') . '</p>';
     } else {
         if (count($settings['walks']) > 0) {
             // can edit it
             $r .= '<p>' . lang::get('This site has walks recorded on it. Please do not change the site details without considering the impact on the existing data.') . '</p>';
         }
     }
     $list = explode(',', str_replace(' ', '', $args['spatial_systems']));
     foreach ($list as $system) {
         $systems[$system] = lang::get($system);
     }
     if (isset(data_entry_helper::$entity_to_load['location:centroid_sref_system']) && in_array(data_entry_helper::$entity_to_load['location:centroid_sref_system'], array('osgb', 'osie'))) {
         data_entry_helper::$entity_to_load['location:centroid_sref_system'] = strtoupper(data_entry_helper::$entity_to_load['location:centroid_sref_system']);
     }
     $r .= data_entry_helper::sref_and_system(array('fieldname' => 'location:centroid_sref', 'geomFieldname' => 'location:centroid_geom', 'label' => 'Grid Ref.', 'systems' => $systems, 'class' => 'required', 'helpText' => lang::get('Click on the map to set the central grid reference.'), 'disabled' => $settings['canEditBody'] ? '' : ' disabled="disabled" '));
     if ($settings['locationId'] && data_entry_helper::$entity_to_load['location:code'] != '' && data_entry_helper::$entity_to_load['location:code'] != null) {
         $r .= data_entry_helper::text_input(array('fieldname' => 'location:code', 'label' => lang::get('Site Code'), 'class' => 'control-width-4', 'disabled' => ' readonly="readonly" '));
     } else {
         $r .= "<p>" . lang::get('The Site Code will be allocated by the Administrator.') . "</p>";
     }
     // setup the map options
     $options = iform_map_get_map_options($args, $auth['read']);
     // find the form blocks that need to go below the map.
     $bottom = '';
     $bottomBlocks = explode("\n", isset($args['bottom_blocks']) ? $args['bottom_blocks'] : '');
     foreach ($bottomBlocks as $block) {
         $bottom .= get_attribute_html($settings['attributes'], $args, array('extraParams' => $auth['read'], 'disabled' => $settings['canEditBody'] ? '' : ' disabled="disabled" '), $block);
     }
     // other blocks to go at the top, next to the map
     if (isset($args['site_help']) && $args['site_help'] != '') {
         $r .= '<p class="ui-state-highlight page-notice ui-corner-all">' . t($args['site_help']) . '</p>';
     }
     $r .= get_attribute_html($settings['attributes'], $args, array('extraParams' => $auth['read']));
     $r .= '</fieldset>';
     $r .= "</div>";
     // left
     $r .= '<div class="right" style="width: 44%">';
     if (!$settings['locationId']) {
         $help = t('Use the search box to find a nearby town or village, then drag the map to pan and click on the map to set the centre grid reference of the transect. ' . 'Alternatively if you know the grid reference you can enter it in the Grid Ref box on the left.');
         $r .= '<p class="ui-state-highlight page-notice ui-corner-all">' . $help . '</p>';
         $r .= data_entry_helper::georeference_lookup(array('label' => lang::get('Search for place'), 'driver' => $args['georefDriver'], 'georefPreferredArea' => $args['georefPreferredArea'], 'georefCountry' => $args['georefCountry'], 'georefLang' => $args['language'], 'readAuth' => $auth['read']));
     }
     if (isset($args['maxPrecision']) && $args['maxPrecision'] != '') {
         $options['clickedSrefPrecisionMax'] = $args['maxPrecision'];
     }
     if (isset($args['minPrecision']) && $args['minPrecision'] != '') {
         $options['clickedSrefPrecisionMin'] = $args['minPrecision'];
     }
     $olOptions = iform_map_get_ol_options($args);
     $options['clickForSpatialRef'] = $settings['canEditBody'];
     $r .= map_helper::map_panel($options, $olOptions);
     $r .= '</div></div>';
     // right
     if (!empty($bottom)) {
         $r .= $bottom;
     }
     if ($args['branch_assignment_permission'] != '') {
         if ($settings['canAllocBranch'] || $settings['locationId']) {
             $r .= self::get_branch_assignment_control($auth['read'], $settings['branchCmsUserAttr'], $args, $settings);
         }
     }
     if ($args['allow_user_assignment']) {
         if ($settings['canAllocUser']) {
             $r .= self::get_user_assignment_control($auth['read'], $settings['cmsUserAttr'], $args);
         } else {
             if (!$settings['locationId']) {
                 // for a new record, we need to link the current user to the location if they are not admin.
                 global $user;
                 $r .= '<input type="hidden" name="locAttr:' . self::$cmsUserAttrId . '" value="' . $user->uid . '">';
             }
         }
     }
     if ($settings['canEditBody']) {
         $r .= '<button type="submit" class="indicia-button right">' . lang::get('Save') . '</button>';
     }
     if ($settings['canEditBody'] && $settings['locationId']) {
         $r .= '<button type="button" class="indicia-button right" id="delete-transect">' . lang::get('Delete') . '</button>';
     }
     $r .= '</form>';
     $r .= '</div>';
     // site-details
     // This must go after the map panel, so it has created its toolbar
     data_entry_helper::$onload_javascript .= "\$('#current-section').change(selectSection);\n";
     if ($settings['canEditBody'] && $settings['locationId']) {
         $walkIDs = array();
         foreach ($settings['walks'] as $walk) {
             $walkIDs[] = $walk['id'];
         }
         $sectionIDs = array();
         foreach ($settings['sections'] as $code => $section) {
             $sectionIDs[] = $section['id'];
         }
         data_entry_helper::$javascript .= "\r\ndeleteSurvey = function(){\r\n  if(confirm(\"" . (count($settings['walks']) > 0 ? count($settings['walks']) . ' ' . lang::get('walks will also be deleted when you delete this location.') . ' ' : '') . lang::get('Are you sure you wish to delete this location?') . "\")){\r\n    deleteWalks([" . implode(',', $walkIDs) . "]);\r\n    deleteSections([" . implode(',', $sectionIDs) . "]);\r\n    \$('#delete-transect').html('Deleting Site');\r\n    deleteLocation(" . $settings['locationId'] . ");\r\n    \$('#delete-transect').html('Done');\r\n    window.location='" . url($args['sites_list_path']) . "';\r\n  };\r\n};\r\n\$('#delete-transect').click(deleteSurvey);\r\n";
     }
     return $r;
 }
Ejemplo n.º 12
0
 /** 
  * Get the map control.
  */
 private static function get_control_map($auth, $args, $tabalias, $options)
 {
     $options = array_merge(iform_map_get_map_options($args, $auth['read']), $options);
     if ($args['interface'] !== 'one_page') {
         $options['tabDiv'] = $tabalias;
     }
     if (self::$want_location_layer) {
         $options['layers'][] = 'locationLayer';
         // Create vector layers to display a selected location onto
         $options['setupJs'] = "\n  locStyleMap = new OpenLayers.StyleMap({\n                  \"default\": new OpenLayers.Style({\n                      fillColor: \"Green\",\n                      strokeColor: \"Black\",\n                      fillOpacity: 0.3,\n                      strokeWidth: 1\n                    })\n    });\n  locationLayer = new OpenLayers.Layer.Vector(\"" . lang::get("LANG_Location_Layer") . "\",\n                                      {styleMap: locStyleMap});\n";
     }
     $olOptions = iform_map_get_ol_options($args);
     return data_entry_helper::map_panel($options, $olOptions);
 }
Ejemplo n.º 13
0
 /** 
  * Get the map control.
  */
 private static function get_control_map($auth, $args, $tabalias, $options)
 {
     $options = array_merge(iform_map_get_map_options($args, $auth['read']), $options);
     $options['layers'][] = 'locationLayer';
     $options['tabDiv'] = $tabalias;
     $olOptions = iform_map_get_ol_options($args);
     return data_entry_helper::map_panel($options, $olOptions);
 }
   /**
    * Return the generated form output.
    * @return Form HTML.
    */
   public static function get_form($args, $node, $response = null)
   {
       global $user;
       global $custom_terms;
       $logged_in = $user->uid > 0;
       $r = '';
       // Get authorisation tokens to update and read from the Warehouse.
       $auth = data_entry_helper::get_read_write_auth($args['website_id'], $args['password']);
       $readAuth = $auth['read'];
       $svcUrl = data_entry_helper::$base_url . '/index.php/services';
       drupal_add_js(drupal_get_path('module', 'iform') . '/media/js/jquery.form.js', 'module');
       data_entry_helper::link_default_stylesheet();
       data_entry_helper::add_resource('jquery_ui');
       $language = iform_lang_iso_639_2($args['language']);
       if ($args['language'] != 'en') {
           data_entry_helper::add_resource('jquery_ui_' . $args['language']);
       }
       // If not logged in: Display an information message.
       // This form should only be called in POST mode when setting the location allocation.
       //  All other posting is now done via AJAX.
       // When invoked by GET there are the following modes:
       // No additional arguments: mode 0.
       // Additional argument - new : mode 1.
       // Additional argument - sample_id=<id> : mode 2.
       // Additional argument - occurrence_id=<id> : mode 3.
       // Additional arguments - merge_sample_id1=<id>&merge_sample_id2=<id> : mode 2.1
       $mode = 0;
       // default mode : output survey selector
       // mode 1: output the main Data Entry page: occurrence list or add/edit occurrence tabs hidden. "Survey" tab active
       // mode 2: output the main Data Entry page, display existing sample. Active tab determined by iform params. No occurence details filled in.
       // mode 2.1: sample 2 has all its occurrences merged into sample 1. sample 2 is then flagged as deleted. sample 1 is then viewed as in normal mode 2.
       // mode 3: output the main Data Entry page, display existing occurrence. "Edit Occurrence" tab active. Occurence details filled in.
       $surveyReadOnly = false;
       // On top of this, things can be flagged as readonly. RO mode 2+4 means no Add Occurrence tab.
       if (!$logged_in) {
           return lang::get('LANG_not_logged_in');
       }
       $parentSample = array();
       $parentLoadID = null;
       $childSample = array();
       $childLoadID = null;
       $thisOccID = -1;
       // IDs have to be >0, so this is outside the valid range
       // Load up attribute details
       $sample_walk_direction_id = self::getAttrID($auth, $args, 'sample', self::ATTR_WALK);
       $sample_reliability_id = self::getAttrID($auth, $args, 'sample', self::ATTR_RELIABILITY);
       $sample_visit_number_id = self::getAttrID($auth, $args, 'sample', self::ATTR_VISIT);
       $sample_wind_id = self::getAttrID($auth, $args, 'sample', self::ATTR_WIND);
       $sample_precipitation_id = self::getAttrID($auth, $args, 'sample', self::ATTR_RAIN);
       $sample_temperature_id = self::getAttrID($auth, $args, 'sample', self::ATTR_TEMP);
       $sample_cloud_id = self::getAttrID($auth, $args, 'sample', self::ATTR_CLOUD);
       $sample_start_time_id = self::getAttrID($auth, $args, 'sample', self::ATTR_START_TIME);
       $sample_end_time_id = self::getAttrID($auth, $args, 'sample', self::ATTR_END_TIME);
       $sample_closure_id = self::getAttrID($auth, $args, 'sample', self::ATTR_CLOSED);
       $uid_attr_id = self::getAttrID($auth, $args, 'sample', self::ATTR_UID);
       $email_attr_id = self::getAttrID($auth, $args, 'sample', self::ATTR_EMAIL);
       $username_attr_id = self::getAttrID($auth, $args, 'sample', self::ATTR_USERNAME);
       $occurrence_confidence_id = self::getAttrID($auth, $args, 'occurrence', self::ATTR_CONFIDENCE);
       $occurrence_count_id = self::getAttrID($auth, $args, 'occurrence', self::ATTR_COUNT);
       $occurrence_approximation_id = self::getAttrID($auth, $args, 'occurrence', self::ATTR_APPROXIMATION);
       $occurrence_territorial_id = self::getAttrID($auth, $args, 'occurrence', self::ATTR_TERRITORIAL);
       $occurrence_atlas_code_id = self::getAttrID($auth, $args, 'occurrence', self::ATTR_ATLAS_CODE);
       $occurrence_overflying_id = self::getAttrID($auth, $args, 'occurrence', self::ATTR_OVERFLYING);
       if (!$sample_closure_id) {
           return '<p>This form must be used with a survey which has the "' . self::ATTR_CLOSED . '" sample attribute allocated to it. Survey_id = ' . $args['survey_id'];
       }
       if (!$uid_attr_id) {
           return '<p>This form must be used with a survey which has the "' . self::ATTR_UID . '" sample attribute allocated to it. Survey_id = ' . $args['survey_id'];
       }
       if (!$email_attr_id) {
           return '<p>This form must be used with a survey which has the "' . self::ATTR_EMAIL . '" sample attribute allocated to it. Survey_id = ' . $args['survey_id'];
       }
       if (!$username_attr_id) {
           return '<p>This form must be used with a survey which has the "' . self::ATTR_USERNAME . '" sample attribute allocated to it. Survey_id = ' . $args['survey_id'];
       }
       if (!$sample_walk_direction_id) {
           return '<p>This form must be used with a survey which has the "' . self::ATTR_WALK . '" sample attribute allocated to it. Survey_id = ' . $args['survey_id'];
       }
       if (!$sample_visit_number_id) {
           return '<p>This form must be used with a survey which has the "' . self::ATTR_VISIT . '" sample attribute allocated to it. Survey_id = ' . $args['survey_id'];
       }
       if (!$occurrence_count_id) {
           return '<p>This form must be used with a survey which has the "' . self::ATTR_COUNT . '" occurrence attribute allocated to it. Survey_id = ' . $args['survey_id'];
       }
       if (!$occurrence_territorial_id) {
           return '<p>This form must be used with a survey which has the "' . self::ATTR_TERRITORIAL . '" occurrence attribute allocated to it. Survey_id = ' . $args['survey_id'];
       }
       if (!$occurrence_atlas_code_id) {
           return '<p>This form must be used with a survey which has the "' . self::ATTR_ATLAS_CODE . '" occurrence attribute allocated to it. Survey_id = ' . $args['survey_id'];
       }
       if ($_POST) {
           if (!array_key_exists('website_id', $_POST)) {
               // non Indicia POST, in this case must be the location allocations. add check to ensure we don't corrept the data by accident
               if (iform_loctools_checkaccess($node, 'admin') && array_key_exists('mnhnlbtw', $_POST)) {
                   iform_loctools_deletelocations($node);
                   foreach ($_POST as $key => $value) {
                       $parts = explode(':', $key);
                       if ($parts[0] == 'location' && $value) {
                           iform_loctools_insertlocation($node, $value, $parts[1]);
                       }
                   }
               }
           }
       } else {
           if (array_key_exists('merge_sample_id1', $_GET) && array_key_exists('merge_sample_id2', $_GET) && user_access($args['edit_permission'])) {
               $mode = 2;
               // first check can access the 2 samples given
               $parentLoadID = $_GET['merge_sample_id1'];
               $url = $svcUrl . '/data/sample/' . $parentLoadID . "?mode=json&view=detail&auth_token=" . $readAuth['auth_token'] . "&nonce=" . $readAuth["nonce"];
               $session = curl_init($url);
               curl_setopt($session, CURLOPT_RETURNTRANSFER, true);
               $entity = json_decode(curl_exec($session), true);
               if (count($entity) == 0 || $entity[0]["parent_id"]) {
                   return '<p>' . lang::get('LANG_No_Access_To_Sample') . ' ' . $parentLoadID . '</p>';
               }
               // The check for id2 is slightly different: there is the possiblity that someone will F5/refresh their browser, after the transfer and delete have taken place.
               // In this case we carry on, but do not do the transfer and delete.
               $url = $svcUrl . '/data/sample/' . $_GET['merge_sample_id2'] . "?mode=json&view=detail&auth_token=" . $readAuth['auth_token'] . "&nonce=" . $readAuth["nonce"];
               $session = curl_init($url);
               curl_setopt($session, CURLOPT_RETURNTRANSFER, true);
               $entity = json_decode(curl_exec($session), true);
               if (count($entity) > 0 && !$entity[0]["parent_id"]) {
                   // now get child samples and point to new parent.
                   $url = $svcUrl . '/data/sample?mode=json&view=detail&auth_token=' . $readAuth['auth_token'] . "&nonce=" . $readAuth["nonce"] . '&parent_id=' . $_GET['merge_sample_id2'];
                   $session = curl_init($url);
                   curl_setopt($session, CURLOPT_RETURNTRANSFER, true);
                   $entities = json_decode(curl_exec($session), true);
                   if (count($entities) > 0) {
                       foreach ($entities as $entity) {
                           $Model = data_entry_helper::wrap(array('id' => $entity['id'], 'parent_id' => $_GET['merge_sample_id1']), 'sample');
                           $request = data_entry_helper::$base_url . "/index.php/services/data/save";
                           $postargs = 'submission=' . json_encode($Model) . '&auth_token=' . $auth['write_tokens']['auth_token'] . '&nonce=' . $auth['write_tokens']['nonce'] . '&persist_auth=true';
                           $postresponse = data_entry_helper::http_post($request, $postargs, false);
                           // the response array will always feature an output, which is the actual response or error message. if it is not json format, assume error text, and json encode that.
                           $response = $postresponse['output'];
                           if (!json_decode($response, true)) {
                               return "<p>" . lang::get('LANG_Error_When_Moving_Sample') . ": id " . $entity['id'] . " : " . $response;
                           }
                       }
                   }
                   // finally delete the no longer used sample
                   $Model = data_entry_helper::wrap(array('id' => $_GET['merge_sample_id2'], 'deleted' => 'true'), 'sample');
                   $request = data_entry_helper::$base_url . "/index.php/services/data/save";
                   $postargs = 'submission=' . json_encode($Model) . '&auth_token=' . $auth['write_tokens']['auth_token'] . '&nonce=' . $auth['write_tokens']['nonce'] . '&persist_auth=true';
                   $postresponse = data_entry_helper::http_post($request, $postargs, false);
                   // the response array will always feature an output, which is the actual response or error message. if it is not json format, assume error text, and json encode that.
                   $response = $postresponse['output'];
                   if (!json_decode($response, true)) {
                       return "<p>" . lang::get('LANG_Error_When_Deleting_Sample') . ": id " . $entity['id'] . " : " . $response;
                   }
               }
           } else {
               if (array_key_exists('sample_id', $_GET)) {
                   $mode = 2;
                   $parentLoadID = $_GET['sample_id'];
               } else {
                   if (array_key_exists('occurrence_id', $_GET)) {
                       $mode = 3;
                       $childLoadID = $_GET['occurrence_id'];
                       $thisOccID = $childLoadID;
                   } else {
                       if (array_key_exists('new', $_GET)) {
                           $mode = 1;
                       }
                   }
               }
           }
           // else default to mode 0
       }
       // define language strings so they can be used for validation translation.
       data_entry_helper::$javascript .= "var translations = [\n";
       foreach ($custom_terms as $key => $value) {
           if (substr($key, 0, 4) != "LANG") {
               data_entry_helper::$javascript .= "  {key: \"" . $key . "\", translated: \"" . $value . "\"},\n";
           }
       }
       data_entry_helper::$javascript .= "];\n";
       // define layers for all maps.
       // each argument is a comma separated list eg:
       // "Name:Lux Outline,URL:http://localhost/geoserver/wms,LAYERS:indicia:nation2,SRS:EPSG:2169,FORMAT:image/png,minScale:0,maxScale:1000000,units:m";
       $optionsArray_Location = array();
       $options = explode(',', $args['locationLayer']);
       foreach ($options as $option) {
           $parts = explode(':', $option);
           $optionName = $parts[0];
           unset($parts[0]);
           $optionsArray_Location[$optionName] = implode(':', $parts);
       }
       // Work out list of locations this user can see.
       $locations = iform_loctools_listlocations($node);
       if ($locations != 'all') {
           data_entry_helper::$javascript .= "var locationList = [" . implode(',', $locations) . "];\n";
       }
       drupal_add_js(drupal_get_path('module', 'iform') . '/media/js/hasharray.js', 'module');
       drupal_add_js(drupal_get_path('module', 'iform') . '/media/js/jquery.datagrid.js', 'module');
       if (method_exists(get_called_class(), 'getHeaderHTML')) {
           $r .= call_user_func(array(get_called_class(), 'getHeaderHTML'), $args);
       }
       // Work out list of locations this user can see.
       // $locations = iform_loctools_listlocations($node);
       ///////////////////////////////////////////////////////////////////
       // default mode 0 : display a page with tabs for survey selector,
       // locations allocator and reports (last two require permissions)
       ///////////////////////////////////////////////////////////////////
       if ($mode == 0) {
           // If the user has permissions, add tabs so can choose to see
           // locations allocator
           $tabs = array('#surveyList' => lang::get('LANG_Surveys'));
           if (iform_loctools_checkaccess($node, 'admin')) {
               $tabs['#setLocations'] = lang::get('LANG_Allocate_Locations');
           }
           if (iform_loctools_checkaccess($node, 'superuser')) {
               $tabs['#downloads'] = lang::get('LANG_Download');
           }
           if (count($tabs) > 1) {
               $r .= "<div id=\"controls\">" . data_entry_helper::enable_tabs(array('divId' => 'controls', 'active' => '#surveyList')) . "<div id=\"temp\"></div>";
               $r .= data_entry_helper::tab_header(array('tabs' => $tabs));
           }
           if ($locations == 'all') {
               $useloclist = 'NO';
               $loclist = '-1';
           } else {
               // an empty list will cause an sql error, lids must be > 0, so push a -1 to prevent the error.
               if (empty($locations)) {
                   $locations[] = -1;
               }
               $useloclist = 'YES';
               $loclist = implode(',', $locations);
           }
           // Create the Survey list datagrid for this user.
           drupal_add_js("jQuery(document).ready(function(){\n  \$('div#smp_grid').indiciaDataGrid('rpt:reports_for_prebuilt_forms/MNHNL/mnhnl_btw_list_samples', {\n    indiciaSvc: '" . $svcUrl . "',\n    dataColumns: ['location_name', 'date', 'num_visit', 'num_occurrences', 'num_taxa'],\n    reportColumnTitles: {location_name : '" . lang::get('LANG_Transect') . "', date : '" . lang::get('LANG_Date') . "', num_visit : '" . lang::get('LANG_Visit_No') . "', num_occurrences : '" . lang::get('LANG_Num_Occurrences') . "', num_taxa : '" . lang::get('LANG_Num_Species') . "'},\n    actionColumns: {" . lang::get('LANG_Show') . " : \"" . url('node/' . $node->nid, array('query' => 'sample_id=£id£')) . "\"},\n    auth : { nonce : '" . $readAuth['nonce'] . "', auth_token : '" . $readAuth['auth_token'] . "'},\n    parameters : { survey_id : '" . $args['survey_id'] . "', visit_attr_id : '" . $sample_visit_number_id . "', closed_attr_id : '" . $sample_closure_id . "', use_location_list : '" . $useloclist . "', locations : '" . $loclist . "'},\n    itemsPerPage : 12,\n    condCss : {field : 'closed', value : '0', css: 'mnhnl-btw-highlight'},\n    cssOdd : ''\n  });\n});\n      ", 'inline');
           data_entry_helper::$javascript .= "\n// Create Layers.\nvar locationListLayer;\nmapInitialisationHooks.push(function (div) {\n      \"use strict\";";
           if ($locations == 'all' || $loclist != '-1') {
               data_entry_helper::$javascript .= "\n  var WMSoptions = {SERVICE: 'WMS', VERSION: '1.1.0', STYLES: '',\n        SRS: div.map.projection.proj.srsCode, /* Now takes it from map */\n        FORMAT: '" . $optionsArray_Location['FORMAT'] . "',\n        TRANSPARENT: 'true', ";
               if ($locations != 'all') {
                   // when given a restricted feature list we have to use the feature id to filter in order to not go over 2000 char limit on the URL
                   // Can only generate the feature id if we access a table directly, not through a view. Go direct to the locations table.
                   // don't need to worry about parent_id in this case as we know exactly which features we want.
                   // need to use btw_transects view for unrestricted so we can filter by parent_id=NULL.
                   $locFeatures = array();
                   foreach ($locations as $location) {
                       $locFeatures[] = "locations." . $location;
                   }
                   data_entry_helper::$javascript .= "\n        LAYERS: 'indicia:locations',\n        FEATUREID: '" . implode(',', $locFeatures) . "'";
               } else {
                   data_entry_helper::$javascript .= " LAYERS: '" . $optionsArray_Location['LAYERS'] . "', CQL_FILTER: 'website_id=" . $args['website_id'] . "'";
               }
               data_entry_helper::$javascript .= "\n  };\n  locationListLayer = new OpenLayers.Layer.WMS('" . $optionsArray_Location['Name'] . "',\n        '" . (function_exists(iform_proxy_url) ? iform_proxy_url($optionsArray_Location['URL']) : $optionsArray_Location['URL']) . "',\n        WMSoptions, {\n        minScale: " . $optionsArray_Location['minScale'] . ",\n        maxScale: " . $optionsArray_Location['maxScale'] . ",\n        units: '" . $optionsArray_Location['units'] . "',\n        isBaseLayer: false,\n        singleTile: true\n  });\n  div.map.addLayer(locationListLayer);\n});\n";
           }
           $r .= '
 <div id="surveyList" class="mnhnl-btw-datapanel"><div id="smp_grid"></div>
   <form><input type="button" value="' . lang::get('LANG_Add_Survey') . '" onclick="window.location.href=\'' . url('node/' . $node->nid, array('query' => 'new')) . '\'"></form></div>';
           // Add the locations allocator if user has admin rights.
           if (iform_loctools_checkaccess($node, 'admin')) {
               $r .= '
 <div id="setLocations" class="mnhnl-btw-datapanel">
   <form method="post">
     <input type="hidden" id="mnhnlbtw" name="mnhnlbtw" value="mnhnlbtw" />';
               $url = $svcUrl . '/data/location?mode=json&view=detail&auth_token=' . $readAuth['auth_token'] . "&nonce=" . $readAuth["nonce"] . "&parent_id=NULL&orderby=name&columns=id,name,parent_id";
               $session = curl_init($url);
               curl_setopt($session, CURLOPT_RETURNTRANSFER, true);
               $entities = json_decode(curl_exec($session), true);
               $userlist = iform_loctools_listusers($node);
               if (!empty($entities)) {
                   foreach ($entities as $entity) {
                       if (!$entity["parent_id"]) {
                           // only assign parent locations.
                           $r .= "\n<label for=\"location:" . $entity["id"] . "\">" . $entity["name"] . ":</label><select id=\"location:" . $entity["id"] . "\" name=\"location:" . $entity["id"] . "\"><option value=\"\" >&lt;" . lang::get('LANG_Not_Allocated') . "&gt;</option>";
                           $defaultuserid = iform_loctools_getuser($node, $entity["id"]);
                           foreach ($userlist as $uid => $a_user) {
                               $r .= "<option value=\"" . $uid . "\" " . ($uid == $defaultuserid ? 'selected="selected" ' : '') . ">" . $a_user->name . "</option>";
                           }
                           $r .= "</select>";
                       }
                   }
               }
               $r .= "\n      <input type=\"submit\" class=\"ui-state-default ui-corner-all\" value=\"" . lang::get('Save Location Allocations') . "\" />\n    </form>\n  </div>";
           }
           // Add the downloader if user has manager (superuser) rights.
           if (iform_loctools_checkaccess($node, 'superuser')) {
               $r .= '
 <div id="downloads" class="mnhnl-btw-datapanel">
   <form method="post" action="' . data_entry_helper::$base_url . '/index.php/services/report/requestReport?report=reports_for_prebuilt_forms/MNHNL/mnhnl_btw_transect_direction_report.xml&reportSource=local&auth_token=' . $readAuth['auth_token'] . '&nonce=' . $readAuth['nonce'] . '&mode=csv">
     <p>' . lang::get('LANG_Direction_Report') . '</p>
     <input type="hidden" name="params" value=\'{"survey_id":' . $args['survey_id'] . ', "direction_attr_id":' . $sample_walk_direction_id . ', "closed_attr_id":' . $sample_closure_id . '}\' />
     <input type="submit" class="ui-state-default ui-corner-all" value="' . lang::get('LANG_Direction_Report_Button') . '">
   </form>
   <form method="post" action="' . data_entry_helper::$base_url . '/index.php/services/report/requestReport?report=reports_for_prebuilt_forms/MNHNL/mnhnl_btw_verified_data_report.xml&reportSource=local&auth_token=' . $readAuth['auth_token'] . '&nonce=' . $readAuth['nonce'] . '&mode=csv">
     <p>' . lang::get('LANG_Verified_Data_Report') . '</p>
     <input type="hidden" name="params" value=\'{"survey_id":' . $args['survey_id'] . '}\' />
     <input type="submit" class="ui-state-default ui-corner-all" value="' . lang::get('LANG_Verified_Data_Report_Button') . '">
   </form>
   <form method="post" action="' . data_entry_helper::$base_url . '/index.php/services/report/requestReport?report=reports_for_prebuilt_forms/MNHNL/mnhnl_btw_download_report_2.xml&reportSource=local&auth_token=' . $readAuth['auth_token'] . '&nonce=' . $readAuth['nonce'] . '&mode=csv">
     <p>' . lang::get('LANG_Initial_Download') . '</p>
     <input type="hidden" name="params" value=\'{"survey_id":' . $args['survey_id'] . ', "closed_attr_id":' . $sample_closure_id . ', "download": "INITIAL", "quality": "!R", "occattrs": "' . $occurrence_confidence_id . ',' . $occurrence_count_id . ',' . $occurrence_approximation_id . ',' . $occurrence_territorial_id . ',' . $occurrence_atlas_code_id . ',' . $occurrence_overflying_id . '", "smpattrs" : "' . $sample_walk_direction_id . ',' . $sample_reliability_id . ',' . $sample_visit_number_id . ',' . $sample_wind_id . ',' . $sample_precipitation_id . ',' . $sample_temperature_id . ',' . $sample_cloud_id . ',' . $sample_start_time_id . ',' . $sample_end_time_id . ',' . $sample_closure_id . ',' . $uid_attr_id . ',' . $email_attr_id . ',' . $username_attr_id . '"}\' />
     <input type="submit" class="ui-state-default ui-corner-all" value="' . lang::get('LANG_Initial_Download_Button') . '">
   </form>
   <form method="post" action="' . data_entry_helper::$base_url . '/index.php/services/report/requestReport?report=reports_for_prebuilt_forms/MNHNL/mnhnl_btw_download_report_2.xml&reportSource=local&auth_token=' . $readAuth['auth_token'] . '&nonce=' . $readAuth['nonce'] . '&mode=csv">
     <p>' . lang::get('LANG_Confirm_Download') . '</p>
     <input type="hidden" name="params" value=\'{"survey_id":' . $args['survey_id'] . ', "closed_attr_id":' . $sample_closure_id . ', "download": "CONFIRM", "quality": "V", "occattrs": "' . $occurrence_confidence_id . ',' . $occurrence_count_id . ',' . $occurrence_approximation_id . ',' . $occurrence_territorial_id . ',' . $occurrence_atlas_code_id . ',' . $occurrence_overflying_id . '", "smpattrs" : "' . $sample_walk_direction_id . ',' . $sample_reliability_id . ',' . $sample_visit_number_id . ',' . $sample_wind_id . ',' . $sample_precipitation_id . ',' . $sample_temperature_id . ',' . $sample_cloud_id . ',' . $sample_start_time_id . ',' . $sample_end_time_id . ',' . $sample_closure_id . ',' . $uid_attr_id . ',' . $email_attr_id . ',' . $username_attr_id . '"}\' />
     <input type="submit" class="ui-state-default ui-corner-all" value="' . lang::get('LANG_Confirm_Download_Button') . '">
   </form>
   <form method="post" action="' . data_entry_helper::$base_url . '/index.php/services/report/requestReport?report=reports_for_prebuilt_forms/MNHNL/mnhnl_btw_download_report_2.xml&reportSource=local&auth_token=' . $readAuth['auth_token'] . '&nonce=' . $readAuth['nonce'] . '&mode=csv">
     <p>' . lang::get('LANG_Final_Download') . '</p>
     <input type="hidden" name="params" value=\'{"survey_id":' . $args['survey_id'] . ', "closed_attr_id":' . $sample_closure_id . ', "download": "FINAL", "quality": "V", "occattrs": "' . $occurrence_confidence_id . ',' . $occurrence_count_id . ',' . $occurrence_approximation_id . ',' . $occurrence_territorial_id . ',' . $occurrence_atlas_code_id . ',' . $occurrence_overflying_id . '", "smpattrs" : "' . $sample_walk_direction_id . ',' . $sample_reliability_id . ',' . $sample_visit_number_id . ',' . $sample_wind_id . ',' . $sample_precipitation_id . ',' . $sample_temperature_id . ',' . $sample_cloud_id . ',' . $sample_start_time_id . ',' . $sample_end_time_id . ',' . $sample_closure_id . ',' . $uid_attr_id . ',' . $email_attr_id . ',' . $username_attr_id . '"}\' />
     <input type="submit" class="ui-state-default ui-corner-all" value="' . lang::get('LANG_Final_Download_Button') . '">
   </form>
   <form method="post" action="' . data_entry_helper::$base_url . '/index.php/services/report/requestReport?report=reports_for_prebuilt_forms/MNHNL/mnhnl_btw_download_report_2.xml&reportSource=local&auth_token=' . $readAuth['auth_token'] . '&nonce=' . $readAuth['nonce'] . '&mode=csv">
     <p>' . lang::get('LANG_Complete_Final_Download') . '</p>
     <input type="hidden" name="params" value=\'{"survey_id":' . $args['survey_id'] . ', "closed_attr_id":' . $sample_closure_id . ', "download": "OFF", "quality": "NA", "occattrs": "' . $occurrence_confidence_id . ',' . $occurrence_count_id . ',' . $occurrence_approximation_id . ',' . $occurrence_territorial_id . ',' . $occurrence_atlas_code_id . ',' . $occurrence_overflying_id . '", "smpattrs" : "' . $sample_walk_direction_id . ',' . $sample_reliability_id . ',' . $sample_visit_number_id . ',' . $sample_wind_id . ',' . $sample_precipitation_id . ',' . $sample_temperature_id . ',' . $sample_cloud_id . ',' . $sample_start_time_id . ',' . $sample_end_time_id . ',' . $sample_closure_id . ',' . $uid_attr_id . ',' . $email_attr_id . ',' . $username_attr_id . '"}\' />
     <input type="submit" class="ui-state-default ui-corner-all" value="' . lang::get('LANG_Complete_Final_Download_Button') . '">
   </form>
 </div>';
           }
           // Create Map
           $options = iform_map_get_map_options($args, $readAuth);
           $olOptions = iform_map_get_ol_options($args);
           //      if($locations == 'all' || $loclist != '-1')
           //        $options['layers'] = array('locationListLayer');
           $options['searchLayer'] = 'false';
           $options['editLayer'] = 'false';
           $options['initialFeatureWkt'] = null;
           $options['proxy'] = '';
           $options['scroll_wheel_zoom'] = false;
           $options['width'] = 'auto';
           // TBD remove from arglist
           $r .= "<div class=\"mnhnl-btw-mappanel\">\n" . data_entry_helper::map_panel($options, $olOptions) . "</div>\n";
           data_entry_helper::$javascript .= "\n\$('#controls').bind('tabsshow', function(event, ui) {\n  var y = \$('.mnhnl-btw-datapanel:visible').outerHeight(true) + \$('.mnhnl-btw-datapanel:visible').position().top;\n  if(y < \$('.mnhnl-btw-mappanel').outerHeight(true)+ \$('.mnhnl-btw-mappanel').position().top){\n    y = \$('.mnhnl-btw-mappanel').outerHeight(true)+ \$('.mnhnl-btw-mappanel').position().top;\n  }\n  \$('#controls').height(y - \$('#controls').position().top);\n});\n";
           if (count($tabs) > 1) {
               // close tabs div if present
               $r .= "</div>";
           }
           if (method_exists(get_called_class(), 'getTrailerHTML')) {
               $r .= call_user_func(array(get_called_class(), 'getTrailerHTML'), $args);
           }
           return $r;
       }
       ///////////////////////////////////////////////////////////////////
       // At this point there are 3 modes:
       // Adding a new survey
       // editing/showing an existing survey
       // editing/showing an existing occurrence
       // First load the occurrence (and its position sample) if provided
       // Then load the parent sample if provided, or derived from occurrence.
       // $occReadOnly is set if the occurrence has been downloaded. Not even an admin user can modify it in this case.
       data_entry_helper::$javascript .= "\n// Create Layers.\nvar locationLayer, occListLayer, control;\nmapInitialisationHooks.push(function (div) {\n  \"use strict\";\n  // Create vector layers: one to display the location onto, and another for the occurrence list\n  // the default edit layer is used for the occurrences themselves\n  var locStyleMap = new OpenLayers.StyleMap({\n      'default': new OpenLayers.Style({\n        fillColor: 'Green',\n        strokeColor: 'Black',\n        fillOpacity: 0.2,\n        strokeWidth: 1\n  })});\n  locationLayer = new OpenLayers.Layer.Vector('" . lang::get("LANG_Location_Layer") . "', {styleMap: locStyleMap});\n  var occStyleMap = new OpenLayers.StyleMap({\n      'default': new OpenLayers.Style({\n        pointRadius: 3,\n        fillColor: 'Red',\n        fillOpacity: 0.3,\n        strokeColor: 'Red',\n        strokeWidth: 1\n  })});\n  occListLayer = new OpenLayers.Layer.Vector(\"" . lang::get("LANG_Occurrence_List_Layer") . "\", {styleMap: occStyleMap});\n  div.map.addLayer(locationLayer);\n  div.map.addLayer(occListLayer);\n  var control = new OpenLayers.Control.SelectFeature(occListLayer);\n  occListLayer.map.addControl(control);\n  function onPopupClose(evt) {\n    // 'this' is the popup.\n    control.unselect(this.feature);\n  }\n  function onFeatureSelect(evt) {\n    feature = evt.feature;\n    popup = new OpenLayers.Popup.FramedCloud(\"featurePopup\",\n               feature.geometry.getBounds().getCenterLonLat(),\n                             new OpenLayers.Size(100,100),\n                             feature.attributes.taxon + \" (\" + feature.attributes.count + \")\",\n                             null, true, onPopupClose);\n    feature.popup = popup;\n    popup.feature = feature;\n    feature.layer.map.addPopup(popup);\n  }\n  function onFeatureUnselect(evt) {\n    feature = evt.feature;\n    if (feature.popup) {\n        popup.feature = null;\n        feature.layer.map.removePopup(feature.popup);\n        feature.popup.destroy();\n        feature.popup = null;\n    }\n  }\n  occListLayer.events.on({\n    'featureselected': onFeatureSelect,\n    'featureunselected': onFeatureUnselect\n  });\n  control.activate();\n});\n";
       $occReadOnly = false;
       $childSample = array();
       if ($childLoadID) {
           // load the occurrence and its associated sample (which holds the position)
           $url = $svcUrl . '/data/occurrence/' . $childLoadID;
           $url .= "?mode=json&view=detail&auth_token=" . $readAuth['auth_token'] . "&nonce=" . $readAuth["nonce"];
           $session = curl_init($url);
           curl_setopt($session, CURLOPT_RETURNTRANSFER, true);
           $entity = json_decode(curl_exec($session), true);
           if (count($entity) == 0) {
               return '<p>' . lang::get('LANG_No_Access_To_Occurrence') . '</p>';
           }
           foreach ($entity[0] as $key => $value) {
               $childSample['occurrence:' . $key] = $value;
           }
           if ($entity[0]['downloaded_flag'] == 'F') {
               // Final download complete, now readonly
               $occReadOnly = true;
           }
           $url = $svcUrl . '/data/sample/' . $childSample['occurrence:sample_id'];
           $url .= "?mode=json&view=detail&auth_token=" . $readAuth['auth_token'] . "&nonce=" . $readAuth["nonce"];
           $session = curl_init($url);
           curl_setopt($session, CURLOPT_RETURNTRANSFER, true);
           $entity = json_decode(curl_exec($session), true);
           if (count($entity) == 0) {
               return '<p>' . lang::get('LANG_No_Access_To_Occurrence') . '</p>';
           }
           foreach ($entity[0] as $key => $value) {
               $childSample['sample:' . $key] = $value;
           }
           $childSample['sample:geom'] = '';
           // value received from db is not WKT, which is assumed by all the code.
           $childSample['taxon'] = $childSample['occurrence:taxon'];
           $parentLoadID = $childSample['sample:parent_id'];
       }
       $parentSample = array();
       if ($parentLoadID) {
           // load the container master sample
           $url = $svcUrl . '/data/sample/' . $parentLoadID;
           $url .= "?mode=json&view=detail&auth_token=" . $readAuth['auth_token'] . "&nonce=" . $readAuth["nonce"];
           $session = curl_init($url);
           curl_setopt($session, CURLOPT_RETURNTRANSFER, true);
           $entity = json_decode(curl_exec($session), true);
           if (count($entity) == 0) {
               return '<p>' . lang::get('LANG_No_Access_To_Sample') . '</p>';
           }
           foreach ($entity[0] as $key => $value) {
               $parentSample['sample:' . $key] = $value;
           }
           if (is_array($locations) && !in_array($entity[0]["location_id"], $locations)) {
               return '<p>' . lang::get('LANG_No_Access_To_Location') . '</p>';
           }
           if ($entity[0]["parent_id"]) {
               return '<p>' . lang::get('LANG_No_Access_To_Sample') . '</p>';
           }
           $parentSample['sample:date'] = $parentSample['sample:date_start'];
           // bit of a bodge
           $childSample['sample:date'] = $parentSample['sample:date'];
           // enforce a match between child and parent sample dates
           // default values for attributes from DB are picked up automatically.
       }
       data_entry_helper::$entity_to_load = $parentSample;
       $attributes = data_entry_helper::getAttributes(array('id' => data_entry_helper::$entity_to_load['sample:id'], 'valuetable' => 'sample_attribute_value', 'attrtable' => 'sample_attribute', 'key' => 'sample_id', 'fieldprefix' => 'smpAttr', 'extraParams' => $readAuth));
       $closedFieldName = $attributes[$sample_closure_id]['fieldname'];
       $closedFieldValue = data_entry_helper::check_default_value($closedFieldName, array_key_exists('default', $attributes[$sample_closure_id]) ? $attributes[$sample_closure_id]['default'] : '0');
       // default is not closed
       if ($closedFieldValue == '') {
           $closedFieldValue = '0';
       }
       if ($closedFieldValue == '1' && !user_access($args['edit_permission'])) {
           // sample has been closed, no admin perms. Everything now set to read only.
           $surveyReadOnly = true;
           $disabledText = "disabled=\"disabled\"";
           $defAttrOptions = array('extraParams' => $readAuth, 'disabled' => $disabledText);
       } else {
           // sample editable. Admin users can modify closed samples.
           $disabledText = "";
           $defAttrOptions = array('extraParams' => $readAuth);
       }
       // with the AJAX code, we deal with the validation semi manually: Form name is meant be invalid as we only want code included.
       data_entry_helper::enable_validation(null);
       $r .= "<div id=\"controls\">\n";
       $activeTab = 'survey';
       // mode 1 = new Sample, display sample.
       if ($mode == 2) {
           // have specified a sample ID
           if ($args["on_edit_survey_nav"] == "survey") {
               $activeTab = 'survey';
           } else {
               if ($surveyReadOnly || $args["on_edit_survey_nav"] == "list") {
                   $activeTab = 'occurrenceList';
               } else {
                   $activeTab = 'occurrence';
               }
           }
           if ($surveyReadOnly) {
               data_entry_helper::$javascript .= "jQuery('#occ-form').hide();";
           }
       } else {
           if ($mode == 3) {
               // have specified an occurrence ID
               $activeTab = 'occurrence';
           }
       }
       // Set Up form tabs.
       $r .= data_entry_helper::enable_tabs(array('divId' => 'controls', 'active' => $activeTab));
       $r .= "<div id=\"temp\"></div>";
       $r .= data_entry_helper::tab_header(array('tabs' => array('#survey' => lang::get('LANG_Survey'), '#occurrence' => lang::get($surveyReadOnly || $occReadOnly ? 'LANG_Show_Occurrence' : (isset($childSample['sample:id']) ? 'LANG_Edit_Occurrence' : 'LANG_Add_Occurrence')), '#occurrenceList' => lang::get('LANG_Occurrence_List'))));
       // Set up main Survey Form.
       $r .= "<div id=\"survey\" class=\"mnhnl-btw-datapanel\">\n  <p id=\"read-only-survey\"><strong>" . lang::get('LANG_Read_Only_Survey') . "</strong></p>";
       if (user_access($args['edit_permission']) && array_key_exists('sample:id', data_entry_helper::$entity_to_load)) {
           // check for other surveys of same date/transect: only if admin user.
           $url = $svcUrl . '/data/sample?mode=json&view=detail&auth_token=' . $readAuth['auth_token'] . "&nonce=" . $readAuth["nonce"] . "&date_start=" . $parentSample['sample:date_start'] . "&location_id=" . $parentSample['sample:location_id'];
           $session = curl_init($url);
           curl_setopt($session, CURLOPT_RETURNTRANSFER, true);
           $entity = json_decode(curl_exec($session), true);
           if (count($entity) > 1) {
               // ignore ourselves!
               $r .= "<div id=\"mergeSurveys\"><p><strong>" . lang::get('LANG_Found_Mergable_Surveys') . "</strong></p>";
               foreach ($entity as $survey) {
                   if ($survey['id'] != $parentSample['sample:id']) {
                       $r .= "<form action=\"" . url('node/' . $node->nid, array()) . "\" method=\"get\"><input type=\"submit\" value=\"" . lang::get('LANG_Merge_With_ID') . " " . $survey['id'] . "\"><input type=\"hidden\" name=\"merge_sample_id1\" value=\"" . $parentSample['sample:id'] . "\" /><input type=\"hidden\" name=\"merge_sample_id2\" value=\"" . $survey['id'] . "\" /></form>";
                   }
               }
               $r .= "</div>";
           }
       }
       $r .= "<form id=\"SurveyForm\" action=\"" . iform_ajaxproxy_url($node, 'sample') . "\" method=\"post\">\n    <input type=\"hidden\" id=\"website_id\" name=\"website_id\" value=\"" . $args['website_id'] . "\" />\n    <input type=\"hidden\" id=\"sample:survey_id\" name=\"sample:survey_id\" value=\"" . $args['survey_id'] . "\" />";
       if (array_key_exists('sample:id', data_entry_helper::$entity_to_load)) {
           $r .= "<input type=\"hidden\" id=\"sample:id\" name=\"sample:id\" value=\"" . data_entry_helper::$entity_to_load['sample:id'] . "\" />\n";
       } else {
           $r .= "<input type=\"hidden\" id=\"sample:id\" name=\"sample:id\" value=\"\" disabled=\"disabled\" />\n";
           // GvB 19/Nov/2012 : change to user detail defaults
           // logic is now much simpler, and they are only included/created if the sample is new.
           $fieldName = $attributes[$uid_attr_id]['fieldname'];
           $fieldValue = data_entry_helper::check_default_value($fieldName, $user->uid);
           $r .= "<input type=\"hidden\" name=\"" . $fieldName . "\" value=\"" . $fieldValue . "\" />\n";
           $fieldName = $attributes[$email_attr_id]['fieldname'];
           $fieldValue = data_entry_helper::check_default_value($fieldName, $user->mail);
           $r .= "<input type=\"hidden\" name=\"" . $fieldName . "\" value=\"" . $fieldValue . "\" />\n";
           $fieldName = $attributes[$username_attr_id]['fieldname'];
           $fieldValue = data_entry_helper::check_default_value($fieldName, $user->name);
           $r .= "<input type=\"hidden\" name=\"" . $fieldName . "\" value=\"" . $fieldValue . "\" />\n";
       }
       $defAttrOptions['validation'] = array('required');
       if ($locations == 'all') {
           $locOptions = array_merge(array('label' => lang::get('LANG_Transect')), $defAttrOptions);
           $locOptions['extraParams'] = array_merge(array('parent_id' => 'NULL', 'view' => 'detail', 'orderby' => 'name'), $locOptions['extraParams']);
           $r .= data_entry_helper::location_select($locOptions);
       } else {
           // can't use location select due to location filtering.
           $r .= "<label for=\"imp-location\">" . lang::get('LANG_Transect') . ":</label>\n<select id=\"imp-location\" name=\"sample:location_id\" " . $disabled_text . " class=\" \"  >";
           $url = $svcUrl . '/data/location?mode=json&view=detail&parent_id=NULL&orderby=name&auth_token=' . $readAuth['auth_token'] . '&nonce=' . $readAuth["nonce"];
           $session = curl_init($url);
           curl_setopt($session, CURLOPT_RETURNTRANSFER, true);
           $entities = json_decode(curl_exec($session), true);
           if (!empty($entities)) {
               foreach ($entities as $entity) {
                   if (in_array($entity["id"], $locations)) {
                       if ($entity["id"] == data_entry_helper::$entity_to_load['sample:location_id']) {
                           $selected = 'selected="selected"';
                       } else {
                           $selected = '';
                       }
                       $r .= "<option value=\"" . $entity["id"] . "\" " . $selected . ">" . $entity["name"] . "</option>";
                   }
               }
           }
           $r .= "</select><span class=\"deh-required\">*</span><br />";
       }
       $languageFilteredAttrOptions = $defAttrOptions + array('language' => iform_lang_iso_639_2($args['language']));
       $r .= data_entry_helper::outputAttribute($attributes[$sample_walk_direction_id], $languageFilteredAttrOptions) . ($sample_reliability_id ? data_entry_helper::outputAttribute($attributes[$sample_reliability_id], $languageFilteredAttrOptions) : "<span style=\"display: none;\">Sample attribute '" . self::ATTR_RELIABILITY . "' not assigned to this survey</span>") . data_entry_helper::outputAttribute($attributes[$sample_visit_number_id], array_merge($languageFilteredAttrOptions, array('default' => 1, 'noBlankText' => true)));
       if (isset(data_entry_helper::$entity_to_load['sample:date']) && preg_match('/^(\\d{4})/', data_entry_helper::$entity_to_load['sample:date'])) {
           // Date has 4 digit year first (ISO style) - convert date to expected output format
           $d = new DateTime(data_entry_helper::$entity_to_load['sample:date']);
           data_entry_helper::$entity_to_load['sample:date'] = $d->format('d/m/Y');
       }
       if ($args['language'] != 'en') {
           data_entry_helper::add_resource('jquery_ui_' . $args['language']);
       }
       // this will autoload the jquery_ui resource. The date_picker does not have access to the args.
       if ($surveyReadOnly) {
           $r .= data_entry_helper::text_input(array_merge($defAttrOptions, array('label' => lang::get('LANG_Date'), 'fieldname' => 'sample:date', 'disabled' => $disabledText)));
       } else {
           $r .= data_entry_helper::date_picker(array('label' => lang::get('LANG_Date'), 'fieldname' => 'sample:date', 'class' => 'vague-date-picker'));
       }
       $r .= ($sample_wind_id ? data_entry_helper::outputAttribute($attributes[$sample_wind_id], $languageFilteredAttrOptions) : "<span style=\"display: none;\">Sample attribute '" . self::ATTR_WIND . "' not assigned to this survey</span>") . ($sample_precipitation_id ? data_entry_helper::outputAttribute($attributes[$sample_precipitation_id], $languageFilteredAttrOptions) : "<span style=\"display: none;\">Sample attribute '" . self::ATTR_RAIN . "' not assigned to this survey</span>") . ($sample_temperature_id ? data_entry_helper::outputAttribute($attributes[$sample_temperature_id], array_merge($defAttrOptions, array('suffixTemplate' => 'nosuffix'))) . "<span class=\"attr-trailer\"> &deg;C</span><br />" : "<span style=\"display: none;\">Sample attribute '" . self::ATTR_TEMP . "' not assigned to this survey</span>") . ($sample_cloud_id ? data_entry_helper::outputAttribute($attributes[$sample_cloud_id], $defAttrOptions) : "<span style=\"display: none;\">Sample attribute '" . self::ATTR_CLOUD . "' not assigned to this survey</span>") . ($sample_start_time_id ? data_entry_helper::outputAttribute($attributes[$sample_start_time_id], array_merge($defAttrOptions, array('suffixTemplate' => 'nosuffix'))) . "<span class=\"attr-trailer\"> hh:mm</span><br />" : "<span style=\"display: none;\">Sample attribute '" . self::ATTR_START_TIME . "' not assigned to this survey</span>") . ($sample_end_time_id ? data_entry_helper::outputAttribute($attributes[$sample_end_time_id], array_merge($defAttrOptions, array('suffixTemplate' => 'nosuffix'))) . "<span class=\"attr-trailer\"> hh:mm</span><br />" : "<span style=\"display: none;\">Sample attribute '" . self::ATTR_END_TIME . "' not assigned to this survey</span>");
       data_entry_helper::$javascript .= "\njQuery('.attr-trailer').prev('br').remove();\n";
       unset($defAttrOptions['suffixTemplate']);
       unset($defAttrOptions['validation']);
       if (user_access($args['edit_permission'])) {
           //  users with admin permissions can override the closing of the
           // sample by unchecking the checkbox.
           // Because this is attached to the sample, we have to include the sample required fields in the
           // the post. This means they can't be disabled, so we enable all fields in this case.
           // Normal users can only set this to closed, and they do this using a button/hidden field.
           $r .= data_entry_helper::outputAttribute($attributes[$sample_closure_id], $defAttrOptions);
           // In addition admin users can delete a survey/sample.
           $r .= data_entry_helper::checkbox(array('label' => lang::get('Deleted'), 'fieldname' => 'sample:deleted', 'id' => 'main-sample-deleted'));
       } else {
           // hidden closed
           $r .= "<input type=\"hidden\" id=\"main-sample-closed\" name=\"" . $closedFieldName . "\" value=\"" . $closedFieldValue . "\" />\n";
       }
       data_entry_helper::$javascript .= "\n\$.validator.messages.required = \"" . lang::get('validation_required') . "\";\n\$.validator.defaults.onsubmit = false; // override default - so that we handle all submission validation.\n";
       if (!$surveyReadOnly) {
           // NB that we don't even include the buttons when readonly.
           data_entry_helper::$javascript .= "\njQuery('#read-only-survey').hide();\njQuery('#ro-sur-occ-warn').hide();\n";
           $r .= "<input type=button id=\"close1\" class=\"ui-state-default ui-corner-all \" value=\"" . lang::get('LANG_Save_Survey_Details') . "\";\n        onclick=\"var result = \$('#SurveyForm input').valid();\n          var result2 = \$('#SurveyForm select').valid();\n          if (!result || !result2) {\n              return;\n            }\n            jQuery('#close1').addClass('loading-button');\n            jQuery('#SurveyForm').submit();\">\n";
           if (!user_access($args['edit_permission'])) {
               if ($mode == 1) {
                   data_entry_helper::$javascript .= "jQuery('#close2').hide();\n";
               }
               $r .= "<input type=button id=\"close2\" class=\"ui-state-default ui-corner-all \" value=\"" . lang::get('LANG_Save_Survey_And_Close') . "\"\n        onclick=\"if(confirm('" . lang::get('LANG_Close_Survey_Confirm') . "')){\n          var result = \$('#SurveyForm input').valid();\n          var result2 = \$('#SurveyForm select').valid();\n          if (!result || !result2) {\n              return;\n            }\n            jQuery('#main-sample-closed').val('1');\n            jQuery('#close2').addClass('loading-button');\n            jQuery('#SurveyForm').submit();\n          };\">\n";
           }
       }
       $r .= "</form></div>\n";
       data_entry_helper::$javascript .= "\nalertIndiciaError = function(data){\n\tvar errorString = \"" . lang::get('LANG_Indicia_Warehouse_Error') . "\";\n\tif(data.error){\terrorString = errorString + ' : ' + data.error;\t}\n\tif(data.errors){\n\t\tfor (var i in data.errors){\n\t\t\terrorString = errorString + ' : ' + data.errors[i];\n\t\t}\n\t}\n\talert(errorString);\n\t// the most likely cause is authentication failure - eg the read authentication has timed out.\n\t// prevent further use of the form:\n\t\$('.loading-panel').remove();\n\t\$('.loading-hide').removeClass('loading-hide');\n};\nerrorPos = null;\nclearErrors = function(formSel) {\n\tjQuery(formSel).find('.inline-error').remove();\n\terrorPos = null;\n};\nmyScrollTo = function(selector){\n\tjQuery(selector).filter(':visible').each(function(){\n\t\tif(errorPos == null || jQuery(this).offset().top < errorPos){\n\t\t\terrorPos = jQuery(this).offset().top;\n\t\t\twindow.scroll(0,errorPos);\n\t\t}\n\t});\n};\nmyScrollToError = function(){\n\tjQuery('.inline-error,.error').filter(':visible').prev().each(function(){\n\t\tif(errorPos == null || jQuery(this).offset().top < errorPos){\n\t\t\terrorPos = jQuery(this).offset().top;\n\t\t\twindow.scroll(0,errorPos);\n\t\t}\n\t});\n};\njQuery('#SurveyForm').ajaxForm({\n\tasync: false,\n\tdataType:  'json',\n    beforeSubmit:   function(data, obj, options){\n    \tvar valid = true;\n    \tclearErrors('form#SurveyForm');\n    \tif (!jQuery('form#SurveyForm > input').valid()) {\n\t\t\tmyScrollToError();\n  \t\t\tjQuery('.loading-button').removeClass('loading-button');\n\t\t\treturn false;\n  \t\t};\n  \t\tSurveyFormRetVal = true;\n  \t\tif(jQuery('#main-sample-deleted:checked').length == 0){ // only do check if not deleting\n          jQuery.ajax({ // now check if there are any other samples with this combination of date and location\n            type: 'GET',\n            url: \"" . $svcUrl . "/data/sample?mode=json&view=detail\" +\n                \"&nonce=" . $readAuth['nonce'] . "&auth_token=" . $readAuth['auth_token'] . "\" +\n                \"&orderby=id&callback=?&location_id=\"+jQuery('#imp-location').val()+\"&date_start=\"+jQuery('#SurveyForm [name=sample\\:date]').val(),\n            data: {},\n            success: function(detData) {\n              for(i=0, j=0; i< detData.length; i++){\n                if(detData[i].id != jQuery('#SurveyForm [name=sample\\:id]').val()) j++;\n              }\n              if(j) {\n              \tSurveyFormRetVal = confirm(\"" . lang::get('LANG_Survey_Already_Exists') . "\");\n              }\n            },\n            dataType: 'json',\n            async: false\n          });\n        }\n\t\treturn SurveyFormRetVal;\n\t},\n    success:   function(data){\n       // this will leave all the fields populated.\n       \tif(data.success == 'multiple records' && data.outer_table == 'sample'){\n          jQuery('#occ-form').show();\n          jQuery('#na-occ-warn,#mergeSurveys').hide();";
       if (!user_access($args['edit_permission'])) {
           // don't need to worry about record_status value for non admins as they can't modify when closed.
           data_entry_helper::$javascript .= "\n          if(jQuery('#main-sample-closed').val() == '1'){\n            jQuery('#read-only-survey,#ro-sur-occ-warn').show();\n            jQuery('#close1,#close2,#occ-form').hide(); //can't enter any more occurrences\n            jQuery('#SurveyForm').children().attr('disabled','disabled');\n          };\n";
       } else {
           data_entry_helper::$javascript .= "\n          jQuery('#occurrence\\\\:record_status').val(jQuery('#smpAttr\\\\:" . $attributes[$sample_closure_id]['attributeId'] . ":checked').length > 0 ? 'C' : 'I');\n          if(jQuery('#main-sample-deleted:checked').length > 0){\n            jQuery('#return-to-main').click();\n            return;\n          };\n";
       }
       data_entry_helper::$javascript .= "// If sample_id filled in -> we have a previously saved collection, so possibly have subsamples.\nif(jQuery('#SurveyForm > input[name=sample\\:id]').val() != ''){\n    // Put up warning dialogue that we are checking the subsamples: include a progress bar: set to zero%.\n    var dialog = \$('<span id=\"subsample-progress-span\"><p>'+\"" . lang::get('Please wait whilst some data integrity checks are carried out.') . "\"+'</p><div id=\"subsample-progress\"></div></span>').dialog({ title: \"" . lang::get('Checks') . "\", zIndex: 4000 });\n    jQuery('#subsample-progress').progressbar({value: 0});\n    jQuery.ajax({ // get all subsamples/occurrences to check if the dates match\n            type: 'GET',\n            url: \"" . $svcUrl . "/report/requestReport?report=library/occurrences/occurrences_list_for_parent_sample.xml&reportSource=local&mode=json&nonce=" . $readAuth['nonce'] . "&auth_token=" . $readAuth['auth_token'] . "\" +\n                \"&callback=?&sample_id=\"+data.outer_id+\"&survey_id=&date_from=&date_to=&taxon_group_id=&smpattrs=&occattrs=\",\n            data: {},\n            success: function(subData) {\n              jQuery('#subsample-progress').data('max',subData.length+1);\n              var mainDate = \$.datepicker.formatDate('yy-mm-dd', jQuery('#SurveyForm > input[name=sample\\:date]').datepicker(\"getDate\"));\n              for(i=0; i< subData.length; i++){ // loop through all subsamples\n                jQuery('#subsample-progress').progressbar('option','value',(i+1)*100/jQuery('#subsample-progress').data('max'));\n                var values = {};\n                var url = '';\n                // Check if date on subsamples matches supersample date: if not set up a post array for the sample, with correct date.\n                if(subData[i].date_start != mainDate){\n                  values['sample:id']=subData[i].sample_id;\n                  values['sample:date']=mainDate;\n                  url=\"" . iform_ajaxproxy_url($node, 'sample') . "\";\n                }\n";
       // Send AJAX request to set occurrence to 'C' if closed : use sync
       if (!user_access($args['edit_permission'])) {
           data_entry_helper::$javascript .= "                if(jQuery('#main-sample-closed').val() == '1'){\n";
       } else {
           data_entry_helper::$javascript .= "                if(jQuery('#smpAttr\\\\:" . $attributes[$sample_closure_id]['attributeId'] . ":checked').length > 0){\n";
       }
       // If records are already verified, they are left verified, as if the records themselves are saved
       // they will flagged as no longer verified: But have to force a re verification if date is changed.
       data_entry_helper::$javascript .= "\n                  if(subData[i].record_status == 'I' || typeof values['sample:id'] != 'undefined'){\n                    values['occurrence:id']=subData[i].occurrence_id;\n                    values['occurrence:record_status']='C';\n                    url=(url == '' ? \"" . iform_ajaxproxy_url($node, 'occurrence') . "\" : \"" . iform_ajaxproxy_url($node, 'smp-occ') . "\");\n                  }\n                } else { // any occurrences on unclosed collections must be flagged as 'I' - reopening unverifies.\n                  if(subData[i].record_status != 'I'){\n                    values['occurrence:id']=subData[i].occurrence_id;\n                    values['occurrence:record_status']='I';\n                    url=(url == '' ? \"" . iform_ajaxproxy_url($node, 'occurrence') . "\" : \"" . iform_ajaxproxy_url($node, 'smp-occ') . "\");\n                  }\n                }\n                if(url!=''){\n                  values['website_id']=" . $args['website_id'] . ";\n                  jQuery.ajax({ type: 'POST', url: url, data: values, dataType: 'json', async: false});\n                }\n              }\n            },\n            dataType: 'json',\n            async: false\n    });\n    dialog.dialog('close');\n    dialog.dialog('destroy');\n    jQuery('#subsample-progress-span').remove();\n}\n\n\t\t\twindow.scroll(0,0);\n            jQuery('#SurveyForm > input[name=sample\\:id]').removeAttr('disabled').val(data.outer_id);\n            jQuery('#occ-form > input[name=sample\\:parent_id]').val(data.outer_id);\n            jQuery('#occ-form > input[name=sample\\:date]').val(jQuery('#SurveyForm > input[name=sample\\:date]').val());\n            loadAttributes('sample_attribute_value', 'sample_attribute_id', 'sample_id', data.outer_id, 'smpAttr');\n            switch(\"" . $args["on_save_survey_nav"] . "\"){\n\t\t\t\tcase \"list\":\n\t\t\t\t\tvar a = \$('ul.ui-tabs-nav a')[2];\n\t\t\t\t\t\$(a).click();\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"survey\":\n\t\t\t\t\tbreak;\n\t\t\t\tdefault:";
       if (!user_access($args['edit_permission'])) {
           data_entry_helper::$javascript .= "\n\t\t\t\t\tif(jQuery('#main-sample-closed').val() == 0){\n\t\t\t\t\t\tvar a = \$('ul.ui-tabs-nav a')[1];\n\t\t\t\t\t\t\$(a).click();\n\t\t\t\t\t};";
       } else {
           data_entry_helper::$javascript .= "\n\t\t\t\t\tvar a = \$('ul.ui-tabs-nav a')[1];\n\t\t\t\t\t\$(a).click();";
       }
       data_entry_helper::$javascript .= "\n\t\t\t\t\tbreak;\n\t\t\t}\n        } else {\n\t\t\tif(data.error){\n\t\t\t\tvar lastIndex = data.error.lastIndexOf('Validation error');\n    \t\t\tif (lastIndex != -1 && lastIndex  == (data.error.length - 16)){\n\t\t\t\t\tif(data.errors){\n\t\t\t\t\t\t// TODO translation\n\t\t\t\t\t\tfor (i in data.errors){\n\t\t\t\t\t\t\tvar label = \$('<p/>').addClass('inline-error').html(data.errors[i]);\n\t\t\t\t\t\t\tlabel.insertAfter('[name='+i+']');\n\t\t\t\t\t\t}\n\t\t\t\t\t\tmyScrollToError();\n\t\t\t\t\t\treturn;\n  \t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\talertIndiciaError(data);\n        }\n\t},\n    complete: function (){\n  \t\tjQuery('.loading-button').removeClass('loading-button');\n  \t}\n});\n// In this case, all the samples attributes are on the survey tab, and all the occurrence attributes are on the occurrence tab. No need to worry about getting the correct form.\nloadAttributes = function(attributeTable, attributeKey, key, keyValue, prefix){\n    jQuery.ajax({\n        type: \"GET\",\n        url: \"" . $svcUrl . "/data/\" + attributeTable + \"?mode=json&view=list\" +\n        \t\"&reset_timeout=true&nonce=" . $readAuth['nonce'] . "&auth_token=" . $readAuth['auth_token'] . "\" +\n   \t\t\t\"&\" + key + \"=\" + keyValue + \"&callback=?\",\n        data: {},\n        success: (function(attrPrefix, attrKey) {\n          var retVal = function(attrdata) {\n            if(!(attrdata instanceof Array)){\n              alertIndiciaError(attrdata);\n            } else if (attrdata.length>0) {\n              for (var i=0;i<attrdata.length;i++){\n                // in all cases if the attribute already has the <prefix>:<X>:<Y> format name we leave. Other wise we update <prefix>:<X> to <prefix>:<X>:<Y>\n                // We leave all values unchanged.\n                // need to be careful about Cloud: this is a drop down, but it is not language specific: the termlist is\n                // always in english, so the iso won't match.\n                if (attrdata[i].id){\n                  if (attrdata[i].iso == null || attrdata[i].iso == '') // no iso - not a look up.\n                    jQuery('[name='+attrPrefix+'\\:'+attrdata[i][attrKey]+']').attr('name', attrPrefix+':'+attrdata[i][attrKey]+':'+attrdata[i].id);\n                  else {\n                    if (attrdata[i].iso == '" . $language . "') // this is our actual language so OK\n                      jQuery('[name='+attrPrefix+'\\:'+attrdata[i][attrKey]+']').attr('name', attrPrefix+':'+attrdata[i][attrKey]+':'+attrdata[i].id);\n                    else {// not our language: look up all the other attrs, and if we don't find one of this id for our language, use this one.\n                      var found = false;\n                      for (var j=0;j<attrdata.length;j++)\n                        found = found || (i!=j && attrdata[i][attrKey] == attrdata[j][attrKey] && attrdata[j].iso == '" . $language . "');\n                      if(!found)\n                        jQuery('[name='+attrPrefix+'\\:'+attrdata[i][attrKey]+']').attr('name', attrPrefix+':'+attrdata[i][attrKey]+':'+attrdata[i].id);\n                    }\n                  }\n                }\n              }\n            }};\n          return retVal;\n          })(prefix, attributeKey),\n\t\tdataType: 'json',\n\t    async: false\n\t});\n}";
       // Set up Occurrence List tab: don't include when creating a new sample as it will have no occurrences
       // Grid populated at a later point
       $r .= "<div id=\"occurrenceList\" class=\"mnhnl-btw-datapanel\"><div id=\"occ_grid\"></div>\n  <form method=\"post\" action=\"" . data_entry_helper::$base_url . "/index.php/services/report/requestReport?report=reports_for_prebuilt_forms/MNHNL/mnhnl_btw_occurrences_report.xml&reportSource=local&auth_token=" . $readAuth['auth_token'] . "&nonce=" . $readAuth['nonce'] . "&mode=csv\">\n    <input type=\"hidden\" id=\"params\" name=\"params\" value='{\"survey_id\":" . $args['survey_id'] . ", \"sample_id\":" . data_entry_helper::$entity_to_load['sample:id'] . "}' />\n    <input type=\"submit\" class=\"ui-state-default ui-corner-all\" value=\"" . lang::get('LANG_Download_Occurrences') . "\">\n  </form></div>";
       if ($occReadOnly) {
           // NB that we don't even include the buttons when readonly.
           data_entry_helper::$javascript .= "\njQuery('#ro-occ-occ-warn').show();\njQuery('#ro-sur-occ-warn').hide();\n";
       } else {
           data_entry_helper::$javascript .= "\njQuery('#ro-occ-occ-warn').hide();\n";
       }
       if ($mode == 1) {
           data_entry_helper::$javascript .= "jQuery('#occ-form').hide();";
       } else {
           data_entry_helper::$javascript .= "jQuery('#na-occ-warn').hide();";
       }
       // Set up Occurrence tab: don't allow entry of a new occurrence until after top level sample is saved.
       data_entry_helper::$entity_to_load = $childSample;
       $attributes = data_entry_helper::getAttributes(array('id' => data_entry_helper::$entity_to_load['occurrence:id'], 'valuetable' => 'occurrence_attribute_value', 'attrtable' => 'occurrence_attribute', 'key' => 'occurrence_id', 'fieldprefix' => 'occAttr', 'extraParams' => $readAuth));
       $extraParams = $readAuth + array('taxon_list_id' => $args['list_id'], 'view' => 'detail', 'query' => urlencode(json_encode(array('in' => array('language_iso', array('lat', iform_lang_iso_639_2($args['language'])))))));
       if ($occReadOnly) {
           // if the occurrence has been downloaded, no one can modify it.
           $disabledText = "disabled=\"disabled\"";
           $defAttrOptions['disabled'] = $disabledText;
       }
       $species_ctrl_args = array('label' => lang::get('LANG_Species'), 'fieldname' => 'occurrence:taxa_taxon_list_id', 'table' => 'taxa_taxon_list', 'captionField' => 'taxon', 'valueField' => 'id', 'columns' => 2, 'extraParams' => $extraParams, 'disabled' => $disabledText, 'defaultCaption' => data_entry_helper::$entity_to_load['occurrence:taxon']);
       $r .= "  <div id=\"occurrence\" class=\"mnhnl-btw-datapanel\">\n    <p id=\"ro-occ-occ-warn\"><strong>" . lang::get('LANG_Read_Only_Occurrence') . "</strong></p>\n    <p id=\"ro-sur-occ-warn\"><strong>" . lang::get('LANG_Read_Only_Survey') . "</strong></p>\n    <p id=\"na-occ-warn\"><strong>" . lang::get('LANG_Page_Not_Available') . "</strong></p>\n    <form method=\"post\" id=\"occ-form\" action=\"" . iform_ajaxproxy_url($node, 'smp-occ') . "\" >\n    <input type=\"hidden\" id=\"website_id\" name=\"website_id\" value=\"" . $args['website_id'] . "\" />\n    <input type=\"hidden\" id=\"sample:survey_id\" name=\"sample:survey_id\" value=\"" . $args['survey_id'] . "\" />\n    <input type=\"hidden\" id=\"sample:parent_id\" name=\"sample:parent_id\" value=\"" . $parentSample['sample:id'] . "\" />\n    <input type=\"hidden\" id=\"sample:date\" name=\"sample:date\" value=\"" . data_entry_helper::$entity_to_load['sample:date'] . "\" />\n    <input type=\"hidden\" id=\"sample:id\" name=\"sample:id\" value=\"" . data_entry_helper::$entity_to_load['sample:id'] . "\" />\n    <input type=\"hidden\" id=\"occurrence:id\" name=\"occurrence:id\" value=\"" . data_entry_helper::$entity_to_load['occurrence:id'] . "\" />\n    <input type=\"hidden\" id=\"occurrence:record_status\" name=\"occurrence:record_status\" value=\"" . ($closedFieldValue == '0' ? 'I' : 'C') . "\" />\n    <input type=\"hidden\" id=\"occurrence:downloaded_flag\" name=\"occurrence:downloaded_flag\" value=\"N\" />\n    " . data_entry_helper::autocomplete($species_ctrl_args) . "\n    " . ($occurrence_confidence_id ? data_entry_helper::outputAttribute($attributes[$occurrence_confidence_id], array_merge($languageFilteredAttrOptions, array('noBlankText' => ''))) : "<span style=\"display: none;\">Occurrence attribute '" . self::ATTR_CONFIDENCE . "' not assigned to this survey</span>") . "\n    " . data_entry_helper::sref_and_system(array('label' => lang::get('LANG_Spatial_ref'), 'systems' => array('2169' => 'Luref (Gauss Luxembourg)'))) . "\n    <p>" . lang::get('LANG_Click_on_map') . "</p>\n    " . data_entry_helper::outputAttribute($attributes[$occurrence_count_id], array_merge($defAttrOptions, array('default' => 1))) . "\n    " . ($occurrence_approximation_id ? data_entry_helper::outputAttribute($attributes[$occurrence_approximation_id], $defAttrOptions) : "<span style=\"display: none;\">Occurrence attribute '" . self::ATTR_APPROXIMATION . "' not assigned to this survey</span>") . "\n    " . data_entry_helper::outputAttribute($attributes[$occurrence_territorial_id], array_merge($defAttrOptions, array('default' => 1, 'id' => 'occ-territorial'))) . "\n    " . data_entry_helper::outputAttribute($attributes[$occurrence_atlas_code_id], $languageFilteredAttrOptions) . "\n    " . ($occurrence_overflying_id ? data_entry_helper::outputAttribute($attributes[$occurrence_overflying_id], $defAttrOptions) : "<span style=\"display: none;\">Occurrence attribute '" . self::ATTR_OVERFLYING . "' not assigned to this survey</span>") . "\n    " . data_entry_helper::textarea(array('label' => lang::get('LANG_Comment'), 'fieldname' => 'occurrence:comment', 'disabled' => $disabledText));
       if (!$surveyReadOnly && !$occReadOnly) {
           if ($mode == 3) {
               $r .= data_entry_helper::checkbox(array('label' => lang::get('Delete'), 'fieldname' => 'sample:deleted', 'id' => 'occ-sample-deleted'));
           }
           $r .= "<input type=\"submit\" id=\"occ-submit\" class=\"ui-state-default ui-corner-all\" value=\"" . lang::get('LANG_Save_Occurrence_Details') . "\" />";
       }
       $r .= "  </form>\n";
       data_entry_helper::$javascript .= "\n// because of ID tracking it is easier to rebuild entire list etc.\nretriggerGrid = function(){\n  \$('div#occ_grid').empty();\n  occListLayer.destroyFeatures();\n  activateAddList = 1;\n  thisOccID = -1;\n  \$('div#occ_grid').indiciaDataGrid('rpt:reports_for_prebuilt_forms/MNHNL/mnhnl_btw_list_occurrences', {\n    indiciaSvc: '" . $svcUrl . "',\n    dataColumns: ['taxon', 'territorial', 'count'],\n    reportColumnTitles: {taxon : '" . lang::get('LANG_Species') . "', territorial : '" . lang::get('LANG_Territorial') . "', count : '" . lang::get('LANG_Count') . "'},\n    actionColumns: {'" . lang::get('LANG_Show') . "' : \"" . url('node/' . $node->nid, array('query' => 'occurrence_id=£id£')) . "\",\n            '" . lang::get('LANG_Highlight') . "' : \"script:highlight(£id£);\"},\n    auth : { nonce : '" . $readAuth['nonce'] . "', auth_token : '" . $readAuth['auth_token'] . "'},\n    parameters : { survey_id : '" . $args['survey_id'] . "',\n            parent_id : jQuery('#SurveyForm [name=sample\\:id]').val(),\n            territorial_attr_id : '" . $occurrence_territorial_id . "',\n            count_attr_id : '" . $occurrence_count_id . "'},\n    itemsPerPage : 12,\n    callback : addListFeature ,\n    cssOdd : ''\n  });\n}\n\njQuery('#occ-form').ajaxForm({\n\tasync: false,\n\tdataType:  'json',\n    beforeSubmit:   function(data, obj, options){\n    \tvar valid = true;\n    \tclearErrors('form#occ-form');\n    \tif (!jQuery('form#occ-form > input').valid()) { valid = false; }\n    \tif (!jQuery('form#occ-form > select').valid()) { valid = false; }\n    \tif(!valid) {\n\t\t\tmyScrollToError();\n\t\t\treturn false;\n\t\t};\n\t\tjQuery('#occ-submit').addClass('loading-button');\n\t\treturn true;\n\t},\n    success:   function(data){\n       // this will leave all the fields populated.\n       \tif(data.success == 'multiple records' && data.outer_table == 'sample'){\n\t\t\twindow.scroll(0,0);\n\t\t\t// cant use reset form, as returns it to original values: if this was called with occurrence_id =<x> then it would repopulate with original occurrence's values\n\t\t\t// website_id, survey_id, record_status, downloaded_flag, sample:entered_sref_system are constants and are left alone. parent_id, date are only set referring to parent sample.\n\t\t\tjQuery('form#occ-form').find('[name^=occAttr\\:]').each(function(){\n\t\t\t\tvar name = jQuery(this).attr('name').split(':');\n\t\t\t\tjQuery(this).attr('name', name[0]+':'+name[1]);\n\t\t\t});\n\t\t\tjQuery('form#occ-form').find('[name=occurrence\\:id],[name=sample\\:id]').val('').attr('disabled', 'disabled');\n\t\t\tjQuery('form#occ-form').find('[name=occurrence\\:taxa_taxon_list_id],[name=occurrence\\:taxa_taxon_list_id\\:taxon],[name=sample\\:entered_sref],[name=sample\\:geom],[name=occurrence\\:comment]').val('');\n\t\t\tjQuery('form#occ-form').find('[name=occAttr\\:" . $occurrence_confidence_id . "]').find('option').removeAttr('selected');\n\t\t\tjQuery('form#occ-form').find('[name=occAttr\\:" . $occurrence_count_id . "]').val('1');\n\t\t\tjQuery('form#occ-form').find('input[name=occAttr\\:" . $occurrence_approximation_id . "],input[name=occAttr\\:" . $occurrence_overflying_id . "]').removeAttr('checked','checked');\n\t\t\tjQuery('form#occ-form').find('#occ-territorial').attr('checked','checked');\n\t\t\tjQuery('label[for=occ-sample-deleted]').remove(); // sample deleted only applicable when editing an existing occurrence. After saving reverts to Add Occurreence: no delete. Remove label then actual checkbox\n\t\t\tjQuery('form#occ-form').find('[name=sample\\:deleted]').remove(); // This removes both parts of the checkbox.\n\t\t\tsetAtlasStatus();\n\t\t\tretriggerGrid();\n\t\t\tlocationLayer.map.editLayer.destroyFeatures();\n\t\t\tvar a = \$('ul.ui-tabs-nav a')[1];\n\t\t\t\$(a).empty().html('<span>" . lang::get('LANG_Add_Occurrence') . "</span>');\n\t\t\tswitch(\"" . $args["on_save_occurrence_nav"] . "\"){\n\t\t\t\tcase \"list\":\n\t\t\t\t\ta = \$('ul.ui-tabs-nav a')[2];\n\t\t\t\t\t\$(a).click();\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"survey\":\n\t\t\t\t\ta = \$('ul.ui-tabs-nav a')[0];\n\t\t\t\t\t\$(a).click();\n\t\t\t\t\tbreak;\n\t\t\t\tdefault:\n\t\t\t\t\tbreak;\n\t\t\t}\n        } else {\n\t\t\tif(data.error){\n\t\t\t\tvar lastIndex = data.error.lastIndexOf('Validation error');\n    \t\t\tif (lastIndex != -1 && lastIndex  == (data.error.length - 16)){\n\t\t\t\t\tif(data.errors){\n\t\t\t\t\t\t// TODO translation\n\t\t\t\t\t\tfor (i in data.errors){\n\t\t\t\t\t\t\tvar label = \$('<p/>').addClass('inline-error').html(data.errors[i]);\n\t\t\t\t\t\t\tlabel.insertAfter('[name='+i+']');\n\t\t\t\t\t\t}\n\t\t\t\t\t\tmyScrollToError();\n\t\t\t\t\t\treturn;\n  \t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\talertIndiciaError(data);\n        }\n\t},\n    complete: function (){\n  \t\tjQuery('.loading-button').removeClass('loading-button');\n  \t}\n});\nsetAtlasStatus = function() {\n  if (jQuery(\"#occ-territorial:checked\").length == 0) {\n      jQuery(\"select[name=occAttr\\:" . $occurrence_atlas_code_id . "],select[name^=occAttr\\:" . $occurrence_atlas_code_id . "\\:]\").val('');\n  } else {\n      if(jQuery(\"select[name=occAttr\\:" . $occurrence_atlas_code_id . "],select[name^=occAttr\\:" . $occurrence_atlas_code_id . "\\:]\").val() == '') {\n        // Find the BB02 option (depends on the language what val it has)\n        var bb02;\n        jQuery.each(jQuery(\"select[name=occAttr\\:" . $occurrence_atlas_code_id . "],select[name^=occAttr\\:" . $occurrence_atlas_code_id . "\\:]\").find('option'), function(index, option) {\n          if (option.text.substr(0,4)=='BB02') {\n            bb02 = option.value;\n            return; // just from the each loop\n          }\n        });\n        jQuery(\"select[name=occAttr\\:" . $occurrence_atlas_code_id . "],select[name^=occAttr\\:" . $occurrence_atlas_code_id . "\\:]\").val(bb02);\n      }\n  }\n};\njQuery(\"#occ-territorial\").change(setAtlasStatus);\nif(\$.browser.msie) {\n    jQuery(\"#occ-territorial\").click(function() {\n        \$(this).change();\n    });\n}\n\n";
       if ($mode != 3) {
           data_entry_helper::$javascript .= "setAtlasStatus();\n";
       }
       // reset the atlas when not looking at a old occurrence.
       $r .= '</div>';
       // add map panel.
       $options = iform_map_get_map_options($args, $readAuth);
       $olOptions = iform_map_get_ol_options($args);
       // $options['layers'] = array('locationLayer', 'occListLayer');
       $options['searchLayer'] = 'false';
       $options['initialFeatureWkt'] = null;
       $options['proxy'] = '';
       $options['scroll_wheel_zoom'] = false;
       $options['width'] = 'auto';
       // TBD remove from arglist
       $r .= "<div class=\"mnhnl-btw-mappanel\">\n";
       $r .= data_entry_helper::map_panel($options, $olOptions);
       // for timing reasons, all the following has to be done after the map is loaded.
       // 1) feature selector for occurrence list must have the map present to attach the control
       // 2) location placer must have the location layer populated and the map present in
       //    order to zoom the map into the location.
       // 3) occurrence list feature adder must have map present in order to zoom into any
       //    current selection.
       data_entry_helper::$onload_javascript .= "\n\n\nlocationChange = function(obj){\n  locationLayer.destroyFeatures();\n  if(obj.value != ''){\n    jQuery.getJSON(\"" . $svcUrl . "\" + \"/data/location/\"+obj.value +\n      \"?mode=json&view=detail&auth_token=" . $readAuth['auth_token'] . "&nonce=" . $readAuth["nonce"] . "\" +\n      \"&callback=?\", function(data) {\n            if (data.length>0) {\n              var parser = new OpenLayers.Format.WKT();\n              for (var i=0;i<data.length;i++)\n        {\n          if(data[i].centroid_geom){\n            " . self::readBoundaryJs('data[i].centroid_geom', $args['map_projection']) . "\n            feature.style = {label: data[i].name,\n\t\t\t\t\t\t     strokeColor: \"Green\",\n                             strokeWidth: 2,\n                             fillOpacity: 0};\n            centre = feature.geometry.getCentroid();\n            centrefeature = new OpenLayers.Feature.Vector(centre, {}, {label: data[i].name});\n            locationLayer.addFeatures([feature, centrefeature]);\n          }\n          if(data[i].boundary_geom){\n            " . self::readBoundaryJs('data[i].boundary_geom', $args['map_projection']) . "\n            feature.style = {strokeColor: \"Blue\", strokeWidth: 2};\n            locationLayer.addFeatures([feature]);\n          }\n          locationLayer.map.zoomToExtent(locationLayer.getDataExtent());\n        }\n      }\n    });\n     jQuery.getJSON(\"" . $svcUrl . "\" + \"/data/location\" +\n      \"?mode=json&view=detail&auth_token=" . $readAuth['auth_token'] . "&nonce=" . $readAuth["nonce"] . "&callback=?&parent_id=\"+obj.value, function(data) {\n            if (data.length>0) {\n              var parser = new OpenLayers.Format.WKT();\n              for (var i=0;i<data.length;i++)\n        {\n          if(data[i].centroid_geom){\n            " . self::readBoundaryJs('data[i].centroid_geom', $args['map_projection']) . "\n            locationLayer.addFeatures([feature]);\n          }\n          if(data[i].boundary_geom){\n            " . self::readBoundaryJs('data[i].boundary_geom', $args['map_projection']) . "\n            feature.style = {label: data[i].name,\n              labelAlign: \"cb\",\n              strokeColor: \"Blue\",\n                        strokeWidth: 2};\n            locationLayer.addFeatures([feature]);\n           }\n         }\n      }\n        });\n  }\n};\n// upload location initial value into map.\njQuery('#imp-location').each(function(){\n  locationChange(this);\n});\njQuery('#imp-location').unbind('change');\njQuery('#imp-location').change(function(){\n  locationChange(this);\n});\nvar selected = \$('#controls').tabs('option', 'selected');\n\n// Only leave the click control activated for edit/add occurrence tab.\nif(selected != 1){\n    locationLayer.map.editLayer.clickControl.deactivate();\n}\n\$('#controls').bind('tabsshow', function(event, ui) {\n        if(ui.index == 1)\n        {\n         locationLayer.map.editLayer.clickControl.activate();\n        }\n        else\n        {\n         locationLayer.map.editLayer.clickControl.deactivate();\n        }\n    }\n);\nactivateAddList = 1;\nthisOccID = " . $thisOccID . ";\naddListFeature = function(div, r, record, count) {\n  if(activateAddList == 0)\n    return;\n  if(r == count)\n    activateAddList = 0;\n    var parser = new OpenLayers.Format.WKT();\n    " . self::readBoundaryJs('record.geom', $args['map_projection']) . "\n    if(record.id != thisOccID || 1==" . ($surveyReadOnly ? 1 : 0) . " || 1==" . ($occReadOnly ? 1 : 0) . "){\n      feature.attributes.id = record.id;\n      feature.attributes.taxon = record.taxon;\n      feature.attributes.count = record.count;\n      occListLayer.addFeatures([feature]);\n      if(record.id == " . $thisOccID . "){\n        var bounds=feature.geometry.getBounds();\n        locationLayer.map.setCenter(bounds.getCenterLonLat());\n      }\n    } else {\n      locationLayer.map.editLayer.destroyFeatures();\n      locationLayer.map.editLayer.addFeatures([feature]);\n      var bounds=feature.geometry.getBounds()\n      var centre=bounds.getCenterLonLat();\n      locationLayer.map.setCenter(centre);\n    }\n};\nhighlight = function(id){\n  if(id == " . $thisOccID . "){\n    if(occListLayer.map.editLayer.features.length > 0){\n      var bounds=occListLayer.map.editLayer.features[0].geometry.getBounds()\n      var centre=bounds.getCenterLonLat();\n      occListLayer.map.setCenter(centre);\n      return;\n    }\n  }\n  for(var i = 0; i < occListLayer.features.length; i++){\n    if(occListLayer.features[i].attributes.id == id){\n      control.unselectAll();\n      var bounds=occListLayer.features[i].geometry.getBounds()\n      var centre=bounds.getCenterLonLat();\n      occListLayer.map.setCenter(centre);\n      control.select(occListLayer.features[i]);\n      return;\n    }\n  }\n}\n";
       if ($mode != 1) {
           data_entry_helper::$onload_javascript .= "\n\$('div#occ_grid').indiciaDataGrid('rpt:reports_for_prebuilt_forms/MNHNL/mnhnl_btw_list_occurrences', {\n    indiciaSvc: '" . $svcUrl . "',\n    dataColumns: ['taxon', 'territorial', 'count'],\n    reportColumnTitles: {taxon : '" . lang::get('LANG_Species') . "', territorial : '" . lang::get('LANG_Territorial') . "', count : '" . lang::get('LANG_Count') . "'},\n    actionColumns: {'" . lang::get('LANG_Show') . "' : \"" . url('node/' . $node->nid, array('query' => 'occurrence_id=£id£')) . "\",\n            '" . lang::get('LANG_Highlight') . "' : \"script:highlight(£id£);\"},\n    auth : { nonce : '" . $readAuth['nonce'] . "', auth_token : '" . $readAuth['auth_token'] . "'},\n    parameters : { survey_id : '" . $args['survey_id'] . "',\n            parent_id : '" . $parentSample['sample:id'] . "',\n            territorial_attr_id : '" . $occurrence_territorial_id . "',\n            count_attr_id : '" . $occurrence_count_id . "'},\n    itemsPerPage : 12,\n    callback : addListFeature ,\n    cssOdd : ''\n  });\n\n// activateAddList = 0;\n\n";
       }
       $r .= "</div><div><form><input id=\"return-to-main\" type=\"button\" value=\"" . lang::get('LANG_Return') . "\" onclick=\"window.location.href='" . url('node/' . $node->nid, array('query' => 'Main')) . "'\"></form></div></div>\n";
       if (method_exists(get_called_class(), 'getTrailerHTML')) {
           $r .= call_user_func(array(get_called_class(), 'getTrailerHTML'), $args);
       }
       return $r;
   }
Ejemplo n.º 15
0
 /**
  * Draw Map section of the page.
  * @return string The output map panel.
  * 
  * @package    Client
  * @subpackage PrebuiltForms
  */
 protected static function get_control_map($auth, $args, $tabalias, $options)
 {
     iform_load_helpers(array('data_entry_helper'));
     self::load_record($auth);
     $options = array_merge(iform_map_get_map_options($args, $auth['read']), array('maxZoom' => 14), $options);
     if (isset(self::$record['geom'])) {
         $options['initialFeatureWkt'] = self::$record['geom'];
     }
     if ($args['interface'] !== 'one_page') {
         $options['tabDiv'] = $tabalias;
     }
     $olOptions = iform_map_get_ol_options($args);
     if (!isset($options['standardControls'])) {
         $options['standardControls'] = array('layerSwitcher', 'panZoom');
     }
     return '<div class="detail-panel" id="detail-panel-map"><h3>Map</h3>' . data_entry_helper::map_panel($options, $olOptions) . '</div>';
 }
Ejemplo n.º 16
0
 /** 
  * Get the map control.
  */
 protected static function get_control_map($auth, $args, $tabalias, $options)
 {
     $options = array_merge(iform_map_get_map_options($args, $auth['read']), $options);
     // If a drawing tool is on the map we can support boundaries or if automatic plot creation is enabled.
     $boundaries = false;
     if (!empty($options['clickForPlot']) && $options['clickForPlot'] == true) {
         $boundaries = true;
     }
     foreach ($options['standardControls'] as $ctrl) {
         if (substr($ctrl, 0, 4) === 'draw') {
             $boundaries = true;
             break;
         }
     }
     if (isset(data_entry_helper::$entity_to_load['location:centroid_geom'])) {
         $options['initialFeatureWkt'] = data_entry_helper::$entity_to_load['location:centroid_geom'];
     }
     if ($boundaries && isset(data_entry_helper::$entity_to_load['location:boundary_geom'])) {
         $options['initialBoundaryWkt'] = data_entry_helper::$entity_to_load['location:boundary_geom'];
     }
     if ($args['interface'] !== 'one_page') {
         $options['tabDiv'] = $tabalias;
     }
     $olOptions = iform_map_get_ol_options($args);
     if (!isset($options['standardControls'])) {
         $options['standardControls'] = array('layerSwitcher', 'panZoom');
     }
     $r = '';
     $r .= data_entry_helper::map_panel($options, $olOptions);
     // Add a geometry hidden field for boundary support
     if ($boundaries) {
         if (!empty(data_entry_helper::$entity_to_load['location:boundary_geom'])) {
             $impBoundaryGeomVal = data_entry_helper::$entity_to_load['location:boundary_geom'];
         } else {
             $impBoundaryGeomVal = '';
         }
         $r .= '<input type="hidden" name="location:boundary_geom" id="imp-boundary-geom" value="' . $impBoundaryGeomVal . '"/>';
     }
     return $r;
 }
Ejemplo n.º 17
0
    /**
     * Return the generated form output.
     * @return Form HTML.
     */
    public static function get_form($args, $node)
    {
        global $user;
        // There is a language entry in the args parameter list: this is derived from the $language DRUPAL global.
        // It holds the 2 letter code, used to pick the language file from the lang subdirectory of prebuilt_forms.
        // There should be no explicitly output text in this file.
        // We must translate any field names and ensure that the termlists and taxonlists use the correct language.
        // For attributes, the caption is automatically translated by data_entry_helper.
        $logged_in = $user->uid > 0;
        $uid = $user->uid;
        $email = $user->mail;
        $username = $user->name;
        if (!user_access('IForm n' . $node->nid . ' access')) {
            return "<p>" . lang::get('LANG_Insufficient_Privileges') . "</p>";
        }
        $r = '';
        // Get authorisation tokens to update and read from the Warehouse.
        $readAuth = data_entry_helper::get_read_auth($args['website_id'], $args['password']);
        $svcUrl = data_entry_helper::$base_url . '/index.php/services';
        drupal_add_js(drupal_get_path('module', 'iform') . '/media/js/jquery.form.js', 'module');
        data_entry_helper::link_default_stylesheet();
        data_entry_helper::add_resource('jquery_ui');
        data_entry_helper::add_resource('autocomplete');
        if ($args['language'] != 'en') {
            data_entry_helper::add_resource('jquery_ui_' . $args['language']);
        }
        data_entry_helper::enable_validation('cc-1-collection-details');
        // don't care about ID itself, just want resources
        if ($args['help_module'] != '' && $args['help_inclusion_function'] != '' && module_exists($args['help_module']) && function_exists($args['help_inclusion_function'])) {
            $use_help = true;
            data_entry_helper::$javascript .= call_user_func($args['help_inclusion_function']);
        } else {
            $use_help = false;
        }
        // The only things that will be editable after the collection is saved will be the identifiaction of the flower/insects.
        // no id - just getting the attributes, rest will be filled in using AJAX
        $sample_attributes = data_entry_helper::getAttributes(array('valuetable' => 'sample_attribute_value', 'attrtable' => 'sample_attribute', 'key' => 'sample_id', 'fieldprefix' => 'smpAttr', 'extraParams' => $readAuth, 'survey_id' => $args['survey_id']));
        $occurrence_attributes = data_entry_helper::getAttributes(array('valuetable' => 'occurrence_attribute_value', 'attrtable' => 'occurrence_attribute', 'key' => 'occurrence_id', 'fieldprefix' => 'occAttr', 'extraParams' => $readAuth, 'survey_id' => $args['survey_id']));
        $location_attributes = data_entry_helper::getAttributes(array('valuetable' => 'location_attribute_value', 'attrtable' => 'location_attribute', 'key' => 'location_id', 'fieldprefix' => 'locAttr', 'extraParams' => $readAuth, 'survey_id' => $args['survey_id']));
        $taxon_attributes = data_entry_helper::getAttributes(array('valuetable' => 'taxa_taxon_list_attribute_value', 'attrtable' => 'taxa_taxon_list_attribute', 'key' => 'taxa_taxon_list_id', 'fieldprefix' => 'taxAttr', 'extraParams' => $readAuth), false);
        if (count($taxon_attributes) != 1 || $taxon_attributes[0][caption] != "XPER ID") {
            return "<p>Internal error: Expected 1 taxon attribute (XPER ID), got " . count($taxon_attributes) . "</p>Dump:<br/>" . print_r($taxon_attributes, true);
        }
        $defNRAttrOptions = array('extraParams' => $readAuth + array('orderby' => 'id'), 'lookUpListCtrl' => 'radio_group', 'lookUpKey' => 'meaning_id', 'language' => iform_lang_iso_639_2($args['language']), 'booleanCtrl' => 'radio', 'containerClass' => 'group-control-box', 'sep' => ' &nbsp; ');
        $defAttrOptions = $defNRAttrOptions;
        $defAttrOptions['validation'] = array('required');
        $checkOptions = $defNRAttrOptions;
        $checkOptions['lookUpListCtrl'] = 'checkbox_group';
        $language = iform_lang_iso_639_2($args['language']);
        global $indicia_templates;
        $indicia_templates['sref_textbox_latlong'] = '<div class="latLongDiv"><label for="{idLat}">{labelLat}:</label>' . '<input type="text" id="{idLat}" name="{fieldnameLat}" {class} {disabled} value="{default}" /></div>' . '<div class="latLongDiv"><label for="{idLong}">{labelLong}:</label>' . '<input type="text" id="{idLong}" name="{fieldnameLong}" {class} {disabled} value="{default}" /></div>';
        $base = base_path();
        if (substr($base, -1) != '/') {
            $base .= '/';
        }
        $r .= '<script type="text/javascript">
/* <![CDATA[ */
document.write("<div class=\\"ui-widget ui-widget-content ui-corner-all loading-panel\\" ><img src=\\"' . $base . drupal_get_path('module', 'iform') . '/media/images/ajax-loader2.gif\\" />' . lang::get('loading') . '...<span class=\\"poll-loading-extras\\">0</span></div>");
document.write("<div class=\\"poll-loading-hide\\" style=\\"display:none;\\">");
/* ]]> */</script>
';
        data_entry_helper::$javascript .= "var flowerTaxa = [";
        $extraParams = $readAuth + array('taxon_list_id' => $args['flower_list_id'], 'view' => 'list');
        $species_data_def = array('table' => 'taxa_taxon_list', 'extraParams' => $extraParams);
        $taxa = data_entry_helper::get_population_data($species_data_def);
        $first = true;
        // Flowers do not have XPER ID. Flowers list still required to do multiple selection list conversion.
        foreach ($taxa as $taxon) {
            data_entry_helper::$javascript .= ($first ? '' : ',') . "{id: " . $taxon['id'] . ", taxon: \"" . str_replace('"', '\\"', $taxon['taxon']) . "\"}\n";
            $first = false;
        }
        data_entry_helper::$javascript .= "];\nvar insectTaxa = [";
        $extraParams = $readAuth + array('taxon_list_id' => $args['insect_list_id'], 'view' => 'list');
        $taxa_attribute_values_data_def = array('table' => 'taxa_taxon_list_attribute_value', 'extraParams' => $extraParams);
        $taxa_attribute_values = data_entry_helper::get_population_data($taxa_attribute_values_data_def);
        // full list : no allow_data_entry filter.
        $extraParams['taxon_list_id'] = $args['insect_list_id'];
        $species_data_def['extraParams'] = $extraParams;
        $taxa = data_entry_helper::get_population_data($species_data_def);
        $first = true;
        foreach ($taxa as $taxon) {
            // TODO this is not the most performance orientated, but it works.
            $xperID = "NoXPERID";
            foreach ($taxa_attribute_values as $xperRecord) {
                if ($xperRecord["id"] != NULL && $xperRecord['taxa_taxon_list_id'] == $taxon['id']) {
                    $xperID = $xperRecord['value'];
                    break;
                }
            }
            data_entry_helper::$javascript .= ($first ? '' : ',') . '{id: ' . $taxon['id'] . ', taxon: "' . str_replace('"', '\\"', $taxon['taxon']) . '", xperID: "' . $xperID . '"}' . "\n";
            $first = false;
        }
        data_entry_helper::$javascript .= "];";
        // note we have to proxy the post. Every time a write transaction is carried out, the write nonce is trashed.
        // For security reasons we don't want to give the user the ability to generate their own nonce, so we use
        // the fact that the user is logged in to drupal as the main authentication/authorisation/identification
        // process for the user. The proxy packages the post into the correct format
        //
        // There are 2 types of submission:
        // When a user validates a panel using the validate button, the following panel is opened on success
        // When a user presses a modify button, the open panel gets validated, and the panel to be modified is opened.
        // loadAttribute
        // <form id="cc-1-collection-details"
        // has the main sample (+attributes), location (no attributes).
        // form id="cc-1-delete-collection" just has the main sample.
        // form id="cc-2-flower-upload" just uploads the flower picture: no DB
        // form id="cc-2-environment-upload" just uploads the location picture: no DB
        // form id="cc-2-floral-station"
        // has the location (+attributes), location_image, main sample (no attributes), flower occurrence (+attributes), determination, flower_image
        // form id="cc-3-delete-session" just has the session sample.
        // form class=\"poll-session-form\" has the session (+attributes)
        // form id="cc-4-insect-upload" just uploads the insect picture: no DB
        // form id="cc-4-main-form"
        // has the insect occurrence (+attributes), determination, insect image
        // form id="cc-4-delete-insect" just has the insect occurrence.
        // form id="cc-5-collection" has the main sample and closed attribute (forced to 1).
        $r .= '
<div id="refresh-message" style="display:none" ><p>' . lang::get('LANG_Please_Refresh_Page') . '</p></div>
<div id="cc-1" class="poll-section">
  <div id="cc-1-title" class="ui-accordion-header ui-helper-reset ui-state-active ui-corner-top poll-section-title">
  	<span id="cc-1-title-details">' . lang::get('LANG_Collection_Details') . '</span>
    <div class="right">
      <div>
        <span id="cc-1-reinit-button" class="ui-state-default ui-corner-all reinit-button">' . lang::get('LANG_Reinitialise') . '</span>
        <span id="cc-1-mod-button" class="ui-state-default ui-corner-all mod-button">' . lang::get('LANG_Modify') . '</span>
      </div>
    </div>
  </div>
  <div id="cc-1-details" class="ui-accordion-content ui-helper-reset ui-widget-content">
    <span id="cc-1-protocol-details"></span>
  </div>
  <div id="cc-1-body" class="ui-accordion-content ui-helper-reset ui-widget-content ui-accordion-content-active poll-section-body">
   <form id="cc-1-collection-details" action="' . iform_ajaxproxy_url($node, 'loc-sample') . '" method="POST">
    <input type="hidden" id="website_id"       name="website_id" value="' . $args['website_id'] . '" />
    <input type="hidden" id="imp-sref"         name="location:centroid_sref"  value="" />
    <input type="hidden" id="imp-geom"         name="location:centroid_geom" value="" />
    <input type="hidden" id="X-sref-system"  name="location:centroid_sref_system" value="900913" />
    <input type="hidden" id="sample:survey_id" name="sample:survey_id" value="' . $args['survey_id'] . '" />
    ' . iform_pollenators::help_button($use_help, "collection-help-button", $args['help_function'], $args['help_collection_arg']) . '
    <label for="location:name">' . lang::get('LANG_Collection_Name_Label') . ':</label>
 	<input type="text" id="location:name"      name="location:name" value="" class="required"/>
    <input type="hidden" id="sample:location_name" name="sample:location_name" value=""/>
 	' . str_replace("\n", "", data_entry_helper::outputAttribute($sample_attributes[$args['protocol_attr_id']], $defNRAttrOptions)) . '    <input type="hidden"                       name="sample:date" value="2010-01-01"/>
    <input type="hidden" id="smpAttr:' . $args['complete_attr_id'] . '" name="smpAttr:' . $args['complete_attr_id'] . '" value="0" />
    <input type="hidden" id="smpAttr:' . $args['uid_attr_id'] . '" name="smpAttr:' . $args['uid_attr_id'] . '" value="' . $uid . '" />
    <input type="hidden" id="smpAttr:' . $args['email_attr_id'] . '" name="smpAttr:' . $args['email_attr_id'] . '" value="' . $email . '" />
    <input type="hidden" id="smpAttr:' . $args['username_attr_id'] . '" name="smpAttr:' . $args['username_attr_id'] . '" value="' . $username . '" />  
    <input type="hidden" id="locations_website:website_id" name="locations_website:website_id" value="' . $args['website_id'] . '" />
    <input type="hidden" id="location:id"      name="location:id" value="" disabled="disabled" />
    <input type="hidden" id="sample:id"        name="sample:id" value="" disabled="disabled" />
    </form>
    <div class="button-container">
      <div id="cc-1-valid-button" class="ui-state-default ui-corner-all save-button">' . lang::get('LANG_Validate') . '</div>
    </div>
  </div>
  <div id="cc-1-trailer" class="poll-section-trailer">
    <div id="cc-1-trailer-image" ><img src="' . $base . drupal_get_path('module', 'iform') . '/media/images/exclamation.jpg" /></div>
    <p>' . lang::get('LANG_Collection_Trailer_Point_1') . '</p>
    <p>' . lang::get('LANG_Collection_Trailer_Point_2') . '</p>
  </div>
<div style="display:none" />
    <form id="cc-1-delete-collection" action="' . iform_ajaxproxy_url($node, 'sample') . '" method="POST">
       <input type="hidden" name="website_id" value="' . $args['website_id'] . '" />
       <input type="hidden" name="sample:survey_id" value="' . $args['survey_id'] . '" />
       <input type="hidden" name="sample:id" value="" />
       <input type="hidden" name="sample:date" value="2010-01-01"/>
       <input type="hidden" name="sample:location_id" value="" />
       <input type="hidden" name="sample:deleted" value="t" />
    </form>
</div>
  <div id="cc-1-main-body" class="ui-accordion-content ui-helper-reset ui-widget-content ui-corner-bottom ui-accordion-content-active">
';
        data_entry_helper::$javascript .= "\n\$.validator.messages.required = \"" . lang::get('validation_required') . "\";\nvar sessionCounter = 0;\njQuery('#imp-georef-search-btn').removeClass('indicia-button').addClass('search-button');\n// can't use shuffle to side as dynamic generated code does like it in IE7\n\nhtmlspecialchars = function(value){\n\treturn value.replace(/[<>\"'&]/g, function(m){return replacechar(m)})\n};\n\nreplacechar = function(match){\n\tif (match==\"<\") return \"&lt;\"\n\telse if (match==\">\") return \"&gt;\"\n\telse if (match=='\"') return \"&quot;\"\n\telse if (match==\"'\") return \"&#039;\"\n\telse if (match==\"&\") return \"&amp;\"\n};\n\n\$.fn.foldPanel = function(){\n\tthis.children('.poll-section-body,.poll-section-footer,.poll-section-trailer').hide();\n\tthis.children('.poll-section-title').find('.reinit-button,.mod-button').show();\n\tthis.children('.photoReelContainer').addClass('ui-corner-all').removeClass('ui-corner-top'); /* visibility depends on specific circumstances */\n};\n\n\$.fn.unFoldPanel = function(){\n\tthis.children('.poll-section-body,.poll-section-footer,.poll-section-trailer,.photoReelContainer').show();\n\tthis.children('.poll-section-title').find('.mod-button').hide();\n\tthis.children('.photoReelContainer').addClass('ui-corner-top').removeClass('ui-corner-all');\n\twindow.scroll(0,0); // force the window to display the top.\n\tbuildMap();\n\tcheckSessionButtons();\n\t// any reinit button is left in place\n};\n\n\$.fn.showPanel = function(){\n\tthis.show();\n\tthis.unFoldPanel();\n};\n\n\$.fn.hidePanel = function(){\n\tthis.hide(); \n};\n\ninseeLayer = null;\n\nnewDefaultSref = '0, 0';\noldDefaultSref = '" . ((int) $args['map_centroid_lat'] > 0 ? $args['map_centroid_lat'] . 'N' : -(int) $args['map_centroid_lat'] . 'S') . ' ' . ((int) $args['map_centroid_long'] > 0 ? $args['map_centroid_long'] . 'E' : -(int) $args['map_centroid_long'] . 'W') . "';\ndefaultGeom = '';\n\$.getJSON('" . $svcUrl . "' + '/spatial/sref_to_wkt'+\n        \t\t\t'?sref=' + newDefaultSref +\n          \t\t\t'&system=' + jQuery('#imp-sref-system').val() +\n          \t\t\t'&callback=?', function(data) {\n            \tdefaultGeom = data.wkt;\n                   \t});\n\n\$.fn.resetPanel = function(){\n\tthis.find('.poll-section-body').show();\n\tthis.find('.poll-section-footer,.poll-section-trailer').show();\n\tthis.find('.reinit-button').show();\n\tthis.find('.mod-button').show();\n\tthis.find('.poll-image').empty();\n\tthis.find('.poll-session').remove();\n\tthis.find('.inline-error').remove();\n\tthis.find('#imp-georef-search').val('');\n\tthis.find('#imp-georef-div').hide();\n\tthis.find('#imp-georef-output-div').empty();\n\tthis.find('[name=place\\:INSEE]').val('" . lang::get('LANG_INSEE') . "');\n\tthis.find('#imp-sref-lat').val('');\n\tthis.find('#imp-sref-long').val('');\n\tthis.find('#X-sref-system').val('900913'); //note only one of these in cc-1, distinct from location:centroid_sref_system. This indicates no geolocation loaded.\n\t// TODO Map\n\tthis.find('.thumb').not('.blankPhoto').remove();\n\tthis.find('.blankPhoto').addClass('currentPhoto');\n\t\n\t// resetForm does not reset the hidden fields. record_status, website_id and survey_id are not altered so do not reset.\n\t// hidden Attributes generally hold unchanging data, but the name needs to be reset (does it for non hidden as well).\n\t// hidden location:name are set in code anyway.\n\tthis.find('.poll-dummy-form input').val('');\n\tthis.find('.poll-dummy-form input').removeAttr('checked');\n\tthis.find('.poll-dummy-form select').val('');\n\tthis.find('.poll-dummy-form textarea').val('');\n\tthis.find('.poll-dummy-form').find('[name\$=\\:determination_type]').val('A');\n\tthis.find('form').each(function(){\n\t\tjQuery(this).resetForm();\n\t\tjQuery(this).find('[name=sample\\:location_name],[name=location_image\\:path],[name=occurrence_image\\:path]').val('');\n\t\tjQuery(this).filter('#cc-1-collection-details').find('[name=sample\\:id],[name=location\\:id]').val('').attr('disabled', 'disabled');\n\t\tjQuery(this).find('[name=location_image\\:id],[name=occurrence\\:id],[name=determination\\:id],[name=occurrence_image\\:id]').val('').attr('disabled', 'disabled');\n\t\tjQuery(this).find('[name=sample\\:date]:hidden').val('2010-01-01');\n\t\tjQuery(this).find('input[name=locations_website\\:website_id]').removeAttr('disabled');\n\t\tjQuery(this).find('[name=locAttr\\:" . $args['location_picture_camera_attr_id'] . "],[name^=locAttr\\:" . $args['location_picture_camera_attr_id'] . "\\:],[name=locAttr\\:" . $args['location_picture_datetime_attr_id'] . "],[name^=locAttr\\:" . $args['location_picture_datetime_attr_id'] . "\\:],[name=occAttr\\:" . $args['occurrence_picture_camera_attr_id'] . "],[name^=occAttr\\:" . $args['occurrence_picture_camera_attr_id'] . "\\:],[name=occAttr\\:" . $args['occurrence_picture_datetime_attr_id'] . "],[name^=occAttr\\:" . $args['occurrence_picture_datetime_attr_id'] . "\\:]').val('');\n\t\tjQuery(this).find('[name^=smpAttr\\:],[name^=locAttr\\:],[name^=occAttr\\:]').filter('.multiselect').remove();\n\t\tjQuery(this).find('[name^=smpAttr\\:],[name^=locAttr\\:],[name^=occAttr\\:]').each(function(){\n\t\t\tvar name = jQuery(this).attr('name').split(':');\n\t\t\tif(name[1].indexOf('[]') > 0) name[1] = name[1].substr(0, name[1].indexOf('[]'));\n\t\t\tjQuery(this).attr('name', name[0]+':'+name[1]);\n\t\t});\n\t\tjQuery(this).find('[name^=smpAttr\\:],[name^=locAttr\\:],[name^=occAttr\\:]').filter(':checkbox').removeAttr('checked').each(function(){\n\t\t\tvar name = jQuery(this).attr('name').split(':');\n\t\t\tvar similar = jQuery('[name='+name[0]+'\\:'+name[1]+'],[name='+name[0]+'\\:'+name[1]+'\\[\\]]').filter(':checkbox');\n\t\t\tif(similar.length > 1)\n\t\t\t\tjQuery(this).attr('name', name[0]+':'+name[1]+'[]');\n\t\t});\n\t\tjQuery(this).find('input[name=location\\:centroid_sref]').val('');\n\t\tjQuery(this).find('input[name=location\\:centroid_geom]').val('');\n    });\t\n  };\n\nalertIndiciaError = function(data){\n\tvar errorString = \"" . lang::get('LANG_Indicia_Warehouse_Error') . "\";\n\tif(data.error){\terrorString = errorString + ' : ' + data.error;\t}\n\tif(data.errors){\n\t\tfor (var i in data.errors){\n\t\t\terrorString = errorString + ' : ' + data.errors[i];\n\t\t}\t\t\t\t\n\t}\n\talert(errorString);\n\t// the most likely cause is authentication failure - eg the read authentication has timed out.\n\t// prevent further use of the form:\n\t\$('.loading-panel').remove();\n\t\$('.poll-loading-hide').show();\n\tjQuery('#cc-1').hide();\n\tjQuery('#refresh-message').show();\n\tthrow('WAREHOUSE ERROR');\n};\n\t\t\t\ncheckProtocolStatus = function(display){\n  \tvar checkedProtocol = jQuery('[name=smpAttr\\:" . $args['protocol_attr_id'] . "],[name^=smpAttr\\:" . $args['protocol_attr_id'] . "\\:]').filter('[checked]').parent();\n    if(jQuery('[name=location\\:name]').val() != '' && checkedProtocol.length > 0) {\n        jQuery('#cc-1-title-details').empty().text(jQuery('#cc-1-collection-details input[name=location\\:name]:first').val());\n        firstBracket = checkedProtocol.find('label')[0].innerHTML.indexOf('(');\n        secondBracket = checkedProtocol.find('label')[0].innerHTML.lastIndexOf(')');\n        jQuery('#cc-1-protocol-details').empty().show().html('<strong>" . lang::get('LANG_Protocol_Title_Label') . "</strong> : <span class=\"protocol-head\">' +\n                  checkedProtocol.find('label')[0].innerHTML.slice(0, firstBracket-1) +\n                  '</span><span class=\"protocol-description\"> | ' +\n                  checkedProtocol.find('label')[0].innerHTML.slice(firstBracket+1, secondBracket) + '</span>');\n    } else {\n        jQuery('#cc-1-title-details').empty().text(\"" . lang::get('LANG_Collection_Details') . "\");\n        // TODO autogenerate a name\n        jQuery('#cc-1-protocol-details').empty().hide();\n    }\n    if(display == true){\n      jQuery('#cc-1-details').addClass('ui-accordian-content-active');\n    } else if(display == false){\n      jQuery('#cc-1-details').removeClass('ui-accordian-content-active');\n    } // anything else just leave\n};\ncheckForagingStatus = function(setForagingConfirm){\n\tjQuery('[name=occAttr\\:" . $args['foraging_attr_id'] . "],[name^=occAttr\\:" . $args['foraging_attr_id'] . ":]').filter('[checked]').each(function(index, elem){\n\t\tif(elem.value==1){ // need to allow string 1 comparison so no ===\n\t\t\tjQuery('#Foraging_Confirm').show();\n\t\t\tif(setForagingConfirm)\n\t\t\t\tjQuery('[name=dummy_foraging_confirm]').filter('[value=1]').attr('checked',true);\n\t\t} else\n\t\t\tjQuery('#Foraging_Confirm').hide();\n\t});\n};\ncheckSessionButtons = function(){\n\tif (jQuery('#cc-3-body').children().length === 1) {\n\t    jQuery('#cc-3').find('.delete-button').hide();\n\t    jQuery('#cc-3-valid-button').empty().text(\"" . lang::get('LANG_Validate_Session') . "\")\n  \t} else {\n\t\tjQuery('#cc-3').find('.delete-button').show();\n\t    jQuery('#cc-3-valid-button').empty().text(\"" . lang::get('LANG_Validate_Session_Plural') . "\")\n  \t}\n\tif(jQuery('[name=smpAttr\\:" . $args['protocol_attr_id'] . "],[name^=smpAttr\\:" . $args['protocol_attr_id'] . "\\:]').filter(':first').filter('[checked]').length >0){\n\t    jQuery('#cc-3-title-title').empty().text(\"" . lang::get('LANG_Sessions_Title') . "\");\n\t\tjQuery('#cc-3').find('.add-button').hide();\n\t} else {\n\t    jQuery('#cc-3-title-title').empty().text(\"" . lang::get('LANG_Sessions_Title_Plural') . "\");\n\t\tjQuery('#cc-3').find('.add-button').show();\n  \t}\n};\n\nshowStationPanel = true;\n\n// The validate functionality for each panel is sufficiently different that we can't generalise a function\n// this is the one called when we don't want the panel following to be opened automatically.\nvalidateCollectionPanel = function(){\n\tclearErrors('form#cc-1-collection-details');\n\tif(jQuery('#cc-1-body:visible').length == 0) return true; // body hidden so data already been validated successfully.\n\tif(!jQuery('#cc-1-body').find('form > input').valid()){\n\t\tmyScrollToError();\n\t\treturn false;\n  \t}\n\t// no need to check protocol - if we are this far, we've already filled it in.\n  \tshowStationPanel = false;\n\tjQuery('#cc-1-collection-details').submit();\n\treturn true;\n  };\n\nerrorPos = null;\nclearErrors = function(formSel) {\n\tjQuery(formSel).find('.inline-error').remove();\n\terrorPos = null;\n};\nmyScrollTo = function(selector){\n\tjQuery(selector).filter(':visible').each(function(){\n\t\tif(errorPos == null || jQuery(this).offset().top < errorPos){\n\t\t\terrorPos = jQuery(this).offset().top;\n\t\t\twindow.scroll(0,errorPos);\n\t\t}\n\t});\n};\nmyScrollToError = function(){\n\tjQuery('.inline-error,.error').filter(':visible').prev().each(function(){\n\t\tif(errorPos == null || jQuery(this).offset().top < errorPos){\n\t\t\terrorPos = jQuery(this).offset().top;\n\t\t\twindow.scroll(0,errorPos);\n\t\t}\n\t});\n};\n\nvalidateRadio = function(name, formSel){\n    var controls = jQuery(formSel).find('[name='+name+'],[name^='+name+'\\:]');\n    if(controls.filter('[checked]').length < 1) {\n        var label = \$('<p/>')\n\t\t\t\t.attr({'for': name})\n\t\t\t\t.addClass('inline-error')\n\t\t\t\t.html(\$.validator.messages.required);\n\t\tlabel.insertBefore(controls.filter(':first').parent());\n\t\treturn false;\n    }\n    return true;\n}\n\nvalidateRequiredField = function(name, formSel){\n    var control = jQuery(formSel).find('[name='+name+']');\n    if(control.val() == '') {\n        var label = \$('<p/>')\n\t\t\t\t.attr({'for': name})\n\t\t\t\t.addClass('inline-error')\n\t\t\t\t.html(\$.validator.messages.required);\n\t\tlabel.insertBefore(control);\n\t\treturn false;\n    }\n    return true;\n}\n\nvalidateOptInt = function(name, formSel){\n\tvar control = jQuery(formSel).find('[name='+name+'],[name^='+name+'\\:]');\n\tvar ctrvalue = control.val();\n\tvar OK = true;\n\tif(ctrvalue == '') return true;\n\tfor (i = 0 ; i < ctrvalue.length ; i++) {\n\t\tif ((ctrvalue.charAt(i) < '0') || (ctrvalue.charAt(i) > '9')) OK = false\n\t}\n\tif(OK) return OK;\n\tvar label = \$('<p/>')\n\t\t\t\t.attr({'for': name})\n\t\t\t\t.addClass('inline-error')\n\t\t\t\t.html(\"" . lang::get('validation_integer') . "\");\n\tlabel.insertBefore(control);\n\treturn false;\n}\n\ninsertImage = function(path, target, ratio){\n\tvar img = new Image();\n\tjQuery(img).load(function () {\n        target.removeClass('loading').append(this);\n        if(this.width/this.height > ratio){\n\t    \tjQuery(this).css('width', '100%').css('height', 'auto').css('vertical-align', 'middle').css('margin-left', 'auto').css('margin-right', 'auto').css('display', 'block');\n  \t\t} else {\n\t        jQuery(this).css('width', (100*this.width/(this.height*ratio))+'%').css('height', 'auto').css('vertical-align', 'middle').css('margin-left', 'auto').css('margin-right', 'auto').css('display', 'block');\n  \t\t}\n\t}).attr('src', '" . data_entry_helper::$base_url . data_entry_helper::$indicia_upload_path . "'+path);\n}\n\t\t\t\t    \n\$('#cc-1').ajaxError(function(event, request, settings){\n\tvar insectURL = insectIDstruc.pollURL+insectIDstruc.sessionID;\n\tif(settings.url != insectURL){ // this url may not be present.\n\t\talert(\"" . lang::get('ajax_error') . "\" + '\\n' + settings.url + '\\n' + request.status + ' ' + request.statusText + '\\n' + \"" . lang::get('ajax_error_bumpf') . "\");\n\t\t// unknown data state so prevent further use of the form:\n\t\t\$('.loading-panel').remove();\n\t\t\$('.poll-loading-hide').show();\n\t\tjQuery('#cc-1').hide();\n\t\tjQuery('#refresh-message').show();\n\t\tthrow('AJAX ERROR');\n\t}\n});\n \nvalidateTime = function(name, formSel){\n    var control = jQuery(formSel).find('[name='+name+'],[name^='+name+'\\:]');\n    if(control.val().match(/^(2[0-3]|[0,1][0-9]):[0-5][0-9]\$/) == null) {\n        var label = \$('<p/>')\n\t\t\t\t.attr({'for': name})\n\t\t\t\t.addClass('inline-error')\n\t\t\t\t.html('" . lang::get('validation_time') . "');\n\t\tlabel.insertBefore(control);\n\t\treturn false;\n    }\n    return true;\n}\n\n\$('#cc-1-collection-details').ajaxForm({\n\t\tasync: false,\n        dataType:  'json', \n        beforeSubmit:   function(data, obj, options){\n        \t// if location id filled in but sample id is not -> error\n        \tif(data.length == 15 && data[14].value == ''){\n        \t\talertIndiciaError({error : \"" . lang::get('Internal Error 1: sample id not filled in, so not safe to save collection') . "\"});\n\t\t\t\treturn false;\n\t\t\t}\n        \tclearErrors('form#cc-1-collection-details');\n        \tvar valid = true;\n        \tif (!jQuery('form#cc-1-collection-details > input').valid()) { valid = false; }\n        \tif (!validateRadio('smpAttr\\:" . $args['protocol_attr_id'] . "', 'form#cc-1-collection-details')) { valid = false; }\n\t       \tif ( valid == false ) {\n\t\t\t\tmyScrollToError();\n\t\t\t\treturn false;\n  \t\t\t};\n  \t\t\t// Warning this assumes that:\n  \t\t\t// 1) the location:name is the sixth field in the form.\n  \t\t\t// 1) the sample:location_name is the seventh field in the form.\n  \t\t\tdata[6].value = data[5].value;\n  \t\t\tif(data[3].value=='900913'){\n  \t\t\t\tdata[1].value=newDefaultSref;\n  \t\t\t\tdata[2].value=defaultGeom;\n  \t\t\t}\n  \t\t\tjQuery('#cc-2-floral-station > input[name=location\\:name]').val(data[5].value);\n  \t\t\tjQuery('#cc-1-valid-button').addClass('loading-button');\n        \treturn true;\n  \t\t},\n        success:   function(data){\n        \tif(data.success == 'multiple records' && data.outer_table == 'location'){\n        \t    jQuery('[name=location\\:id],[name=sample\\:location_id]').removeAttr('disabled').val(data.outer_id);\n        \t    jQuery('[name=locations_website\\:website_id]').attr('disabled', 'disabled');\n        \t    // data.struct.children[0] holds the details of the sample record.\n\t\t\t\tjQuery('#cc-6-consult-collection').attr('href', '" . url('node/' . $args['gallery_node']) . "'+'?collection_id='+data.struct.children[0].id);\n\t\t\t\tjQuery('#cc-1-collection-details,#cc-2-floral-station,#cc-1-delete-collection').find('[name=sample\\:id]').removeAttr('disabled').val(data.struct.children[0].id);\n\t\t\t\t// In this case we use loadAttributes to set the names of the attributes to include the attribute_value id.\n\t\t\t\t// cant use the struct as it can't tell which attribute is which. \n\t\t\t\tloadAttributes('#cc-1-collection-details,#cc-5-collection', 'sample_attribute_value', 'sample_attribute_id', 'sample_id', data.struct.children[0].id, 'smpAttr', true, true);\n\t\t\t   \tcheckProtocolStatus(true);\n        \t\t\$('#cc-1').foldPanel();\n    \t\t\tif(showStationPanel){ \$('#cc-2').showPanel(); }\n\t\t    \tshowStationPanel = true;\n        \t}  else \n\t\t\t\talertIndiciaError(data);\n        },\n        complete: function (){\n  \t\t\tjQuery('.loading-button').removeClass('loading-button');\n  \t\t}\n});\n\n\$('#cc-1-delete-collection').ajaxForm({ \n\t\tasync: false,\n\t\tdataType:  'json', \n        beforeSubmit:   function(data, obj, options){\n  \t\t\t// Warning this assumes that the data is fixed position:\n       \t\tdata[3].value = jQuery('#cc-1-collection-details input[name=sample\\:date]').val();\n        \tif(data[2].value == '') return false;\n\t\t\tif(data[4].value == ''){ // double check that location id is filled in\n\t\t\t\talertIndiciaError({error : \"" . lang::get('Internal Error 3: location id not set, so unsafe to delete collection.') . "\"});\n\t\t\t\treturn false;\n\t\t\t}\n  \t\t\tjQuery('#cc-1-reinit-button').addClass('loading-button');\n        \treturn true;\n  \t\t},\n        success:   function(data){\n        \tif(data.success == 'multiple records' && data.outer_table == 'sample'){\n        \t\tjQuery('#cc-3-body').empty();\n        \t\tpollReset(insectIDstruc);\n\t        \tjQuery('.poll-section').resetPanel();\n\t\t\t\tsessionCounter = 0;\n\t\t\t\taddSession();\n\t\t\t\tcheckProtocolStatus(false);\n\t\t\t\tjQuery('.poll-section').hidePanel();\n\t\t\t\tjQuery('.poll-image').empty();\n\t\t\t\tjQuery('#cc-1').showPanel();\n\t\t\t\tjQuery('.reinit-button').hide();\n\t\t\t\tif(jQuery('#map').children().length > 0) {\n\t\t\t\t\tvar div = jQuery('#map')[0];\n\t\t\t\t\tdiv.map.editLayer.destroyFeatures();\n\t\t\t\t\tdiv.map.searchLayer.destroyFeatures();\n\t\t\t\t\tif(inseeLayer != null) inseeLayer.destroyFeatures();\n\t\t\t\t\tjQuery('#cc-2-loc-description').empty();\n\t\t\t\t\tvar center = new OpenLayers.LonLat(" . $args['map_centroid_long'] . ", " . $args['map_centroid_lat'] . ");\n\t\t\t\t\tcenter.transform(div.map.displayProjection, div.map.projection);\n\t\t\t\t\tdiv.map.setCenter(center, " . (int) $args['map_zoom'] . ");\n\t\t\t\t}\n        \t}  else \n\t\t\t\talertIndiciaError(data);\n  \t\t},\n        complete: function (){\n  \t\t\tjQuery('.loading-button').removeClass('loading-button');\n  \t\t}\n});\n\n\$('#cc-1-valid-button').click(function() {\n\tjQuery('#cc-1-collection-details').submit();\n});\n\n\$('#cc-1-reinit-button').click(function() {\n    clearErrors('form#cc-1-collection-details');\n\tif(jQuery('form#cc-1-collection-details > input[name=sample\\:id]').filter('[disabled]').length > 0) { return } // sample id is disabled, so no data has been saved - do nothing.\n    if (!jQuery('form#cc-1-collection-details > input').valid()) {\n    \tmyScrollToError();\n    \talert(\"" . lang::get('LANG_Unable_To_Reinit') . "\");\n        return ;\n  \t}\n\tif(confirm(\"" . lang::get('LANG_Confirm_Reinit') . "\")){\n\t\tjQuery('#cc-1-delete-collection').submit();\n\t}\n});\n\n";
        // Flower Station section.
        $options = iform_map_get_map_options($args, $readAuth);
        $olOptions = iform_map_get_ol_options($args);
        // The maps internal projection will be left at its default of 900913.
        $options['searchLayer'] = 'true';
        $options['initialFeatureWkt'] = null;
        $options['proxy'] = '';
        // Switch to degrees, minutes, seconds for lat long.
        $options['latLongFormat'] = 'DMS';
        if (lang::get('msgGeorefSelectPlace') != 'msgGeorefSelectPlace') {
            $options['msgGeorefSelectPlace'] = lang::get('msgGeorefSelectPlace');
        }
        if (lang::get('msgGeorefNothingFound') != 'msgGeorefNothingFound') {
            $options['msgGeorefNothingFound'] = lang::get('msgGeorefNothingFound');
        }
        $extraParams = $readAuth + array('taxon_list_id' => $args['flower_list_id'], 'view' => 'detail', 'orderby' => 'taxonomic_sort_order', 'allow_data_entry' => 't');
        $species_ctrl_args = array('fieldname' => 'flowerSelect', 'table' => 'taxa_taxon_list', 'captionField' => 'taxon', 'listCaptionSpecialChars' => true, 'valueField' => 'id', 'columns' => 2, 'blankText' => lang::get('LANG_Choose_Taxon'), 'extraParams' => $extraParams, 'suffixTemplate' => 'nosuffix');
        $r .= '
<div id="cc-2" class="poll-section">
  <div id="cc-2-title" class="ui-accordion-header ui-helper-reset ui-state-active ui-corner-all poll-section-title"><span>' . lang::get('LANG_Flower_Station') . '</span>
    <div class="right">
      <span id="cc-2-mod-button" class="ui-state-default ui-corner-all mod-button">' . lang::get('LANG_Modify') . '</span>
    </div>
  </div>
  <div id="cc-2-body" class="ui-accordion-content ui-helper-reset ui-widget-content ui-corner-top ui-accordion-content-active poll-section-body">
    <div id="cc-2-flower" >
	  <div id="cc-2-flower-title">' . lang::get('LANG_Upload_Flower') . '</div>
	  <form id="cc-2-flower-upload" enctype="multipart/form-data" action="' . iform_ajaxproxy_url($node, 'media') . '" method="POST">
    		<input type="hidden" id="website_id" name="website_id" value="' . $args['website_id'] . '" />
    		<input name="upload_file" type="file" class="required" />
     		<input type="submit" value="' . lang::get('LANG_Upload') . '" class="btn-submit" />
 	  		<div id="cc-2-flower-image" class="poll-image"></div>
      </form>
      <div id="cc-2-flower-identify" class="poll-dummy-form">
        <div class="id-tool-group">
          ' . iform_pollenators::help_button($use_help, "flower-help-button", $args['help_function'], $args['help_flower_arg']) . '
		  <p><strong>' . lang::get('LANG_Identify_Flower') . ' :</strong></p>
          <div class="id-later-group">
            <label for="id-flower-later" class="follow-on">' . lang::get('LANG_ID_Flower_Later') . ' </label><input type="checkbox" id="id-flower-later" name="id-flower-later" /> 
          </div>
		  <input type="hidden" id="flower:taxon_details" name="flower:taxon_details" value=""/>
          <input type="hidden" name="flower:determination_type" value="A" />
          <input type="hidden" name="flower:taxa_taxon_list_id" value="" />
          <label for="id-flower-unknown" class="follow-on">' . lang::get('LANG_ID_Flower_Unknown') . ' </label><input type="checkbox" id="id-flower-unknown" name="id-flower-unknown" /><br/>
          ' . lang::get('LANG_Known_Species') . ' : <input name="flowerAutocomplete" id="flowerAutocomplete" />' . data_entry_helper::select($species_ctrl_args) . '
          <table id="flower-species-list"><tbody id="flower-species-list-body"></tbody></table>
        </div>
 	    <div class="id-specified-group">
          <label for="flower:taxon_extra_info" class="follow-on">' . lang::get('LANG_ID_More_Precise') . ' </label> 
          <input type="text" id="flower:taxon_extra_info" name="flower:taxon_extra_info" class="taxon-info" />
        </div>
      </div>
      <div class="id-comment">
        <label for="flower:comment" >' . lang::get('LANG_ID_Comment') . ' </label>
        <textarea id="flower:comment" name="flower:comment" class="taxon-comment" rows="3" ></textarea>
      </div>
    </div>
    <div class="poll-break"></div>
 	<div id="cc-2-environment">
	  ' . iform_pollenators::help_button($use_help, "environment-help-button", $args['help_function'], $args['help_environment_arg']) . '
	  <div id="cc-2-environment-title">' . lang::get('LANG_Upload_Environment') . '</div>
 	  <form id="cc-2-environment-upload" enctype="multipart/form-data" action="' . iform_ajaxproxy_url($node, 'media') . '" method="POST">
    	<input type="hidden" id="website_id" name="website_id" value="' . $args['website_id'] . '" />
    	<input name="upload_file" type="file" class="required" />
    	<input type="submit" value="' . lang::get('LANG_Upload') . '" class="btn-submit" />
 	  	<div id="cc-2-environment-image" class="poll-image"></div>
      </form>
 	</div>
 	<form id="cc-2-floral-station" action="' . iform_ajaxproxy_url($node, 'loc-smp-occ') . '" method="POST">
      <input type="hidden" id="website_id" name="website_id" value="' . $args['website_id'] . '" />
      <input type="hidden" id="location:id" name="location:id" value="" />
      <input type="hidden" id="location:name" name="location:name" value=""/>
      <input type="hidden" name="location:centroid_sref" />
      <input type="hidden" name="location:centroid_geom" />
      <input type="hidden" id="imp-sref-system" name="location:centroid_sref_system" value="4326" />
      <input type="hidden" id="location_image:path" name="location_image:path" value="" />
      <input type="hidden" id="location_picture_camera_attr" name="locAttr:' . $args['location_picture_camera_attr_id'] . '" value="" />
      <input type="hidden" id="location_picture_datetime_attr" name="locAttr:' . $args['location_picture_datetime_attr_id'] . '" value="" />
      <input type="hidden" id="sample:survey_id" name="sample:survey_id" value="' . $args['survey_id'] . '" />
      <input type="hidden" id="sample:id" name="sample:id" value=""/>
      <input type="hidden" name="sample:date" value="2010-01-01"/>
      <input type="hidden" name="determination:taxa_taxon_list_id" value=""/>  
      <input type="hidden" name="determination:taxon_details" value=""/>  
      <input type="hidden" name="determination:taxon_extra_info" value=""/>  
      <input type="hidden" name="determination:comment" value=""/>  
      <input type="hidden" name="determination:determination_type" value="A" />  
      <input type="hidden" name="determination:cms_ref" value="' . $uid . '" />
      <input type="hidden" name="determination:email_address" value="' . $email . '" />
      <input type="hidden" name="determination:person_name" value="' . $username . '" />  
      <input type="hidden" name="occurrence:use_determination" value="Y"/>    
      <input type="hidden" name="occurrence:record_status" value="C" />
      <input type="hidden" id="location_image:id" name="location_image:id" value="" disabled="disabled" />
      <input type="hidden" id="occurrence:id" name="occurrence:id" value="" disabled="disabled" />
      <input type="hidden" id="determination:id" name="determination:id" value="" disabled="disabled" />
      <input type="hidden" id="occurrence_image:id" name="occurrence_image:id" value="" disabled="disabled" />
      <input type="hidden" id="occurrence_image:path" name="occurrence_image:path" value="" />
      <input type="hidden" id="flower_picture_camera_attr" name="occAttr:' . $args['occurrence_picture_camera_attr_id'] . '" value="" />
      <input type="hidden" id="flower_picture_datetime_attr" name="occAttr:' . $args['occurrence_picture_datetime_attr_id'] . '" value="" />
      ' . str_replace("\n", "", data_entry_helper::outputAttribute($occurrence_attributes[$args['flower_type_attr_id']], $defNRAttrOptions)) . str_replace("\n", "", data_entry_helper::outputAttribute($location_attributes[$args['distance_attr_id']], $defNRAttrOptions)) . str_replace("\n", "", data_entry_helper::outputAttribute($location_attributes[$args['within50m_attr_id']], $defNRAttrOptions)) . str_replace("\n", "", data_entry_helper::outputAttribute($location_attributes[$args['habitat_attr_id']], $checkOptions)) . '
    </form>
    <div class="poll-break"></div>
    <div id="cc-2-location-container">
      ' . iform_pollenators::help_button($use_help, "location-help-button", $args['help_function'], $args['help_location_arg']) . '
      <div id="cc-2-location-notes" >' . lang::get('LANG_Location_Notes') . '</div>
      <div id="cc-2-location-entry">
        ' . data_entry_helper::georeference_lookup(iform_map_get_georef_options($args, $readAuth)) . '
  	    <label for="place:INSEE">' . lang::get('LANG_Or') . '</label><input type="text" id="place:INSEE" name="place:INSEE" value="' . lang::get('LANG_INSEE') . '"
	 		onclick="if(this.value==\'' . lang::get('LANG_INSEE') . '\'){this.value=\'\'; this.style.color=\'#000\'}"  
            onblur="if(this.value==\'\'){this.value=\'' . lang::get('LANG_INSEE') . '\'; this.style.color=\'#555\'}" /><input type="button" id="search-insee-button" class="ui-corner-all ui-widget-content ui-state-default search-button" value="' . lang::get('search') . '" />
 	    <label >' . lang::get('LANG_Or') . '</label>
    	' . data_entry_helper::sref_textbox(array('srefField' => 'place:entered_sref', 'systemfield' => 'place:entered_sref_system', 'id' => 'place-sref', 'fieldname' => 'place:name', 'splitLatLong' => true, 'labelLat' => lang::get('Latitude'), 'fieldnameLat' => 'place:lat', 'labelLong' => lang::get('Longitude'), 'fieldnameLong' => 'place:long', 'idLat' => 'imp-sref-lat', 'idLong' => 'imp-sref-long')) . '
 	  </div>
 	  <div class="poll-map-container">';
        $tempScript = data_entry_helper::$onload_javascript;
        data_entry_helper::$onload_javascript = '';
        $r .= data_entry_helper::map_panel($options, $olOptions);
        $map1JS = data_entry_helper::$onload_javascript;
        data_entry_helper::$onload_javascript = $tempScript;
        $r .= '</div>
 	  <div id="cc-2-loc-description"></div>
    </div>
  </div>
  <div id="cc-2-footer" class="ui-accordion-content ui-helper-reset ui-widget-content ui-corner-bottom ui-accordion-content-active poll-section-footer">
    <div id="cc-2-valid-button" class="ui-state-default ui-corner-all save-button">' . lang::get('LANG_Validate_Flower') . '</div>
  </div>
</div>';
        // NB the distance attribute is left blank at the moment if unknown: TODO put in a checkbox : checked if blank for nsp
        data_entry_helper::$javascript .= "\njQuery('input#flowerAutocomplete').autocomplete(flowerTaxa,\n      { matchContains: true,\n        parse: function(data)\n        {\n          var results = [];\n          jQuery.each(data, function(i, item) {\n            results[results.length] =\n            {\n              'data' : item,\n              'result' : item.id,\n              'value' : item.taxon\n            };\n          });\n          return results;\n        },\n      formatItem: function(item)\n      {\n        return item.taxon;\n      }\n      // {max}\n});\njQuery('input#flowerAutocomplete').result(function(event, data) {\n  if(jQuery('#flower-species-list input[value='+data.id+']').length > 0) return;\n  jQuery('input#flowerAutocomplete').val('');\n  jQuery('<tr class=\"flower-species-list-entry\"><td><input type=\"hidden\" name=\"flower:taxa_taxon_list_id_list[]\" value=\"'+data.id+'\"\\>'+htmlspecialchars(data.taxon)+'</td><td><img class=\"removeRow\" src=\"/misc/watchdog-error.png\" alt=\"" . lang::get('Remove this entry') . "\" title=\"" . lang::get('Remove this entry') . "\"/></td></tr>').appendTo('#flower-species-list-body');\n  jQuery('#cc-2-flower-identify [name=flower\\:determination_type]').val('A');\n  jQuery('#id-flower-unknown').removeAttr('checked');\n  jQuery('#id-flower-later').removeAttr('checked').attr('disabled','disabled');\n});\njQuery('select#flowerSelect').change(function() {\n  if(jQuery('#flower-species-list input[value='+jQuery(this).val()+']').length > 0) return;\n  jQuery('<tr class=\"flower-species-list-entry\"><td><input type=\"hidden\" name=\"flower:taxa_taxon_list_id_list[]\" value=\"'+jQuery(this).val()+'\"\\>'+htmlspecialchars(jQuery(this).find('option[value='+jQuery(this).val()+']').text())+'</td><td><img class=\"removeRow\" src=\"/misc/watchdog-error.png\" alt=\"" . lang::get('Remove this entry') . "\" title=\"" . lang::get('Remove this entry') . "\"/></td></tr>').appendTo('#flower-species-list-body');\n  jQuery('#cc-2-flower-identify [name=flower\\:determination_type]').val('A');\n  jQuery('select#flowerSelect').val('');\n  jQuery('#id-flower-unknown').removeAttr('checked');\n  jQuery('#id-flower-later').removeAttr('checked').attr('disabled','disabled');\n});\nshowSessionsPanel = true;\n\nbuildMap = function (){\n\tif(jQuery('.poll-map-container:visible').length == 0) return; \n\tif(jQuery('#map').children().length == 0) {\n\t\t" . $map1JS . "\n  \t\tjQuery('#map')[0].map.searchLayer.events.register('featuresadded', {}, function(a1){\n\t\t\tif(inseeLayer != null) inseeLayer.destroyFeatures();\n\t\t});\n\t\tjQuery('#map')[0].map.editLayer.events.register('featuresadded', {}, function(a1){\n\t\t\tif(inseeLayer != null) inseeLayer.destroy();\n\t\t\tjQuery('#cc-2-loc-description').empty();\n\t\t  \tvar filter = new OpenLayers.Filter.Spatial({type: OpenLayers.Filter.Spatial.CONTAINS, property: 'the_geom', value: jQuery('#map')[0].map.editLayer.features[0].geometry});\n\t\t\tvar strategy = new OpenLayers.Strategy.Fixed({preload: false, autoActivate: false});\n\t\t\tvar styleMap = new OpenLayers.StyleMap({\"default\": new OpenLayers.Style({fillColor: \"Red\", strokeColor: \"Red\", fillOpacity: 0, strokeWidth: 1})});\n\t\t\tinseeLayer = new OpenLayers.Layer.Vector('INSEE Layer', {\n\t\t\t\tstyleMap: styleMap,\n\t\t\t\tstrategies: [strategy],\n\t\t\t\tdisplayInLayerSwitcher: false,\n\t\t\t\tprotocol: new OpenLayers.Protocol.WFS({\n\t\t\t\t\turl:  '" . str_replace("{HOST}", $_SERVER['HTTP_HOST'], $args['INSEE_url']) . "',\n\t\t\t\t\tfeaturePrefix: '" . $args['INSEE_prefix'] . "',\n\t\t\t\t\tfeatureType: '" . $args['INSEE_type'] . "',\n\t\t\t\t\tgeometryName:'the_geom',\n\t\t\t\t\tfeatureNS: '" . $args['INSEE_ns'] . "',\n\t\t\t\t\tsrsName: 'EPSG:900913',\n\t\t\t\t\tversion: '1.1.0'                  \n\t\t\t\t\t,propertyNames: ['the_geom', 'NOM', 'INSEE_NEW', 'DEPT_NUM', 'DEPT_NOM', 'REG_NUM', 'REG_NOM']\n\t\t\t\t}),\n\t\t\t\tfilter: filter\n\t\t\t});\n\t\t    inseeLayer.events.register('featuresadded', {}, function(a1){\n    \t\t\tif(a1.features.length > 0)\n\t\t\t    \tjQuery('<span>'+a1.features[0].attributes.NOM+' ('+a1.features[0].attributes.INSEE_NEW+'), '+a1.features[0].attributes.DEPT_NOM+' ('+a1.features[0].attributes.DEPT_NUM+'), '+a1.features[0].attributes.REG_NOM+' ('+a1.features[0].attributes.REG_NUM+')</span>').appendTo('#cc-2-loc-description');\n\t\t    });\n\t\t\tjQuery('#map')[0].map.addLayer(inseeLayer);\n\t\t\tstrategy.load({});\n\t\t});\n\t}\n}\n\nflowerIDstruc = {\n\ttype: 'flower',\n\tselector: '#cc-2-flower-identify',\n\tmainForm: 'form#cc-2-floral-station',\n\tuseKey: false,\n\tstoredTaxaList: [],\n\tname: 'flowerIDstruc',\n\ttaxaList: flowerTaxa\n};\n\ntoolPoller = function(toolStruct){\n\tif(toolStruct.sessionID == '') return;\n\ttoolStruct.pollTimer = setTimeout('toolPoller('+toolStruct.name+');', " . $args['ID_tool_poll_interval'] . ");\n\tjQuery.ajax({\n\t url: toolStruct.pollURL+toolStruct.sessionID,\n\t dataType: 'jsonp',\n     toolStruct: toolStruct,\n\t success: function(da){ // now jsonp form, so comes in already parsed.\n\t  pollReset(this.toolStruct);\n\t  var status = da.data.sddversion + ' : ' + JSON.stringify(da.data.history);\n      jQuery(this.toolStruct.selector+' [name='+this.toolStruct.type+'\\:taxon_details]').val(status); // Stores details how the identification was arrived at within the tool.\n      if(typeof da.urlimage != 'undefined' && da.urlimage != 'none'){\n        // Upload image file into server.\n        // TODO ids should be data driven from ID Struct items.\n        jQuery('#cc-4-insect-upload input[name=upload_file]').val('');\n        \$('#cc-4-insect-image').empty();\n        \$('#cc-4-insect-image').addClass('loading');\n        jQuery('form#cc-4-main-form input[name=occurrence_image\\:path]').val('');\n        \$.post('" . iform_ajaxproxy_url($node, 'remoteMedia') . "',\n\t\t\t{ website_id : '" . $args['website_id'] . "',\n\t\t\t  file_url : da.urlimage },\n\t\t\tfunction(data) {\n\t\t\t\t\$('#cc-4-insect-image').removeClass('loading');\n        \t\tif(data.success == true){\n\t        \t\t// There is only one file\n\t        \t\tjQuery('form#cc-4-main-form input[name=occurrence_image\\:path]').val(data.files[0].filename);\n\t        \t\tjQuery('#insect_picture_camera_attr').val(data.files[0].EXIF_Camera_Make);\n\t        \t\tjQuery('#insect_picture_datetime_attr').val(data.files[0].EXIF_DateTime);\n\t        \t\tinsertImage('med-'+data.files[0].filename, jQuery('#cc-4-insect-image'), " . $args['Insect_Image_Ratio'] . ");\n\t\t\t\t}  else\n\t\t\t\t\talertIndiciaError(data);\n\t\t\t},\n\t\t\t'json');\n      }\n      var items = da.data.itemsselected;\n\t  var count = items.length;\n\t  if(count <= 0){\n\t  \t// no valid stuff so blank it all out.\n\t  \tjQuery('#'+this.toolStruct.type+'_taxa_list').append(\"" . lang::get('LANG_Taxa_Unknown_In_Tool') . "\");\n\t  \tjQuery(this.toolStruct.selector+' [name='+this.toolStruct.type+'\\:determination_type]').val('X'); // Unidentified.\n      } else {\n      \tvar resultsIDs = [];\n      \tvar resultsText = \"" . lang::get('LANG_Taxa_Returned') . "<br />{ \";\n      \tvar notFound = '';\n\t\tfor(var j=0; j < count; j++){\n\t\t\tvar found = false;\n\t\t\tfor(i = 0; i< this.toolStruct.taxaList.length; i++){\n  \t\t\t\tif(this.toolStruct.taxaList[i].xperID == items[j].itemId){\n\t  \t\t\t\tresultsIDs.push(this.toolStruct.taxaList[i].id);\n\t  \t\t\t\tresultsText = resultsText + (j == 0 ? '' : '<br />&nbsp;&nbsp;') + htmlspecialchars(this.toolStruct.taxaList[i].taxon);\n\t  \t\t\t\tfound = true;\n\t  \t\t\t\tbreak;\n  \t\t\t\t}\n  \t\t\t};\n  \t\t\tif(!found){\n  \t\t\t\tnotFound = (notFound == '' ? '' : notFound + ', ') + items[j].itemId; // don't need special chars as going into an input field\n  \t\t\t}\n  \t\t}\n\t\tjQuery('#'+this.toolStruct.type+'_taxa_list').append(resultsText+ ' }');\n\t\tthis.toolStruct.storedTaxaList = resultsIDs;\n\t  \tif(notFound != ''){\n\t\t\tvar comment = jQuery('[name='+this.toolStruct.type+'\\:comment]');\n\t\t\tcomment.val('" . lang::get('LANG_ID_Unrecognised') . " '+notFound+'. '+comment.val());\n\t\t}\n  \t  }\n    }});\n};\n\npollReset = function(toolStruct){\n\tclearTimeout(toolStruct.timeOutTimer);\n\tclearTimeout(toolStruct.pollTimer);\n\tjQuery('#'+toolStruct.type+'-id-cancel').hide();\n\tjQuery('#'+toolStruct.type+'-id-button').show();\n\ttoolStruct.storedTaxaList = [];\n\tjQuery(toolStruct.selector+' [name='+toolStruct.type+'\\:taxon_details]').val('');\n\tjQuery('#'+toolStruct.type+'_taxa_list').empty();\n\ttoolStruct.sessionID='';\n\ttoolStruct.timeOutTimer = null;\n\ttoolStruct.pollTimer = null;\n};\n\nidButtonPressed = function(toolStruct){\n    if(!toolStruct.useKey) return;\n\tjQuery(toolStruct.selector+' [name='+toolStruct.type+'\\:determination_type]').val('A');\n\tjQuery('#id-'+toolStruct.type+'-later').removeAttr('checked');\n\ttoolStruct.storedTaxaList = [];\n\tjQuery(toolStruct.selector+' [name='+toolStruct.type+'\\:taxon_details]').val('');\n\tjQuery('#'+toolStruct.type+'_taxa_list').empty();\n\tjQuery(toolStruct.selector+' [name='+toolStruct.type+'\\:taxa_taxon_list_id]').val('');\n\tjQuery('#'+toolStruct.type+'-id-cancel').show();\n\tjQuery('#'+toolStruct.type+'-id-button').hide();\n\tvar d = new Date;\n\tvar s = d.getTime();\n\ttoolStruct.sessionID = '" . session_id() . "_'+s.toString()\n\tclearTimeout(toolStruct.timeOutTimer);\n\tclearTimeout(toolStruct.pollTimer);\n\tvar toolURL = toolStruct.invokeURL+'" . $args['ID_tool_session_param'] . "'+toolStruct.sessionID;\n\tvar path = jQuery('form#cc-4-main-form input[name=occurrence_image\\:path]').val();\n\tif(path != '') {\n    \tvar file = '" . data_entry_helper::$base_url . data_entry_helper::$indicia_upload_path . "'+path;\n    \ttoolURL += '&urlimageuser='******'','');\n\ttoolStruct.pollTimer = setTimeout('toolPoller('+toolStruct.name+');', " . $args['ID_tool_poll_interval'] . ");\n\ttoolStruct.timeOutTimer = setTimeout('toolReset('+toolStruct.name+');', " . $args['ID_tool_poll_timeout'] . ");\n};\n\ntaxonChosen = function(toolStruct){\n  \tjQuery('#id-'+toolStruct.type+'-later').removeAttr('checked');\n\ttoolStruct.storedTaxaList = [];\n\tjQuery(toolStruct.selector+' [name='+toolStruct.type+'\\:taxon_details]').val('');\n\tjQuery('#'+toolStruct.type+'_taxa_list').empty();\n\tjQuery('[name='+toolStruct.type+'\\:comment]').val('');\n\tjQuery(toolStruct.selector+' [name='+toolStruct.type+'\\:taxon_extra_info]').val('');\n\tjQuery(toolStruct.selector+' [name='+toolStruct.type+'\\:determination_type]').val('A');\n};\n\nidLater = function (toolStruct){\n  if (jQuery('#id-'+toolStruct.type+'later').attr('checked') != '') {\n    jQuery(toolStruct.selector+' [name='+toolStruct.type+'\\:determination_type]').val('A');\n    jQuery('.'+toolStruct.type+'-species-list-entry').remove();\n    jQuery('#id-'+toolStruct.type+'-unknown').removeAttr('checked');\n    toolStruct.storedTaxaList = [];\n    jQuery(toolStruct.selector+' [name='+toolStruct.type+'\\:taxon_details]').val('');\n    jQuery('#'+toolStruct.type+'_taxa_list').empty();\n    jQuery(toolStruct.selector+' [name='+toolStruct.type+'\\:taxa_taxon_list_id]').val('');\n    jQuery(toolStruct.selector+' [name='+toolStruct.type+'\\:taxon_extra_info]').val(''); // more precise info\n    jQuery('[name='+toolStruct.type+'\\:comment]').val('');\n  }\n};\njQuery('#id-flower-later').change(function (){\n\tidLater(flowerIDstruc);\n});\njQuery('#id-flower-unknown').change(function (){\n  if (jQuery('#id-flower-unknown').attr('checked') != '') {\n    jQuery('#id-flower-later').removeAttr('checked').attr('disabled','disabled');\n    jQuery('#cc-2-flower-identify [name=flower\\:determination_type]').val('X');\n    jQuery('.flower-species-list-entry').remove();\n    jQuery('#cc-2-flower-identify [name=flower\\:taxon_details]').val('');\n    jQuery('#cc-2-flower-identify [name=flower\\:taxa_taxon_list_id]').val('');\n    jQuery('#cc-2-flower-identify [name=flower\\:taxon_extra_info]').val(''); // more precise info\n    jQuery('[name=flower\\:comment]').val('');\n  } else\n    jQuery('#id-flower-later').removeAttr('disabled');\n});\njQuery('.removeRow').live('click', function (){\n  if(jQuery('.removeRow').length <= 1)\n    jQuery('#id-flower-later').removeAttr('disabled');\n  jQuery(this).closest('tr.flower-species-list-entry').remove();\n});\n\njQuery('#search-insee-button').click(function(){\n\tif(inseeLayer != null)\n\t\tinseeLayer.destroy();\n\tvar filters = [];\n  \tvar place = jQuery('input[name=place\\:INSEE]').val();\n  \tif(place == '" . lang::get('LANG_INSEE') . "') return;\n  \tfilters.push(new OpenLayers.Filter.Comparison({\n  \t\t\ttype: OpenLayers.Filter.Comparison.EQUAL_TO ,\n    \t\tproperty: 'INSEE_NEW',\n    \t\tvalue: place\n  \t\t}));\n  \tfilters.push(new OpenLayers.Filter.Comparison({\n  \t\t\ttype: OpenLayers.Filter.Comparison.EQUAL_TO ,\n    \t\tproperty: 'INSEE_OLD',\n    \t\tvalue: place\n  \t\t}));\n\n\tvar strategy = new OpenLayers.Strategy.Fixed({preload: false, autoActivate: false});\n\tvar styleMap = new OpenLayers.StyleMap({\n                \"default\": new OpenLayers.Style({\n                    fillColor: \"Red\",\n                    strokeColor: \"Red\",\n                    fillOpacity: 0,\n                    strokeWidth: 1\n                  })\n\t});\n\tinseeLayer = new OpenLayers.Layer.Vector('INSEE Layer', {\n\t\t  styleMap: styleMap,\n          strategies: [strategy],\n          displayInLayerSwitcher: false,\n\t      protocol: new OpenLayers.Protocol.WFS({\n              url:  '" . str_replace("{HOST}", $_SERVER['HTTP_HOST'], $args['INSEE_url']) . "',\n              featurePrefix: '" . $args['INSEE_prefix'] . "',\n              featureType: '" . $args['INSEE_type'] . "',\n              geometryName:'the_geom',\n              featureNS: '" . $args['INSEE_ns'] . "',\n              srsName: 'EPSG:900913',\n              version: '1.1.0'                  \n      \t\t  ,propertyNames: ['the_geom']\n  \t\t\t}),\n  \t\t  filter: new OpenLayers.Filter.Logical({\n\t\t\t      type: OpenLayers.Filter.Logical.OR,\n\t\t\t      filters: filters\n\t\t  })\n    });\n\tinseeLayer.events.register('featuresadded', {}, function(a1){\n\t\tvar div = jQuery('#map')[0];\n\t\tdiv.map.searchLayer.destroyFeatures();\n\t\tvar bounds=inseeLayer.getDataExtent();\n    \tvar dy = (bounds.top-bounds.bottom)/10;\n    \tvar dx = (bounds.right-bounds.left)/10;\n    \tbounds.top = bounds.top + dy;\n    \tbounds.bottom = bounds.bottom - dy;\n    \tbounds.right = bounds.right + dx;\n    \tbounds.left = bounds.left - dx;\n    \t// if showing a point, don't zoom in too far\n    \tif (dy===0 && dx===0) {\n    \t\tdiv.map.setCenter(bounds.getCenterLonLat(), div.settings.maxZoom);\n    \t} else {\n    \t\tdiv.map.zoomToExtent(bounds);\n    \t}\n    });\n\tinseeLayer.events.register('loadend', {}, function(){\n\t\tif(inseeLayer.features.length == 0){\n\t\t\talert(\"" . lang::get('LANG_NO_INSEE') . "\");\n\t\t}\n    });\n    jQuery('#map')[0].map.addLayer(inseeLayer);\n\tstrategy.load({});\n});\n\nvalidateStationPanel = function(){\n\tvar myPanel = jQuery('#cc-2');\n\tvar valid = true;\n\tclearErrors('form#cc-2-floral-station');\n\tclearErrors('#cc-2-flower-identify');\n\tif(myPanel.filter(':visible').length == 0) return true; // panel is not visible so no data to fail validation.\n\tif(myPanel.find('.poll-section-body:visible').length == 0) return true; // body hidden so data already been validated successfully.\n\t// If no data entered also return true: this can only be the case when pressing the modify button on the collections panel\n\tif(jQuery('form#cc-2-floral-station > input[name=location_image\\:path]').val() == '' &&\n\t\t\tjQuery('form#cc-2-floral-station > input[name=occurrence\\:id]').val() == '' &&\n\t\t\tjQuery('form#cc-2-floral-station > input[name=occurrence_image\\:path]').val() == '' &&\n\t\t\tjQuery('.flower-species-list-entry').length == 0 &&\n\t\t\tjQuery('#cc-2-flower-identify [name=flower\\:taxon_extra_info]').val() == '' &&\n\t\t\tjQuery('[name=flower\\:comment]').val() == '' &&\n\t\t\tjQuery('[name=occAttr\\:" . $args['flower_type_attr_id'] . "],[name^=occAttr\\:" . $args['flower_type_attr_id'] . "\\:]').filter('[checked]').length == 0 &&\n\t\t\tjQuery('[name=locAttr\\:" . $args['within50m_attr_id'] . "],[name^=locAttr\\:" . $args['within50m_attr_id'] . "\\:]').filter('[checked]').length == 0 &&\n\t\t\tjQuery('[name=locAttr\\:" . $args['habitat_attr_id'] . "],[name^=locAttr\\:" . $args['habitat_attr_id'] . "\\:]').filter('[checked]').length == 0 &&\n    \t\tjQuery('[name=locAttr\\:" . $args['distance_attr_id'] . "],[name^=locAttr\\:" . $args['distance_attr_id'] . "\\:]').val() == '') {\n\t\tjQuery('#cc-2').foldPanel();\n\t\treturn true;\n\t}\n    if(jQuery('form#cc-2-floral-station > input[name=location_image\\:path]').val() == '' ||\n\t\t\t\t\tjQuery('form#cc-2-floral-station > input[name=occurrence_image\\:path]').val() == ''){\n\t\tif(jQuery('form#cc-2-floral-station > input[name=occurrence_image\\:path]').val() == '')\n\t\t\tmyScrollTo('#cc-2-flower-upload');\n\t\telse\n\t\t\tmyScrollTo('#cc-2-environment-upload');\n\t\talert(\"" . lang::get('LANG_Must_Provide_Pictures') . "\");\n\t\tvalid = false;\n\t}\n    if(jQuery('#imp-geom').val() == '') {\n\t\talert(\"" . lang::get('LANG_Must_Provide_Location') . "\");\n\t\tmyScrollTo('.poll-map-container');\n\t\tvalid = false;\n\t}\n\tif (jQuery('#id-flower-later').attr('checked') == '' && jQuery('#id-flower-unknown').attr('checked') == '' && jQuery('.flower-species-list-entry').length == 0){\n\t\talert(\"" . lang::get('LANG_Must_Provide_Identification') . "\");\n\t\tmyScrollTo('#id-flower-later');\n\t\tvalid = false;\n    }\n\tif (!jQuery('form#cc-2-floral-station > input').valid()) { valid = false; }\n\tif (!validateRadio('occAttr\\:" . $args['flower_type_attr_id'] . "', 'form#cc-2-floral-station')) { valid = false; }\n\tif (!validateRadio('locAttr\\:" . $args['within50m_attr_id'] . "', 'form#cc-2-floral-station')) { valid = false; }\n\tif (!validateOptInt('locAttr\\:" . $args['distance_attr_id'] . "', 'form#cc-2-floral-station')) { valid = false; }\n   \tif ( valid == false ) {\n   \t\tmyScrollToError();\n   \t\treturn valid;\n   \t}\n\tshowSessionsPanel = false;\n\tjQuery('form#cc-2-floral-station').submit();\n\treturn true;\n};\n\n// Flower upload picture form.\n\$('#cc-2-flower-upload').ajaxForm({ \n\t\tasync: false,\n\t\tdataType:  'json', \n        beforeSubmit:   function(data, obj, options){\n         \tif (!jQuery('form#cc-2-flower-upload').valid() ||\n                    jQuery('#cc-2-flower-image').hasClass('loading')) {\n   \t\t\t\treturn false;\n   \t\t\t}\n   \t\t\t\$('#cc-2-flower-image').empty();\n        \t\$('#cc-2-flower-image').addClass('loading');\n\t\t   \tjQuery('form#cc-2-floral-station input[name=occurrence_image\\:path]').val('');\n  \t\t},\n        success:   function(data){\n        \tif(data.success == true){\n\t        \t// There is only one file\n\t        \tjQuery('form#cc-2-floral-station input[name=occurrence_image\\:path]').val(data.files[0].filename);\n\t        \tjQuery('#flower_picture_camera_attr').val(data.files[0].EXIF_Camera_Make);\n\t        \tjQuery('#flower_picture_datetime_attr').val(data.files[0].EXIF_DateTime);\n\t        \tinsertImage('med-'+data.files[0].filename, jQuery('#cc-2-flower-image'), " . $args['Flower_Image_Ratio'] . ");\n\t        \tjQuery('#cc-2-flower-upload input[name=upload_file]').val('');\n  \t\t\t} else\n\t\t\t\talertIndiciaError(data);\n  \t\t},\n  \t\tcomplete: function(){\n\t\t\t\$('#cc-2-flower-image').removeClass('loading');\n  \t\t}\n});\n\n// Flower upload picture form.\n\$('#cc-2-environment-upload').ajaxForm({ \n\t\tasync: false,\n\t\tdataType:  'json', \n        beforeSubmit:   function(data, obj, options){\n         \tif (!jQuery('form#cc-2-environment-upload').valid()) {\n   \t\t\t\treturn false;\n   \t\t\t}\n        \t\$('#cc-2-environment-image').empty();\n        \t\$('#cc-2-environment-image').addClass('loading')\n\t       \tjQuery('form#cc-2-floral-station input[name=location_image\\:path]').val('');\n  \t\t},\n        success:   function(data){\n        \tif(data.success == true){\n\t        \t// There is only one file\n\t        \tjQuery('form#cc-2-floral-station input[name=location_image\\:path]').val(data.files[0].filename);\n\t        \tjQuery('#location_picture_camera_attr').val(data.files[0].EXIF_Camera_Make);\n\t        \tjQuery('#location_picture_datetime_attr').val(data.files[0].EXIF_DateTime);\n\t        \tinsertImage('med-'+data.files[0].filename, jQuery('#cc-2-environment-image'), " . $args['Environment_Image_Ratio'] . ");\n\t\t\t\tjQuery('#cc-2-environment-upload input[name=upload_file]').val('');\n\t\t\t} else\n\t\t\t\talertIndiciaError(data);\n        },\n  \t\tcomplete: function(){\n\t\t\t\$('#cc-2-environment-image').removeClass('loading');\n  \t\t}\n});\n\nfindID = function(name, data){\n\tfor(var i=0; i< data.length;i++){\n\t\tif(data[i].name == name) return i;\n\t}\n};\n\n\$('#cc-2-floral-station').ajaxForm({ \n\tasync: false,\n\tdataType:  'json', \n    beforeSubmit:   function(data, obj, options){\n\t\tvar valid = true;\n\t\tclearErrors('form#cc-2-floral-station');\n\t\tclearErrors('#cc-2-flower-identify');\n    \tif(jQuery('form#cc-2-floral-station > input[name=location_image\\:path]').val() == '' ||\n\t\t\t\t\tjQuery('form#cc-2-floral-station > input[name=occurrence_image\\:path]').val() == '' ){\n\t\t\tif(jQuery('form#cc-2-floral-station > input[name=occurrence_image\\:path]').val() == '')\n\t\t\t\tmyScrollTo('#cc-2-flower-upload');\n\t\t\telse\n\t\t\t\tmyScrollTo('#cc-2-environment-upload');\n\t\t\talert(\"" . lang::get('LANG_Must_Provide_Pictures') . "\");\n\t\t\tvalid = false;\n\t\t}\n\t\tif(jQuery('#imp-geom').val() == '') {\n\t\t\tmyScrollTo('.poll-map-container');\n\t\t\talert(\"" . lang::get('LANG_Must_Provide_Location') . "\");\n\t\t\tvalid = false;\n\t\t}\n\t\tif (!jQuery('form#cc-2-floral-station > input').valid()) { valid = false; }\n\t\tif (!validateRadio('occAttr\\:" . $args['flower_type_attr_id'] . "', 'form#cc-2-floral-station')) { valid = false; }\n\t\tif (!validateRadio('locAttr\\:" . $args['within50m_attr_id'] . "', 'form#cc-2-floral-station')) { valid = false; }\n\t\tif (!validateOptInt('locAttr\\:" . $args['distance_attr_id'] . "', 'form#cc-2-floral-station')) { valid = false; }\n\t\tdata[findID('location:centroid_sref', data)].value = jQuery('#imp-sref').val();\n\t\tdata[findID('location:centroid_geom', data)].value = jQuery('#imp-geom').val();\n\t\tif (jQuery('#id-flower-later').attr('checked') == ''){\n\t\t    var entries = jQuery('.flower-species-list-entry');\n\t\t    if (jQuery('#id-flower-unknown').attr('checked') == '' && entries.length == 0){\n\t\t      alert(\"" . lang::get('LANG_Must_Provide_Identification') . "\");\n\t\t      myScrollTo('#id-flower-later');\n\t\t      valid = false;\n            }\n\t\t    data[findID('determination:taxa_taxon_list_id', data)].value = '';\n\t\t\tdata[findID('determination:taxon_details', data)].value = jQuery('#cc-2-flower-identify [name=flower\\:taxon_details]').val();\n\t\t\tdata[findID('determination:taxon_extra_info', data)].value = jQuery('#cc-2-flower-identify [name=flower\\:taxon_extra_info]').val();\n\t\t\tdata[findID('determination:comment', data)].value = jQuery('[name=flower\\:comment]').val();\n\t\t\tdata[findID('determination:determination_type', data)].value = jQuery('#cc-2-flower-identify [name=flower\\:determination_type]').val();\n\t\t\tif (data[findID('determination:determination_type', data)].value == 'A'){\n\t\t\t  if(entries.length == 1)\n\t\t\t    data[findID('determination:taxa_taxon_list_id', data)].value = jQuery(entries[0]).find('input').val();\n\t\t\t  else\n\t\t\t    for(var i = 0; i< entries.length; i++){\n\t\t\t\t  data.push({name: 'determination\\:taxa_taxon_list_id_list[]', value: jQuery(entries[i]).find('input').val()});\n                }\n\t\t\t}\n\t\t} else { // ID later - remove determination entries from form.\n\t\t    data.splice(findID('determination:taxa_taxon_list_id', data),1);\n\t\t\tdata.splice(findID('determination:taxon_details', data),1);\n\t\t\tdata.splice(findID('determination:taxon_extra_info', data),1);\n\t\t\tdata.splice(findID('determination:comment', data),1);\n\t\t\tdata.splice(findID('determination:determination_type', data),1);\n\t\t\tdata.splice(findID('determination:cms_ref', data),1);\n\t\t\tdata.splice(findID('determination:email_address', data),1);\n\t\t\tdata.splice(findID('determination:person_name', data),1);\n\t\t\t// data.splice(12,8); \n\t\t}\n   \t\tif ( valid == false ) {\n\t\t\tmyScrollToError();\n\t\t\treturn false;\n\t\t};\n  \t\tjQuery('#cc-2-valid-button').addClass('loading-button');\n   \t\treturn true;\n\t},\n    success:   function(data){\n       \tif(data.success == 'multiple records' && data.outer_table == 'sample'){\n       \t\t// the sample and location ids are already fixed, so just need to populate the occurrence and image IDs, and rename the location and occurrence attribute.\n\t\t\t// ONLY 1 CHILD, THE OCCURRENCE: TBD ADD CHECK THAT IF ALREADY EXISTS THAT VALUES ARE THE SAME.\n\t\t\tjQuery('#cc-2-floral-station > input[name=occurrence\\:id]').removeAttr('disabled').val(data.struct.children[0].id);\n\t\t\t// the occurrence has whole range of children: attributes, image and determination.\n\t\t\tloadAttributes('#cc-2-floral-station', 'occurrence_attribute_value', 'occurrence_attribute_id', 'occurrence_id', data.struct.children[0].id, 'occAttr', false, true);\n\t\t\tfor(i=0; i<data.struct.children[0].children.length; i++){\n\t\t\t\tif(data.struct.children[0].children[i].model == 'occurrence_image'){\n\t\t\t\t\tjQuery('#cc-2-floral-station > input[name=occurrence_image\\:id]').removeAttr('disabled').val(data.struct.children[0].children[i].id);}\n\t\t\t\tif(data.struct.children[0].children[i].model == 'determination'){\n\t\t\t\t\tjQuery('#cc-2-floral-station > input[name=determination\\:id]').removeAttr('disabled').val(data.struct.children[0].children[i].id);}\n\t\t\t}\n\t\t\t// ONLY 1 PARENT, THE LOCATION: TBD ADD CHECK THAT IF ALREADY EXISTS THAT VALUES ARE THE SAME.\n\t\t    var location_id = jQuery('#cc-2-floral-station > input[name=location\\:id]').val();\n       \t\tloadAttributes('#cc-2-floral-station', 'location_attribute_value', 'location_attribute_id', 'location_id', location_id, 'locAttr', true, true);\n\t\t\tfor(i=0; i<data.struct.parents[0].children.length; i++){\n\t\t\t\tif(data.struct.parents[0].children[i].model == 'location_image'){\n\t\t\t\t\tjQuery('#cc-2-floral-station > input[name=location_image\\:id]').removeAttr('disabled').val(data.struct.parents[0].children[i].id);}}\n\t\t\tjQuery('#cc-2').foldPanel();\n\t\t\tif(showSessionsPanel) { jQuery('#cc-3').showPanel(); }\n\t\t\tshowSessionsPanel = true;\n        }  else {\n\t\t\tif(data.error){\n\t\t\t\tvar lastIndex = data.error.lastIndexOf('Validation error'); \n    \t\t\tif (lastIndex != -1 && lastIndex  == (data.error.length - 16)){ \n\t\t\t\t\tif(data.errors){\n\t\t\t\t\t\tif(data.errors['location:centroid_sref']){\n\t\t\t\t\t\t\tvar label = \$('<p/>')\n\t\t\t\t\t\t\t\t.addClass('inline-error')\n\t\t\t\t\t\t\t\t.html(\"" . lang::get('LANG_Invalid_Location') . "\");\n\t\t\t\t\t\t\tlabel.insertBefore('.latLongDiv:first');\n\t\t\t\t\t\t\tmyScrollToError();\n\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\talertIndiciaError(data);\n\t\t}\n\t},\n    complete: function (){\n  \t\tjQuery('.loading-button').removeClass('loading-button');\n  \t}\n});\n\n\$('#cc-2-valid-button').click(function() {\n\tjQuery('#cc-2-floral-station').submit();\n});\n\n";
        // Sessions.
        $r .= '
<div id="cc-3" class="poll-section">
  <div id="cc-3-title" class="ui-accordion-header ui-helper-reset ui-state-active ui-corner-all poll-section-title"><span id="cc-3-title-title" >' . lang::get('LANG_Sessions_Title') . '</span>
    <div id="cc-3-mod-button" class="right ui-state-default ui-corner-all mod-button">' . lang::get('LANG_Modify') . '</div>
  </div>
  <div id="cc-3-body" class="ui-accordion-content ui-helper-reset ui-widget-content ui-corner-top ui-accordion-content-active poll-section-body">
  </div>
  <div id="cc-3-footer" class="ui-accordion-content ui-helper-reset ui-widget-content ui-corner-bottom ui-accordion-content-active poll-section-footer">
	<div id="cc-3-add-button" class="ui-state-default ui-corner-all add-button">' . lang::get('LANG_Add_Session') . '</div>
    <div id="cc-3-valid-button" class="ui-state-default ui-corner-all save-button">' . lang::get('LANG_Validate_Session') . '</div>
  </div>
</div>
<div style="display:none" />
    <form id="cc-3-delete-session" action="' . iform_ajaxproxy_url($node, 'sample') . '" method="POST">
       <input type="hidden" name="website_id" value="' . $args['website_id'] . '" />
       <input type="hidden" name="sample:survey_id" value="' . $args['survey_id'] . '" />
       <input type="hidden" name="sample:id" value="" />
       <input type="hidden" name="sample:date" value="2010-01-01"/>
       <input type="hidden" name="sample:location_id" value="" />
       <input type="hidden" name="sample:deleted" value="t" />
    </form>
</div>';
        data_entry_helper::$javascript .= "\n\$('#cc-3-delete-session').ajaxForm({ \n\t\tasync: false,\n\t\tdataType:  'json', \n\t\tbeforeSubmit:   function(data, obj, options){\n\t\t\t// Warning this assumes that the data is fixed position:\n\t\t\tdata[4].value = jQuery('#cc-1-collection-details input[name=location\\:id]').val();\n\t\t\tif(data[2].value == '') return false;\n\t\t\t// double check that location id is filled in\n\t\t\tif(data[4].value == ''){\n\t\t\t\talertIndiciaError({error : \"" . lang::get('Internal Error 7: location id not set, so unsafe to delete session.') . "\"});\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\t// don't have to worry about parent_id\n\t\t\treturn true;\n  \t\t},\n        success:   function(data){\n        \tif(data.success != 'multiple records' || data.outer_table != 'sample')\n\t\t\t\talertIndiciaError(data);\n  \t\t}\n        ,complete: function (){\n  \t\t\tjQuery('.loading-button').removeClass('loading-button');\n  \t\t}\n});\npopulateSessionSelect = function(){\n\tvar insectSessionSelect = jQuery('form#cc-4-main-form > select[name=occurrence\\:sample_id]');\n\tvar value = insectSessionSelect.val();\n\tinsectSessionSelect.empty();\n\t// NB at this point the attributes have been loaded so have full name.\n\t\$('.poll-session-form').each(function(i){\n\t\tjQuery('<option value=\"'+\n\t\t\t\tjQuery(this).children('input[name=sample\\:id]').val()+\n\t\t\t\t'\">'+\n\t\t\t\tjQuery(this).children('input[name=dummy_date]').val()+\n\t\t\t\t' : '+\n\t\t\t\tjQuery(this).children('[name=smpAttr\\:" . $args['start_time_attr_id'] . "],[name^=smpAttr\\:" . $args['start_time_attr_id'] . "\\:]').val()+\n\t\t\t\t' > '+\n\t\t\t\tjQuery(this).children('[name=smpAttr\\:" . $args['end_time_attr_id'] . "],[name^=smpAttr\\:" . $args['end_time_attr_id'] . "\\:]').val()+\n\t\t\t\t'</option>')\n\t\t\t.appendTo(insectSessionSelect);\n\t});\n\tinsectSessionSelect.find('option').each(function(i,obj){\n  \t\tif(i == 0 || jQuery(obj).val() == value)\n\t\t\tinsectSessionSelect.val(insectSessionSelect.find('option').filter(':first').val());\n  \t});\n}\ncompareTimes = function(nameStart, nameEnd, formSel){\n    var controlStart = jQuery(formSel).find('[name='+nameStart+'],[name^='+nameStart+'\\:]');\n    var controlEnd = jQuery(formSel).find('[name='+nameEnd+'],[name^='+nameEnd+'\\:]');\n    var valueStart = controlStart.val().split(':');\n    var valueEnd = controlEnd.val().split(':');\n    var minsDiff = (valueEnd[0]-valueStart[0])*60+(valueEnd[1]-valueStart[1]);\n    if(minsDiff < 0){\n        \$('<p/>').attr({'for': nameEnd}).addClass('inline-error').html(\"" . lang::get('validation_endtime_before_start') . "\").insertBefore(controlEnd);\n\t\treturn false;\n    }\n    // The Flash selection is first, Long second for the protocol: So\n    var isFlashProtocol = jQuery('[name=smpAttr\\:" . $args['protocol_attr_id'] . "],[name^=smpAttr\\:" . $args['protocol_attr_id'] . "\\:]').filter(':first').filter('[checked]').length >0;\n    if(!isFlashProtocol && minsDiff < 20){ // Long Protocol, session must not be less than 20mins\n        \$('<p/>').attr({'for': nameStart}).addClass('inline-error').html(\"" . lang::get('validation_time_less_than_20') . "\").insertBefore(controlStart);\n        \$('<p/>').attr({'for': nameEnd}).addClass('inline-error').html(\"" . lang::get('validation_please_check') . "\").insertBefore(controlEnd);\n\t\treturn false;\n    }\n    if(isFlashProtocol && minsDiff != 20){ // Flash Protocol, session must be exactly 20mins\n        \$('<p/>').attr({'for': nameStart}).addClass('inline-error').html(\"" . lang::get('validation_time_not_20') . "\").insertBefore(controlStart);\n        \$('<p/>').attr({'for': nameEnd}).addClass('inline-error').html(\"" . lang::get('validation_please_check') . "\").insertBefore(controlEnd);\n\t\treturn false;\n    }\n    return true;\n}\nconvertDate = function(dateStr){\n\t// Converts a YYYY-MM-DD date to YYYY/MM/DD so IE can handle it.\n\treturn dateStr.slice(0,4)+'/'+dateStr.slice(5,7)+'/'+dateStr.slice(8,10);\n} \n\ncheckDate = function(name, formSel){\n  var control = jQuery(formSel).find('[name='+name+']');\n  var session = this;\n  var dateError = false;\n  var d2 = new Date(convertDate(control.val()));\n  var two_days=1000*60*61*(24+25); // allows a bit of leaway, plus extra hour for Day light saving transition. (milliSeconds)\n  jQuery('.required').filter('[name=sample:date]').each(function(){\n    var d1 = new Date(convertDate(jQuery(this).val()));\n    if(Math.abs(d1.getTime()-d2.getTime()) > two_days){\n      dateError=true;\n    }\n  });\n  if(dateError){\n    \$('<p/>').attr({'for': name}).addClass('inline-error').html(\"" . lang::get('validation_session_date_error') . "\").insertBefore(control);\n    return false;\n  };\n  return true;\n}\n\nvalidateAndSubmitOpenSessions = function(){\n\tvar valid = true;\n\t// only check the visible forms as rest have already been validated successfully.\n\t\$('.poll-session-form:visible').each(function(i){\n\t\tclearErrors(this);\n   \t\tif (valid && !checkDate('sample\\:date', this)) { valid = false; }\n\t\tif (!jQuery(this).children('input').valid()) { valid = false; }\n\t    if (!validateTime('smpAttr\\:" . $args['start_time_attr_id'] . "', this)) { valid = false; }\n   \t\tif (!validateTime('smpAttr\\:" . $args['end_time_attr_id'] . "', this)) { valid = false; }\n   \t\tif (valid && !compareTimes('smpAttr\\:" . $args['start_time_attr_id'] . "', 'smpAttr\\:" . $args['end_time_attr_id'] . "', this)) { valid = false; }\n   \t\tif (!validateRadio('smpAttr\\:" . $args['sky_state_attr_id'] . "', this)) { valid = false; }\n   \t\tif (!validateRadio('smpAttr\\:" . $args['temperature_attr_id'] . "', this)) { valid = false; }\n   \t\tif (!validateRadio('smpAttr\\:" . $args['wind_attr_id'] . "', this)) { valid = false; }\n   \t\tif (!validateRadio('smpAttr\\:" . $args['shade_attr_id'] . "', this)) { valid = false; }\n   });\n\tif(valid == false) {\n\t\tmyScrollToError();\n\t\treturn false;\n\t};\n\t\$('.poll-session-form:visible').submit();\n\treturn true;\n}\n\naddSession = function(){\n\tsessionCounter = sessionCounter + 1;\n\t// dynamically build the contents of the session block.\n\tvar newSession = jQuery('<div id=\"cc-3-session-'+sessionCounter+'\" class=\"poll-session\"/>')\n\t\t.appendTo('#cc-3-body');\n\tvar newTitle = jQuery('<div class=\"poll-session-title\">" . lang::get('LANG_Session') . " '+sessionCounter+'</div>')\n\t\t.appendTo(newSession);\n\tvar newModButton = jQuery('<div class=\"right ui-state-default ui-corner-all mod-button\">" . lang::get('LANG_Modify') . "</div>')\n\t\t.appendTo(newTitle).hide();\n\tvar newDeleteButton = jQuery('<div class=\"right ui-state-default ui-corner-all delete-button\">" . lang::get('LANG_Delete_Session') . "</div>')\n\t\t.appendTo(newTitle);\t\n\tnewModButton.click(function() {\n\t\tif(!validateAndSubmitOpenSessions()) return false;\n\t\tvar session=\$(this).parents('.poll-session');\n\t\tsession.show();\n\t\tsession.children().show();\n\t\tsession.children(':first').children(':first').hide(); // this is the mod button itself\n    });\n    var formContainer = jQuery('<div />').appendTo(newSession);\n    var newForm = jQuery('<form action=\"" . iform_ajaxproxy_url($node, 'sample') . "\" method=\"POST\" class=\"poll-session-form\" />').appendTo(formContainer);\n\tjQuery('<input type=\"hidden\" name=\"website_id\" value=\"" . $args['website_id'] . "\" />').appendTo(newForm);\n\tjQuery('<input type=\"hidden\" name=\"sample:survey_id\" value=\"" . $args['survey_id'] . "\" />').appendTo(newForm);\n\tjQuery('<input type=\"hidden\" name=\"sample:parent_id\" />').appendTo(newForm).val(jQuery('#cc-1-collection-details > input[name=sample\\:id]').val());\n\tjQuery('<input type=\"hidden\" name=\"sample:location_id\" />').appendTo(newForm).val(jQuery('#cc-1-collection-details > input[name=location\\:id]').val());\n\tjQuery('<input type=\"hidden\" name=\"sample:id\" value=\"\" disabled=\"disabled\" />').appendTo(newForm);\n";
        if ($use_help) {
            data_entry_helper::$javascript .= "\n\tvar helpDiv = jQuery('<div class=\"right ui-state-default ui-corner-all help-button\">" . lang::get('LANG_Help_Button') . "</div>');\n\thelpDiv.click(function(){\n\t\t" . $args['help_function'] . "(" . $args['help_session_arg'] . ");\n\t});\n\thelpDiv.appendTo(newForm);";
        }
        // we have to be careful with the dates: Indicia supplies dates as YYYY-MM-DD, but this is not ready understood by the IE JS Date, which is OK with YYYY/MM/DD.
        // We keep the YYYY-MM-DD internally for consistency.
        data_entry_helper::$javascript .= "\n\tvar dateID = 'cc-3-session-date-'+sessionCounter;\n\tvar dateAttr = '<label for=\"'+dateID+'\">" . lang::get('LANG_Date') . " :</label><input type=\"text\" size=\"10\" class=\"vague-date-picker required\" id=\"'+dateID+'\" name=\"dummy_date\" value=\"" . lang::get('click here') . "\" /> ';\n\tdateAttr = dateAttr + '<input type=\"hidden\" id=\"real-'+dateID+'\" name=\"sample:date\" value=\"\" class=\"required\"/> ';\n    jQuery(dateAttr).appendTo(newForm);\n\tjQuery('#'+dateID).datepicker({\n\t\tdateFormat : 'dd/mm/yy',\n\t\tconstrainInput: false,\n\t\tmaxDate: '0',\n\t\taltField : '#real-'+dateID,\n\t\taltFormat : 'yy-mm-dd'\n\t});\n    jQuery('" . str_replace("\n", "", data_entry_helper::outputAttribute($sample_attributes[$args['start_time_attr_id']], $defAttrOptions)) . "').appendTo(newForm);\n\tjQuery('" . str_replace("\n", "", data_entry_helper::outputAttribute($sample_attributes[$args['end_time_attr_id']], $defAttrOptions)) . "').appendTo(newForm);\n\tjQuery('" . str_replace("\n", "", data_entry_helper::outputAttribute($sample_attributes[$args['sky_state_attr_id']], $defNRAttrOptions)) . "').appendTo(newForm);\n\tjQuery('" . str_replace("\n", "", data_entry_helper::outputAttribute($sample_attributes[$args['temperature_attr_id']], $defNRAttrOptions)) . "').appendTo(newForm);\n\tjQuery('" . str_replace("\n", "", data_entry_helper::outputAttribute($sample_attributes[$args['wind_attr_id']], $defNRAttrOptions)) . "').appendTo(newForm);\n\tjQuery('" . str_replace("\n", "", data_entry_helper::outputAttribute($sample_attributes[$args['shade_attr_id']], array_merge($defNRAttrOptions, array('default' => '-1')))) . "').appendTo(newForm);\n\tnewDeleteButton.click(function() {\n\t\tvar container = \$(this).parent().parent();\n\t\tjQuery('#cc-3-delete-session').find('[name=sample\\:id]').val(container.find('[name=sample\\:id]').val());\n\t\tjQuery('#cc-3-delete-session').find('[name=sample\\:date]').val(container.find('[name=sample\\:date]').val());\n\t\tjQuery('#cc-3-delete-session').find('[name=sample\\:location_id]').val(container.find('[name=sample\\:location_id]').val());\n\t\tif(container.find('[name=sample\\:id]').filter('[disabled]').length == 0){\n\t\t\tjQuery(this).addClass('loading-button');\n\t\t\t\$.getJSON(\"" . $svcUrl . "/data/occurrence/\" +\n\t\t\t\t\t\"?mode=json&view=detail&reset_timeout=true&nonce=" . $readAuth['nonce'] . "&auth_token=" . $readAuth['auth_token'] . "\" +\n\t\t\t\t\t\"&sample_id=\"+container.find('[name=sample\\:id]').val()+\"&deleted=f&callback=?\", function(insectData) {\n\t\t\t\tif(!(insectData instanceof Array)){\n   \t\t\t\t\talertIndiciaError(insectData);\n   \t\t\t\t} else if (insectData.length>0) {\n\t\t\t\t\tjQuery('.loading-button').removeClass('loading-button');\n\t\t\t\t\talert(\"" . lang::get('LANG_Cant_Delete_Session') . "\");\n\t\t\t\t} else if(confirm(\"" . lang::get('LANG_Confirm_Session_Delete') . "\")){\n\t\t\t\t\tjQuery('#cc-3-delete-session').submit();\n\t\t\t\t\tcontainer.remove();\n\t\t\t\t\tcheckSessionButtons();\n\t\t\t\t}\n\t\t\t});\n\t\t} else if(confirm(\"" . lang::get('LANG_Confirm_Session_Delete') . "\")){\n\t\t\tcontainer.remove();\n\t\t\tcheckSessionButtons();\n\t\t}\n    });\n    newForm.ajaxForm({\n   \t\tasync: false,\n    \tdataType:  'json',\n    \tbeforeSubmit:   function(data, obj, options){\n\t\t\t// double check that location id and sample id are filled in\n\t\t\tif(jQuery('#cc-1-collection-details input[name=location\\:id]').val() == ''){\n\t\t\t\talertIndiciaError({error : \"" . lang::get('Internal Error 8: location id not set, so unsafe to save session.') . "\"});\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\tif(jQuery('#cc-1-collection-details input[name=sample\\:id]').val() == ''){\n\t\t\t\talertIndiciaError({error : \"" . lang::get('Internal Error 9: sample id not set, so unsafe to save session.') . "\"});\n\t\t\t\treturn false;\n\t\t\t}\n\t    \tvar valid = true;\n    \t\tclearErrors(obj);\n    \t\tif (!obj.find('input').valid()) {\n    \t\t\tvalid = false; }\n    \t\tif (!validateRadio('smpAttr\\:" . $args['sky_state_attr_id'] . "', obj)) { valid = false; }\n   \t\t\tif (!validateRadio('smpAttr\\:" . $args['temperature_attr_id'] . "', obj)) { valid = false; }\n   \t\t\tif (!validateRadio('smpAttr\\:" . $args['wind_attr_id'] . "', obj)) { valid = false; }\n   \t\t\tif (!validateRadio('smpAttr\\:" . $args['shade_attr_id'] . "', obj)) { valid = false; }\n   \t\t\tdata[2].value = jQuery('#cc-1-collection-details > input[name=sample\\:id]').val();\n\t\t\tdata[3].value = jQuery('#cc-1-collection-details > input[name=location\\:id]').val();\n\t\t\tjQuery('#cc-3-valid-button').addClass('loading-button');\n\t\t\tif(!valid) myScrollToError();\n\t\t\treturn valid;\n\t\t},\n   \t    success:   function(data, status, form){\n   \t    \tvar thisSession = form.parents('.poll-session');\n    \t\tif(data.success == 'multiple records' && data.outer_table == 'sample'){\n   \t    \t    form.children('input[name=sample\\:id]').removeAttr('disabled').val(data.outer_id);\n   \t    \t    loadAttributes(form, 'sample_attribute_value', 'sample_attribute_id', 'sample_id', data.outer_id, 'smpAttr', true, true);\n\t\t\t\tthisSession.show();\n\t\t\t\tthisSession.children(':first').show().find('*').show();\n\t\t\t\tthisSession.children().not(':first').hide();\n  \t\t\t} else \n\t        \talertIndiciaError(data);\n  \t\t},\n        complete: function (){\n  \t\t\tjQuery('.loading-button').removeClass('loading-button');\n  \t\t}\n\t});\n\tnewSession.find('.deh-required').remove();\n    return(newSession);\n};\n\nvalidateSessionsPanel = function(){\n\tif(jQuery('#cc-3:visible').length == 0) return true; // panel is not visible so no data to fail validation.\n\tif(jQuery('#cc-3').find('.poll-section-body:visible').length == 0) return true; // body hidden so data already been validated successfully.\n\tvar openSession = jQuery('.poll-session-form:visible');\n\tif(openSession.length > 0){\n\t\tif(jQuery('input[name=sample\\:id]', openSession).val() == '' &&\n\t\t\t\tjQuery('input[name=sample\\:date]', openSession).val() == '' &&\n\t\t\t\tjQuery('[name=smpAttr\\:" . $args['start_time_attr_id'] . "],[name^=smpAttr\\:" . $args['start_time_attr_id'] . "\\:]', openSession).val() == '' &&\n\t\t\t\tjQuery('[name=smpAttr\\:" . $args['end_time_attr_id'] . "],[name^=smpAttr\\:" . $args['end_time_attr_id'] . "\\:]', openSession).val() == '' &&\n\t\t\t\tjQuery('[name=smpAttr\\:" . $args['sky_state_attr_id'] . "],[name^=smpAttr\\:" . $args['sky_state_attr_id'] . "\\:]', openSession).filter('[checked]').length == 0 &&\n    \t\t\tjQuery('[name=smpAttr\\:" . $args['temperature_attr_id'] . "],[name^=smpAttr\\:" . $args['temperature_attr_id'] . "\\:]', openSession).filter('[checked]').length == 0 &&\n    \t\t\tjQuery('[name=smpAttr\\:" . $args['wind_attr_id'] . "],[name^=smpAttr\\:" . $args['wind_attr_id'] . "\\:]', openSession).filter('[checked]').length == 0 &&\n    \t\t\tjQuery('[name=smpAttr\\:" . $args['shade_attr_id'] . "],[name^=smpAttr\\:" . $args['shade_attr_id'] . "\\:]', openSession).filter('[checked]').length == 0) {\n    \t\tjQuery('#cc-3').foldPanel();\n\t\t\treturn true;\n\t\t}\n\t}\n\t// not putting in an empty data set check here - user can delete the session if needed, and there must be at least one.\n\tif(!validateAndSubmitOpenSessions()) return false;\n\tjQuery('#cc-3').foldPanel();\n\tpopulateSessionSelect();\n\treturn true;\n};\njQuery('#cc-3-valid-button').click(function(){\n\tif(!validateAndSubmitOpenSessions()) return;\n\tjQuery('#cc-3').foldPanel();\n\tjQuery('#cc-4').showPanel();\n\tpopulateSessionSelect();\n});\njQuery('#cc-3-add-button').click(function(){\n\tif(!validateAndSubmitOpenSessions()) return;\n\taddSession();\n\tcheckSessionButtons();\n});\n\njQuery('.mod-button').click(function() {\n\t// first close all the other panels, ensuring any data is saved.\n\tif(!validateCollectionPanel() || !validateStationPanel() || !validateSessionsPanel() || !validateInsectPanel())\n\t\treturn;\n\tjQuery('#cc-5').hidePanel();\n\tjQuery(this).parents('.poll-section-title').parent().unFoldPanel(); //slightly complicated because cc-1 contains the rest.\n});\n\n";
        $extraParams = $readAuth + array('taxon_list_id' => $args['insect_list_id'], 'view' => 'detail', 'orderby' => 'taxonomic_sort_order', 'allow_data_entry' => 't');
        $species_ctrl_args = array('label' => lang::get('LANG_Insect_Species'), 'fieldname' => 'insect:taxa_taxon_list_id', 'table' => 'taxa_taxon_list', 'captionField' => 'taxon', 'listCaptionSpecialChars' => true, 'valueField' => 'id', 'columns' => 2, 'blankText' => lang::get('LANG_Choose_Taxon'), 'extraParams' => $extraParams);
        $checkOptions['labelClass'] = 'checkbox-label';
        $r .= '
<div id="cc-4" class="poll-section">
  <div id="cc-4-title" class="ui-accordion-header ui-helper-reset ui-state-active ui-corner-all poll-section-title">' . lang::get('LANG_Photos') . '
    <div id="cc-4-mod-button" class="right ui-state-default ui-corner-all mod-button">' . lang::get('LANG_Modify') . '</div>
  </div>
  <div id="cc-4-photo-reel" class="ui-accordion-content ui-helper-reset ui-widget-content ui-corner-top ui-accordion-content-active photoReelContainer" >
    <div class="photo-blurb">' . lang::get('LANG_Photo_Blurb') . '</div>
    <div class="blankPhoto thumb currentPhoto"></div>
  </div>
  <div id="cc-4-body" class="ui-accordion-content ui-helper-reset ui-widget-content ui-accordion-content-active poll-section-body">  
    <div id="cc-4-insect">
      <div id="cc-4-insect-title">' . lang::get('LANG_Upload_Insect') . '</div>
      <form id="cc-4-insect-upload" enctype="multipart/form-data" action="' . iform_ajaxproxy_url($node, 'media') . '" method="POST">
    	<input type="hidden" id="website_id" name="website_id" value="' . $args['website_id'] . '" />
    	<input name="upload_file" type="file" class="required" />
        <input type="submit" value="' . lang::get('LANG_Upload') . '" class="btn-submit" />
 	    <div id="cc-4-insect-image" class="poll-image"></div>
      </form>
      <div id="cc-4-insect-identify" class="poll-dummy-form">
 	    <div class="id-tool-group">
          ' . iform_pollenators::help_button($use_help, "insect-help-button", $args['help_function'], $args['help_insect_arg']) . '
          <p><strong>' . lang::get('LANG_Identify_Insect') . '</strong></p>
          <input type="hidden" id="insect:taxon_details" name="insect:taxon_details" />
          <input type="hidden" name="insect:determination_type" value="A" />  
		  <label for="insect-id-button">' . lang::get('LANG_Insect_ID_Key_label') . ' :</label><span id="insect-id-button" class="ui-state-default ui-corner-all poll-id-button" >' . lang::get('LANG_Launch_ID_Key') . '</span>
		  <span id="insect-id-cancel" class="ui-state-default ui-corner-all poll-id-cancel" >' . lang::get('LANG_Cancel_ID') . '</span>
		  <p id="insect_taxa_list"></p> 
 	    </div>
 	    <div class="id-later-group">
 	      <label for="id-insect-later" class="follow-on">' . lang::get('LANG_ID_Insect_Later') . ' </label><input type="checkbox" id="id-insect-later" name="id-insect-later" />
 	    </div>
 	    <div class="id-specified-group">
 	      ' . data_entry_helper::select($species_ctrl_args) . '
          <label for="insect:taxon_extra_info" class="follow-on">' . lang::get('LANG_ID_More_Precise') . ' </label> 
    	  <input type="text" id="insect:taxon_extra_info" name="insect:taxon_extra_info" class="taxon-info" />
        </div>
      </div>
 	  <div class="id-comment">
        <label for="insect:comment" >' . lang::get('LANG_ID_Comment') . ' </label>
        <textarea id="insect:comment" name="insect:comment" class="taxon-comment" rows="3" ></textarea>
      </div>
    </div>
    <div class="poll-break"></div> 
 	<form id="cc-4-main-form" action="' . iform_ajaxproxy_url($node, 'occurrence') . '" method="POST" >
    	<input type="hidden" id="website_id" name="website_id" value="' . $args['website_id'] . '" />
    	<input type="hidden" id="occurrence_image:path" name="occurrence_image:path" value="" />
    	<input type="hidden" id="occurrence:record_status" name="occurrence:record_status" value="C" />
        <input type="hidden" name="occurrence:use_determination" value="Y"/>    
        <input type="hidden" name="determination:taxa_taxon_list_id" value=""/> 
        <input type="hidden" name="determination:taxon_details" value=""/>  	
        <input type="hidden" name="determination:taxon_extra_info" value=""/>  	
        <input type="hidden" name="determination:comment" value=""/>  	
    	<input type="hidden" name="determination:determination_type" value="A" /> 
        <input type="hidden" name="determination:cms_ref" value="' . $uid . '" />
    	<input type="hidden" name="determination:email_address" value="' . $email . '" />
    	<input type="hidden" name="determination:person_name" value="' . $username . '" /> 
    	<input type="hidden" id="occurrence:id" name="occurrence:id" value="" disabled="disabled" />
	    <input type="hidden" id="determination:id" name="determination:id" value="" disabled="disabled" />
	    <input type="hidden" id="occurrence_image:id" name="occurrence_image:id" value="" disabled="disabled" />
        <input type="hidden" id="insect_picture_camera_attr" name="occAttr:' . $args['occurrence_picture_camera_attr_id'] . '" value="" />
        <input type="hidden" id="insect_picture_datetime_attr" name="occAttr:' . $args['occurrence_picture_datetime_attr_id'] . '" value="" />
	    <label for="occurrence:sample_id">' . lang::get('LANG_Session') . ' :</label>
	    <select id="occurrence:sample_id" name="occurrence:sample_id" value="" class="required" /></select>
	    ' . data_entry_helper::textarea(array('label' => lang::get('LANG_Comment'), 'fieldname' => 'occurrence:comment')) . str_replace("\n", "", data_entry_helper::outputAttribute($occurrence_attributes[$args['number_attr_id']], $defNRAttrOptions)) . str_replace("\n", "", data_entry_helper::outputAttribute($occurrence_attributes[$args['foraging_attr_id']], $checkOptions)) . '
	<div id="Foraging_Confirm"><label>' . lang::get('Foraging_Confirm') . '</label><div class="control-box "><nobr><span><input type="radio" name="dummy_foraging_confirm" value="0" checked="checked"  /><label>' . lang::get('No') . '</label></span></nobr> &nbsp; <nobr><span><input type="radio" name="dummy_foraging_confirm" value="1" /><label>' . lang::get('Yes') . '</label></span></nobr></div></div></form><br />
    <div class="button-container">
      <span id="cc-4-valid-insect-button" class="ui-state-default ui-corner-all save-button">' . lang::get('LANG_Validate_Insect') . '</span>
      <span id="cc-4-delete-insect-button" class="ui-state-default ui-corner-all delete-button">' . lang::get('LANG_Delete_Insect') . '</span>
    </div>
  </div>
  <div id="cc-4-footer" class="ui-accordion-content ui-helper-reset ui-widget-content ui-corner-bottom ui-accordion-content-active poll-section-footer">
    <div id="cc-4-valid-photo-button" class="ui-state-default ui-corner-all save-button">' . lang::get('LANG_Validate_Photos') . '</div>
  </div>
</div>
<div style="display:none" />
    <form id="cc-4-delete-insect" action="' . iform_ajaxproxy_url($node, 'occurrence') . '" method="POST">
       <input type="hidden" name="website_id" value="' . $args['website_id'] . '" />
       <input type="hidden" name="occurrence:use_determination" value="Y"/>    
       <input type="hidden" name="occurrence:id" value="" />
       <input type="hidden" name="occurrence:sample_id" value="" />
       <input type="hidden" name="occurrence:deleted" value="t" />
    </form>
</div>';
        data_entry_helper::$javascript .= "\njQuery('#Foraging_Confirm').hide();\njQuery('[name=occAttr\\:" . $args['foraging_attr_id'] . "],[name^=occAttr\\:" . $args['foraging_attr_id'] . ":]').change(function(){\n\tjQuery('[name=dummy_foraging_confirm]').filter('[value=0]').attr('checked',true);\n\tcheckForagingStatus(false);\n});\n\ninsectIDstruc = {\n\ttype: 'insect',\n\tselector: '#cc-4-insect-identify',\n\tmainForm: '#cc-4-main-form',\n\tuseKey: true,\n\tstoredTaxaList: [],\n\ttimeOutTimer: null,\n\tpollTimer: null,\n\tsessionID: '',\n\tinvokeURL: '" . $args['ID_tool_insect_url'] . "',\n\tpollURL: '" . str_replace("{HOST}", $_SERVER['HTTP_HOST'], $args['ID_tool_insect_poll_dir']) . "',\n\tname: 'insectIDstruc',\n\ttaxaList: insectTaxa\n};\n\njQuery('#insect-id-button').click(function(){\n\tidButtonPressed(insectIDstruc);\n});\n\njQuery('#insect-id-cancel').click(function(){\n\tpollReset(insectIDstruc);\n});\njQuery('#insect-id-cancel').hide();\n\njQuery('#cc-4-insect-identify select[name=insect\\:taxa_taxon_list_id]').change(function(){\n\tpollReset(insectIDstruc);\n\ttaxonChosen(insectIDstruc);\n});\njQuery('#id-insect-later').change(function (){\n\tpollReset(insectIDstruc);\n\tidLater(insectIDstruc);\n});\n\n// Insect upload picture form.\n\$('#cc-4-insect-upload').ajaxForm({ \n\t\tasync: false,\n\t\tdataType:  'json', \n        beforeSubmit:   function(data, obj, options){\n        \tif(jQuery('#cc-4-insect-upload input[name=upload_file]').val() == '')\n        \t\treturn false;\n        \t\$('#cc-4-insect-image').empty();\n        \t\$('#cc-4-insect-image').addClass('loading');\n        \tjQuery('form#cc-4-main-form input[name=occurrence_image\\:path]').val('');\n        },\n        success:   function(data){\n        \tif(data.success == true){\n\t        \t// There is only one file\n\t        \tjQuery('form#cc-4-main-form input[name=occurrence_image\\:path]').val(data.files[0].filename);\n\t        \tjQuery('#insect_picture_camera_attr').val(data.files[0].EXIF_Camera_Make);\n\t        \tjQuery('#insect_picture_datetime_attr').val(data.files[0].EXIF_DateTime);\n\t        \tinsertImage('med-'+data.files[0].filename, jQuery('#cc-4-insect-image'), " . $args['Insect_Image_Ratio'] . ");\n\t\t\t\tjQuery('#cc-4-insect-upload input[name=upload_file]').val('');\n\t\t\t}  else\n\t\t\t\talertIndiciaError(data);\n  \t\t},\n  \t\tcomplete: function(){\n\t\t\t\$('#cc-4-insect-image').removeClass('loading');\n  \t\t}\n});\n\n\$('#cc-4-main-form').ajaxForm({ \n\tasync: false,\n\tdataType:  'json', \n    beforeSubmit:   function(data, obj, options){\n    \tvar valid = true;\n    \tclearErrors('form#cc-4-main-form');\n    \tclearErrors('#cc-4-insect-identify');\n    \tif (!jQuery('form#cc-4-main-form > input').valid()) { valid = false; }\n\t\tif (!validateRequiredField('occurrence\\:sample_id', 'form#cc-4-main-form')) { valid = false; }\n\t\tif (!validateRadio('occAttr\\:" . $args['number_attr_id'] . "', obj)) { valid = false; }\n    \tif(data[1].value == '' ){\n    \t\tmyScrollTo('#cc-4-insect-upload');\n\t\t\talert(\"" . lang::get('LANG_Must_Provide_Insect_Picture') . "\");\n\t\t\tvalid = false;\n\t\t}\n\t\tif (jQuery('#id-insect-later').attr('checked') == ''){\n\t\t\tprepPhotoReelForNew(false, jQuery('#cc-4-main-form').find('[name=occurrence\\:id]').val());\n\t\t\tdata[findID('determination:taxa_taxon_list_id', data)].value = jQuery('#cc-4-insect-identify select[name=insect\\:taxa_taxon_list_id]').val();\n\t\t\tdata[findID('determination:taxon_details', data)].value = jQuery('#cc-4-insect-identify [name=insect\\:taxon_details]').val();\n\t\t\tdata[findID('determination:taxon_extra_info', data)].value = jQuery('#cc-4-insect-identify [name=insect\\:taxon_extra_info]').val();\n\t\t\tdata[findID('determination:comment', data)].value = jQuery('[name=insect\\:comment]').val();\n\t\t\tdata[findID('determination:determination_type', data)].value = jQuery('#cc-4-insect-identify [name=insect\\:determination_type]').val();\n\t\t\tif (jQuery('#cc-4-insect-identify [name=insect\\:taxon_details]').val() == ''){\n\t\t\t\tif (!validateRequiredField('insect\\:taxa_taxon_list_id', '#cc-4-insect-identify')) {\n\t\t\t\t\tvalid = false;\n  \t\t\t\t} else {\n\t\t\t\t\tdata.push({name: 'determination:taxa_taxon_list_id_list[]', value: ''});\n  \t\t\t\t}\n\t\t\t} else {\n\t\t\t\tvar toolValues = insectIDstruc.storedTaxaList;\n\t\t\t\tfor(var i = 0; i<toolValues.length; i++){\n\t\t\t\t\tdata.push({name: 'determination:taxa_taxon_list_id_list[]', value: toolValues[i]});\n\t\t\t\t}\t\t\t\n\t\t\t}\n\t\t} else {\n\t\t\tprepPhotoReelForNew(true, jQuery('#cc-4-main-form').find('[name=occurrence\\:id]').val());\n\t\t\tdata.splice(4,8); // remove determination entries: TODO expand to be explicit - see flowers\n\t\t}\n   \t\tif ( valid == false ) {\n\t\t\tmyScrollToError();\n\t\t\treturn false;\n\t\t};\n\t\tjQuery('#cc-4-valid-insect-button').addClass('loading-button');\n\t\treturn true;\n\t},\n    success:   function(data){\n       \tif(data.success == 'multiple records' && data.outer_table == 'occurrence'){\n       \t\taddNewToPhotoReel(data.outer_id);\n\t\t\twindow.scroll(0,0);\n        } else\n\t\t\talertIndiciaError(data);\n\t},\n    complete: function (){\n  \t\tjQuery('.loading-button').removeClass('loading-button');\n  \t}\n});\n\nvalidateInsectPanel = function(){\n\tif(jQuery('#cc-4:visible').length == 0) return true; // panel is not visible so no data to fail validation.\n\tif(jQuery('#cc-4-body:visible').length == 0) return true; // body hidden so data already been validated successfully.\n\tif(!validateInsect()){ return false; }\n\tclearInsect();\n  \tjQuery('#cc-4').foldPanel();\n\treturn true;\n};\n\nclearInsect = function(){\n\tjQuery('#cc-4-main-form').resetForm();\n\tinsectIDstruc.storedTaxaList = [];\n\tjQuery('#insect_taxa_list').empty();\n\tjQuery('[name=insect\\:taxa_taxon_list_id],[name=insect\\:taxon_extra_info],[name=insect\\:comment],[name=insect\\:taxon_details]').val('');\n    jQuery('[name=insect\\:determination_type]').val('A'); \n\tjQuery('#id-insect-later').removeAttr('checked').removeAttr('disabled');\n    jQuery('#cc-4-main-form').find('[name=determination\\:cms_ref]').val('" . $uid . "');\n    jQuery('#cc-4-main-form').find('[name=determination\\:email_address]').val('" . $email . "');\n    jQuery('#cc-4-main-form').find('[name=determination\\:person_name]').val('" . $username . "'); \n    jQuery('#cc-4-main-form').find('[name=determination\\:determination_type]').val('A'); \n    jQuery('#cc-4-main-form').find('[name=occurrence_image\\:path]').val('');\n\tjQuery('#cc-4-main-form').find('[name=occurrence\\:id],[name=occurrence_image\\:id],[name=determination\\:id]').val('').attr('disabled', 'disabled');\n\t// First rename, to be safe. Then add [] to multiple choice checkboxes.\n\tjQuery('#cc-4-main-form').find('[name^=occAttr\\:]').each(function(){\n\t\tvar name = jQuery(this).attr('name').split(':');\n\t\tif(name[1].indexOf('[]') > 0) name[1] = name[1].substr(0, name[1].indexOf('[]'));\n\t\tjQuery(this).attr('name', 'occAttr:'+name[1]);\n\t});\n\tjQuery('#cc-4-main-form').find('[name^=occAttr\\:]').filter(':checkbox').removeAttr('checked').each(function(){\n\t\tvar myName = jQuery(this).attr('name').split(':');\n\t\tvar similar = jQuery('[name=occAttr\\:'+name[1]+'],[name=occAttr\\:'+name[1]+'\\[\\]]').filter(':checkbox');\n\t\tif(similar.length > 1) jQuery(this).attr('name', 'occAttr:'+name[1]+'[]');\n\t});\n    jQuery('#cc-4-insect-image').empty();\n    populateSessionSelect();\n    jQuery('#Foraging_Confirm').hide();\n    jQuery('[name=dummy_foraging_confirm]').filter('[value=0]').attr('checked',true);\n    jQuery('#cc-4').find('.inline-error').remove();\n\tjQuery('.currentPhoto').removeClass('currentPhoto');\n\tjQuery('.blankPhoto').addClass('currentPhoto');\n};\n\nloadInsect = function(id){\n\tclearInsect();\n\tjQuery('form#cc-4-main-form > input[name=occurrence\\:id]').removeAttr('disabled').val(id);\n\tloadAttributes('form#cc-4-main-form', 'occurrence_attribute_value', 'occurrence_attribute_id', 'occurrence_id', id, 'occAttr', true, true);\n\tloadImage('occurrence_image', 'occurrence_id', 'occurrence\\:id', id, '#cc-4-insect-image', " . $args['Insect_Image_Ratio'] . ", true);\n\t\$.getJSON(\"" . $svcUrl . "/data/occurrence/\" + id +\n          \"?mode=json&view=detail&nonce=" . $readAuth['nonce'] . "&auth_token=" . $readAuth['auth_token'] . "&callback=?\", function(data) {\n\t    if(!(data instanceof Array)){\n   \t\t\talertIndiciaError(data);\n   \t\t} else if (data.length>0) {\n\t        jQuery('form#cc-4-main-form > [name=occurrence\\:sample_id]').val(data[0].sample_id);\n\t\t\tjQuery('form#cc-4-main-form > textarea[name=occurrence\\:comment]').val(data[0].comment);\n  \t\t} else {\n   \t\t\talertIndiciaError({error : \"" . lang::get('Internal Error 10: no insect data available for id ') . "\"+id});\n  \t\t}\n\t});\n\t\$.getJSON(\"" . $svcUrl . "/data/determination?occurrence_id=\" + id +\n          \"&mode=json&view=list&nonce=" . $readAuth['nonce'] . "&auth_token=" . $readAuth['auth_token'] . "&orderby=id&deleted=f&callback=?\", function(data) {\n        if(!(data instanceof Array)){\n   \t\t\talertIndiciaError(data);\n   \t\t} else loadDetermination(data, insectIDstruc);\n\t});\t\n\tjQuery('.currentPhoto').removeClass('currentPhoto');\n\tjQuery('[occId='+id+']').addClass('currentPhoto');\n}\n\nprepPhotoReelForNew = function(notID, id){\n\tvar container;\n\tif(id == '')\n\t\tcontainer = jQuery('<div/>').addClass('thumb').insertBefore('.blankPhoto').attr('occId', 'new');\n\telse\n\t\tcontainer = jQuery('[occId='+id+']').empty();\n\tif(notID){\n\t\tvar img = new Image();\n\t\tvar src = '" . $base . drupal_get_path('module', 'iform') . "/client_helpers/prebuilt_forms/images/boundary-unknown.png';\n\t\timg = jQuery(img).attr('src', src).attr('width', container.width()).attr('height', container.height()).addClass('thumb-image').addClass('unidentified').appendTo(container);\n\t}\n}\n\naddNewToPhotoReel = function(occId){\n\tvar container = jQuery('[occId='+occId+']');\n\tif(container.length == 0) {\n\t\tcontainer = jQuery('[occId=new]');\n\t\tcontainer.attr('occId', occId.toString()).click(function () {\n\t\t    setInsect(occId)});\n\t}\n\t\$.getJSON(\"" . $svcUrl . "/data/occurrence_image\" +\n\t\t\t\"?mode=json&view=list&nonce=" . $readAuth['nonce'] . "&auth_token=" . $readAuth['auth_token'] . "\" +\n\t\t\t\"&occurrence_id=\" + occId + \"&callback=?\", function(imageData) {\n\t\tif(!(imageData instanceof Array)){\n\t\t\talertIndiciaError(imageData);\n\t\t} else if (imageData.length>0) {\n\t\t\tvar img = new Image();\n\t\t\tvar container = jQuery('[occId='+imageData[0].occurrence_id+']');\n\t\t\tif(container.children().length>0){\n\t\t\t\tvar background = '" . data_entry_helper::$base_url . data_entry_helper::$indicia_upload_path . "thumb-'+imageData[0].path;\n\t\t\t\tcontainer.children().css('background', 'url('+background+')').css('background-size','100% 100%');\n\t\t\t} else {\n\t\t\t\tjQuery(img).attr('src', '" . data_entry_helper::$base_url . data_entry_helper::$indicia_upload_path . "thumb-'+imageData[0].path)\n\t\t\t\t    .attr('width', container.width()).attr('height', container.height()).addClass('thumb-image').appendTo(container);\n\t\t\t}\n\t\t} else {\n\t\t\talertIndiciaError({error : \"" . lang::get('Internal Error 11: image could not be loaded into photoreel for insect ') . "\"+occId});\n\t\t}});\n}\n\naddExistingToPhotoReel = function(occId){\n\tvar container = jQuery('[occId='+occId+']');\n\tif(container.length == 0)\n\t\tcontainer = jQuery('<div/>').addClass('thumb').insertBefore('.blankPhoto').attr('occId', occId.toString()).click(function () {\n\t\t    setInsect(occId)});\n\telse\n\t\tcontainer.empty();\n\t// we use the presence of the text to determine whether the \n\t// insect has been identified or not. NB an insect tagged as unidentified (type = 'X') has actually been through the ID\n\t// process, so is not unidentified!!!\n\tjQuery.ajax({ \n        type: \"GET\", \n        url: \"" . $svcUrl . "/data/determination\" + \n    \t\t\"?mode=json&view=list&nonce=" . $readAuth['nonce'] . "&auth_token=" . $readAuth['auth_token'] . "\" + \n    \t\t\"&reset_timeout=true&occurrence_id=\" + occId + \"&orderby=id&deleted=f&callback=?\", \n        success: function(detData) {\n\t    \tif(!(detData instanceof Array)){\n   \t\t\t\talertIndiciaError(detData);\n   \t\t\t} else if (detData.length>0) {\n\t\t\t\t\$.getJSON(\"" . $svcUrl . "/data/occurrence_image\" +\n\t\t\t\t\t\t\"?mode=json&view=list&nonce=" . $readAuth['nonce'] . "&auth_token=" . $readAuth['auth_token'] . "\" +\n\t\t\t\t\t\t\"&occurrence_id=\" + occId + \"&callback=?\", function(imageData) {\n\t\t\t\t\tif(!(imageData instanceof Array)){\n\t\t\t\t\t\talertIndiciaError(imageData);\n\t\t\t\t\t} else if (imageData.length>0) {\n\t\t\t\t\t\tvar img = new Image();\n\t\t\t\t\t\tvar container = jQuery('[occId='+imageData[0].occurrence_id+']');\n\t\t\t\t\t\tjQuery(img).attr('src', '" . data_entry_helper::$base_url . data_entry_helper::$indicia_upload_path . "thumb-'+imageData[0].path)\n\t\t\t    \t\t\t.attr('width', container.width()).attr('height', container.height()).addClass('thumb-image').appendTo(container);\n\t\t\t\t\t} else {\n\t\t\t\t\t\talertIndiciaError({error : \"" . lang::get('Internal Error 12: image could not be loaded into photoreel for existing insect ') . "\"+occId});\n\t\t\t\t\t}\n\t\t\t\t});\n\t    \t} else { // is conceivable that insect is not identified yet -> does not have determinations\n\t\t\t\t\$.getJSON(\"" . $svcUrl . "/data/occurrence_image\" +\n\t\t\t\t\t\t\"?mode=json&view=list&nonce=" . $readAuth['nonce'] . "&auth_token=" . $readAuth['auth_token'] . "\" +\n\t\t\t\t\t\t\"&occurrence_id=\" + occId + \"&callback=?\", function(imageData) {\n\t\t\t\t\tif(!(imageData instanceof Array)){\n\t\t\t\t\t\talertIndiciaError(imageData);\n\t\t\t\t\t} else if (imageData.length>0) {\n\t\t\t\t\t\tvar img = new Image();\n\t\t\t\t\t\tvar container = jQuery('[occId='+imageData[0].occurrence_id+']');\n\t\t\t\t\t\tvar src = '" . $base . drupal_get_path('module', 'iform') . "/client_helpers/prebuilt_forms/images/boundary-unknown.png';\n\t\t\t\t\t\tvar background = '" . data_entry_helper::$base_url . data_entry_helper::$indicia_upload_path . "thumb-'+imageData[0].path;\n\t\t\t\t\t\timg = jQuery(img).attr('src', src).attr('width', container.width()).attr('height', container.height()).addClass('thumb-image').addClass('unidentified').appendTo(container);\n\t\t\t\t\t\timg.css('background', 'url('+background+')').css('background-size','100% 100%');\n\t\t\t\t\t} else {\n\t\t\t\t\t\talertIndiciaError({error : \"" . lang::get('Internal Error 12: image could not be loaded into photoreel for existing insect ') . "\"+occId});\n\t\t\t\t\t}\n\t\t\t\t});\n\t    \t}\n  \t\t}, \n    \tdataType: 'json' \n    });\n}\n\nsetInsect = function(id){\n\t// first close all the other panels, ensuring any data is saved.\n\tif(!validateCollectionPanel() || !validateStationPanel() || !validateSessionsPanel())\n\t\treturn;\n\tjQuery('#cc-5').hidePanel();\n\n\tif(jQuery('#cc-4-body:visible').length == 0)\n\t\tjQuery('div#cc-4').unFoldPanel();\n\telse\n\t\tif(!validateInsect()){ return ; }\n\tloadInsect(id);\n};\n\nsetNoInsect = function(){\n\t// first close all the other panels, ensuring any data is saved.\n\tif(!validateCollectionPanel() || !validateStationPanel() || !validateSessionsPanel())\n\t\treturn;\n\t\t\n\tif(jQuery('#cc-4-body:visible').length == 0)\n\t\tjQuery('div#cc-4').unFoldPanel();\n\telse\n\t\tif(!validateInsect()){ return ; }\n\tclearInsect();\n};\n\njQuery('.blankPhoto').click(setNoInsect);\n\n// TODO separate photoreel out into own js\nvalidateInsect = function(){\n    clearErrors('form#cc-4-main-form');\n    clearErrors('#cc-4-insect-identify');\n    if(jQuery('form#cc-4-main-form > input[name=occurrence\\:id]').val() == '' &&\n\t\t\tjQuery('form#cc-4-main-form > input[name=occurrence_image\\:path]').val() == '' &&\n\t\t\tjQuery('[name=insect\\:taxa_taxon_list_id]').val() == '' &&\n\t\t\tjQuery('[name=insect\\:taxon_details]').val() == '' &&\n\t\t\tjQuery('[name=insect\\:comment]').val() == '' &&\n\t\t\tjQuery('[name=insect\\:taxon_extra_info]').val() == '' &&\n\t\t\tjQuery('form#cc-4-main-form > textarea[name=occurrence\\:comment]').val() == '' &&\n\t\t\tjQuery('[name=occAttr\\:" . $args['number_attr_id'] . "],[name^=occAttr\\:" . $args['number_attr_id'] . "\\:]').filter('[checked]').length == 0){\n\t\treturn true;\n\t}\n\tvar valid = true;\n    if (!jQuery('form#cc-4-main-form > input').valid()) { valid = false; }\n  \tif (!validateRadio('occAttr\\:" . $args['number_attr_id'] . "', 'form#cc-4-main-form')) { valid = false; }\n\tif (jQuery('#id-insect-later').attr('checked') == '' && jQuery('[name=insect\\:taxon_details]').val() == ''){\n\t\tif (!validateRequiredField('insect\\:taxa_taxon_list_id', '#cc-4-insect-identify')) { valid = false; }\n\t}\n \tif (!validateRequiredField('occurrence\\:sample_id', 'form#cc-4-main-form')) { valid = false; }\n\tif(jQuery('form#cc-4-main-form input[name=occurrence_image\\:path]').val() == ''){\n    \tmyScrollTo('#cc-4-insect-upload');\n\t\talert(\"" . lang::get('LANG_Must_Provide_Insect_Picture') . "\");\n\t\tvalid = false;\n\t}\n\tif(jQuery('[name=occAttr\\:" . $args['foraging_attr_id'] . "],[name^=occAttr\\:" . $args['foraging_attr_id'] . ":]').filter('[checked]').val()==1){\n\t\tif(jQuery('[name=dummy_foraging_confirm]').filter('[checked]').val()==0){\n\t\t\tvalid = false;\n\t        var label = \$('<p/>')\n\t\t\t\t.attr({'for': 'dummy_foraging_confirm'})\n\t\t\t\t.addClass('inline-error')\n\t\t\t\t.html(\"" . lang::get('Foraging_Validation') . "\");\n\t\t\tlabel.appendTo(jQuery('#Foraging_Confirm'));\n\t\t}\n\t}\n\tif(valid == false) {\n\t\tmyScrollToError();\n\t\treturn false;\n\t}\n\tjQuery('form#cc-4-main-form').submit();\n\tclearInsect();\n\tmyScrollTo('.blankPhoto')\n\treturn true;\n}\n\n\$('#cc-4-valid-insect-button').click(validateInsect);\n\n\$('#cc-4-delete-insect-button').click(function() {\n\tvar container = \$(this).parent().parent();\n\tjQuery('#cc-4-delete-insect').find('[name=occurrence\\:id]').val(jQuery('#cc-4-main-form').find('[name=occurrence\\:id]').val()).removeAttr('disabled');\n\tjQuery('#cc-4-delete-insect').find('[name=occurrence\\:sample_id]').val(jQuery('#cc-4-main-form').find('[name=occurrence\\:sample_id]').val()).removeAttr('disabled');\n\tif(confirm(\"" . lang::get('LANG_Confirm_Insect_Delete') . "\")){\n\t\tif(jQuery('#cc-4-main-form').find('[name=occurrence\\:id]').filter('[disabled]').length == 0){\n\t\t\tjQuery('#cc-4-delete-insect').submit();\n\t\t\tjQuery('.currentPhoto').remove();\n\t\t\tjQuery('.blankPhoto').addClass('currentPhoto');\n\t\t}\n\t\tclearInsect();\n\t\tmyScrollTo('.blankPhoto')\n\t}\n});\n\n\$('#cc-4-delete-insect').ajaxForm({ \n\t\tasync: false,\n\t\tdataType:  'json', \n        beforeSubmit:   function(data, obj, options){\n  \t\t\t// Warning this assumes that the data is fixed position:\n        \tif(data[2].value == '') return false;\n\t\t\tif(data[3].value == ''){\n\t\t\t\talertIndiciaError({error : \"" . lang::get('Internal Error 13: sample id not set, so unsafe to save insect.') . "\"});\n\t\t\t\treturn false;\n\t\t\t}\n        \tjQuery('#cc-4-delete-insect').addClass('loading-button');\n        \treturn true;\n  \t\t},\n        success:   function(data){\n       \t\tif(data.success != 'multiple records' || data.outer_table != 'occurrence')\n        \t\talertIndiciaError(data);\n  \t\t},\n        complete: function (){\n  \t\t\tjQuery('.loading-button').removeClass('loading-button');\n  \t\t}\n});\n\n\$('#cc-4-valid-photo-button').click(function(){\n\tif(!validateInsect()) return;\n\tjQuery('#cc-4').foldPanel();\n\tjQuery('#cc-5').showPanel();\n\tvar numInsects = jQuery('#cc-4-photo-reel').find('.thumb').length - 1; // ignore blank\n\tvar numUnidentified = jQuery('#cc-4-photo-reel').find('.unidentified').length;\n\tif(jQuery('#id-flower-later').attr('checked') != '' || (numInsects>0 && (numUnidentified/numInsects > (1-(" . $args['percent_insects'] . "/100.0))))){\n\t\tjQuery('#cc-5-bad').show();\n\t\tjQuery('#cc-5-good,#cc-5-body2,#cc-5-complete-collection').hide();\n    } else {\n    \tjQuery('#cc-5-bad').hide(); // photoreel is left showing\n    \tjQuery('#cc-5-good,#cc-5-body2,#cc-5-complete-collection').show();\n\t}\n});\n";
        $r .= '
<div id="cc-5" class="poll-section">
  <div id="cc-5-body" class="ui-accordion-header ui-helper-reset ui-state-active ui-corner-top poll-section-body"> 
   <p id="cc-5-good">' . lang::get('LANG_Can_Complete_Msg') . '</p> 
   <p id="cc-5-bad">' . lang::get('LANG_Cant_Complete_Msg') . '</p> 
   <div style="display:none" />
    <form id="cc-5-collection" action="' . iform_ajaxproxy_url($node, 'sample') . '" method="POST">
       <input type="hidden" name="website_id" value="' . $args['website_id'] . '" />
       <input type="hidden" name="sample:survey_id" value="' . $args['survey_id'] . '" />
       <input type="hidden" name="sample:id" value="" />
       <input type="hidden" name="sample:date_start" value="2010-01-01"/>
       <input type="hidden" name="sample:date_end" value="2010-01-01"/>
       <input type="hidden" name="sample:date_type" value="D"/>
       <input type="hidden" name="sample:location_id" value="" />
       <input type="hidden" id="smpAttr:' . $args['complete_attr_id'] . '" name="smpAttr:' . $args['complete_attr_id'] . '" value="1" />
    </form>
   </div>
  </div>
  <div id="cc-5-body2" class="ui-accordion-content ui-helper-reset ui-widget-content ui-accordion-content-active poll-section-body">
    <p><img src="' . $base . drupal_get_path('module', 'iform') . '/media/images/exclamation.jpg" /> ' . lang::get('LANG_Trailer_Head') . ' :</p>
    <ul>
      <li>' . lang::get('LANG_Trailer_Point_1') . '</li>
      <li>' . lang::get('LANG_Trailer_Point_2') . '</li>
      <li>' . lang::get('LANG_Trailer_Point_3') . '</li>
      <li>' . lang::get('LANG_Trailer_Point_4') . '</li>
    </ul>
  </div>
  <div id="cc-5-trailer" class="ui-accordion-content ui-helper-reset ui-widget-content ui-corner-bottom ui-accordion-content-active poll-section-footer">
    <div id="cc-5-complete-collection" class="ui-state-default ui-corner-all complete-button">' . lang::get('LANG_Complete_Collection') . '</div>
  </div>
</div>';
        data_entry_helper::$javascript .= "\n\$('#cc-5-collection').ajaxForm({ \n\t\tasync: false,\n\t\tdataType:  'json', \n        beforeSubmit:   function(data, obj, options){\n            // double check that location id and sample id are filled in\n\t\t\tif(jQuery('#cc-1-collection-details input[name=location\\:id]').val() == ''){\n\t\t\t\talertIndiciaError({error : \"" . lang::get('Internal Error 14: location id not set, so unsafe to save collection.') . "\"});\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\tif(jQuery('#cc-1-collection-details input[name=sample\\:id]').val() == ''){\n\t\t\t\talertIndiciaError({error : \"" . lang::get('Internal Error 15: sample id not set, so unsafe to save collection.') . "\"});\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\tjQuery('#cc-5-complete-collection').addClass('loading-button');\n        \tdata[findID('sample:id', data)].value = jQuery('#cc-1-collection-details input[name=sample\\:id]').val();\n\t\t\tdata[findID('sample:date_start', data)].value = '';\n\t\t\tdata[findID('sample:date_end', data)].value = '';\n\t\t\tdate_start = '';\n\t\t\tdate_end = '';\n\t\t\tjQuery('.poll-session-form').each(function(i){\n\t\t\t\tif(jQuery(this).find('input[name=sample\\:id]').val() != '') {\n\t\t\t\t\tvar sessDate = jQuery(this).find('input[name=sample\\:date]').val();\n\t\t\t\t\tvar sessDateDate = new Date(convertDate(sessDate)); // sessions are only on one date.\n\t\t\t\t\tif(date_start == '' || date_start > sessDateDate) {\n\t\t\t\t\t\tdate_start = sessDateDate;\n\t\t\t\t\t\tdata[findID('sample:date_start', data)].value = sessDate;\n\t\t\t\t\t}\n\t\t\t\t\tif(date_end == '' || date_end < sessDateDate) {\n\t\t\t\t\t\tdate_end = sessDateDate;\n\t\t\t\t\t\tdata[findID('sample:date_end', data)].value = sessDate;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t});\n\t\t\tif(data[findID('sample:date_start', data)].value == '') {\n\t\t\t\talert(\"" . lang::get('LANG_Session_Error') . "\");\n\t\t\t\tjQuery('#cc-5-complete-collection').removeClass('loading-button');\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\tdata[findID('sample:date_type', data)].value = (data[3].value == data[4].value ? 'D' : 'DD');\n\t       \tjQuery('#cc-1-collection-details,#cc-2').find('[name=sample\\:date]:hidden').val(data[3].value);\n  \t\t\tdata[findID('sample:location_id', data)].value = jQuery('#cc-1-collection-details input[name=location\\:id]').val();\n       \t\tdata[7].name = jQuery('#cc-1-collection-details input[name^=smpAttr\\:" . $args['complete_attr_id'] . "\\:]').attr('name');\n       \t\treturn true;\n  \t\t},\n        success:   function(data){\n       \t\tif(data.success == 'multiple records' && data.outer_table == 'sample'){\n\t\t\t\t\$('#cc-6').showPanel();\n  \t\t\t}  else\n\t\t\t\talertIndiciaError(data);\n  \t\t},\n        complete: function (){\n  \t\t\tjQuery('.loading-button').removeClass('loading-button');\n  \t\t}\n});\n\$('#cc-5-complete-collection').click(function(){\n\tjQuery('#cc-5-complete-collection').addClass('loading-button');\n\tjQuery('#cc-2,#cc-3,#cc-4,#cc-5').hidePanel();\n\tjQuery('.reinit-button').hide();\n\tjQuery('.mod-button').hide();\n\tjQuery('#cc-5-collection').submit();\n});\n";
        $r .= '
<div id="cc-6" class="poll-section">
  <div id="cc-6-body" class="ui-accordion-header ui-helper-reset ui-state-active ui-corner-top poll-section-body"> 
   <p>' . lang::get('LANG_Final_1') . '</p> 
   <p>' . lang::get('LANG_Final_2') . '</p> 
   </div>
  <div id="cc-6-footer" class="ui-accordion-content ui-helper-reset ui-widget-content ui-corner-bottom ui-accordion-content-active poll-section-footer">
    <a id="cc-6-consult-collection" href="" class="ui-state-default ui-corner-all link-button">' . lang::get('LANG_Consult_Collection') . '</a>
    <a href="' . url('node/' . $node->nid) . '" class="ui-state-default ui-corner-all link-button">' . lang::get('LANG_Create_New_Collection') . '</a>
  </div>
</div>
</div></div>
<script type="text/javascript">
/* <![CDATA[ */
document.write("</div>");
/* ]]> */</script>
';
        data_entry_helper::$javascript .= "\nloadAttributes = function(formsel, attributeTable, attributeKey, key, keyValue, prefix, reset_timeout, required){\n\t// first need to remove any hidden multiselect checkbox unclick fields\n\tjQuery(formsel).find('[name^='+prefix+'\\:]').filter('.multiselect').remove();\n\t// rename, to be safe. Then add [] to multiple choice checkboxes.\n\tjQuery(formsel).find('[name^='+prefix+'\\:]').each(function(){\n\t\tvar name = jQuery(this).attr('name').split(':');\n\t\tif(name[1].indexOf('[]') > 0) name[1] = name[1].substr(0, name[1].indexOf('[]'));\n\t\tjQuery(this).attr('name', name[0]+':'+name[1]);\n\t});\n\tjQuery(formsel).find('[name^='+prefix+'\\:]').filter(':checkbox').removeAttr('checked').each(function(){\n\t\tvar myName = jQuery(this).attr('name').split(':');\n\t\tvar similar = jQuery('[name='+myName[0]+'\\:'+myName[1]+'],[name='+myName[0]+'\\:'+myName[1]+'\\[\\]]').filter(':checkbox');\n\t\tif(similar.length > 1)\n\t\t\tjQuery(this).attr('name', myName[0]+':'+myName[1]+'[]');\n\t});\n    jQuery.ajax({ \n        type: \"GET\", \n        url: \"" . $svcUrl . "/data/\" + attributeTable + \"?mode=json&view=list\" +\n        \t(reset_timeout ? \"&reset_timeout=true\" : \"\") + \"&nonce=" . $readAuth['nonce'] . "&auth_token=" . $readAuth['auth_token'] . "\" +\n   \t\t\t\"&\" + key + \"=\" + keyValue + \"&callback=?\", \n        data: {},\n        myFormsel: formsel,\n        myAttributeKey: attributeKey,\n        success: function(attrdata) {\n\t\t  if(!(attrdata instanceof Array)){\n   \t\t\talertIndiciaError(attrdata);\n   \t\t  } else if (attrdata.length>0) {\n\t\t\tfor (var i=0;i<attrdata.length;i++){\n\t\t\t\t// attribute list views now use id rather than meaning_id for the term.\n\t\t\t\t// This means (1) that the term will be either not present or wrong, as we are storing the meaning_id.\n\t\t\t\t// and (2) only one row will be returned per attribute.\n\t\t\t\t// As we already use raw_value below, the only change is no need to check the iso field.\n\t\t\t\tif (attrdata[i].id){\n\t\t\t\t\tvar radiobuttons = jQuery(this.myFormsel).find('[name='+prefix+'\\:'+attrdata[i][this.myAttributeKey]+'],[name^='+prefix+'\\:'+attrdata[i][this.myAttributeKey]+'\\:]').filter(':radio');\n\t\t\t\t\tvar multicheckboxes = jQuery(this.myFormsel).find('[name='+prefix+'\\:'+attrdata[i][this.myAttributeKey]+'\\[\\]],[name^='+prefix+'\\:'+attrdata[i][this.myAttributeKey]+':]').filter(':checkbox');\n\t\t\t\t\tvar boolcheckbox = jQuery(this.myFormsel).find('[name='+prefix+'\\:'+attrdata[i][this.myAttributeKey]+'],[name^='+prefix+'\\:'+attrdata[i][this.myAttributeKey]+':]').filter(':checkbox');\n\t\t\t\t\tif(radiobuttons.length > 0){ // radio buttons all share the same name, only one checked.\n\t\t\t\t\t\tradiobuttons\n\t\t\t\t\t\t\t.attr('name', prefix+':'+attrdata[i][this.myAttributeKey]+':'+attrdata[i].id)\n\t\t\t\t\t\t\t.filter('[value='+attrdata[i].raw_value+']')\n\t\t\t\t\t\t\t.attr('checked', 'checked');\n\t\t\t\t\t} else if(multicheckboxes.length > 0){ // individually named\n\t\t\t\t\t\tmulticheckboxes = multicheckboxes.filter('[value='+attrdata[i].raw_value+']')\n\t\t\t\t\t\t\t.attr('name', prefix+':'+attrdata[i][this.myAttributeKey]+':'+attrdata[i].id)\n\t\t\t\t\t\t\t.attr('checked', 'checked');\n\t\t\t\t\t\tmulticheckboxes.each(function(){\n\t\t\t\t\t\t\tjQuery('<input type=\"hidden\" value=\"0\" class=\"multiselect\">').attr('name', jQuery(this).attr('name')).insertBefore(this);\n\t\t\t\t\t\t});\n\t\t\t\t\t} else if(boolcheckbox.length > 0){ // has extra hidden field to force zero if unchecked.\n\t\t\t\t\t\tjQuery(this.myFormsel).find('[name='+prefix+'\\:'+attrdata[i][this.myAttributeKey]+'],[name^='+prefix+'\\:'+attrdata[i][this.myAttributeKey]+':]')\n\t\t\t\t\t\t\t.attr('name', prefix+':'+attrdata[i][this.myAttributeKey]+':'+attrdata[i].id);\n\t\t\t\t\t\tif (attrdata[i].raw_value == '1')\n\t\t\t\t\t\t\tboolcheckbox.attr('checked', 'checked');\n\t\t\t\t\t} else if (prefix == 'smpAttr' && attrdata[i][this.myAttributeKey] == " . $args['complete_attr_id'] . ") {\n\t\t\t\t\t\t// The hidden closed attributes are special: these have forced values, and are used to control the state. Do not update their values.\n\t\t\t\t\t\tjQuery(this.myFormsel).find('[name='+prefix+'\\:'+attrdata[i][this.myAttributeKey]+']')\n\t\t\t\t\t\t\t.attr('name', prefix+':'+attrdata[i][this.myAttributeKey]+':'+attrdata[i].id);\n\t\t\t\t\t} else {\n\t\t\t\t\t\tjQuery(this.myFormsel).find('[name='+prefix+'\\:'+attrdata[i][this.myAttributeKey]+']')\n\t\t\t\t\t\t\t.attr('name', prefix+':'+attrdata[i][this.myAttributeKey]+':'+attrdata[i].id)\n\t\t\t\t\t\t\t.val(attrdata[i].raw_value);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t  } else if (required){\n\t\t\talertIndiciaError({error : \"" . lang::get('Internal Error 16: could not load attributes ') . "\"+attributeTable+' '+keyName+' '+keyValue});\n\t\t  }\n\t\t  checkProtocolStatus('leave');\n\t\t  populateSessionSelect();\n\t\t  checkForagingStatus(true);\n\t\t},\n\t\tdataType: 'json'\n\t});\n}\n\nloadImage = function(imageTable, key, keyName, keyValue, target, ratio, required){\n\t\t\t\t\t// location_image, location_id, location:id, 1, #cc-4-insect-image\n\t\$.getJSON(\"" . $svcUrl . "/data/\" + imageTable +\n   \t\t\t\"?mode=json&view=list&nonce=" . $readAuth['nonce'] . "&auth_token=" . $readAuth['auth_token'] . "\" +\n   \t\t\t\"&\" + key + \"=\" + keyValue + \"&callback=?\", function(imageData) {\n\t\tif(!(imageData instanceof Array)){\n   \t\t\talertIndiciaError(imageData);\n   \t\t} else if (imageData.length>0) {\n\t\t\tvar form = jQuery('input[name='+keyName+'][value='+keyValue+']').parent();\n\t\t\tjQuery('[name='+imageTable+'\\:id]', form).val(imageData[0].id).removeAttr('disabled');\n\t\t\tjQuery('[name='+imageTable+'\\:path]', form).val(imageData[0].path);\n\t        insertImage('med-'+imageData[0].path, jQuery(target), ratio);\n\t\t} else if(required){\n\t\t\talertIndiciaError({error : \"" . lang::get('Internal Error 17: could not load ') . "\"+imageTable+' '+keyName+' '+keyValue});\n\t\t}\n\t});\n}\n\nloadDetermination = function(detData, toolStruc){\n\tjQuery('#'+toolStruc.type+'_taxa_list').empty();\n\ttoolStruc.storedTaxaList = [];\n\tjQuery(toolStruc.mainForm+' input[name=determination\\:id]').val('').attr('disabled', 'disabled');\n\tjQuery('#id-'+toolStruc.type+'-later').removeAttr('checked').removeAttr('disabled');\n\tjQuery('[name='+toolStruc.type+'\\:determination_type]').val('A');\n\tjQuery(toolStruc.mainForm+' input[name=determination\\:determination_type]').val('A');\n\tjQuery('[name='+toolStruc.type+'\\:taxon_details],[name='+toolStruc.type+'\\:taxa_taxon_list_id],[name='+toolStruc.type+'\\:comment],[name='+toolStruc.type+'\\:taxon_extra_info]').val('');\n\n\tif (detData.length>0) {\n\t\tjQuery('#id-'+toolStruc.type+'-later').attr('disabled', 'disabled');\n\t\tjQuery(toolStruc.mainForm+' input[name=determination\\:id]').val(detData[0].id).removeAttr('disabled');\n\t\tjQuery('[name='+toolStruc.type+'\\:taxon_details]').val(detData[0].taxon_details);\n\t\tjQuery('[name='+toolStruc.type+'\\:determination_type]').val(detData[0].determination_type);\n\t\tjQuery('[name='+toolStruc.type+'\\:taxa_taxon_list_id]').val(detData[0].taxa_taxon_list_id == null ? '' : detData[0].taxa_taxon_list_id);\n\t\tjQuery('[name='+toolStruc.type+'\\:comment]').val(detData[0].comment);\n\t\tjQuery('[name='+toolStruc.type+'\\:taxon_extra_info]').val(detData[0].taxon_extra_info == null ? '' : detData[0].taxon_extra_info);\n\t\tif(detData[0].determination_type == 'X'){\n\t\t\tjQuery('#'+toolStruc.type+'_taxa_list').append(\"" . lang::get('LANG_Taxa_Unknown_In_Tool') . "\");\n\t\t} else {\n\t\t\tvar resultsIDs = [];\n\t\t\tif(detData[0].taxa_taxon_list_id_list != null && detData[0].taxa_taxon_list_id_list != ''){\n\t\t\t  \tvar resultsText = \"" . lang::get('LANG_Taxa_Returned') . "<br />{ \";\n\t\t\t  \tresultsIDs = detData[0].taxa_taxon_list_id_list.substring(1, detData[0].taxa_taxon_list_id_list.length - 1).split(',');\n\t\t\t  \tfor(var j=0; j < resultsIDs.length; j++){\n\t\t\t\t\tfor(i = 0; i< toolStruc.taxaList.length; i++)\n\t\t\t\t\t\tif(toolStruc.taxaList[i].id == resultsIDs[j])\n\t\t\t\t\t\t\tresultsText = resultsText + (j == 0 ? '' : '<br />&nbsp;&nbsp;') + htmlspecialchars(toolStruc.taxaList[i].taxon);\n\t\t  \t\t}\n\t  \t\t\tif(resultsIDs.length>1 || resultsIDs[0] != '')\n\t\t\t\t\tjQuery('#'+toolStruc.type+'_taxa_list').append(resultsText+ ' }');\n\t\t\t}\n\t\t\ttoolStruc.storedTaxaList = resultsIDs;\n  \t\t}\n\t} else {\n\t\tjQuery('#id-'+toolStruc.type+'-later').attr('checked', 'checked');\n\t}\n};\n// Flowers no longer uses the taxa_taxon_list_id, but instead uses its list equivalent for known species.\n// the flower identification is not held with the cc-2-floral-station form.\nloadFlowerDetermination = function(detData){\n  jQuery('form#cc-2-floral-station input[name=determination\\:id]').val('').attr('disabled', 'disabled');\n  jQuery('#id-flower-later').removeAttr('checked').removeAttr('disabled');\n  jQuery('#id-flower-unknown').removeAttr('checked').removeAttr('disabled');\n  jQuery('[name=flower\\:determination_type]').val('A'); // hidden\n  jQuery('form#cc-2-floral-station input[name=determination\\:determination_type]').val('A');// hidden\n  jQuery('.flower-species-list-entry').remove();\n  jQuery('[name=flower\\:taxon_details],[name=flower\\:taxa_taxon_list_id],[name=flower\\:comment],[name=flower\\:taxon_extra_info]').val('');\n\n  if (detData.length>0) {\n    jQuery('#id-flower-later').attr('disabled', 'disabled');\n    jQuery('form#cc-2-floral-station input[name=determination\\:id]').val(detData[0].id).removeAttr('disabled');\n    jQuery('[name=flower\\:taxon_details]').val(detData[0].taxon_details == null ? '' : detData[0].taxon_details); // stores details from tool.\n    jQuery('[name=flower\\:determination_type]').val(detData[0].determination_type);\n    jQuery('[name=flower\\:comment]').val(detData[0].comment == null ? '' : detData[0].comment);\n    jQuery('[name=flower\\:taxon_extra_info]').val(detData[0].taxon_extra_info == null ? '' : detData[0].taxon_extra_info);\n    if(detData[0].determination_type == 'X') {\n      jQuery('#id-flower-unknown').attr('checked', 'checked');\n    } else if(detData[0].taxa_taxon_list_id != null) { // already set blank up above for null\n      // copy existing data forward to array.\n      for(i = 0; i< flowerTaxa.length; i++)\n        if(flowerTaxa [i].id == detData[0].taxa_taxon_list_id) {\n          jQuery('<tr class=\"flower-species-list-entry\"><td><input type=\"hidden\" name=\"flower:taxa_taxon_list_id_list[]\" value=\"'+flowerTaxa [i].id+'\"\\>'+htmlspecialchars(flowerTaxa[i].taxon)+'<td><img  class=\"removeRow\" src=\"/misc/watchdog-error.png\" alt=\"" . lang::get('Remove this entry') . "\" title=\"" . lang::get('Remove this entry') . "\"/></td></tr>').insertBefore('#flowerAutocompleteRow');\n          break;\n        }\n    } else {\n      if(detData[0].taxa_taxon_list_id_list != null && detData[0].taxa_taxon_list_id_list != ''){\n        var resultsIDs = detData[0].taxa_taxon_list_id_list.substring(1, detData[0].taxa_taxon_list_id_list.length - 1).split(','); // stringified array\n        for(var j=0; j < resultsIDs.length; j++)\n          for(i = 0; i< flowerTaxa.length; i++)\n            if(flowerTaxa[i].id == resultsIDs[j])\n              jQuery('<tr class=\"flower-species-list-entry\"><td><input type=\"hidden\" name=\"flower:taxa_taxon_list_id_list[]\" value=\"'+flowerTaxa [i].id+'\"\\>'+htmlspecialchars(flowerTaxa[i].taxon)+'<td><img class=\"removeRow\" src=\"/misc/watchdog-error.png\" alt=\"" . lang::get('Remove this entry') . "\" title=\"" . lang::get('Remove this entry') . "\"/></td></tr>').insertBefore('#flowerAutocompleteRow');\n      }\n    }\n  } else {\n    jQuery('#id-flower-later').attr('checked', 'checked');\n  }\n};\n\n// load in any existing incomplete collection.\n// general philosophy is that you are taken back to the stage last verified.\n// Load in the first if there are more than one. Use the internal report which provides my collections.\n// Requires that there is an attribute for completeness, and one for the CMS\n// load the data in the order it is entered, so can stop when get to the point where the user finished.\n// have to reset the entire form first...\njQuery('.poll-section').resetPanel();\n// Default state: hide everything except the collection details block.\njQuery('.poll-section').hidePanel();\njQuery('#cc-1').showPanel();\njQuery('.reinit-button').hide();\naddSession();\njQuery('.flower-species-list-entry').remove();\njQuery('#insect_taxa_list').empty();\npreloading=true;\npreloadIDs={location_loaded : false,\n\t\t\tsessions: []};\nsetPreloadStage = function(stage){\n\tpreloadStage=stage;\n\t\$('.poll-loading-extras').empty().text(stage);\n};\nsetPreloadStage(1);\n\njQuery('#cc-1').ajaxStop(function(){\n\tif(!preloading) return;\n\tswitch(preloadStage){\n\t\tcase 1: // just finished the report request\n\t\t\tif(typeof preloadIDs.sample_id == 'undefined' || typeof preloadIDs.location_id == 'undefined'){\n\t\t\t\t\$('.loading-panel').remove();\n\t\t\t\t\$('.poll-loading-hide').show();\n\t\t\t\tpreloading=false;\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tsetPreloadStage(2);\n\t\t\t// main sample date is only set when collection is completed, so don't need to load collection sample itself, and keep date as default \n\t\t\tloadAttributes('#cc-1-collection-details,#cc-5-collection', 'sample_attribute_value', 'sample_attribute_id', 'sample_id', preloadIDs.sample_id, 'smpAttr', false, true);\n  \t\t\tjQuery.getJSON('" . $svcUrl . "/data/location/' + preloadIDs.location_id +\n          \t\t\t\t\t\"?mode=json&view=detail&nonce=" . $readAuth['nonce'] . "&auth_token=" . $readAuth['auth_token'] . "\" +\n          \t\t\t\t\t\"&callback=?\", \n\t\t\t\t\tfunction(locationdata) {\n\t\t    \t\t  if(!(locationdata instanceof Array)){\n   \t\t\t\t\t\talertIndiciaError(locationdata);\n   \t\t\t\t\t  } else if (locationdata.length>0) {\n\t    \t\t\t\tjQuery('input[name=location\\:name]').val(locationdata[0].name);\n       \t\t\t\t\tjQuery('input[name=sample\\:location_name]').val(locationdata[0].name); // make sure the 2 coincide\n\t    \t\t\t\tjQuery('input[name=locations_website\\:website_id]').attr('disabled', 'disabled');\n\t\t\t\t\t\t// The location only holds a valid place if the floral station has been saved: otherwise it holds a default value.\n\t\t\t\t\t\t// we use the centroid_sref_system to indicate this: when the initial save is done the system is 900913,\n\t\t\t\t\t\t// but when a user has loaded one it is in 4326\n\t\t\t\t\t\t// NB the location geometry is stored in centroid, due to restrictions in location model.\n\t\t\t\t\t\tif(locationdata[0].centroid_sref_system == 4326 && locationdata[0].centroid_sref != oldDefaultSref){\n\t\t\t\t\t\t\tjQuery('input[name=location\\:centroid_sref]').val(locationdata[0].centroid_sref);\n\t\t\t\t\t\t\tjQuery('input[name=location\\:centroid_sref_system]').val(locationdata[0].centroid_sref_system); // note this will change the 900913 in cc-1 to 4326\n\t\t\t\t\t\t\tjQuery('input[name=location\\:centroid_geom]').val(locationdata[0].centroid_geom);\n\t\t\t\t\t\t\tvar parts=locationdata[0].centroid_sref.split(' ');\n\t\t\t\t\t\t\tvar refx = parts[0].split(',');\n\t\t\t\t\t\t\tjQuery('input[name=place\\:lat]').val(refx[0]);\n\t\t\t\t\t\t\tjQuery('input[name=place\\:long]').val(parts[1]);\n  \t\t\t\t\t\t}\n  \t\t\t\t\t\tpreloadIDs.location_loaded=true;\n\t\t\t\t\t  } else {\n\t\t\t\t\t\talertIndiciaError({error : \"" . lang::get('Internal Error 18: could not load data for location ') . "\"+data[i].location_id});\n\t\t\t\t\t  }});\n\t\t\tbreak;\n\t\tcase 2: // just finished the collection attributes and the location.\n\t\t\tif(preloadIDs.location_loaded==false)\n\t\t\t\treturn alertIndiciaError({error : \"" . lang::get('Internal Error 19: could not load data for location ') . "\"+preloadIDs.location_id});\n\t\t\tif(jQuery('[name=smpAttr\\:" . $args['protocol_attr_id'] . "]').length > 0)\n\t\t\t\treturn alertIndiciaError({error : \"" . lang::get('Internal Error 20: could not load attributes for sample ') . "\"+preloadIDs.sample_id});\n\t\t\t\$('#cc-1').foldPanel();\n\t\t\tcheckProtocolStatus(true);\n\t\t\t\$('#cc-2').showPanel();\n\t\t\tsetPreloadStage(3);\n\t\t\t// now load floral station stuff.\n\t\t\tloadAttributes('#cc-2-floral-station', 'location_attribute_value', 'location_attribute_id', 'location_id', preloadIDs.location_id, 'locAttr', false, false);\n\t\t\tloadImage('location_image', 'location_id', 'location\\:id', preloadIDs.location_id, '#cc-2-environment-image', " . $args['Environment_Image_Ratio'] . ", false);\n\t\t\tjQuery.getJSON(\"" . $svcUrl . "/data/occurrence/\" +\n          \t\t\t\t\t\"?mode=json&view=detail&nonce=" . $readAuth['nonce'] . "&auth_token=" . $readAuth['auth_token'] . "\" +\n          \t\t\t\t\t\"&sample_id=\"+preloadIDs.sample_id+\"&deleted=f&callback=?\", \n\t\t\t\t\tfunction(flowerData) {\n          \t\t\t  // there will only be an occurrence if the floral station panel has previously been displayed & validated. \n\t\t    \t\t  if(!(flowerData instanceof Array)){\n\t\t\t\t\t\talertIndiciaError(flowerData);\n\t\t\t\t\t  } else if (flowerData.length>0) { // do we need another >1 check as well?\n\t\t\t\t\t\tpreloadIDs.flower_id = flowerData[0].id;\n\t\t\t\t\t\tjQuery('form#cc-2-floral-station > input[name=occurrence\\:sample_id]').val(preloadIDs.sample_id);\n\t\t\t\t\t\tjQuery('form#cc-2-floral-station > input[name=occurrence\\:id]').val(flowerData[0].id).removeAttr('disabled');\n    \t   \t\t\t  }});\n\t\t\tbreak;\n\t\tcase 3: // just finished the location attributes, location image and flower.\n\t\t\t// all must be present or none at all: but location_attributes are all optional.\n\t\t\tif(typeof preloadIDs.flower_id == 'undefined' &&\n\t\t\t\t\tjQuery('[name=location_image\\:id]').val() == '') {\n\t\t\t\t\$('.loading-panel').remove();\n\t\t\t\t\$('.poll-loading-hide').show();\n\t\t\t\tbuildMap();\n\t\t\t\tpreloading=false;\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif(typeof preloadIDs.flower_id == 'undefined')\n\t\t\t\treturn alertIndiciaError({error : \"" . lang::get('Internal Error 21: could not load flower data for collection ') . "\"+preloadIDs.sample_id});\n\t\t\tif(jQuery('[name=location_image\\:id]').val() == '')\n\t\t\t\treturn alertIndiciaError({error : \"" . lang::get('Internal Error 23: could not load environment image for location ') . "\"+preloadIDs.location_id});\n\t\t\tsetPreloadStage(4);\n\t\t\tloadAttributes('#cc-2-floral-station', 'occurrence_attribute_value', 'occurrence_attribute_id', 'occurrence_id', preloadIDs.flower_id, 'occAttr', false, true);\n\t\t\tloadImage('occurrence_image', 'occurrence_id', 'occurrence\\:id', preloadIDs.flower_id, '#cc-2-flower-image', " . $args['Flower_Image_Ratio'] . ", true);\n\t\t\tjQuery.getJSON(\"" . $svcUrl . "/data/determination\" + \n\t\t\t\t\t\"?mode=json&view=list&nonce=" . $readAuth['nonce'] . "&auth_token=" . $readAuth['auth_token'] . "&occurrence_id=\"+preloadIDs.flower_id+\"&orderby=id&deleted=f&callback=?\", \n\t\t\t\tfunction(detData) {\n\t\t\t\t\tif(!(detData instanceof Array)){\n   \t\t\t\t\t\talertIndiciaError(detData);\n   \t\t\t\t\t } else loadFlowerDetermination(detData, flowerIDstruc);\n  \t\t\t\t});\n\t\t\tbreak;\n\t\tcase 4: // just finished the flower attributes, flower image and optional flower determination. Attrs and image mandatory at this point.\n\t\t\tif(jQuery('#cc-2-floral-station > input[name=occurrence_image\\:id]').val() == '')\n\t\t\t\treturn alertIndiciaError({error : \"" . lang::get('Internal Error 24: could not load image for flower ') . "\"+preloadIDs.flower_id});\n\t\t\tif(jQuery('[name=occAttr\\:" . $args['flower_type_attr_id'] . "]').length>0)\n\t\t\t\treturn alertIndiciaError({error : \"" . lang::get('Internal Error 25: could not load attributes for flower ') . "\"+preloadIDs.flower_id});\n\t\t\tsetPreloadStage(5);\n\t\t\tjQuery('#cc-2').foldPanel();\n\t\t\tjQuery('#cc-3').showPanel();\n\t\t\tjQuery.getJSON(\"" . $svcUrl . "/data/sample\" + \n\t\t\t\t\t\"?mode=json&view=detail&nonce=" . $readAuth['nonce'] . "&auth_token=" . $readAuth['auth_token'] . "&parent_id=\"+preloadIDs.sample_id+\"&callback=?\", \n\t\t\t\tfunction(sessiondata) {\n\t\t\t\t\tif(!(sessiondata instanceof Array)){\n\t\t\t\t\t\talertIndiciaError(sessiondata);\n\t\t\t\t\t} else if (sessiondata.length>0) { // may have zero sessions\n\t\t\t\t\t\tsessionCounter = 0;\n\t\t\t\t\t\tjQuery('#cc-3-body').empty();\n\t\t\t\t\t\tfor (var i=0;i<sessiondata.length;i++){\n\t\t\t\t\t\t\tvar thisSession = addSession();\n\t\t\t\t\t\t\tpreloadIDs.sessions.push({id : sessiondata[i].id, div : thisSession});\n\t\t\t\t\t\t\tjQuery('input[name=sample\\:id]', thisSession).val(sessiondata[i].id).removeAttr('disabled');\n\t\t\t\t\t\t\tjQuery('input[name=sample\\:date]', thisSession).val(sessiondata[i].date_start);\n\t\t\t\t\t\t\tjQuery('input[name=dummy_date]', thisSession).datepicker('disable').datepicker('setDate', new Date(convertDate(sessiondata[i].date_start))).datepicker('enable');\n\t\t\t\t\t\t\t// fold this session.\n\t\t\t\t\t\t\tthisSession.show();\n\t\t\t\t\t\t\tthisSession.children(':first').show().children().show();\n\t\t\t\t\t\t\tthisSession.children().not(':first').hide();\n\t\t\t\t\t\t}\n\t\t\t\t\t\tpopulateSessionSelect();\n\t\t\t\t\t}});\n\t\t\tbreak;\n\t\tcase 5: // just finished the sessions. no error situations\n\t\t\tif(preloadIDs.sessions.length == 0){\n\t\t\t\t\$('.loading-panel').remove();\n\t\t\t\t\$('.poll-loading-hide').show();\n\t\t\t\tpreloading=false;\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tsetPreloadStage(6);\n\t\t\t\$('#cc-3').foldPanel();\n\t\t\t\$('#cc-4').showPanel();\n\t\t\tpopulateSessionSelect();\n\t\t\tvar sessionIDs = [];\n\t\t\tfor (var i=0;i<preloadIDs.sessions.length;i++){\n\t\t\t\tloadAttributes(preloadIDs.sessions[i].div, 'sample_attribute_value', 'sample_attribute_id', 'sample_id', preloadIDs.sessions[i].id, 'smpAttr', false, true);\n\t\t\t\tsessionIDs.push(preloadIDs.sessions[i].id);\n\t\t\t}\n\t\t\t\$.getJSON(\"" . $svcUrl . "/data/occurrence/\" +\n\t\t\t\t\t\t\"?mode=json&view=detail&nonce=" . $readAuth['nonce'] . "&auth_token=" . $readAuth['auth_token'] . "&orderby=id\" +\n\t\t\t\t\t\t\"&deleted=f&callback=?&query=\"+escape(escape(JSON.stringify({'in': {'sample_id': sessionIDs}}))),\n\t\t\t\tfunction(insectData) {\n\t\t\t\t\tif(!(insectData instanceof Array)) return alertIndiciaError(insectData);\n\t\t\t\t\tif (insectData.length>0)\n\t\t\t\t\t\tfor (var j=0;j<insectData.length;j++)\n\t\t\t\t\t\t\taddExistingToPhotoReel(insectData[j].id);\n\t\t\t});\n\t\t\tbreak;\n\t\tcase 6: // just finished the session attributes and insects.\n\t\t\t// at this point the insects are optional, as are their determinations, so can't check for their presence.\n\t\t\tfor (var i=0;i<preloadIDs.sessions.length;i++){ // check attributes loaded for each session\n\t\t\t\tif(jQuery('[name=smpAttr\\:" . $args['start_time_attr_id'] . "]', preloadIDs.sessions[i].div).length>0)\n\t\t\t\t\treturn alertIndiciaError({error : \"" . lang::get('Internal Error 26: could not load attributes for session ') . "\"+preloadIDs.sessions[i].id});\n\t\t\t}\n\t\t\t\$('.loading-panel').remove();\n\t\t\t\$('.poll-loading-hide').show();\n\t\t\tpreloading=false;\n\t\t\tbreak;\n  }\n});\njQuery.getJSON(\"" . $svcUrl . "\" + \"/report/requestReport?report=reports_for_prebuilt_forms/poll_my_collections.xml&reportSource=local&mode=json\" +\n\t\t\t\"&auth_token=" . $readAuth['auth_token'] . "&reset_timeout=true&nonce=" . $readAuth["nonce"] . "\" + \n\t\t\t\"&survey_id=" . $args['survey_id'] . "&userID_attr_id=" . $args['uid_attr_id'] . "&userID=" . $uid . "&complete_attr_id=" . $args['complete_attr_id'] . "&callback=?\", \n\tfunction(data) {\n\tif(!(data instanceof Array)){\n   \t\talertIndiciaError(data);\n   \t  } else if (data.length>0) { // could have zero length\n\t\tvar i;\n       \tfor ( i=0;i<data.length;i++) {\n       \t\tif(data[i].completed == '0'){\n       \t\t\tjQuery('#cc-1-collection-details,#cc-1-delete-collection,#cc-2').find('[name=sample\\:id]').val(data[i].id).removeAttr('disabled');\n\t\t    \tjQuery('[name=location\\:id],[name=sample\\:location_id]').val(data[i].location_id).removeAttr('disabled');\n       \t\t\tjQuery('#cc-6-consult-collection').attr('href', '" . url('node/' . $args['gallery_node']) . "'+'?collection_id='+data[i].id);\n       \t\t\tpreloadIDs.sample_id = data[i].id;\n       \t\t\tpreloadIDs.location_id = data[i].location_id;\n\t\t\t\t// only use the first one which is not complete..\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n      }\n    });\n  ";
        // because of the use of getJson to retrieve the data - which is asynchronous, the use of the normal loading_block_end
        // is not practical - it will do its stuff before the data is loaded, defeating the purpose. Also it uses hide (display:none)
        // which is a no-no in relation to the map. This means we have to dispense with the slow fade in.
        // it is also complicated by the attibutes and images being loaded asynchronously - and non-linearly.
        // Do the best we can!
        //    data_entry_helper::$onload_javascript = "jQuery('.my-loading-hide').addClass('loading-hide').removeClass('my-loading-hide');\n".data_entry_helper::$onload_javascript."\nbuildMap();";
        data_entry_helper::$onload_javascript .= "\nbuildMap();";
        return $r;
    }
Ejemplo n.º 18
0
 /**
  * Return the generated form output.
  * @return Form HTML.
  */
 public static function get_form($args)
 {
     require_once drupal_get_path('module', 'iform') . '/client_helpers/map_helper.php';
     $hidden = str_replace("\r\n", "\n", $args['hide_fields']);
     $hidden = explode("\n", $hidden);
     if (empty($_GET['occurrence_id'])) {
         return 'This form requires an occurrence_id parameter in the URL.';
     }
     // Get authorisation tokens to update and read from the Warehouse.
     $auth = data_entry_helper::get_read_auth($args['website_id'], $args['password']);
     data_entry_helper::load_existing_record($auth, 'occurrence', $_GET['occurrence_id']);
     data_entry_helper::load_existing_record($auth, 'sample', data_entry_helper::$entity_to_load['occurrence:sample_id']);
     $r .= "<div id=\"controls\">\n";
     $r .= "<table>\n";
     if (!in_array('Species', $hidden)) {
         $r .= "<tr><td><strong>" . lang::get('Species') . "</strong></td><td>" . data_entry_helper::$entity_to_load['occurrence:taxon'] . "</td></tr>\n";
     }
     if (!in_array('Date', $hidden)) {
         $r .= "<tr><td><strong>Date</strong></td><td>" . data_entry_helper::$entity_to_load['sample:date'] . "</td></tr>\n";
     }
     if (!in_array('Grid Reference', $hidden)) {
         $r .= "<tr><td><strong>Grid Reference</strong></td><td>" . data_entry_helper::$entity_to_load['sample:entered_sref'] . "</td></tr>\n";
     }
     $siteLabels = array();
     if (!empty(data_entry_helper::$entity_to_load['sample:location'])) {
         $siteLabels[] = data_entry_helper::$entity_to_load['sample:location'];
     }
     if (!empty(data_entry_helper::$entity_to_load['sample:location_name'])) {
         $siteLabels[] = data_entry_helper::$entity_to_load['sample:location_name'];
     }
     if (!in_array('Site', $hidden) && !empty($siteLabels)) {
         $r .= "<tr><td><strong>Site</strong></td><td>" . implode(' | ', $siteLabels) . "</td></tr>\n";
     }
     $smpAttrs = data_entry_helper::getAttributes(array('id' => data_entry_helper::$entity_to_load['sample:id'], 'valuetable' => 'sample_attribute_value', 'attrtable' => 'sample_attribute', 'key' => 'sample_id', 'extraParams' => $auth, 'survey_id' => data_entry_helper::$entity_to_load['occurrence:survey_id']));
     $occAttrs = data_entry_helper::getAttributes(array('id' => $_GET['occurrence_id'], 'valuetable' => 'occurrence_attribute_value', 'attrtable' => 'occurrence_attribute', 'key' => 'occurrence_id', 'extraParams' => $auth, 'survey_id' => data_entry_helper::$entity_to_load['occurrence:survey_id']));
     $attributes = array_merge($smpAttrs, $occAttrs);
     foreach ($attributes as $attr) {
         if (!in_array($attr['caption'], $hidden)) {
             $r .= "<tr><td><strong>" . lang::get($attr['caption']) . "</strong></td><td>" . $attr['displayValue'] . "</td></tr>\n";
         }
     }
     $r .= "</table>\n";
     $r .= "</div>\n";
     $options = iform_map_get_map_options($args, $readAuth);
     $olOptions = iform_map_get_ol_options($args);
     $options['initialFeatureWkt'] = data_entry_helper::$entity_to_load['occurrence:wkt'];
     $r .= map_helper::map_panel($options, $olOptions);
     return $r;
 }
Ejemplo n.º 19
0
function iform_mnhnl_locModTool($auth, $args, $node)
{
    global $indicia_templates;
    if (!isset($args['clientSideValidation']) || $args['clientSideValidation']) {
        data_entry_helper::enable_validation('entry_form');
    }
    if ($args['locationMode'] == 'multi') {
        $args['locationMode'] = 'parent';
    }
    data_entry_helper::$entity_to_load = array();
    $retVal = "<div id=\"locations\">";
    if ($args['shpFileDownloadURL'] != "") {
        $request = $args['shpFileDownloadURL'] . "/geoserver/wfs?request=GetFeature&service=wfs&version=1.0.0&outputformat=SHAPE-ZIP&srsName=EPSG:2169";
        if ($args['LocationTypeTerm'] == '' && isset($args['loctoolsLocTypeID'])) {
            $args['LocationTypeTerm'] = $args['loctoolsLocTypeID'];
        }
        $primary = iform_mnhnl_getTermID($auth, 'indicia:location_types', $args['LocationTypeTerm']);
        $request .= "&cql_filter=website_id=" . $args['website_id'] . " AND ";
        if ($args['SecondaryLocationTypeTerm'] != '') {
            $secondary = iform_mnhnl_getTermID($auth, 'indicia:location_types', $args['SecondaryLocationTypeTerm']);
            $request .= "(type_id=" . $primary . "OR type_id=" . $secondary . ")";
        } else {
            $request .= "type_id=" . $primary;
        }
        $request .= "&typename=" . $args['shpFileFeaturePrefix'] . ':';
        $filedetails = "&format_options=filename:" . $args['reportFilenamePrefix'];
        $retValList = "";
        if ($args['usePoints'] != 'none' || isset($args['shpDownloadPoints']) && $args['shpDownloadPoints']) {
            $retValList .= "<a href=\"" . $request . "point_locations" . $filedetails . "_Points.zip\">" . lang::get('Points') . "</a>";
        }
        if ($args['useLines'] != 'none' || isset($args['shpDownloadLines']) && $args['shpDownloadLines']) {
            $retValList .= ($retValList == "" ? "" : " : ") . "<a href=\"" . $request . "line_locations" . $filedetails . "_Lines.zip\">" . lang::get('Lines') . "</a>";
        }
        if ($args['usePolygons'] != 'none' || isset($args['shpDownloadPolygons']) && $args['shpDownloadPolygons']) {
            $retValList .= ($retValList == "" ? "" : " : ") . "<a href=\"" . $request . "polygon_locations" . $filedetails . "_Polygons.zip\">" . lang::get('Polygons') . "</a>";
        }
        $retVal .= "<fieldset><legend>" . lang::get('LANG_SHP_Download_Legend') . "</legend>\n      <p>" . lang::get('LANG_Shapefile_Download') . " " . $retValList . "</p></fieldset>";
    }
    $includeOutsideSquare = $args['locationMode'] == 'parent';
    // includes multi - see above
    // filtered
    if ($args['locationMode'] == 'filtered') {
        $filterAttrs = explode(',', $args['filterAttrs']);
        foreach ($filterAttrs as $idx => $filterAttr) {
            $filterAttr = explode(':', $filterAttr);
            if ($filterAttr[0] == 'Parent' && $filterAttr[1] == "true") {
                $includeOutsideSquare = true;
            }
        }
    }
    if ($includeOutsideSquare) {
        $confirmedLocationTypeID = iform_mnhnl_getTermID($auth, 'indicia:location_types', $args['SecondaryLocationTypeTerm']);
        if (is_null($confirmedLocationTypeID)) {
            $confirmedLocationTypeID = "0";
        }
        $submittedLocationTypeID = iform_mnhnl_getTermID($auth, 'indicia:location_types', $args['LocationTypeTerm']);
        $retVal .= "<fieldset><legend>" . lang::get('LANG_Outside_Square_Reports') . "</legend>\n  \t<form method='post' action='" . data_entry_helper::$base_url . '/index.php/services/report/requestReport?report=reports_for_prebuilt_forms/MNHNL/luxbio_outside_squares_1.xml&reportSource=local&auth_token=' . $auth['read']['auth_token'] . '&nonce=' . $auth['read']['nonce'] . '&mode=csv&filename=' . $args['reportFilenamePrefix'] . "CentreOutsideSquaresReport'>\n      <label style='width:auto;'>" . lang::get('LANG_Outside_Square_Download_1') . ":</label>\n      <input type='hidden' name='params' value='{\"website_id\":" . $args['website_id'] . ", \"survey_id\":" . $args['survey_id'] . ", \"primary_loc_type_id\":" . $submittedLocationTypeID . ", \"secondary_loc_type_id\":" . $confirmedLocationTypeID . "}' />\n      <input type='submit' class='ui-state-default ui-corner-all' value='" . lang::get('Download') . "'>\n    </form>\n  \t<form method='post' action='" . data_entry_helper::$base_url . '/index.php/services/report/requestReport?report=reports_for_prebuilt_forms/MNHNL/luxbio_outside_squares_2.xml&reportSource=local&auth_token=' . $auth['read']['auth_token'] . '&nonce=' . $auth['read']['nonce'] . '&mode=csv&filename=' . $args['reportFilenamePrefix'] . "BoundaryCutsSquaresReport'>\n      <label style='width:auto;'>" . lang::get('LANG_Outside_Square_Download_2') . ":</label>\n      <input type='hidden' name='params' value='{\"website_id\":" . $args['website_id'] . ", \"survey_id\":" . $args['survey_id'] . ", \"primary_loc_type_id\":" . $submittedLocationTypeID . ", \"secondary_loc_type_id\":" . $confirmedLocationTypeID . "}' />\n      <input type='submit' class='ui-state-default ui-corner-all' value='" . lang::get('Download') . "'>\n    </form>\n    </fieldset>";
    }
    $retVal .= "<form method=\"post\" id=\"entry_form\">" . $auth['write'] . "<input type=\"hidden\" id=\"source\" name=\"source\" value=\"iform_mnhnl_locModTool\" />" . "<input type=\"hidden\" id=\"website_id\" name=\"website_id\" value=\"" . $args['website_id'] . "\" />" . "<input type=\"hidden\" id=\"survey_id\" name=\"survey_id\" value=\"" . $args['survey_id'] . "\" />";
    $retVal .= iform_mnhnl_lux5kgridControl($auth, $args, $node, array('Instructions2' => lang::get('LANG_LocModTool_Instructions2'), 'MainFieldLabel' => lang::get('LANG_LocModTool_IDLabel'), 'NameLabel' => lang::get('LANG_LocModTool_NameLabel'), 'ParentLabel' => lang::get('LANG_LocModTool_ParentLabel'), 'AdminMode' => true));
    $retVal .= "<label for=\"location-delete\">" . lang::get("LANG_LocModTool_DeleteLabel") . ":</label> <input type=checkbox id=\"location-delete\" name=\"location:deleted\" value='t'><br />\n  <p>" . lang::get("LANG_LocModTool_DeleteInstructions") . "</p>";
    // location comments are included as a separate control on the main form.
    if (isset($args['includeLocationComment']) && $args['includeLocationComment']) {
        $retVal .= data_entry_helper::textarea(array('id' => 'location-comment', 'fieldname' => 'location:comment', 'label' => lang::get("LANG_LocationModTool_CommentLabel"))) . "<br />";
    }
    $laArgs = array("lookUpKey" => "meaning_id", "sep" => " ", "class" => "wide", "tabNameFilter" => "", "numValues" => 10000);
    $defs = array();
    if (isset($args['siteTabSplitAttrs']) && $args['siteTabSplitAttrs'] != "") {
        $defs = explode(':', $args['siteTabSplitAttrs']);
        $defs1 = explode(',', $defs[0]);
        $laArgs["tabNameFilter"] = $defs1[0];
        $laArgs["class"] = $defs1[1];
    }
    $retVal .= iform_mnhnl_locationattributes($auth, $args, '', $laArgs);
    $retVal .= iform_mnhnl_SrefFields($auth, $args, true);
    if (count($defs) > 1) {
        $defs1 = explode(',', $defs[1]);
        $laArgs["tabNameFilter"] = $defs1[0];
        $laArgs["class"] = $defs1[1];
        $retVal .= iform_mnhnl_locationattributes($auth, $args, '', $laArgs);
    }
    $args['interface'] = 'Tabs';
    $mapOptions = iform_map_get_map_options($args, $auth['read']);
    $olOptions = iform_map_get_ol_options($args);
    if ($args['locationMode'] != 'parent') {
        // this includes multi as well (see above)
        // can't call the protested control function
        $georefOpts = iform_map_get_georef_options($args, $auth['read']);
        // can't use place search without the driver API key
        if ($georefOpts['driver'] == 'geoplanet' && empty(helper_config::$geoplanet_api_key)) {
            $retVal .= '<p>The form structure includes a [place search] control but needs a geoplanet api key.</p>';
        } else {
            $retVal .= data_entry_helper::georeference_lookup($georefOpts);
        }
        $mapOptions['searchLayer'] = true;
        $mapOptions['searchUpdatesSref'] = false;
        $mapOptions['searchDisplaysPoint'] = false;
    }
    // For main page we force to Tabs to ensure map drawn correctly
    $mapOptions['tabDiv'] = 'locations';
    $mapOptions['standardControls'] = array('layerSwitcher', 'panZoomBar');
    $mapOptions['editLayer'] = false;
    $mapOptions['maxZoom'] = $args['zoomLevel'];
    if (isset($args['locationLayerWMS']) && $args['locationLayerWMS'] != '') {
        $mapOptions['layers'] = array('ParentWMSLayer', "ParentLocationLayer", "SiteLabelLayer", "SiteAreaLayer", "SitePathLayer", "SitePointLayer");
        $mapOptions['clickableLayers'] = array('ParentWMSLayer');
        $mapOptions['clickableLayersOutputMode'] = 'custom';
        $mapOptions['clickableLayersOutputDiv'] = 'clickableLayersOutputDiv';
        $mapOptions['clickableLayersOutputFn'] = 'setClickedParent';
    } else {
        $mapOptions['layers'] = array("ParentLocationLayer", "SiteLabelLayer", "SiteAreaLayer", "SitePathLayer", "SitePointLayer");
    }
    $retVal .= data_entry_helper::map_panel($mapOptions, $olOptions);
    $retVal .= iform_mnhnl_PointGrid($auth, $args, array('srefs' => '2169,LUREF (m),X,Y,;4326,Lat/Long Deg,Lat,Long,D;4326,Lat/Long Deg:Min,Lat,Long,DM;4326,Lat/Long Deg:Min:Sec,Lat,Long,DMS'));
    $retVal .= '    <input type="submit" class="ui-state-default ui-corner-all" value="' . lang::get('LANG_Submit') . '">
    <a href="' . iform_mnhnl_getReloadPath() . '"><input class="ui-state-default ui-corner-all" type="button" name="cancel" value="' . lang::get('LANG_Cancel') . '" /></a>
    </form></div>';
    data_entry_helper::$javascript .= "\nmapInitialisationHooks.push(function(mapdiv) {\n// try to identify if this map is the secondary small one\n  if(mapdiv.id=='map')\n    jQuery(\"#dummy-parent-id\").val('').change();});\n";
    return $retVal;
}
Ejemplo n.º 20
0
 /**
  * Return the generated form output.
  * @return Form HTML.
  */
 public static function get_form($args, $node)
 {
     global $user;
     $logged_in = $user->uid > 0;
     $r = '';
     // Get authorisation tokens to update and read from the Warehouse.
     $writeAuth = data_entry_helper::get_auth($args['website_id'], $args['password']);
     $readAuth = data_entry_helper::get_read_auth($args['website_id'], $args['password']);
     $svcUrl = data_entry_helper::$base_url . '/index.php/services';
     $mode = 0;
     // default mode : display survey selector
     // mode 1: display new sample
     // mode 2: display existing sample
     $loadID = null;
     $displayThisOcc = true;
     // when populating from the DB rather than POST we have to be
     // careful with selection object, as geom in wrong format.
     if ($_POST) {
         if (!is_null(data_entry_helper::$entity_to_load)) {
             $mode = 2;
             // errors with new sample, entity poulated with post, so display this data.
         }
         // else valid save, so go back to gridview: default mode 0
     } else {
         if (array_key_exists('sample_id', $_GET)) {
             $mode = 2;
             $loadID = $_GET['sample_id'];
         } else {
             if (array_key_exists('newSample', $_GET)) {
                 $mode = 1;
                 data_entry_helper::$entity_to_load = array();
             }
         }
         // else default to mode 0
     }
     ///////////////////////////////////////////////////////////////////
     // default mode 0 : display survey selector
     ///////////////////////////////////////////////////////////////////
     if ($mode == 0) {
         // Create the Sample list datagrid for this user.
         drupal_add_js(drupal_get_path('module', 'iform') . '/media/js/hasharray.js', 'module');
         drupal_add_js(drupal_get_path('module', 'iform') . '/media/js/jquery.datagrid.js', 'module');
         drupal_add_js("jQuery(document).ready(function(){\n  \$('div#smp_grid').indiciaDataGrid('rpt:mnhnl_collab_list_samples', {\n    indiciaSvc: '" . $svcUrl . "',\n    dataColumns: ['location_name', 'entered_sref', 'date', 'num_occurrences', 'completed'],\n    reportColumnTitles: {location_name : '" . lang::get('LANG_Location') . "', entered_sref : '" . lang::get('LANG_Spatial_ref') . "', date : '" . lang::get('LANG_Date') . "', num_occurrences : '" . lang::get('LANG_Num_Occurrences') . "', completed : '" . lang::get('LANG_Completed') . "'},\n    actionColumns: {" . lang::get('LANG_Edit') . " : \"" . url('node/' . $node->nid, array('query' => 'sample_id=�id�')) . "\"},\n    auth : { nonce : '" . $readAuth['nonce'] . "', auth_token : '" . $readAuth['auth_token'] . "'},\n    parameters : {\n    \t\t\tsurvey_id : '" . $args['survey_id'] . "',\n    \t\t\tuserID_attr_id : '" . $args['uid_attr_id'] . "',\n    \t\t\tuserID : '" . $user->uid . "'\n    \t\t\t\t},\n    itemsPerPage : 12 \n  });\n});\n\n", 'inline');
         $r .= '<div id="sampleList" class="mnhnl-btw-datapanel"><div id="smp_grid"></div>';
         $r .= '<form><input type="button" value="' . lang::get('LANG_Add_Sample') . '" onclick="window.location.href=\'' . url('node/' . $node->nid, array('query' => 'newSample')) . '\'"></form></div>';
         $r .= "</div>\n";
         return $r;
     }
     ///////////////////////////////////////////////////////////////////
     data_entry_helper::$javascript .= "\n// Create vector layers: one to display the location onto, and another for the occurrence list\n// the default edit layer is used for the occurrences themselves\nlocStyleMap = new OpenLayers.StyleMap({\n                \"default\": new OpenLayers.Style({\n                    fillColor: \"Green\",\n                    strokeColor: \"Black\",\n                    fillOpacity: 0.3,\n                    strokeWidth: 1\n                  })\n  });\nlocationLayer = new OpenLayers.Layer.Vector(\"" . lang::get("LANG_Location_Layer") . "\",\n                                    {styleMap: locStyleMap});\n";
     if ($loadID) {
         // Can't cache these as data may have just changed
         data_entry_helper::$entity_to_load['occurrence:record_status'] = 'I';
         $url = $svcUrl . '/data/sample/' . $loadID;
         $url .= "?mode=json&view=detail&auth_token=" . $readAuth['auth_token'] . "&nonce=" . $readAuth["nonce"];
         $session = curl_init($url);
         curl_setopt($session, CURLOPT_RETURNTRANSFER, true);
         $entity = json_decode(curl_exec($session), true);
         // Attributes should be loaded by get_attributes.
         data_entry_helper::$entity_to_load = array();
         foreach ($entity[0] as $key => $value) {
             data_entry_helper::$entity_to_load['sample:' . $key] = $value;
         }
         $url = $svcUrl . '/data/occurrence';
         $url .= "?mode=json&view=detail&auth_token=" . $readAuth['auth_token'] . "&nonce=" . $readAuth["nonce"] . "&sample_id=" . $loadID . "&deleted=FALSE";
         $session = curl_init($url);
         curl_setopt($session, CURLOPT_RETURNTRANSFER, true);
         $entities = json_decode(curl_exec($session), true);
         foreach ($entities as $entity) {
             data_entry_helper::$entity_to_load['occurrence:record_status'] = $entity['record_status'];
             data_entry_helper::$entity_to_load['sc:' . $entity['taxa_taxon_list_id'] . ':' . $entity['id'] . ':present'] = true;
         }
         data_entry_helper::$entity_to_load['sample:geom'] = '';
         // value received from db is not WKT, which is assumed by all the code.
         data_entry_helper::$entity_to_load['sample:date'] = data_entry_helper::$entity_to_load['sample:date_start'];
         // bit of a bodge to get around vague dates.
     }
     $defAttrOptions = array('extraParams' => $readAuth);
     //    $r .= "<h1>MODE = ".$mode."</h1>";
     //    $r .= "<h2>readOnly = ".$readOnly."</h2>";
     $r = "<form method=\"post\" id=\"entry_form\">\n";
     // Get authorisation tokens to update and read from the Warehouse.
     $r .= $writeAuth;
     $r .= "<input type=\"hidden\" id=\"website_id\" name=\"website_id\" value=\"" . $args['website_id'] . "\" />\n";
     $r .= "<input type=\"hidden\" id=\"sample:survey_id\" name=\"sample:survey_id\" value=\"" . $args['survey_id'] . "\" />\n";
     if (array_key_exists('sample:id', data_entry_helper::$entity_to_load)) {
         $r .= "<input type=\"hidden\" id=\"sample:id\" name=\"sample:id\" value=\"" . data_entry_helper::$entity_to_load['sample:id'] . "\" />\n";
     }
     // request automatic JS validation
     data_entry_helper::enable_validation('entry_form');
     $attributes = data_entry_helper::getAttributes(array('id' => data_entry_helper::$entity_to_load['sample:id'], 'valuetable' => 'sample_attribute_value', 'attrtable' => 'sample_attribute', 'key' => 'sample_id', 'fieldprefix' => 'smpAttr', 'extraParams' => $readAuth, 'survey_id' => $args['survey_id']));
     if ($logged_in) {
         // If logged in, output some hidden data about the user
         $uid = $user->uid;
         $email = $user->mail;
         $username = $user->name;
         $uid_attr_id = $args['uid_attr_id'];
         $email_attr_id = $args['email_attr_id'];
         $username_attr_id = $args['username_attr_id'];
         // This assumes that we have the following attributes : no built in error checking.
         $r .= "<input type=\"hidden\" name=\"" . $attributes[$uid_attr_id]['fieldname'] . "\" value=\"{$uid}\" />\n";
         $r .= "<input type=\"hidden\" name=\"" . $attributes[$email_attr_id]['fieldname'] . "\" value=\"{$email}\" />\n";
         $r .= "<input type=\"hidden\" name=\"" . $attributes[$username_attr_id]['fieldname'] . "\" value=\"{$username}\" />\n";
     }
     $r .= "<div id=\"controls\">\n";
     if ($args['interface'] != 'one_page') {
         $r .= "<ul>\n";
         if (!$logged_in) {
             $r .= '  <li><a href="#about_you"><span>' . lang::get('LANG_About_You_Tab') . "</span></a></li>\n";
         }
         $r .= '  <li><a href="#species"><span>' . lang::get('LANG_Species_Tab') . "</span></a></li>\n";
         $r .= '  <li><a href="#place"><span>' . lang::get('LANG_Place_Tab') . "</span></a></li>\n";
         $r .= '  <li><a href="#other"><span>' . lang::get('LANG_Other_Information_Tab') . "</span></a></li>\n";
         $r .= "</ul>\n";
         data_entry_helper::enable_tabs(array('divId' => 'controls', 'style' => $args['interface']));
     }
     ////////////////////////////////////////////////////////////////////////////////////////////////////////////
     if (!$logged_in) {
         $r .= "<div id=\"about_you\">\n";
         $r .= '<p class="page-notice ui-state-highlight ui-corner-all">' . lang::get('LANG_About_You_Tab_Instructions') . "</p>";
         $defAttrOptions['class'] = 'control-width-4';
         $r .= data_entry_helper::outputAttribute($attributes[$args['first_name_attr_id']], $defAttrOptions);
         $r .= data_entry_helper::outputAttribute($attributes[$args['surname_attr_id']], $defAttrOptions);
         $r .= data_entry_helper::outputAttribute($attributes[$args['email_attr_id']], $defAttrOptions);
         $r .= data_entry_helper::outputAttribute($attributes[$args['phone_attr_id']], $defAttrOptions);
         if ($args['interface'] == 'wizard') {
             $r .= data_entry_helper::wizard_buttons(array('divId' => 'controls', 'page' => 'first'));
         }
         unset($defAttrOptions['class']);
         $r .= "</div>\n";
     }
     ////////////////////////////////////////////////////////////////////////////////////////////////////////////
     global $indicia_templates;
     $indicia_templates['taxon_label'] = '<div class="biota"><span class="nobreak sci binomial"><em>{taxon}</em></span> {authority}</div>';
     $r .= "<div id=\"species\">\n";
     $r .= '<p class="page-notice ui-state-highlight ui-corner-all">' . lang::get('LANG_Species_Tab_Instructions') . "</p>";
     $extraParams = $readAuth + array('taxon_list_id' => $args['list_id']);
     $species_list_args = array('label' => lang::get('occurrence:taxa_taxon_list_id'), 'fieldname' => 'occurrence:taxa_taxon_list_id', 'table' => 'taxa_taxon_list', 'captionField' => 'taxon', 'valueField' => 'id', 'columns' => 1, 'view' => 'detail', 'parentField' => 'parent_id', 'occAttrs' => explode(',', $args['checklist_attributes']), 'extraParams' => $extraParams, 'survey_id' => $args['survey_id']);
     $r .= data_entry_helper::species_checklist($species_list_args);
     $r .= "<label for=\"sample:comment\">" . lang::get('LANG_Sample_Comment_Label') . "</label><input type=\"text\" id=\"sample:comment\" name=\"sample:comment\" value=\"" . data_entry_helper::$entity_to_load['sample:comment'] . "\" />\n";
     if ($args['interface'] == 'wizard') {
         $r .= data_entry_helper::wizard_buttons(array('divId' => 'controls', 'page' => $user->id == 0 ? 'first' : 'middle'));
     }
     $r .= "</div>\n";
     ////////////////////////////////////////////////////////////////////////////////////////////////////////////
     $r .= "<div id=\"place\">\n";
     $r .= '<p class="page-notice ui-state-highlight ui-corner-all">' . lang::get('LANG_Place_Tab_Instructions') . "</p>";
     // Build the array of spatial reference systems into a format Indicia can use.
     $systems = array();
     $list = explode(',', str_replace(' ', '', $args['spatial_systems']));
     foreach ($list as $system) {
         $systems[$system] = lang::get($system);
     }
     $r .= data_entry_helper::sref_and_system(array('label' => lang::get('LANG_SRef_Label'), 'systems' => $systems));
     $location_list_args = array('label' => lang::get('LANG_Location_Label'), 'view' => 'detail', 'extraParams' => array_merge(array('view' => 'detail', 'orderby' => 'name'), $extraParams));
     $r .= call_user_func(array('data_entry_helper', $args['location_ctrl']), $location_list_args);
     $r .= data_entry_helper::georeference_lookup(array('label' => lang::get('LANG_Georef_Label'), 'georefPreferredArea' => $args['georefPreferredArea'], 'georefCountry' => $args['georefCountry'], 'georefLang' => $args['language']));
     $options = iform_map_get_map_options($args, $readAuth);
     $options['layers'][] = 'locationLayer';
     $olOptions = iform_map_get_ol_options($args);
     $r .= data_entry_helper::map_panel($options, $olOptions);
     if ($args['interface'] == 'wizard') {
         $r .= data_entry_helper::wizard_buttons(array('divId' => 'controls'));
     }
     $r .= "</div>\n";
     ////////////////////////////////////////////////////////////////////////////////////////////////////////////
     $r .= "<div id=\"other\">\n";
     $r .= '<p class="page-notice ui-state-highlight ui-corner-all">' . lang::get('LANG_Other_Information_Tab_Instructions') . "</p>";
     $r .= data_entry_helper::date_picker(array('label' => lang::get('LANG_Date'), 'fieldname' => 'sample:date'));
     $r .= data_entry_helper::outputAttribute($attributes[$args['biotope_attr_id']], $defAttrOptions);
     $r .= data_entry_helper::outputAttribute($attributes[$args['voucher_attr_id']], $defAttrOptions);
     $values = array('I', 'C');
     // not initially doing V=Verified
     $r .= '<label for="occurrence:record_status">' . lang::get('LANG_Record_Status_Label') . '</label><select id="occurrence:record_status" name="occurrence:record_status">';
     foreach ($values as $value) {
         $r .= '<option value="' . $value . '"';
         if (isset(data_entry_helper::$entity_to_load['occurrence:record_status'])) {
             if (data_entry_helper::$entity_to_load['occurrence:record_status'] == $value) {
                 $r .= ' selected="selected"';
             }
         }
         $r .= '>' . lang::get('LANG_Record_Status_' . $value) . '</option>';
     }
     $r .= '</select>';
     //  TODO image upload - not sure how to do this as images are attached to occurrences, and occurrences
     //  are embedded in the species list.
     //    $r .= "<label for='occurrence:image'>".lang::get('LANG_Image_Label')."</label>\n".
     //        data_entry_helper::image_upload('occurrence:image');
     $r .= '<br/><br/>';
     if ($args['interface'] == 'wizard') {
         $r .= data_entry_helper::wizard_buttons(array('divId' => 'controls', 'page' => 'last'));
     } else {
         $r .= "<input type=\"submit\" class=\"ui-state-default ui-corner-all\" value=\"" . lang::get('LANG_Save') . "\" />\n";
     }
     $r .= "</div>\n";
     $r .= "</div>\n";
     if (!empty(data_entry_helper::$validation_errors)) {
         $r .= data_entry_helper::dump_remaining_errors();
     }
     $r .= "</form>";
     // may need to keep following code for location change functionality
     data_entry_helper::$onload_javascript .= "\n    \nlocationChange = function(obj){\n\tlocationLayer.destroyFeatures();\n\tif(obj.value != ''){\n\t\tjQuery.getJSON(\"" . $svcUrl . "\" + \"/data/location/\"+obj.value +\n\t\t\t\"?mode=json&view=detail&auth_token=" . $readAuth['auth_token'] . "&nonce=" . $readAuth["nonce"] . "\" +\n\t\t\t\"&callback=?\", function(data) {\n            if (data.length>0) {\n            \tvar parser = new OpenLayers.Format.WKT();\n            \tfor (var i=0;i<data.length;i++)\n\t\t\t\t{\n\t      \t\t\tif(data[i].centroid_geom){\n\t\t\t\t\t\tfeature = parser.read(data[i].centroid_geom);\n\t\t\t\t\t\tcentre = feature.geometry.getCentroid();\n\t\t\t\t\t\tcentrefeature = new OpenLayers.Feature.Vector(centre, {}, {label: data[i].name});\n\t\t\t\t\t\tlocationLayer.addFeatures([feature, centrefeature]); \n\t\t\t\t\t}\n\t\t\t\t\tif(data[i].boundary_geom){\n\t\t\t\t\t\tfeature = parser.read(data[i].boundary_geom);\n\t\t\t\t\t\tfeature.style = {strokeColor: \"Blue\",\n    \t                \tstrokeWidth: 2,\n  \t\t\t\t\t\t\tlabel: (data[i].centroid_geom ? \"\" : data[i].name)};\n\t\t\t\t\t\tlocationLayer.addFeatures([feature]);\n \t\t\t\t\t}\n    \t\t\t\tlocationLayer.map.zoomToExtent(locationLayer.getDataExtent());\n  \t\t\t\t}\n\t\t\t}\n\t\t});\n  }\n};\njQuery('#imp-location').unbind('change');\njQuery('#imp-location').change(function(){\n\tlocationChange(this);\n});\n// upload location & sref initial values into map.\njQuery('#imp-location').change();\njQuery('#imp-sref').change();\n\n";
     return $r;
 }
 protected static function get_your_route_tab($auth, $args, $settings)
 {
     $r = '<div id="your-route" class="ui-helper-clearfix">';
     $olOptions = iform_map_get_ol_options($args);
     $options = iform_map_get_map_options($args, $auth['read']);
     $options['divId'] = 'route-map';
     $options['toolbarDiv'] = 'top';
     $options['tabDiv'] = 'your-route';
     $options['gridRefHint'] = true;
     if ($settings['canEditBody']) {
         $options['toolbarPrefix'] = self::section_selector($settings, 'section-select-route');
         if ($settings['canEditSections'] && count($settings['sections']) > 1 && $settings['numSectionsAttr'] != "") {
             // do not allow deletion of last section, or if the is no section number attribute
             $options['toolbarSuffix'] = '<input type="button" value="' . lang::get('Remove Section') . '" class="remove-section form-button right" title="' . lang::get('Completely remove the highlighted section. The total number of sections will be reduced by one. The form will be reloaded after the section is deleted.') . '">';
         } else {
             $options['toolbarSuffix'] = '';
         }
         $options['toolbarSuffix'] .= '<input type="button" value="' . lang::get('Erase Route') . '" class="erase-route form-button right" title="' . lang::get('If the Draw Line control is active, this will erase each drawn point one at a time. If not active, then this will erase the whole highlighted route. This keeps the Section, allowing you to redraw the route for it.') . '">';
         if ($settings['canEditSections'] && count($settings['sections']) < $args['maxSectionCount'] && $settings['numSectionsAttr'] != "") {
             // do not allow insertion of section if it exceeds max number, or if the is no section number attribute
             $options['toolbarSuffix'] .= '<input type="button" value="' . lang::get('Insert Section') . '" class="insert-section form-button right" title="' . lang::get('This inserts an extra section after the currently selected section. All subsequent sections are renumbered, increasing by one. All associated occurrences are kept with the moved sections. This can be used to facilitate the splitting of this section.') . '">';
         }
         // also let the user click on a feature to select it. The highlighter just makes it easier to select one.
         // these controls are not present in read-only mode: all you can do is look at the map.
         $options['standardControls'][] = 'selectFeature';
         $options['standardControls'][] = 'hoverFeatureHighlight';
         $options['standardControls'][] = 'drawLine';
         $options['standardControls'][] = 'modifyFeature';
         $options['switchOffSrefRetrigger'] = true;
         $help = lang::get('Select a section from the list then click on the map to draw the route and double click to finish. ' . 'You can also select a section using the query tool to click on the section lines. If you make a mistake in the middle ' . 'of drawing a route, then you can use the Erase Route button to remove the last point drawn. After a route has been ' . 'completed use the Modify a feature tool to correct the line shape (either by dragging one of the circles along the ' . 'line to form the correct shape, or by placing the mouse over a circle and pressing the Delete button on your keyboard ' . 'to remove that point). Alternatively you could just redraw the line - this new line will then replace the old one ' . 'completely. If you are not in the middle of drawing a line, the Erase Route button will erase the whole route for the ' . 'currently selected section.') . ($settings['numSectionsAttr'] != "" ? '<br />' . (count($settings['sections']) > 1 ? lang::get('The Remove Section button will remove the section completely, reducing the number of sections by one.') . ' ' : '') . lang::get('To increase the number of sections, return to the Site Details tab, and increase the value in the No. of sections field there.') : '');
         $r .= '<p class="ui-state-highlight page-notice ui-corner-all">' . $help . '</p>';
     }
     $options['clickForSpatialRef'] = false;
     // override the opacity so the parent square does not appear filled in.
     $options['fillOpacity'] = 0;
     // override the map height and buffer size, which are specific to this map.
     $options['height'] = $args['route_map_height'];
     $options['maxZoomBuffer'] = $args['route_map_buffer'];
     $r .= map_helper::map_panel($options, $olOptions);
     if (count($settings['section_attributes']) == 0) {
         $r .= '<button class="indicia-button right" type="button" title="' . lang::get('Returns to My Sites page. Any changes to sections carried out on this page (including creating new ones) are saved to the database as they are done, but changes to the Site Details must be saved using the Save button on that tab.') . '" onclick="window.location.href=\'' . url($args['redirect_on_success']) . '\'">' . lang::get('Return to My Sites') . '</button>';
     }
     $r .= '</div>';
     return $r;
 }
Ejemplo n.º 22
0
    /**
     * Return the generated form output.
     * @return Form HTML.
     */
    public static function get_form($args, $node)
    {
        global $user;
        // There is a language entry in the args parameter list: this is derived from the $language DRUPAL global.
        // It holds the 2 letter code, used to pick the language file from the lang subdirectory of prebuilt_forms.
        // There should be no explicitly output text in this file.
        // We must translate any field names and ensure that the termlists and taxonlists use the correct language.
        // For attributes, the caption is automatically translated by data_entry_helper.
        $logged_in = $user->uid > 0;
        $uid = $user->uid;
        $email = $user->mail;
        $username = $user->name;
        if (!user_access('IForm n' . $node->nid . ' access')) {
            return "<p>" . lang::get('LANG_Insufficient_Privileges') . "</p>";
        }
        $r = '';
        // Get authorisation tokens to update and read from the Warehouse.
        $readAuth = data_entry_helper::get_read_auth($args['website_id'], $args['password']);
        $svcUrl = data_entry_helper::$base_url . '/index.php/services';
        drupal_add_js(drupal_get_path('module', 'iform') . '/media/js/jquery.form.js', 'module');
        data_entry_helper::link_default_stylesheet();
        data_entry_helper::add_resource('jquery_ui');
        data_entry_helper::enable_validation('cc-1-collection-details');
        // don't care about ID itself, just want resources
        if ($args['help_module'] != '' && $args['help_inclusion_function'] != '' && module_exists($args['help_module']) && function_exists($args['help_inclusion_function'])) {
            $use_help = true;
            data_entry_helper::$javascript .= call_user_func($args['help_inclusion_function']);
        } else {
            $use_help = false;
        }
        if ($args['ID_tool_module'] != '' && $args['ID_tool_inclusion_function'] != '' && module_exists($args['ID_tool_module']) && function_exists($args['ID_tool_inclusion_function'])) {
            $use_ID_tool = true;
            data_entry_helper::$javascript .= call_user_func($args['ID_tool_inclusion_function']);
        } else {
            $use_ID_tool = false;
        }
        // The only things that will be editable after the collection is saved will be the identifiaction of the flower/insects.
        // no id - just getting the attributes, rest will be filled in using AJAX
        $sample_attributes = data_entry_helper::getAttributes(array('valuetable' => 'sample_attribute_value', 'attrtable' => 'sample_attribute', 'key' => 'sample_id', 'fieldprefix' => 'smpAttr', 'extraParams' => $readAuth, 'survey_id' => $args['survey_id']));
        $occurrence_attributes = data_entry_helper::getAttributes(array('valuetable' => 'occurrence_attribute_value', 'attrtable' => 'occurrence_attribute', 'key' => 'occurrence_id', 'fieldprefix' => 'occAttr', 'extraParams' => $readAuth, 'survey_id' => $args['survey_id']));
        $location_attributes = data_entry_helper::getAttributes(array('valuetable' => 'location_attribute_value', 'attrtable' => 'location_attribute', 'key' => 'location_id', 'fieldprefix' => 'locAttr', 'extraParams' => $readAuth, 'survey_id' => $args['survey_id']));
        $defAttrOptions = array('extraParams' => $readAuth, 'lookUpListCtrl' => 'radio_group', 'validation' => array('required'), 'language' => iform_lang_iso_639_2($args['language']), 'containerClass' => 'group-control-box', 'suffixTemplate' => 'nosuffix');
        $language = iform_lang_iso_639_2($args['language']);
        global $indicia_templates;
        $indicia_templates['sref_textbox_latlong'] = '<label for="{idLat}">{labelLat}:</label>' . '<input type="text" id="{idLat}" name="{fieldnameLat}" {class} {disabled} value="{default}" />' . '<label for="{idLong}">{labelLong}:</label>' . '<input type="text" id="{idLong}" name="{fieldnameLong}" {class} {disabled} value="{default}" />';
        $r .= data_entry_helper::loading_block_start();
        // note we have to proxy the post. Every time a write transaction is carried out, the write nonce is trashed.
        // For security reasons we don't want to give the user the ability to generate their own nonce, so we use
        // the fact that the user is logged in to drupal as the main authentication/authorisation/identification
        // process for the user. The proxy packages the post into the correct format
        //
        // There are 2 types of submission:
        // When a user validates a panel using the validate button, the following panel is opened on success
        // When a user presses a modify button, the open panel gets validated, and the panel to be modified is opened.
        $r .= '
<div id="cc-1" class="poll-section">
  <div id="cc-1-title" class="ui-accordion-header ui-helper-reset ui-state-active ui-corner-top poll-section-title">
  	<span id="cc-1-title-details">' . lang::get('LANG_Collection_Details') . '</span>
    <div class="right">
      <div>
        <span id="cc-1-reinit-button" class="ui-state-default ui-corner-all reinit-button">' . lang::get('LANG_Reinitialise') . '</span>
        <span id="cc-1-mod-button" class="ui-state-default ui-corner-all mod-button">' . lang::get('LANG_Modify') . '</span>
      </div>
    </div>
  </div>
  <div id="cc-1-details" class="ui-accordion-content ui-helper-reset ui-widget-content ui-accordion-content-active">
    <span id="cc-1-protocol-details"></span>
  </div>
  <div id="cc-1-body" class="ui-accordion-content ui-helper-reset ui-widget-content ui-accordion-content-active poll-section-body">
   <form id="cc-1-collection-details" action="' . iform_ajaxproxy_url($node, 'loc-sample') . '" method="POST">
    <input type="hidden" id="website_id"       name="website_id" value="' . $args['website_id'] . '" />
    <input type="hidden" id="imp-sref"         name="location:centroid_sref"  value="" />
    <input type="hidden" id="imp-geom"         name="location:centroid_geom" value="" />
    <input type="hidden" id="imp-sref-system"  name="location:centroid_sref_system" value="4326" />
    <input type="hidden" id="sample:survey_id" name="sample:survey_id" value="' . $args['survey_id'] . '" />
    ' . iform_pollenators::help_button($use_help, "collection-help-button", $args['help_function'], $args['help_collection_arg']) . '
    <label for="location:name">' . lang::get('LANG_Collection_Name_Label') . '</label>
 	<input type="text" id="location:name"      name="location:name" value="" class="required"/>
    <input type="hidden" id="sample:location_name" name="sample:location_name" value=""/>
 	' . data_entry_helper::outputAttribute($sample_attributes[$args['protocol_attr_id']], $defAttrOptions) . '    <input type="hidden"                       name="sample:date" value="2010-01-01"/>
    <input type="hidden" id="smpAttr:' . $args['complete_attr_id'] . '" name="smpAttr:' . $args['complete_attr_id'] . '" value="0" />
    <input type="hidden" id="smpAttr:' . $args['uid_attr_id'] . '" name="smpAttr:' . $args['uid_attr_id'] . '" value="' . $uid . '" />
    <input type="hidden" id="smpAttr:' . $args['email_attr_id'] . '" name="smpAttr:' . $args['email_attr_id'] . '" value="' . $email . '" />
    <input type="hidden" id="smpAttr:' . $args['username_attr_id'] . '" name="smpAttr:' . $args['username_attr_id'] . '" value="' . $username . '" />  
    <input type="hidden" id="locations_website:website_id" name="locations_website:website_id" value="' . $args['website_id'] . '" />
    <input type="hidden" id="location:id"      name="location:id" value="" disabled="disabled" />
    <input type="hidden" id="sample:id"        name="sample:id" value="" disabled="disabled" />
    </form>
    <div id="cc-1-valid-button" class="ui-state-default ui-corner-all save-button">' . lang::get('LANG_Validate') . '</div>
  </div>  
<div style="display:none" />
    <form id="cc-1-delete-collection" action="' . iform_ajaxproxy_url($node, 'sample') . '" method="POST">
       <input type="hidden" name="website_id" value="' . $args['website_id'] . '" />
       <input type="hidden" name="sample:survey_id" value="' . $args['survey_id'] . '" />
       <input type="hidden" name="sample:id" value="" />
       <input type="hidden" name="sample:date" value="2010-01-01"/>
       <input type="hidden" name="sample:location_id" value="" />
       <input type="hidden" name="sample:deleted" value="t" />
    </form>
</div>
  <div id="cc-1-main-body" class="ui-accordion-content ui-helper-reset ui-widget-content ui-corner-bottom ui-accordion-content-active">
';
        data_entry_helper::$javascript .= "\n\$.validator.messages.required = \"" . lang::get('validation_required') . "\";\nvar sessionCounter = 0;\n\n\$.fn.foldPanel = function(){\n\tthis.children('.poll-section-body').addClass('poll-hide');\n\tthis.children('.poll-section-footer').addClass('poll-hide');\n\tthis.children('.poll-section-title').find('.reinit-button').show();\n\tthis.children('.poll-section-title').find('.mod-button').show();\n\tthis.children('.photoReelContainer').addClass('ui-corner-all').removeClass('ui-corner-top')\n};\n\n\$.fn.unFoldPanel = function(){\n\tthis.children('.poll-section-body').removeClass('poll-hide');\n\tthis.children('.poll-section-footer').removeClass('poll-hide');\n\tthis.children('.poll-section-title').find('.mod-button').hide();\n\tthis.children('.photoReelContainer').addClass('ui-corner-top').removeClass('ui-corner-all')\n\twindow.scroll(0,0); // force the window to display the top.\n\t// any reinit button is left in place\n};\n\n// because the map has to be generated in a properly sized div, we can't use the normal hide/show functions.\n// just move the panels off to the side.\n\$.fn.showPanel = function(){\n\tthis.removeClass('poll-hide');\n\tthis.unFoldPanel();\n};\n\n\$.fn.hidePanel = function(){\n\tthis.addClass('poll-hide'); \n};\n\ninseeLayer = null;\n\ndefaultSref = '" . ((int) $args['map_centroid_lat'] > 0 ? $args['map_centroid_lat'] . 'N' : -(int) $args['map_centroid_lat'] . 'S') . ' ' . ((int) $args['map_centroid_long'] > 0 ? $args['map_centroid_long'] . 'E' : -(int) $args['map_centroid_long'] . 'W') . "';\ndefaultGeom = '';\n\$.getJSON('" . $svcUrl . "' + '/spatial/sref_to_wkt'+\n        \t\t\t'?sref=' + defaultSref +\n          \t\t\t'&system=' + jQuery('#imp-sref-system').val() +\n          \t\t\t'&callback=?', function(data) {\n            \tdefaultGeom = data.wkt;\n        \t});\n\n\$.fn.resetPanel = function(){\n\tthis.find('.poll-section-body').removeClass('poll-hide');\n\tthis.find('.poll-section-footer').removeClass('poll-hide');\n\tthis.find('.reinit-button').show();\n\tthis.find('.mod-button').show();\n\tthis.find('.poll-image').empty();\n\tthis.find('.poll-session').empty();\n\n\t// resetForm does not reset the hidden fields. record_status, imp-sref-system, website_id and survey_id are not altered so do not reset.\n\t// hidden Attributes generally hold unchanging data, but the name needs to be reset (does it for non hidden as well).\n\t// hidden location:name are set in code anyway.\n\tthis.find('form').each(function(){\n\t\tjQuery(this).resetForm();\n\t\tjQuery(this).find('[name=sample\\:location_name],[name=location_image\\:path],[name=occurrence_image\\:path]').val('');\n\t\tjQuery(this).filter('#cc-1-collection-details').find('[name=sample\\:id],[name=location\\:id]').val('').attr('disabled', 'disabled');\n\t\tjQuery(this).find('[name=location_image\\:id],[name=occurrence\\:id],[name=occurrence_image\\:id]').val('').attr('disabled', 'disabled');\n\t\tjQuery(this).find('[name=sample\\:date]:hidden').val('2010-01-01');\t\t\n        jQuery(this).find('input[name=locations_website\\:website_id]').removeAttr('disabled');\n\t\tjQuery(this).find('[name^=smpAttr\\:],[name^=locAttr\\:],[name^=occAttr\\:]').each(function(){\n\t\t\tvar name = jQuery(this).attr('name').split(':');\n\t\t\tjQuery(this).attr('name', name[0]+':'+name[1]);\n\t\t});\n\t\tjQuery(this).find('input[name=location\\:centroid_sref]').val('');\n\t\tjQuery(this).find('input[name=location\\:centroid_geom]').val('');\n    });\t\n\tthis.find('.poll-dummy-form > input').val('');\n\tthis.find('.poll-dummy-form > select').val('');\n  };\n\ncheckProtocolStatus = function(){\n\tif (jQuery('#cc-3-body').children().length === 1) {\n\t    jQuery('#cc-3').find('.delete-button').hide();\n  \t} else {\n\t\tjQuery('#cc-3').find('.delete-button').show();\n\t}\n\tif(jQuery('[name=smpAttr\\:" . $args['protocol_attr_id'] . "],[name^=smpAttr\\:" . $args['protocol_attr_id'] . "\\:]').filter(':first').filter('[checked]').length >0){\n\t    jQuery('#cc-3').find('.add-button').hide();\n\t} else {\n\t    jQuery('#cc-3').find('.add-button').show();\n  \t}\n  \tvar checkedProtocol = jQuery('[name=smpAttr\\:" . $args['protocol_attr_id'] . "],[name^=smpAttr\\:" . $args['protocol_attr_id'] . "\\:]').filter('[checked]').parent();\n    if(jQuery('[name=location\\:name]').val() != '' && checkedProtocol.length > 0) {\n        jQuery('#cc-1-title-details').empty().text(jQuery('#cc-1-collection-details input[name=location\\:name]:first').val());\n        jQuery('#cc-1-protocol-details').empty().show().text(\"" . lang::get('LANG_Protocol_Title_Label') . " : \" + checkedProtocol.find('label')[0].innerHTML;\n    } else {\n        jQuery('#cc-1-title-details').empty().text(\"" . lang::get('LANG_Collection_Details') . "\");\n        // TODO autogenerate a name\n        jQuery('#cc-1-protocol-details').empty().hide();\n    }\n};\n\nshowStationPanel = true;\n\n// The validate functionality for each panel is sufficiently different that we can't generalise a function\n// this is the one called when we don't want the panel following to be opened automatically.\nvalidateCollectionPanel = function(){\n\tif(jQuery('#cc-1-body').filter('.poll-hide').length > 0) return true; // body hidden so data already been validated successfully.\n\tif(!jQuery('#cc-1-body').find('form > input').valid()){ return false; }\n\t// no need to check protocol - if we are this far, we've already filled it in.\n  \tshowStationPanel = false;\n\tjQuery('#cc-1-collection-details').submit();\n\treturn true;\n  };\n\nvalidateRadio = function(name, formSel){\n    var controls = jQuery(formSel).find('[name='+name+'],[name^='+name+'\\:]');\n\tcontrols.parent().parent().find('p').remove(); // remove existing errors\n    if(controls.filter('[checked]').length < 1) {\n        var label = \$('<p/>')\n\t\t\t\t.attr({'for': name})\n\t\t\t\t.addClass('radio-error')\n\t\t\t\t.html(\$.validator.messages.required);\n\t\tlabel.insertBefore(controls.filter(':first').parent());\n\t\treturn false;\n    }\n    return true;\n}\n\nvalidateRequiredField = function(name, formSel){\n    var control = jQuery(formSel).find('[name='+name+']');\n\tcontrol.parent().find('.required-error').remove(); // remove existing errors\n    if(control.val() == '') {\n        var label = \$('<p/>')\n\t\t\t\t.attr({'for': name})\n\t\t\t\t.addClass('required-error')\n\t\t\t\t.html(\$.validator.messages.required);\n\t\tlabel.insertBefore(control);\n\t\treturn false;\n    }\n    return true;\n}\n\n\$('#cc-1-collection-details').ajaxForm({ \n        // dataType identifies the expected content type of the server response \n        dataType:  'json', \n        // success identifies the function to invoke when the server response \n        // has been received \n        beforeSubmit:   function(data, obj, options){\n        \tvar valid = true;\n        \tif (!jQuery('form#cc-1-collection-details > input').valid()) { valid = false; }\n        \tif (!validateRadio('smpAttr\\:" . $args['protocol_attr_id'] . "', 'form#cc-1-collection-details')) { valid = false; }\n\t       \tif ( valid == false ) return valid;\n  \t\t\t// Warning this assumes that:\n  \t\t\t// 1) the location:name is the sixth field in the form.\n  \t\t\t// 1) the sample:location_name is the seventh field in the form.\n  \t\t\tdata[6].value = data[5].value;\n  \t\t\tif(data[1].value=='') data[1].value=defaultSref;\n  \t\t\tif(data[2].value=='') data[2].value=defaultGeom;\n  \t\t\tjQuery('#cc-2-floral-station > input[name=location\\:name]').val(data[5].value);\n        \treturn true;\n  \t\t},\n        success:   function(data){\n        \tif(data.success == 'multiple records' && data.outer_table == 'location'){\n        \t    jQuery('#cc-1-collection-details > input[name=location\\:id]').removeAttr('disabled').val(data.outer_id);\n        \t    jQuery('#cc-1-collection-details > input[name=locations_website\\:website_id]').attr('disabled', 'disabled');\n        \t    jQuery('#cc-2-floral-station > input[name=location\\:id]').removeAttr('disabled').val(data.outer_id);\n        \t    \$.getJSON(\"" . $svcUrl . "\" + \"/data/sample\" +\n\t\t\t          \"?mode=json&view=detail&nonce=" . $readAuth['nonce'] . "&auth_token=" . $readAuth['auth_token'] . "\" +\n\t\t\t          \"&location_id=\"+data.outer_id+\"&parent_id=NULL&callback=?\", function(data) {\n\t\t\t\t\tif (data.length>0) {\n\t\t\t       \t\t    jQuery('#cc-6-consult-collection').attr('href', '" . url('node/' . $args['gallery_node']) . "'+'?collection_id='+data[0].id);\n\t\t\t        \t    jQuery('#cc-1-collection-details > input[name=sample\\:id]').removeAttr('disabled').val(data[0].id);\n\t\t\t        \t    jQuery('#cc-2-floral-station > input[name=sample\\:id]').removeAttr('disabled').val(data[0].id);\n\t\t\t        \t    // In this case we use loadAttributes to set the names of the attributes to include the attribute_value id.\n   \t       \t\t\t\t\tloadAttributes('sample_attribute_value', 'sample_attribute_id', 'sample_id', 'sample\\:id', data[0].id, 'smpAttr');\n\t\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t   \tcheckProtocolStatus();\n        \t\t\$('#cc-1').foldPanel();\n    \t\t\tif(showStationPanel){ \$('#cc-2').showPanel(); }\n\t\t    \tshowStationPanel = true;\n        \t}  else {\n\t\t\t\tvar errorString = \"" . lang::get('LANG_Indicia_Warehouse_Error') . "\";\n\t\t\t\tif(data.error){\n\t\t\t\t\terrorString = errorString + ' : ' + data.error;\n\t\t\t\t}\n\t\t\t\tif(data.errors){\n\t\t\t\t\tfor (var i in data.errors)\n\t\t\t\t\t{\n\t\t\t\t\t\terrorString = errorString + ' : ' + data.errors[i];\n\t\t\t\t\t}\t\t\t\t\n\t\t\t\t}\n\t\t\t\talert(errorString);\n\t\t\t}\n        } \n});\n\n\$('#cc-1-delete-collection').ajaxForm({ \n        dataType:  'json', \n        beforeSubmit:   function(data, obj, options){\n  \t\t\t// Warning this assumes that the data is fixed position:\n       \t\tdata[2].value = jQuery('#cc-1-collection-details input[name=sample\\:id]').val();\n       \t\tdata[3].value = jQuery('#cc-1-collection-details input[name=sample\\:date]').val();\n       \t\tdata[4].value = jQuery('#cc-1-collection-details input[name=location\\:id]').val();\n        \tif(data[2].value == '') return false;\n        \treturn true;\n  \t\t},\n        success:   function(data){\n\t\t\tjQuery('#cc-3-body').empty();\n        \tjQuery('.poll-section').resetPanel();\n\t\t\tsessionCounter = 0;\n\t\t\taddSession();\n\t\t\tcheckProtocolStatus();\n\t\t\tjQuery('.poll-section').hidePanel();\n\t\t\tjQuery('.poll-image').empty();\n\t\t\tjQuery('#cc-1').showPanel();\n\t\t\tjQuery('.reinit-button').hide();\n\t\t\tjQuery('#map')[0].map.editLayer.destroyFeatures();\n  \t\t} \n});\n\n\$('#cc-1-valid-button').click(function() {\n\tjQuery('#cc-1-collection-details').submit();\n});\n\n\$('#cc-1-reinit-button').click(function() {\n\tif(jQuery('form#cc-1-collection-details > input[name=sample\\:id]').filter('[disabled]').length > 0) { return } // sample id is disabled, so no data has been saved - do nothing.\n    if (!jQuery('form#cc-1-collection-details > input').valid()) {\n    \talert(\"" . lang::get('LANG_Unable_To_Reinit') . "\");\n        return ;\n  \t}\n\tif(confirm(\"" . lang::get('LANG_Confirm_Reinit') . "\")){\n\t\tjQuery('#cc-1-delete-collection').submit();\n\t}\n});\n\n";
        // Flower Station section.
        $options = iform_map_get_map_options($args, $readAuth);
        $olOptions = iform_map_get_ol_options($args);
        // The maps internal projection will be left at its default of 900913.
        $options['searchLayer'] = 'true';
        $options['initialFeatureWkt'] = null;
        $options['proxy'] = '';
        // Switch to degrees, minutes, seconds for lat long.
        $options['latLongFormat'] = 'DMS';
        $options['suffixTemplate'] = 'nosuffix';
        $extraParams = $readAuth + array('taxon_list_id' => $args['flower_list_id'], 'orderby' => 'taxon');
        $species_ctrl_args = array('label' => lang::get('LANG_Flower_Species'), 'fieldname' => 'flower:taxa_taxon_list_id', 'table' => 'taxa_taxon_list', 'captionField' => 'taxon', 'valueField' => 'id', 'columns' => 2, 'validation' => array('required'), 'blankText' => lang::get('LANG_Choose_Taxon'), 'extraParams' => $extraParams, 'suffixTemplate' => 'nosuffix');
        $r .= '
<div id="cc-2" class="poll-section">
  <div id="cc-2-title" class="ui-accordion-header ui-helper-reset ui-state-active ui-corner-all poll-section-title"><span>' . lang::get('LANG_Flower_Station') . '</span>
    <div class="right">
      <span id="cc-2-mod-button" class="ui-state-default ui-corner-all mod-button">' . lang::get('LANG_Modify') . '</span>
    </div>
  </div>
  <div id="cc-2-body" class="ui-accordion-content ui-helper-reset ui-widget-content ui-corner-top ui-accordion-content-active poll-section-body">
    <div id="cc-2-flower" >
	  <form id="cc-2-flower-upload" enctype="multipart/form-data" action="' . iform_ajaxproxy_url($node, 'media') . '" method="POST">
    		<input type="hidden" id="website_id" name="website_id" value="' . $args['website_id'] . '" />
    		<input name="upload_file" type="file" class="required" />
     		<input type="submit" value="' . lang::get('LANG_Upload_Flower') . '" class="btn-submit" />
      </form>
 	  <div id="cc-2-flower-image" class="poll-image"></div>
 	  <div id="cc-2-flower-identify" class="poll-dummy-form">
        ' . iform_pollenators::help_button($use_help, "flower-help-button", $args['help_function'], $args['help_flower_arg']) . '
 	    <p><strong>' . lang::get('LANG_Identify_Flower') . '</strong></p>
        <label for="id-flower-later" class="follow-on">' . lang::get('LANG_ID_Flower_Later') . ' </label><input type="checkbox" id="id-flower-later" name="id-flower-later" /> 
		' . ($args['ID_tool_flower_url'] != '' && $args['ID_tool_flower_poll_dir'] ? '<label for="flower-id-button">' . lang::get('LANG_Flower_ID_Key_label') . ' :</label><span id="flower-id-button" class="ui-state-default ui-corner-all poll-id-button" >' . lang::get('LANG_Launch_ID_Key') . '</span>' : '') . '<span id="flower-id-cancel" class="ui-state-default ui-corner-all poll-id-cancel" >' . lang::get('LANG_Cancel_ID') . '</span>
    	' . data_entry_helper::select($species_ctrl_args) . '
		<input type="text" name="flower:taxon_text_description" readonly="readonly">
      </div>
 	</div>
    <div class="poll-break"></div>
 	<div id="cc-2-environment">
	  <form id="cc-2-environment-upload" enctype="multipart/form-data" action="' . iform_ajaxproxy_url($node, 'media') . '" method="POST">
    		<input type="hidden" id="website_id" name="website_id" value="' . $args['website_id'] . '" />
    		<input name="upload_file" type="file" class="required" />
    		<input type="submit" value="' . lang::get('LANG_Upload_Environment') . '" class="btn-submit" />
      </form>
 	  <div id="cc-2-environment-image" class="poll-image"></div>
 	</div>
 	<form id="cc-2-floral-station" action="' . iform_ajaxproxy_url($node, 'loc-smp-occ') . '" method="POST">
      <input type="hidden" id="website_id" name="website_id" value="' . $args['website_id'] . '" />
      <input type="hidden" id="location:id" name="location:id" value="" />
      <input type="hidden" id="location:name" name="location:name" value=""/>
      <input type="hidden" name="location:centroid_sref" />
      <input type="hidden" name="location:centroid_geom" />
      <input type="hidden" name="location:centroid_sref_system" value="4326" />
      <input type="hidden" id="location_image:path" name="location_image:path" value="" />
      <input type="hidden" id="sample:survey_id" name="sample:survey_id" value="' . $args['survey_id'] . '" />
      <input type="hidden" id="sample:id" name="sample:id" value=""/>
      <input type="hidden" name="sample:date" value="2010-01-01"/>
      <input type="hidden" name="determination:taxa_taxon_list_id" value=""/>  
      <input type="hidden" name="determination:taxon_text_description" value=""/>  
      <input type="hidden" name="determination:cms_ref" value="' . $uid . '" />
      <input type="hidden" name="determination:email_address" value="' . $email . '" />
      <input type="hidden" name="determination:person_name" value="' . $username . '" />  
      <input type="hidden" name="occurrence:use_determination" value="Y"/>    
      <input type="hidden" name="occurrence:record_status" value="C" />
      <input type="hidden" id="location_image:id" name="location_image:id" value="" disabled="disabled" />
      <input type="hidden" id="occurrence:id" name="occurrence:id" value="" disabled="disabled" />
      <input type="hidden" id="determination:id" name="determination:id" value="" disabled="disabled" />
      <input type="hidden" id="occurrence_image:id" name="occurrence_image:id" value="" disabled="disabled" />
      <input type="hidden" id="occurrence_image:path" name="occurrence_image:path" value="" />
      ' . data_entry_helper::outputAttribute($occurrence_attributes[$args['flower_type_attr_id']], array('extraParams' => $readAuth, 'lookUpListCtrl' => 'radio_group', 'sep' => ' &nbsp; ', 'language' => iform_lang_iso_639_2($args['language']), 'containerClass' => 'group-control-box', 'suffixTemplate' => 'nosuffix')) . data_entry_helper::outputAttribute($location_attributes[$args['distance_attr_id']], array('extraParams' => $readAuth, 'lookUpListCtrl' => 'radio_group', 'sep' => ' &nbsp; ', 'language' => iform_lang_iso_639_2($args['language']), 'containerClass' => 'group-control-box', 'suffixTemplate' => 'nosuffix')) . data_entry_helper::outputAttribute($location_attributes[$args['habitat_attr_id']], array('extraParams' => $readAuth, 'lookUpListCtrl' => 'checkbox_group', 'sep' => ' &nbsp; ', 'language' => iform_lang_iso_639_2($args['language']), 'containerClass' => 'group-control-box', 'suffixTemplate' => 'nosuffix')) . '
    </form>
    <div class="poll-break"></div>
    <div>
      ' . iform_pollenators::help_button($use_help, "location-help-button", $args['help_function'], $args['help_location_arg']) . '
      <div>' . lang::get('LANG_Location_Notes') . '</div>
 	  <div class="poll-map-container">
    ';
        $r .= data_entry_helper::map_panel($options, $olOptions);
        $r .= '
      </div>
      <div><div id="cc-2-location-entry">
        ' . data_entry_helper::georeference_lookup(array('label' => lang::get('LANG_Georef_Label'), 'georefPreferredArea' => $args['georefPreferredArea'], 'georefCountry' => $args['georefCountry'], 'georefLang' => $args['language'], 'suffixTemplate' => 'nosuffix')) . '
    	<span >' . lang::get('LANG_Georef_Notes') . '</span>
 	    <label for="place:INSEE">' . lang::get('LANG_Or') . '</label>
 		<input type="text" id="place:INSEE" name="place:INSEE" value="' . lang::get('LANG_INSEE') . '"
	 		onclick="if(this.value==\'' . lang::get('LANG_INSEE') . '\'){this.value=\'\'; this.style.color=\'#000\'}"  
            onblur="if(this.value==\'\'){this.value=\'' . lang::get('LANG_INSEE') . '\'; this.style.color=\'#555\'}" />
    	<input type="button" id="search-insee-button" class="ui-corner-all ui-widget-content ui-state-default search-button" value="Search" />
        ' . data_entry_helper::sref_textbox(array('srefField' => 'place:entered_sref', 'systemfield' => 'place:entered_sref_system', 'id' => 'place-sref', 'fieldname' => 'place:name', 'splitLatLong' => true, 'labelLat' => lang::get('Latitude'), 'fieldnameLat' => 'place:lat', 'labelLong' => lang::get('Longitude'), 'fieldnameLong' => 'place:long', 'idLat' => 'imp-sref-lat', 'idLong' => 'imp-sref-long', 'suffixTemplate' => 'nosuffix')) . '
 	  </div></div>
      <div id="cc-2-loc-description"></div>
    </div>
  </div>
  <div id="cc-2-footer" class="ui-accordion-content ui-helper-reset ui-widget-content ui-corner-bottom ui-accordion-content-active poll-section-footer">
    <div id="cc-2-valid-button" class="ui-state-default ui-corner-all save-button">' . lang::get('LANG_Validate_Flower') . '</div>
  </div>
</div>';
        // NB the distance attribute is left blank at the moment if unknown: TODO put in a checkbox : checked if blank for nsp
        data_entry_helper::$javascript .= "\n\nshowSessionsPanel = true;\n\nvar flowerTimer1;\nvar flowerTimer2;\nvar IDcounter = 0;\n\nflowerPoller = function(){\n\tflowerTimer1 = setTimeout('flowerPoller();', " . $args['ID_tool_poll_interval'] . ");\n\t\$.get('" . str_replace("{HOST}", $_SERVER['HTTP_HOST'], $args['ID_tool_flower_poll_dir']) . session_id() . "_'+IDcounter.toString(), function(data){\n      var da = data.split('\\n');\n      // first count number of returned items.\n      // if > 1 put all into taxon_description.\n      // if = 1 rip out the description, remove the formatting, scan the flower select for it, and set the value. Set the taxon description.\n\t  da[1] = da[1].replace(/\\\\\\\\i\\{\\}/g, '').replace(/\\\\\\\\i0\\{\\}/g, '');\n      var items = da[1].split(':');\n\t  var count = items.length;\n\t  if(items[count-1] == '') count--;\n\t  if(count <= 0){\n\t  \t// no valid stuff so blank it all out.\n\t  \tjQuery('#cc-2-flower-identify > select[name=flower\\:taxa_taxon_list_id]').val('');\n\t  \tjQuery('#cc-2-flower-identify > select[name=flower\\:taxon_text_description]').val('');\n\t  } else if(count == 1){\n\t  \tjQuery('#cc-2-flower-identify > select[name=flower\\:taxa_taxon_list_id]').val('');\n\t  \tjQuery('#cc-2-flower-identify > select[name=flower\\:taxon_text_description]').val(items[0]);\n  \t\tvar x = jQuery('#cc-2-flower-identify').find('option').filter('[text='+items[0]+']');\n\t  \tif(x.length > 0){\n\t\t\tjQuery('#cc-2-flower-identify > select[name=flower\\:taxon_text_description]').val('');\n\t  \t\tjQuery('#cc-2-flower-identify > select[name=flower\\:taxa_taxon_list_id]').val(x[0].value);\n  \t\t}\n\t  } else {\n\t  \tjQuery('#cc-2-flower-identify > select[name=flower\\:taxa_taxon_list_id]').val('');\n\t  \tjQuery('#cc-2-flower-identify > select[name=flower\\:taxon_text_description]').val(da[1]);\n\t  }\n\t  flowerReset();\n    });\n};\nflowerReset = function(){\n\tclearTimeout(flowerTimer1);\n\tclearTimeout(flowerTimer2);\n\tjQuery('#flower-id-cancel').hide();\n};\n\njQuery('#flower-id-button').click(function(){\n\tIDcounter++;\n\tclearTimeout(flowerTimer1);\n\tclearTimeout(flowerTimer2);\n\twindow.open('" . $args['ID_tool_flower_url'] . session_id() . "_'+IDcounter.toString(),'','') \n\tflowerTimer1 = setTimeout('flowerPoller();', " . $args['ID_tool_poll_interval'] . ");\n\tflowerTimer2 = setTimeout('flowerReset();', " . $args['ID_tool_poll_timeout'] . ");\n\tjQuery('#flower-id-cancel').show();\n});\njQuery('#flower-id-cancel').click(function(){\n\tflowerReset();\n});\njQuery('#flower-id-cancel').hide();\n\njQuery('#search-insee-button').click(function(){\n\tif(inseeLayer != null)\n\t\tinseeLayer.destroy();\n\tvar filters = [];\n  \tvar place = jQuery('input[name=place\\:INSEE]').val();\n  \tif(place == '" . lang::get('LANG_INSEE') . "') return;\n  \tfilters.push(new OpenLayers.Filter.Comparison({\n  \t\t\ttype: OpenLayers.Filter.Comparison.EQUAL_TO ,\n    \t\tproperty: 'INSEE_NEW',\n    \t\tvalue: place\n  \t\t}));\n  \tfilters.push(new OpenLayers.Filter.Comparison({\n  \t\t\ttype: OpenLayers.Filter.Comparison.EQUAL_TO ,\n    \t\tproperty: 'INSEE_OLD',\n    \t\tvalue: place\n  \t\t}));\n\n\tvar strategy = new OpenLayers.Strategy.Fixed({preload: false, autoActivate: false});\n\tvar styleMap = new OpenLayers.StyleMap({\n                \"default\": new OpenLayers.Style({\n                    fillColor: \"Red\",\n                    strokeColor: \"Red\",\n                    fillOpacity: 0,\n                    strokeWidth: 1\n                  })\n\t});\n\tinseeLayer = new OpenLayers.Layer.Vector('INSEE Layer', {\n\t\t  styleMap: styleMap,\n          strategies: [strategy],\n          displayInLayerSwitcher: false,\n\t      protocol: new OpenLayers.Protocol.WFS({\n              url:  '" . str_replace("{HOST}", $_SERVER['HTTP_HOST'], $args['INSEE_url']) . "',\n              featurePrefix: '" . $args['INSEE_prefix'] . "',\n              featureType: '" . $args['INSEE_type'] . "',\n              geometryName:'the_geom',\n              featureNS: '" . $args['INSEE_ns'] . "',\n              srsName: 'EPSG:900913',\n              version: '1.1.0'                  \n      \t\t  ,propertyNames: ['the_geom']\n  \t\t\t})\n    });\n\tinseeLayer.events.register('featuresadded', {}, function(a1){\n\t\tvar div = jQuery('#map')[0];\n\t\tdiv.map.searchLayer.destroyFeatures();\n\t\tvar bounds=inseeLayer.getDataExtent();\n    \tvar dy = (bounds.top-bounds.bottom)/10;\n    \tvar dx = (bounds.right-bounds.left)/10;\n    \tbounds.top = bounds.top + dy;\n    \tbounds.bottom = bounds.bottom - dy;\n    \tbounds.right = bounds.right + dx;\n    \tbounds.left = bounds.left - dx;\n    \t// if showing a point, don't zoom in too far\n    \tif (dy===0 && dx===0) {\n    \t\tdiv.map.setCenter(bounds.getCenterLonLat(), div.settings.maxZoom);\n    \t} else {\n    \t\tdiv.map.zoomToExtent(bounds);\n    \t}\n    });\n\tinseeLayer.events.register('loadend', {}, function(){\n\t\tif(inseeLayer.features.length == 0){\n\t\t\talert(\"" . lang::get('LANG_NO_INSEE') . "\");\n\t\t}\n    });\n    jQuery('#map')[0].map.addLayer(inseeLayer);\n\tstrategy.load({filter: new OpenLayers.Filter.Logical({\n\t\t\t      type: OpenLayers.Filter.Logical.OR,\n\t\t\t      filters: filters\n\t\t  \t  })});\n});\n\nvalidateStationPanel = function(){\n\tvar myPanel = jQuery('#cc-2');\n\tvar valid = true;\n\tif(myPanel.filter('.poll-hide').length > 0) return true; // panel is not visible so no data to fail validation.\n\tif(myPanel.find('.poll-section-body').filter('.poll-hide').length > 0) return true; // body hidden so data already been validated successfully.\n\t// If no data entered also return true: this can only be the case when pressing the modify button on the collections panel\n\tif(jQuery('form#cc-2-floral-station > input[name=location_image\\:path]').val() == '' &&\n\t\t\tjQuery('form#cc-2-floral-station > input[name=occurrence\\:id]').val() == '' &&\n\t\t\tjQuery('form#cc-2-floral-station > input[name=occurrence_image\\:path]').val() == '' &&\n\t\t\tjQuery('#cc-2-flower-identify > select[name=flower\\:taxa_taxon_list_id]').val() == '' &&\n    \t\tjQuery('[name=occAttr\\:" . $args['flower_type_attr_id'] . "],[name^=occAttr\\:" . $args['flower_type_attr_id'] . "\\:]').filter('[checked]').length == 0 &&\n    \t\tjQuery('[name=locAttr\\:" . $args['habitat_attr_id'] . "],[name^=locAttr\\:" . $args['habitat_attr_id'] . "\\:]').filter('[checked]').length == 0 &&\n    \t\tjQuery('[name=locAttr\\:" . $args['distance_attr_id'] . "],[name^=locAttr\\:" . $args['distance_attr_id'] . "\\:]').val() == '') {\n\t\tjQuery('#cc-2').foldPanel();\n\t\treturn true;\n\t}\n    if(jQuery('form#cc-2-floral-station > input[name=location_image\\:path]').val() == '' ||\n\t\t\t\t\tjQuery('form#cc-2-floral-station > input[name=occurrence_image\\:path]').val() == ''){\n\t\talert(\"" . lang::get('LANG_Must_Provide_Pictures') . "\");\n\t\tvalid = false;\n\t}\n    if(jQuery('#imp-geom').val() == '') {\n\t\talert(\"" . lang::get('LANG_Must_Provide_Location') . "\");\n\t\tvalid = false;\n\t}\n\tif (jQuery('#id-flower-later').attr('checked') == ''){\n\t\tif(!validateRequiredField('flower\\:taxa_taxon_list_id', '#cc-2-flower-identify')) { valid = false; }\n\t}\n\tif (!jQuery('form#cc-2-floral-station > input').valid()) { valid = false; }\n   \tif (!validateRadio('occAttr\\:" . $args['flower_type_attr_id'] . "', 'form#cc-2-floral-station')) { valid = false; }\n   \tif ( valid == false ) return valid;\n\tshowSessionsPanel = false;\n\tjQuery('form#cc-2-floral-station').submit();\n\treturn true;\n};\n\n// Flower upload picture form.\n\$('#cc-2-flower-upload').ajaxForm({ \n        dataType:  'json', \n        beforeSubmit:   function(data, obj, options){\n         \tif (!jQuery('form#cc-2-flower-upload').valid()) { return false; }\n        \t\$('#cc-2-flower-image').empty();\n        \t\$('#cc-2-flower-image').addClass('loading')\n        },\n        success:   function(data){\n        \tif(data.success == true){\n\t        \t// There is only one file\n\t        \tjQuery('form#cc-2-floral-station input[name=occurrence_image\\:path]').val(data.files[0]);\n\t        \tvar img = new Image();\n\t        \t\$(img).load(function () {\n        \t\t\t\t\$(this).hide();\n        \t\t\t\t\$('#cc-2-flower-image').removeClass('loading').append(this);\n        \t\t\t\t\$(this).fadeIn();\n\t\t\t    \t})\n\t\t\t\t    .attr('src', '" . data_entry_helper::$base_url . data_entry_helper::$indicia_upload_path . "med-'+data.files[0])\n\t\t\t\t    .css('max-width', \$('#cc-2-flower-image').width()).css('max-height', \$('#cc-2-flower-image').height())\n\t\t\t\t    .css('vertical-align', 'middle').css('margin-left', 'auto').css('margin-right', 'auto').css('display', 'block');\n\t\t\t\tjQuery('#cc-2-flower-upload input[name=upload_file]').val('');\n\t\t\t} else {\n\t\t\t\tvar errorString = \"" . lang::get('LANG_Indicia_Warehouse_Error') . "\";\n\t        \tjQuery('form#cc-2-floral-station input[name=occurrence_image\\:path]').val('');\n\t\t\t\t\$('#cc-2-flower-image').removeClass('loading');\n\t\t\t\tif(data.error){\n\t\t\t\t\terrorString = errorString + ' : ' + data.error;\n\t\t\t\t}\n\t\t\t\tif(data.errors){\n\t\t\t\t\tfor (var i in data.errors)\n\t\t\t\t\t{\n\t\t\t\t\t\terrorString = errorString + ' : ' + data.errors[i];\n\t\t\t\t\t}\t\t\t\t\n\t\t\t\t}\n\t\t\t\talert(errorString);\n\t\t\t}\n  \t\t} \n});\n\n// Flower upload picture form.\n\$('#cc-2-environment-upload').ajaxForm({ \n        dataType:  'json', \n        beforeSubmit:   function(data, obj, options){\n         \tif (!jQuery('form#cc-2-environment-upload').valid()) { return false; }\n        \t\$('#cc-2-environment-image').empty();\n        \t\$('#cc-2-environment-image').addClass('loading')\n        },\n        success:   function(data){\n        \tif(data.success == true){\n\t        \t// There is only one file\n\t        \tjQuery('form#cc-2-floral-station input[name=location_image\\:path]').val(data.files[0]);\n\t        \tvar img = new Image();\n\t        \t\$(img).load(function () {\n        \t\t\t\t\$(this).hide();\n        \t\t\t\t\$('#cc-2-environment-image').removeClass('loading').append(this);\n        \t\t\t\t\$(this).fadeIn();\n\t\t\t    \t})\n\t\t\t\t    .attr('src', '" . data_entry_helper::$base_url . data_entry_helper::$indicia_upload_path . "med-'+data.files[0])\n\t\t\t\t    .css('max-width', \$('#cc-2-environment-image').width()).css('max-height', \$('#cc-2-environment-image').height())\n\t\t\t\t    .css('vertical-align', 'middle').css('margin-left', 'auto').css('margin-right', 'auto').css('display', 'block');\n\t\t\t\tjQuery('#cc-2-environment-upload input[name=upload_file]').val('');\n\t\t\t} else {\n\t\t\t\tvar errorString = \"" . lang::get('LANG_Indicia_Warehouse_Error') . "\";\n\t        \tjQuery('form#cc-2-floral-station input[name=location_image\\:path]').val('');\n\t\t\t\t\$('#cc-2-environment-image').removeClass('loading');\n\t\t\t\tif(data.error){\n\t\t\t\t\terrorString = errorString + ' : ' + data.error;\n\t\t\t\t}\n\t\t\t\tif(data.errors){\n\t\t\t\t\tfor (var i in data.errors)\n\t\t\t\t\t{\n\t\t\t\t\t\terrorString = errorString + ' : ' + data.errors[i];\n\t\t\t\t\t}\t\t\t\t\n\t\t\t\t}\n\t\t\t\talert(errorString);\n\t\t\t}\n        } \n});\n\n\$('#cc-2-floral-station').ajaxForm({ \n    dataType:  'json', \n    beforeSubmit:   function(data, obj, options){\n\t\tvar valid = true;\n    \tif(jQuery('form#cc-2-floral-station > input[name=location_image\\:path]').val() == '' ||\n\t\t\t\t\tjQuery('form#cc-2-floral-station > input[name=occurrence_image\\:path]').val() == '' ){\n\t\t\talert(\"" . lang::get('LANG_Must_Provide_Pictures') . "\");\n\t\t\tvalid = false;\n\t\t}\n\t\tif(jQuery('#imp-geom').val() == '') {\n\t\t\talert(\"" . lang::get('LANG_Must_Provide_Location') . "\");\n\t\t\tvalid = false;\n\t\t}\n\t\tif (!jQuery('form#cc-2-floral-station > input').valid()) { valid = false; }\n   \t\tif (!validateRadio('occAttr\\:" . $args['flower_type_attr_id'] . "', 'form#cc-2-floral-station')) { valid = false; }\n\t\t// DANGER this assumes certain positioning of the centroid sref and geom within the data array\n\t\tif(data[3].name != 'location:centroid_sref' || data[4].name != 'location:centroid_geom') {\n\t\t\talert('Internal error: imp-sref or imp-geom post location mismatch');\n\t\t\treturn false;\n\t\t}\n\t\tdata[3].value = jQuery('#imp-sref').val();\n\t\tdata[4].value = jQuery('#imp-geom').val();\n\t\tdata[10].value = jQuery('#cc-2-flower-identify > select[name=flower\\:taxa_taxon_list_id]').val();\n\t\tdata[11].value = jQuery('#cc-2-flower-identify > select[name=flower\\:taxon_text_description]').val();\n\t\tif (jQuery('#id-flower-later').attr('checked') == ''){\n\t\t\tif (!validateRequiredField('flower\\:taxa_taxon_list_id', '#cc-2-flower-identify')) { valid = false; }\n\t\t} else {\n\t\t\tdata.splice(10,5); // remove determination entries.\n\t\t}\n   \t\tif ( valid == false ) return valid;\n\t\treturn true;\n\t},\n    success:   function(data){\n       \tif(data.success == 'multiple records' && data.outer_table == 'sample'){\n       \t\t// the sample and location ids are already fixed, so just need to populate the occurrence and image IDs, and rename the location and occurrence attribute.\n       \t    \$.getJSON(\"" . $svcUrl . "\" + \"/data/occurrence\" +\n\t\t          \"?mode=json&view=detail&nonce=" . $readAuth['nonce'] . "&auth_token=" . $readAuth['auth_token'] . "\" +\n\t\t          \"&sample_id=\"+data.outer_id+\"&callback=?\", function(occdata) {\n\t\t\t\tif (occdata.length>0) {\n\t\t        \tjQuery('#cc-2-floral-station > input[name=occurrence\\:id]').removeAttr('disabled').val(occdata[0].id);\n       \t\t\t\tloadAttributes('occurrence_attribute_value', 'occurrence_attribute_id', 'occurrence_id', 'occurrence\\:id', occdata[0].id, 'occAttr');\n\t\t\t\t\t\$.getJSON(\"" . $svcUrl . "/data/occurrence_image/\" +\n       \t\t\t\t\t\t\"?mode=json&view=list&nonce=" . $readAuth['nonce'] . "&auth_token=" . $readAuth['auth_token'] . "\" +\n       \t\t\t\t\t\t\"&occurrence_id=\"+occdata[0].id+\"&callback=?\", function(imgdata) {\n\t\t\t\t\t    if (imgdata.length>0) {\n\t\t        \t\t\tjQuery('#cc-2-floral-station > input[name=occurrence_image\\:id]').removeAttr('disabled').val(imgdata[0].id);\n\t\t        \t\t}});\n\t\t        }});\n\t\t    var location_id = jQuery('#cc-2-floral-station > input[name=location\\:id]').val();\n       \t\tloadAttributes('location_attribute_value', 'location_attribute_id', 'location_id', 'location\\:id', location_id, 'locAttr');\n\t\t\t\$.getJSON(\"" . $svcUrl . "/data/location_image/\" +\n       \t\t\t\t\"?mode=json&view=list&nonce=" . $readAuth['nonce'] . "&auth_token=" . $readAuth['auth_token'] . "\" +\n       \t\t\t\t\"&location_id=\"+location_id+\"&callback=?\", function(data) {\n\t\t\t\tif (data.length>0) {\n\t\t        \tjQuery('#cc-2-floral-station > input[name=location_image\\:id]').removeAttr('disabled').val(data[0].id);\n\t\t        }});\n\t\t\tjQuery('#cc-2').foldPanel();\n\t\t\tif(showSessionsPanel) { jQuery('#cc-3').showPanel(); }\n\t\t\tshowSessionsPanel = true;\n        } \n\t}\n});\n\n\$('#cc-2-valid-button').click(function() {\n\tjQuery('#cc-2-floral-station').submit();\n});\n\n";
        // Sessions.
        $r .= '
<div id="cc-3" class="poll-section">
  <div id="cc-3-title" class="ui-accordion-header ui-helper-reset ui-state-active ui-corner-all poll-section-title"><span>' . lang::get('LANG_Sessions_Title') . '</span>
    <div id="cc-3-mod-button" class="right ui-state-default ui-corner-all mod-button">' . lang::get('LANG_Modify') . '</div>
  </div>
  <div id="cc-3-body" class="ui-accordion-content ui-helper-reset ui-widget-content ui-corner-top ui-accordion-content-active poll-section-body">
  </div>
  <div id="cc-3-footer" class="ui-accordion-content ui-helper-reset ui-widget-content ui-corner-bottom ui-accordion-content-active poll-section-footer">
	<div id="cc-3-add-button" class="ui-state-default ui-corner-all add-button">' . lang::get('LANG_Add_Session') . '</div>
    <div id="cc-3-valid-button" class="ui-state-default ui-corner-all save-button">' . lang::get('LANG_Validate_Session') . '</div>
  </div>
</div>
<div style="display:none" />
    <form id="cc-3-delete-session" action="' . iform_ajaxproxy_url($node, 'sample') . '" method="POST">
       <input type="hidden" name="website_id" value="' . $args['website_id'] . '" />
       <input type="hidden" name="sample:survey_id" value="' . $args['survey_id'] . '" />
       <input type="hidden" name="sample:id" value="" />
       <input type="hidden" name="sample:date" value="2010-01-01"/>
       <input type="hidden" name="sample:location_id" value="" />
       <input type="hidden" name="sample:deleted" value="t" />
    </form>
</div>';
        data_entry_helper::$javascript .= "\n\$('#cc-3-delete-session').ajaxForm({ \n        dataType:  'json', \n        beforeSubmit:   function(data, obj, options){\n  \t\t\t// Warning this assumes that the data is fixed position:\n       \t\tdata[4].value = jQuery('#cc-1-collection-details input[name=location\\:id]').val();\n        \tif(data[2].value == '') return false;\n        \treturn true;\n  \t\t},\n        success:   function(data){\n  \t\t} \n});\npopulateSessionSelect = function(){\n\tvar insectSessionSelect = jQuery('form#cc-4-main-form > select[name=occurrence\\:sample_id]');\n\tvar value = insectSessionSelect.val();\n\tinsectSessionSelect.empty();\n\t// NB at this point the attributes have been loaded so have full name.\n\t\$('.poll-session-form').each(function(i){\n\t\tjQuery('<option value=\"'+\n\t\t\t\tjQuery(this).children('input[name=sample\\:id]').val()+\n\t\t\t\t'\">'+\n\t\t\t\tjQuery(this).children('input[name=sample\\:date]').val()+\n\t\t\t\t' : '+\n\t\t\t\tjQuery(this).children('[name=smpAttr\\:" . $args['start_time_attr_id'] . "],[name^=smpAttr\\:" . $args['start_time_attr_id'] . "\\:]').val()+\n\t\t\t\t' > '+\n\t\t\t\tjQuery(this).children('[name=smpAttr\\:" . $args['end_time_attr_id'] . "],[name^=smpAttr\\:" . $args['end_time_attr_id'] . "\\:]').val()+\n\t\t\t\t'</option>')\n\t\t\t.appendTo(insectSessionSelect);\n\t});\n\tif(value)\n\t\tinsectSessionSelect.val(value);\n}\n\nvalidateAndSubmitOpenSessions = function(){\n\tvar valid = true;\n\t// only check the visible forms as rest have already been validated successfully.\n\t\$('.poll-session-form:visible').each(function(i){\n\t    if (!jQuery(this).children('input').valid()) {\n\t    \tvalid = false; }\n\t    if (!jQuery('form#cc-2-floral-station > input').valid()) { valid = false; }\n   \t\tif (!validateRadio('smpAttr\\:" . $args['sky_state_attr_id'] . "', this)) { valid = false; }\n   \t\tif (!validateRadio('smpAttr\\:" . $args['temperature_attr_id'] . "', this)) { valid = false; }\n   \t\tif (!validateRadio('smpAttr\\:" . $args['wind_attr_id'] . "', this)) { valid = false; }\n    });\n\tif(valid == false) return false;\n\t\$('.poll-session-form:visible').submit();\n\treturn true;\n}\n\naddSession = function(){\n\tsessionCounter = sessionCounter + 1;\n\t// dynamically build the contents of the session block.\n\tvar newSession = jQuery('<div id=\"cc-3-session-'+sessionCounter+'\" class=\"poll-session\"/>')\n\t\t.appendTo('#cc-3-body');\n\tvar newTitle = jQuery('<div class=\"poll-session-title\">" . lang::get('LANG_Session') . " '+sessionCounter+'</div>')\n\t\t.appendTo(newSession);\n\tvar newModButton = jQuery('<div class=\"right ui-state-default ui-corner-all mod-button\">" . lang::get('LANG_Modify') . "</div>')\n\t\t.appendTo(newTitle).hide();\n\tvar newDeleteButton = jQuery('<div class=\"right ui-state-default ui-corner-all delete-button\">" . lang::get('LANG_Delete_Session') . "</div>')\n\t\t.appendTo(newTitle);\t\n\tnewModButton.click(function() {\n\t\tif(!validateAndSubmitOpenSessions()) return false;\n\t\tvar session=\$(this).parents('.poll-session');;\n\t\tsession.show();\n\t\tsession.children().show();\n\t\tsession.children(':first').children(':first').hide(); // this is the mod button itself\n    });\n    var formContainer = jQuery('<div />').appendTo(newSession);\n    var newForm = jQuery('<form action=\"" . iform_ajaxproxy_url($node, 'sample') . "\" method=\"POST\" class=\"poll-session-form\" />').appendTo(formContainer);\n\tjQuery('<input type=\"hidden\" name=\"website_id\" value=\"" . $args['website_id'] . "\" />').appendTo(newForm);\n\tjQuery('<input type=\"hidden\" name=\"sample:survey_id\" value=\"" . $args['survey_id'] . "\" />').appendTo(newForm);\n\tjQuery('<input type=\"hidden\" name=\"sample:parent_id\" />').appendTo(newForm).val(jQuery('#cc-1-collection-details > input[name=sample\\:id]').val());\n\tjQuery('<input type=\"hidden\" name=\"sample:location_id\" />').appendTo(newForm).val(jQuery('#cc-1-collection-details > input[name=location\\:id]').val());\n\tjQuery('<input type=\"hidden\" name=\"sample:id\" value=\"\" disabled=\"disabled\" />').appendTo(newForm);\n";
        if ($use_help) {
            data_entry_helper::$javascript .= "\n\tvar helpDiv = jQuery('<div class=\"right ui-state-default ui-corner-all help-button\">" . lang::get('LANG_Help_Button') . "</div>');\n\thelpDiv.click(function(){\n\t\t" . $args['help_function'] . "(" . $args['help_session_arg'] . ");\n\t});\n\thelpDiv.appendTo(newForm);";
        }
        data_entry_helper::$javascript .= "\n\tvar dateAttr = '" . str_replace("\n", "", data_entry_helper::date_picker(array('label' => lang::get('LANG_Date'), 'id' => '<id>', 'fieldname' => 'sample:date', 'class' => 'vague-date-picker required', 'suffixTemplate' => 'nosuffix'))) . "';\n\tvar dateID = 'cc-3-session-date-'+sessionCounter;\n\tjQuery(dateAttr.replace(/<id>/g, dateID)).appendTo(newForm);\n    jQuery('#'+dateID).datepicker({\n\t\tdateFormat : 'yy-mm-dd',\n\t\tconstrainInput: false,\n\t\tmaxDate: '0'\n\t});\n    jQuery('" . data_entry_helper::outputAttribute($sample_attributes[$args['start_time_attr_id']], $defAttrOptions) . "').appendTo(newForm);\n\tjQuery('" . data_entry_helper::outputAttribute($sample_attributes[$args['end_time_attr_id']], $defAttrOptions) . "').appendTo(newForm);\n\tjQuery('" . data_entry_helper::outputAttribute($sample_attributes[$args['sky_state_attr_id']], $defAttrOptions) . "').appendTo(newForm);\n\tjQuery('" . data_entry_helper::outputAttribute($sample_attributes[$args['temperature_attr_id']], $defAttrOptions) . "').appendTo(newForm);\n\tjQuery('" . data_entry_helper::outputAttribute($sample_attributes[$args['wind_attr_id']], $defAttrOptions) . "').appendTo(newForm);\n\tjQuery('" . data_entry_helper::outputAttribute($sample_attributes[$args['shade_attr_id']], $defAttrOptions) . "').appendTo(newForm);\n\tnewDeleteButton.click(function() {\n\t\tvar container = \$(this).parent().parent();\n\t\tjQuery('#cc-3-delete-session').find('[name=sample\\:id]').val(container.find('[name=sample\\:id]').val());\n\t\tjQuery('#cc-3-delete-session').find('[name=sample\\:date]').val(container.find('[name=sample\\:date]').val());\n\t\tjQuery('#cc-3-delete-session').find('[name=sample\\:location_id]').val(container.find('[name=sample\\:location_id]').val());\n\t\tif(container.find('[name=sample\\:id]').filter('[disabled]').length == 0){\n\t\t\t\$.getJSON(\"" . $svcUrl . "/data/occurrence/\" +\n\t\t\t\t\t\"?mode=json&view=detail&nonce=" . $readAuth['nonce'] . "&auth_token=" . $readAuth['auth_token'] . "\" +\n\t\t\t\t\t\"&sample_id=\"+container.find('[name=sample\\:id]').val()+\"&callback=?\", function(insectData) {\n\t\t\t\tif (insectData.length>0) {\n\t\t\t\t\talert(\"" . lang::get('LANG_Cant_Delete_Session') . "\");\n\t\t\t\t} else if(confirm(\"" . lang::get('LANG_Confirm_Session_Delete') . "\")){\n\t\t\t\t\tjQuery('#cc-3-delete-session').submit();\n\t\t\t\t\tcontainer.remove();\n\t\t\t\t\tcheckProtocolStatus();\n\t\t\t\t}\n\t\t\t});\n\t\t} else if(confirm(\"" . lang::get('LANG_Confirm_Session_Delete') . "\")){\n\t\t\tcontainer.remove();\n\t\t\tcheckProtocolStatus();\n\t\t}\n    });\n    newForm.ajaxForm({ \n    \tdataType:  'json',\n    \tbeforeSubmit:   function(data, obj, options){\n    \t\tvar valid = true;\n    \t\tif (!obj.find('input').valid()) {\n    \t\t\tvalid = false; }\n    \t\tif (!validateRadio('smpAttr\\:" . $args['sky_state_attr_id'] . "', obj)) { valid = false; }\n   \t\t\tif (!validateRadio('smpAttr\\:" . $args['temperature_attr_id'] . "', obj)) { valid = false; }\n   \t\t\tif (!validateRadio('smpAttr\\:" . $args['wind_attr_id'] . "', obj)) { valid = false; }\n    \t\tdata[2].value = jQuery('#cc-1-collection-details > input[name=sample\\:id]').val();\n\t\t\tdata[3].value = jQuery('#cc-1-collection-details > input[name=location\\:id]').val();\n\t\t\treturn valid;\n\t\t},\n   \t    success:   function(data, status, form){\n   \t    // TODO: error condition handling, eg no date.\n   \t    \tvar thisSession = form.parents('.poll-session');\n    \t\tif(data.success == 'multiple records' && data.outer_table == 'sample'){\n   \t    \t    form.children('input[name=sample\\:id]').removeAttr('disabled').val(data.outer_id);\n   \t    \t    loadAttributes('sample_attribute_value', 'sample_attribute_id', 'sample_id', 'sample\\:id', data.outer_id, 'smpAttr');\n        \t}\n\t\t\tthisSession.show();\n\t\t\tthisSession.children(':first').show().find('*').show();\n\t\t\tthisSession.children().not(':first').hide();\n  \t\t}\n\t});\n\tcheckProtocolStatus();\n    return(newSession);\n};\n\nvalidateSessionsPanel = function(){\n\tif(jQuery('#cc-3').filter('.poll-hide').length > 0) return true; // panel is not visible so no data to fail validation.\n\tif(jQuery('#cc-3').find('.poll-section-body').filter('.poll-hide').length > 0) return true; // body hidden so data already been validated successfully.\n\tvar openSession = jQuery('.poll-session-form:visible');\n\tif(openSession.length > 0){\n\t\tif(jQuery('input[name=sample\\:id]', openSession).val() == '' &&\n\t\t\t\tjQuery('input[name=sample\\:date]', openSession).val() == '" . lang::get('click here') . "' &&\n\t\t\t\tjQuery('[name=smpAttr\\:" . $args['start_time_attr_id'] . "],[name^=smpAttr\\:" . $args['start_time_attr_id'] . "\\:]', openSession).val() == '' &&\n\t\t\t\tjQuery('[name=smpAttr\\:" . $args['end_time_attr_id'] . "],[name^=smpAttr\\:" . $args['end_time_attr_id'] . "\\:]', openSession).val() == '' &&\n\t\t\t\tjQuery('[name=smpAttr\\:" . $args['sky_state_attr_id'] . "],[name^=smpAttr\\:" . $args['sky_state_attr_id'] . "\\:]', openSession).filter('[checked]').length == 0 &&\n    \t\t\tjQuery('[name=smpAttr\\:" . $args['temperature_attr_id'] . "],[name^=smpAttr\\:" . $args['temperature_attr_id'] . "\\:]', openSession).filter('[checked]').length == 0 &&\n    \t\t\tjQuery('[name=smpAttr\\:" . $args['wind_attr_id'] . "],[name^=smpAttr\\:" . $args['wind_attr_id'] . "\\:]', openSession).filter('[checked]').length == 0) {\n\t\t\t// NB shade is a boolean, and always has one set (default no)\n    \t\tjQuery('#cc-3').foldPanel();\n\t\t\treturn true;\n\t\t}\n\t}\n\t// not putting in an empty data set check here - user can delete the session if needed, and there must be at least one.\n\tif(!validateAndSubmitOpenSessions()) return false;\n\tjQuery('#cc-3').foldPanel();\n\tpopulateSessionSelect();\n\treturn true;\n};\njQuery('#cc-3-valid-button').click(function(){\n\tif(!validateAndSubmitOpenSessions()) return;\n\tjQuery('#cc-3').foldPanel();\n\tjQuery('#cc-4').showPanel();\n\tpopulateSessionSelect();\n});\njQuery('#cc-3-add-button').click(function(){\n\tif(!validateAndSubmitOpenSessions()) return;\n\taddSession();\n});\n\njQuery('.mod-button').click(function() {\n\t// first close all the other panels, ensuring any data is saved.\n\tif(!validateCollectionPanel() || !validateStationPanel() || !validateSessionsPanel() || !validateInsectPanel())\n\t\treturn;\n\tjQuery('#cc-5').hidePanel();\n\tjQuery(this).parents('.poll-section-title').parent().unFoldPanel(); //slightly complicated because cc-1 contains the rest.\n});\n\n";
        $extraParams = $readAuth + array('taxon_list_id' => $args['insect_list_id'], 'orderby' => 'taxon');
        $species_ctrl_args = array('label' => lang::get('LANG_Insect_Species'), 'fieldname' => 'insect:taxa_taxon_list_id', 'table' => 'taxa_taxon_list', 'captionField' => 'taxon', 'valueField' => 'id', 'columns' => 2, 'validation' => array('required'), 'blankText' => lang::get('LANG_Choose_Taxon'), 'extraParams' => $extraParams, 'suffixTemplate' => 'nosuffix');
        $r .= '
<div id="cc-4" class="poll-section">
  <div id="cc-4-title" class="ui-accordion-header ui-helper-reset ui-state-active ui-corner-all poll-section-title">' . lang::get('LANG_Photos') . '
    <div id="cc-4-mod-button" class="right ui-state-default ui-corner-all mod-button">' . lang::get('LANG_Modify') . '</div>
  </div>
  <div id="cc-4-photo-reel" class="ui-accordion-content ui-helper-reset ui-widget-content ui-corner-top ui-accordion-content-active photoReelContainer" >
  </div>
  <div id="cc-4-body" class="ui-accordion-content ui-helper-reset ui-widget-content ui-accordion-content-active poll-section-body">  
    <div id="cc-4-insect">
	  <form id="cc-4-insect-upload" enctype="multipart/form-data" action="' . iform_ajaxproxy_url($node, 'media') . '" method="POST">
    		<input type="hidden" id="website_id" name="website_id" value="' . $args['website_id'] . '" />
    		<input name="upload_file" type="file" class="required" />
    		<input type="submit" value="' . lang::get('LANG_Upload_Insect') . '" class="btn-submit" />
      </form>
 	  <div id="cc-4-insect-image" class="poll-image"></div>
 	  <div id="cc-4-insect-identify" class="poll-dummy-form">
 	    ' . iform_pollenators::help_button($use_help, "insect-help-button", $args['help_function'], $args['help_insect_arg']) . '
        <p><strong>' . lang::get('LANG_Identify_Insect') . '</strong></p>
        <label for="id-insect-later" class="follow-on">' . lang::get('LANG_ID_Insect_Later') . ' </label><input type="checkbox" id="id-insect-later" name="id-insect-later" /> 
		' . ($args['ID_tool_insect_url'] != '' && $args['ID_tool_insect_poll_dir'] ? '<label for="insect-id-button">' . lang::get('LANG_Insect_ID_Key_label') . ' :</label><span id="insect-id-button" class="ui-state-default ui-corner-all poll-id-button" >' . lang::get('LANG_Launch_ID_Key') . '</span>' : '') . '<span id="insect-id-cancel" class="ui-state-default ui-corner-all poll-id-cancel" >' . lang::get('LANG_Cancel_ID') . '</span>' . data_entry_helper::select($species_ctrl_args) . '
		<input type="text" name="insect:taxon_text_description" readonly="readonly">
      </div>
    </div>
    <div class="poll-break"></div> 
 	<form id="cc-4-main-form" action="' . iform_ajaxproxy_url($node, 'occurrence') . '" method="POST" >
    	<input type="hidden" id="website_id" name="website_id" value="' . $args['website_id'] . '" />
    	<input type="hidden" id="occurrence_image:path" name="occurrence_image:path" value="" />
    	<input type="hidden" id="occurrence:record_status" name="occurrence:record_status" value="C" />
        <input type="hidden" name="occurrence:use_determination" value="Y"/>    
    	<input type="hidden" name="determination:taxa_taxon_list_id" value=""/> 
        <input type="hidden" name="determination:taxon_text_description" value=""/>  	
		<input type="hidden" name="determination:cms_ref" value="' . $uid . '" />
    	<input type="hidden" name="determination:email_address" value="' . $email . '" />
    	<input type="hidden" name="determination:person_name" value="' . $username . '" /> 
        <input type="hidden" id="occurrence:id" name="occurrence:id" value="" disabled="disabled" />
	    <input type="hidden" id="determination:id" name="determination:id" value="" disabled="disabled" />
	    <input type="hidden" id="occurrence_image:id" name="occurrence_image:id" value="" disabled="disabled" />
	    <label for="occurrence:sample_id">' . lang::get('LANG_Session') . '</label>
	    <select id="occurrence:sample_id" name="occurrence:sample_id" value="" class="required" /></select>
	    ' . data_entry_helper::textarea(array('label' => lang::get('LANG_Comment'), 'fieldname' => 'occurrence:comment', 'suffixTemplate' => 'nosuffix')) . data_entry_helper::outputAttribute($occurrence_attributes[$args['number_attr_id']], $defAttrOptions) . data_entry_helper::outputAttribute($occurrence_attributes[$args['foraging_attr_id']], $defAttrOptions) . '
    </form>
    <span id="cc-4-valid-insect-button" class="ui-state-default ui-corner-all save-button">' . lang::get('LANG_Validate_Insect') . '</span>
    <span id="cc-4-delete-insect-button" class="ui-state-default ui-corner-all delete-button">' . lang::get('LANG_Delete_Insect') . '</span>
  </div>
  <div id="cc-4-footer" class="ui-accordion-content ui-helper-reset ui-widget-content ui-corner-bottom ui-accordion-content-active poll-section-footer">
    <div id="cc-4-valid-photo-button" class="ui-state-default ui-corner-all save-button">' . lang::get('LANG_Validate_Photos') . '</div>
  </div>
</div>
<div style="display:none" />
    <form id="cc-4-delete-insect" action="' . iform_ajaxproxy_url($node, 'occurrence') . '" method="POST">
       <input type="hidden" name="website_id" value="' . $args['website_id'] . '" />
       <input type="hidden" name="occurrence:use_determination" value="Y"/>    
       <input type="hidden" name="occurrence:id" value="" />
       <input type="hidden" name="occurrence:sample_id" value="" />
       <input type="hidden" name="occurrence:deleted" value="t" />
    </form>
</div>';
        data_entry_helper::$javascript .= "\nloadInsectPanel = null;\n\nvar insectTimer1;\nvar insectTimer2;\n\ninsectPoller = function(){\n\tinsectTimer1 = setTimeout('insectPoller();', " . $args['ID_tool_poll_interval'] . ");\n\t\$.get('" . str_replace("{HOST}", $_SERVER['HTTP_HOST'], $args['ID_tool_insect_poll_dir']) . session_id() . "_'+IDcounter.toString(), function(data){\n\tvar da = data.split('\\n');\n      // first count number of returned items.\n      // if > 1 put all into taxon_description.\n      // if = 1 rip out the description, remove the formatting, scan the flower select for it, and set the value. Set the taxon description.\n\t  da[1] = da[1].replace(/\\\\\\\\i\\{\\}/g, '').replace(/\\\\\\\\i0\\{\\}/g, '');\n      var items = da[1].split(':');\n\t  var count = items.length;\n\t  if(items[count-1] == '') count--;\n\t  if(count <= 0){\n\t  \t// no valid stuff so blank it all out.\n\t  \tjQuery('#cc-4-insect-identify > select[name=insect\\:taxa_taxon_list_id]').val('');\n\t  \tjQuery('#cc-4-flower-identify > select[name=insect\\:taxon_text_description]').val('');\n\t  } else if(count == 1){\n\t  \tjQuery('#cc-4-insect-identify > select[name=insect\\:taxa_taxon_list_id]').val('');\n\t  \tjQuery('#cc-4-insect-identify > select[name=insect\\:taxon_text_description]').val(items[0]);\n\t  \tvar x = jQuery('#cc-4-insect-identify').find('option').filter('[text='+items[0]+']');\n\t  \tif(x.length > 0){\n\t\t  \tjQuery('#cc-4-insect-identify > select[name=insect\\:taxon_text_description]').val('');\n\t  \t\tjQuery('#cc-4-insect-identify > select[name=insect\\:taxa_taxon_list_id]').val(x[0].value);\n  \t\t}\n\t  } else {\n\t  \tjQuery('#cc-4-insect-identify > select[name=insect\\:taxa_taxon_list_id]').val('');\n\t  \tjQuery('#cc-4-insect-identify > select[name=insect\\:taxon_text_description]').val(da[1]);\n\t  }\n\t  insectReset();\n    });\n};\ninsectReset = function(){\n\tclearTimeout(insectTimer1);\n\tclearTimeout(insectTimer2);\n\tjQuery('#insect-id-cancel').hide();\n};\n\njQuery('#insect-id-button').click(function(){\n\tIDcounter++;\n\tclearTimeout(insectTimer1);\n\tclearTimeout(insectTimer2);\n\twindow.open('" . $args['ID_tool_insect_url'] . session_id() . "_'+IDcounter.toString(),'','') \n\tinsectTimer1 = setTimeout('insectPoller();', " . $args['ID_tool_poll_interval'] . ");\n\tinsectTimer2 = setTimeout('insectReset();', " . $args['ID_tool_poll_timeout'] . ");\n\tjQuery('#insect-id-cancel').show();\n});\njQuery('#insect-id-cancel').click(function(){\n\tinsectReset();\n});\njQuery('#insect-id-cancel').hide();\n\n    \n// Insect upload picture form.\n\$('#cc-4-insect-upload').ajaxForm({ \n        dataType:  'json', \n        beforeSubmit:   function(data, obj, options){\n        \tif(jQuery('#cc-4-insect-upload input[name=upload_file]').val() == '')\n        \t\treturn false;\n        \t\$('#cc-4-insect-image').empty();\n        \t\$('#cc-4-insect-image').addClass('loading')\n        },\n        success:   function(data){\n        \tif(data.success == true){\n\t        \t// There is only one file\n\t        \tjQuery('form#cc-4-main-form input[name=occurrence_image\\:path]').val(data.files[0]);\n\t        \tvar img = new Image();\n\t        \t\$(img).load(function () {\n        \t\t\t\t\$(this).hide();\n        \t\t\t\t\$('#cc-4-insect-image').removeClass('loading').append(this);\n        \t\t\t\t\$(this).fadeIn();\n\t\t\t    \t})\n\t\t\t\t    .attr('src', '" . data_entry_helper::$base_url . data_entry_helper::$indicia_upload_path . "med-'+data.files[0])\n\t\t\t\t    .css('max-width', \$('#cc-4-insect-image').width()).css('max-height', \$('#cc-4-insect-image').height())\n\t\t\t\t    .css('vertical-align', 'middle').css('margin-left', 'auto').css('margin-right', 'auto').css('display', 'block');\n\t\t\t\tjQuery('#cc-4-insect-upload input[name=upload_file]').val('');\n\t\t\t} else {\n\t\t\t\tvar errorString = \"" . lang::get('LANG_Indicia_Warehouse_Error') . "\";\n\t        \tjQuery('form#cc-4-main-form input[name=occurrence_image\\:path]').val('');\n\t\t\t\t\$('#cc-4-insect-image').removeClass('loading');\n\t\t\t\tif(data.error){\n\t\t\t\t\terrorString = errorString + ' : ' + data.error;\n\t\t\t\t}\n\t\t\t\tif(data.errors){\n\t\t\t\t\tfor (var i in data.errors)\n\t\t\t\t\t{\n\t\t\t\t\t\terrorString = errorString + ' : ' + data.errors[i];\n\t\t\t\t\t}\t\t\t\t\n\t\t\t\t}\n\t\t\t\talert(errorString);\n\t\t\t}\n        } \n});\n\n\$('#cc-4-main-form').ajaxForm({ \n    dataType:  'json', \n    beforeSubmit:   function(data, obj, options){\n    \tvar valid = true;\n\t\tif (!jQuery('form#cc-4-main-form > input').valid()) { valid = false; }\n\t\tif (!validateRequiredField('occurrence\\:sample_id', 'form#cc-4-main-form')) { valid = false; }\n\t\tif (!validateRadio('occAttr\\:" . $args['number_attr_id'] . "', obj)) { valid = false; }\n    \tif(data[1].value == '' ){\n\t\t\talert(\"" . lang::get('LANG_Must_Provide_Insect_Picture') . "\");\n\t\t\tvalid = false;\n\t\t}\n\t\tdata[4].value = jQuery('select[name=insect\\:taxa_taxon_list_id]').val();\n\t\tdata[5].value = jQuery('select[name=insect\\:taxon_text_description]').val();\n\t\tif (jQuery('#id-insect-later').attr('checked') == ''){\n\t\t\tif (!validateRequiredField('insect\\:taxa_taxon_list_id', '#cc-4-insect-identify')) { valid = false; }\n\t\t} else {\n\t\t\tdata.splice(4,5); // remove determination entries.\n\t\t}\n\t\treturn valid;\n\t},\n    success:   function(data){\n       \tif(data.success == 'multiple records' && data.outer_table == 'occurrence'){\n       \t\t// if the currently highlighted thumbnail is blank, add the new insect.\n       \t\tvar thumbnail = jQuery('[occId='+data.outer_id+']');\n       \t\tif(thumbnail.length == 0){\n       \t\t\taddToPhotoReel(data.outer_id);\n       \t\t} else {\n       \t\t\tupdatePhotoReel(thumbnail, data.outer_id);\n  \t\t\t}\n\t\t\tif(loadInsectPanel == null){\n\t\t\t\tclearInsect();\n\t\t\t} else {\n\t\t\t\tloadInsect(loadInsectPanel);\n\t\t\t}\n\t\t\tloadInsectPanel=null;\n\t\t\twindow.scroll(0,0);\n        }\n\t}\n});\n\nvalidateInsectPanel = function(){\n\tif(jQuery('#cc-4').filter('.poll-hide').length > 0) return true; // panel is not visible so no data to fail validation.\n\tif(jQuery('#cc-4-body').filter('.poll-hide').length > 0) return true; // body hidden so data already been validated successfully.\n\tif(!validateInsect()){ return false; }\n  \tjQuery('#cc-4').foldPanel();\n\treturn true;\n};\n\nclearInsect = function(){\n\tjQuery('#cc-4-main-form').resetForm();\n\tjQuery('[name=insect\\:taxa_taxon_list_id]').val('');\n\tjQuery('[name=insect\\:taxon_text_description]').val('');\n    jQuery('#id-insect-later').removeAttr('checked').removeAttr('disabled');\n    jQuery('#cc-4-main-form').find('[name=determination:cms_ref]').val('" . $uid . "');\n    jQuery('#cc-4-main-form').find('[name=determination:email_address]').val('" . $email . "');\n    jQuery('#cc-4-main-form').find('[name=determination:person_name]').val('" . $username . "'); \n    jQuery('#cc-4-main-form').find('[name=occurrence_image\\:path]').val('');\n\tjQuery('#cc-4-main-form').find('[name=occurrence\\:id],[name=occurrence_image\\:id],[name=determination\\:id]').val('').attr('disabled', 'disabled');\n    jQuery('#cc-4-main-form').find('[name=occurrence_image\\:path]').val('');\n\tjQuery('#cc-4-main-form').find('[name^=occAttr\\:]').each(function(){\n\t\tvar name = jQuery(this).attr('name').split(':');\n\t\tjQuery(this).attr('name', name[0]+':'+name[1]);\n\t});\n    jQuery('#cc-4-insect-image').empty();\n};\n\nloadInsect = function(id){\n\tclearInsect();\n\t\$.getJSON(\"" . $svcUrl . "/data/occurrence/\" + id +\n          \"?mode=json&view=detail&nonce=" . $readAuth['nonce'] . "&auth_token=" . $readAuth['auth_token'] . "&callback=?\", function(data) {\n\t    if (data.length>0) {\n\t        jQuery('form#cc-4-main-form > input[name=occurrence\\:id]').removeAttr('disabled').val(data[0].id);\n\t        jQuery('form#cc-4-main-form > [name=occurrence\\:sample_id]').val(data[0].sample_id);\n\t\t\tjQuery('form#cc-4-main-form > textarea[name=occurrence\\:comment]').val(data[0].comment);\n\t\t\tloadAttributes('occurrence_attribute_value', 'occurrence_attribute_id', 'occurrence_id', 'occurrence\\:id', data[0].id, 'occAttr');\n    \t\tloadImage('occurrence_image', 'occurrence_id', 'occurrence\\:id', data[0].id, '#cc-4-insect-image');\n  \t\t}\n\t});\n\t\$.getJSON(\"" . $svcUrl . "/data/determination?occurrence_id=\" + id +\n          \"&mode=json&view=list&nonce=" . $readAuth['nonce'] . "&auth_token=" . $readAuth['auth_token'] . "&callback=?\", function(data) {\n\t    if (data.length>0) {\n\t    \tjQuery('#id-insect-later').removeAttr('checked').attr('disabled', 'disabled');\n\t        jQuery('form#cc-4-main-form > input[name=determination\\:id]').removeAttr('disabled').val(data[0].id);\n\t        jQuery('form#cc-4-main-form > input[name=determination\\:cms_ref]').val(data[0].cms_ref);\n\t        jQuery('form#cc-4-main-form > input[name=determination\\:email_address]').val(data[0].email_address);\n\t        jQuery('form#cc-4-main-form > input[name=determination\\:person_name]').val(data[0].person_name);\n       \t\tjQuery('[name=insect\\:taxa_taxon_list_id]').val(data[0].taxa_taxon_list_id);\n       \t\tjQuery('[name=insect\\:taxon_text_description]').val(data[0].taxon_text_description);\n  \t\t} else\n  \t\t\tjQuery('#id-insect-later').attr('checked', 'checked').removeAttr('disabled');\n\t});\t\n}\n\nupdatePhotoReel = function(container, occId){\n\tcontainer.empty();\n\t\$.getJSON(\"" . $svcUrl . "/data/occurrence_image\" +\n   \t\t\t\"?mode=json&view=list&nonce=" . $readAuth['nonce'] . "&auth_token=" . $readAuth['auth_token'] . "\" +\n   \t\t\t\"&occurrence_id=\" + occId + \"&callback=?\", function(imageData) {\n\t\tif (imageData.length>0) {\n\t\t\tvar img = new Image();\n\t\t\tjQuery(img).attr('src', '" . data_entry_helper::$base_url . data_entry_helper::$indicia_upload_path . "thumb-'+imageData[0].path)\n\t\t\t    .attr('width', container.width()).attr('height', container.height()).addClass('thumb-image').appendTo(container);\n\t\t}\n\t});\n\t\$.getJSON(\"" . $svcUrl . "/data/determination\" + \n    \t\t\"?mode=json&view=list&nonce=" . $readAuth['nonce'] . "&auth_token=" . $readAuth['auth_token'] . "\" + \n    \t\t\"&occurrence_id=\" + occId + \"&deleted=f&callback=?\", function(detData) {\n\t    if (detData.length==0) {\n\t    \t// no determination records, so no attempt made at identification. Put up a question mark.\n\t\t\tjQuery('<span>?</span>').addClass('thumb-text').appendTo(container);\n\t\t}\n\t});\n}\n\naddToPhotoReel = function(occId){\n\t// last photo in list is the blank empty one. Add to just before this.\n\tvar container = jQuery('<div/>').addClass('thumb').insertBefore('.blankPhoto').attr('occId', occId.toString()).click(function () {setInsect(this, occId)});\n\tupdatePhotoReel(container, occId);\n}\n\nsetInsect = function(context, id){\n\t// first close all the other panels, ensuring any data is saved.\n\tif(!validateCollectionPanel() || !validateStationPanel() || !validateSessionsPanel())\n\t\treturn;\n\t\t\n\tif(jQuery('#cc-4-body').filter('.poll-hide').length > 0) {\n\t\tjQuery('div#cc-4').unFoldPanel();\n\t\tloadInsect(id);\n\t} else {\n\t\tloadInsectPanel=id;\n\t\tif(!validateInsect()){\n\t\t\tloadInsectPanel=null;\n\t\t\treturn;\n\t\t} \n\t}\n\tjQuery('.currentPhoto').removeClass('currentPhoto');\n\tjQuery('[occId='+id+']').addClass('currentPhoto');\n};\n\nsetNoInsect = function(){\n\t// first close all the other panels, ensuring any data is saved.\n\tif(!validateCollectionPanel() || !validateStationPanel() || !validateSessionsPanel())\n\t\treturn;\n\t\t\n\tif(jQuery('#cc-4-body').filter('.poll-hide').length > 0)\n\t\tjQuery('div#cc-4').unFoldPanel();\n\telse\n\t\tif(!validateInsect()){ return ; }\n\t// At this point the empty panel is displayed, as it is reset after a successful validate.\t\n\tjQuery('.currentPhoto').removeClass('currentPhoto');\n\tjQuery('.blankPhoto').addClass('currentPhoto');\n};\n\ncreatePhotoReel = function(div){\n\tjQuery(div).empty();\n\tjQuery('<div/>').addClass('blankPhoto thumb currentPhoto').appendTo(div).click(setNoInsect);\n}\n\ncreatePhotoReel('#cc-4-photo-reel');\n\n// TODO separate photoreel out into own js\n\nvalidateInsect = function(){\n\t// TODO will have to expand when use key.\n\tif(jQuery('form#cc-4-main-form > input[name=occurrence\\:id]').val() == '' &&\n\t\t\tjQuery('form#cc-4-main-form > input[name=occurrence_image\\:path]').val() == '' &&\n\t\t\tjQuery('[name=insect\\:taxa_taxon_list_id]').val() == '' &&\n\t\t\tjQuery('form#cc-4-main-form > textarea[name=occurrence\\:comment]').val() == '' &&\n\t\t\tjQuery('[name=occAttr\\:" . $args['number_attr_id'] . "],[name^=occAttr\\:" . $args['number_attr_id'] . "\\:]').filter('[checked]').length == 0){\n\t\tif(loadInsectPanel != null){\n\t\t\tloadInsect(loadInsectPanel);\n\t\t}\n\t\tloadInsectPanel=null;\n\t\treturn true;\n\t}\n\tvar valid = true;\n    if (!jQuery('form#cc-4-main-form > input').valid()) { return false; }\n  \tif (!validateRadio('occAttr\\:" . $args['number_attr_id'] . "', 'form#cc-4-main-form')) { valid = false; }\n\t\tif (jQuery('#id-insect-later').attr('checked') == ''){\n\t\t\tif (!validateRequiredField('insect\\:taxa_taxon_list_id', '#cc-4-insect-identify')) { valid = false; }\n\t\t}\n \tif (!validateRequiredField('occurrence\\:sample_id', 'form#cc-4-main-form')) { valid = false; }\n\tif(jQuery('form#cc-4-main-form input[name=occurrence_image\\:path]').val() == ''){\n\t\talert(\"" . lang::get('LANG_Must_Provide_Insect_Picture') . "\");\n\t\tvalid = false;;\n\t}\n\tif(valid == false) return false;\n\tjQuery('form#cc-4-main-form').submit();\n\treturn true;\n  }\n\n\$('#cc-4-valid-insect-button').click(validateInsect);\n\n\$('#cc-4-delete-insect-button').click(function() {\n\tvar container = \$(this).parent().parent();\n\tjQuery('#cc-4-delete-insect').find('[name=occurrence\\:id]').val(jQuery('#cc-4-main-form').find('[name=occurrence\\:id]').val());\n\tjQuery('#cc-4-delete-insect').find('[name=occurrence\\:sample_id]').val(jQuery('#cc-4-main-form').find('[name=occurrence\\:sample_id]').val());\n\tif(confirm(\"" . lang::get('LANG_Confirm_Insect_Delete') . "\")){\n\t\tif(jQuery('#cc-4-main-form').find('[name=occurrence\\:id]').filter('[disabled]').length == 0){\n\t\t\tjQuery('#cc-4-delete-insect').submit();\n\t\t\tjQuery('.currentPhoto').remove();\n\t\t\tjQuery('.blankPhoto').addClass('currentPhoto');\n\t\t}\n\t\tclearInsect();\n\t}\n});\n\n\$('#cc-4-delete-insect').ajaxForm({ \n        dataType:  'json', \n        beforeSubmit:   function(data, obj, options){\n  \t\t\t// Warning this assumes that the data is fixed position:\n        \tif(data[2].value == '') return false;\n        \treturn true;\n  \t\t},\n        success:   function(data){\n  \t\t} \n});\n\n\$('#cc-4-valid-photo-button').click(function(){\n\tif(!validateInsect()) return;\n\tjQuery('#cc-4').foldPanel();\n\tjQuery('#cc-5').showPanel();\n\tvar numInsects = jQuery('#cc-4-photo-reel').find('.thumb').length - 1; // ignore blank\n\tvar numUnidentified = jQuery('#cc-4-photo-reel').find('.thumb-text').length;\n\tif(jQuery('#id-flower-later').attr('checked') != '' || numInsects==0 || (numUnidentified/numInsects > (1-(" . $args['percent_insects'] . "/100.0)))){\n\t\tjQuery('#cc-5-good').hide();\n\t\tjQuery('#cc-5-bad').show();\n\t\tjQuery('#cc-5-complete-collection').hide();\n\t\tjQuery('#cc-5-trailer').hide();\n    } else {\n    \tjQuery('#cc-5-good').show();\n\t\tjQuery('#cc-5-bad').hide();\n\t\tjQuery('#cc-5-complete-collection').show();\n\t\tjQuery('#cc-5-trailer').show();\n\t}\n});\n";
        $r .= '
<div id="cc-5" class="poll-section">
  <div id="cc-5-body" class="ui-accordion-header ui-helper-reset ui-state-active ui-corner-all poll-section-body"> 
   <p id="cc-5-good">' . lang::get('LANG_Can_Complete_Msg') . '</p> 
   <p id="cc-5-bad">' . lang::get('LANG_Cant_Complete_Msg') . '</p> 
   <div style="display:none" />
    <form id="cc-5-collection" action="' . iform_ajaxproxy_url($node, 'sample') . '" method="POST">
       <input type="hidden" name="website_id" value="' . $args['website_id'] . '" />
       <input type="hidden" name="sample:survey_id" value="' . $args['survey_id'] . '" />
       <input type="hidden" name="sample:id" value="" />
       <input type="hidden" name="sample:date" value="2010-01-01"/>
       <input type="hidden" name="sample:location_id" value="" />
       <input type="hidden" id="smpAttr:' . $args['complete_attr_id'] . '" name="smpAttr:' . $args['complete_attr_id'] . '" value="1" />
    </form>
   </div>
   <div id="cc-5-complete-collection" class="ui-state-default ui-corner-all complete-button">' . lang::get('LANG_Complete_Collection') . '</div>
  </div>
  <div id="cc-5-trailer" class="poll-section-trailer">
    <p>' . lang::get('LANG_Trailer_Head') . '</p>
    <ul>
      <li>' . lang::get('LANG_Trailer_Point_1') . '</li>
      <li>' . lang::get('LANG_Trailer_Point_2') . '</li>
      <li>' . lang::get('LANG_Trailer_Point_3') . '</li>
      <li>' . lang::get('LANG_Trailer_Point_4') . '</li>
    </ul>
  </div>
</div>';
        data_entry_helper::$javascript .= "\n\$('#cc-5-collection').ajaxForm({ \n        dataType:  'json', \n        beforeSubmit:   function(data, obj, options){\n       \t\tdata[2].value = jQuery('#cc-1-collection-details input[name=sample\\:id]').val();\n       \t\tvar date_start = '';\n       \t\tvar date_end = '';\n       \t\tjQuery('.poll-session').find('[name=sample\\:date]').each(function(index, el){\n       \t\t\tvar value = \$(this).val();\n       \t\t\tif(date_start == '' || date_start > value) {\n       \t\t\t\tdate_start = value;\n       \t\t\t}\n       \t\t\tif(date_end == '' || date_end < value) {\n       \t\t\t\tdate_end = value;\n       \t\t\t}\n  \t\t\t});\n  \t\t\tif(date_start == date_end){\n\t       \t\tdata[3].value = date_start;\n\t       \t} else {\n\t       \t\tdata[3].value = date_start+' to '+date_end;\n  \t\t\t}\n\t       \tjQuery('[name=sample\\:date]:hidden').val(data[3].value);\n  \t\t\tdata[4].value = jQuery('#cc-1-collection-details input[name=location\\:id]').val();\n       \t\tdata[5].name = jQuery('#cc-1-collection-details input[name^=smpAttr\\:" . $args['complete_attr_id'] . "\\:]').attr('name');\n        \treturn true;\n  \t\t},\n        success:   function(data){\n\t\t\t\$('#cc-6').showPanel();\n  \t\t} \n});\n\$('#cc-5-complete-collection').click(function(){\n\tjQuery('#cc-2,#cc-3,#cc-4,#cc-5').hidePanel();\n\tjQuery('.reinit-button').hide();\n\tjQuery('.mod-button').hide();\n\tjQuery('#cc-5-collection').submit();\n});\n";
        $r .= '
<div id="cc-6" class="poll-section">
  <div id="cc-6-body" class="ui-accordion-header ui-helper-reset ui-state-active ui-corner-top poll-section-body"> 
   <p>' . lang::get('LANG_Final_1') . '</p> 
   <p>' . lang::get('LANG_Final_2') . '</p> 
   </div>
  <div id="cc-6-footer" class="ui-accordion-content ui-helper-reset ui-widget-content ui-corner-bottom ui-accordion-content-active poll-section-footer">
    <a id="cc-6-consult-collection" href="" class="ui-state-default ui-corner-all link-button">' . lang::get('LANG_Consult_Collection') . '</a>
    <a href="' . url('node/' . $node->nid) . '" class="ui-state-default ui-corner-all link-button">' . lang::get('LANG_Create_New_Collection') . '</a>
  </div>
</div>
</div></div>';
        data_entry_helper::$javascript .= "\n \t\t\t\nloadAttributes = function(attributeTable, attributeKey, key, keyName, keyValue, prefix){\n\tvar form = jQuery('input[name='+keyName+'][value='+keyValue+']').parent();\n\tvar checkboxes = jQuery('[name^='+prefix+'\\:]', form).filter(':checkbox').removeAttr('checked');\n\tcheckboxes.each(function(){\n\t\tvar name = jQuery(this).attr('name').split(':');\n\t\tif(name.length > 2)\n\t\t\tjQuery(this).attr('name', name[0]+':'+name[1]+'[]');\n\t});\n\t\n\t\$.getJSON(\"" . $svcUrl . "/data/\" + attributeTable +\n   \t\t\t\"?mode=json&view=list&nonce=" . $readAuth['nonce'] . "&auth_token=" . $readAuth['auth_token'] . "\" +\n   \t\t\t\"&\" + key + \"=\" + keyValue + \"&callback=?\", function(attrdata) {\n\t\tif (attrdata.length>0) {\n\t\t\tvar form = jQuery('input[name='+keyName+'][value='+keyValue+']').parent();\n\t\t\tfor (var i=0;i<attrdata.length;i++){\n\t\t\t\tif (attrdata[i].id && (attrdata[i].iso == null || attrdata[i].iso == '' || attrdata[i].iso == '" . $language . "')){\n\t\t\t\t\tvar checkboxes = jQuery('[name='+prefix+'\\:'+attrdata[i][attributeKey]+'\\[\\]],[name^='+prefix+'\\:'+attrdata[i][attributeKey]+':]', form).filter(':checkbox');\n\t\t\t\t\tvar radiobuttons = jQuery('[name='+prefix+'\\:'+attrdata[i][attributeKey]+'],[name^='+prefix+'\\:'+attrdata[i][attributeKey]+':]', form).filter(':radio');\n\t\t\t\t\tif(radiobuttons.length > 0){\n\t\t\t\t\t\tradiobuttons\n\t\t\t\t\t\t\t.attr('name', prefix+':'+attrdata[i][attributeKey]+':'+attrdata[i].id)\n\t\t\t\t\t\t\t.filter('[value='+attrdata[i].raw_value+']')\n\t\t\t\t\t\t\t.attr('checked', 'checked');\n\t\t\t\t\t} else \tif(checkboxes.length > 0){\n\t\t\t\t\t\tvar checkbox = checkboxes.filter('[value='+attrdata[i].raw_value+']')\n\t\t\t\t\t\t\t.attr('name', prefix+':'+attrdata[i][attributeKey]+':'+attrdata[i].id)\n\t\t\t\t\t\t\t.attr('checked', 'checked');\n\t\t\t\t\t} else {\n\t\t\t\t\t\tjQuery('[name='+prefix+'\\:'+attrdata[i][attributeKey]+']', form)\n\t\t\t\t\t\t\t.attr('name', prefix+':'+attrdata[i][attributeKey]+':'+attrdata[i].id)\n\t\t\t\t\t\t\t.val(attrdata[i].raw_value);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tcheckProtocolStatus();\n\t\tpopulateSessionSelect();\n\t});\n}\n\nloadImage = function(imageTable, key, keyName, keyValue, target){\n\t\t\t\t\t// location_image, location_id, location:id, 1, #cc-4-insect-image\n\t\$.getJSON(\"" . $svcUrl . "/data/\" + imageTable +\n   \t\t\t\"?mode=json&view=list&nonce=" . $readAuth['nonce'] . "&auth_token=" . $readAuth['auth_token'] . "\" +\n   \t\t\t\"&\" + key + \"=\" + keyValue + \"&callback=?\", function(imageData) {\n\t\tif (imageData.length>0) {\n\t\t\tvar form = jQuery('input[name='+keyName+'][value='+keyValue+']').parent();\n\t\t\tjQuery('[name='+imageTable+'\\:id]', form).val(imageData[0].id).removeAttr('disabled');\n\t\t\tjQuery('[name='+imageTable+'\\:path]', form).val(imageData[0].path);\n\t\t\tvar img = new Image();\n\t\t\t\$(img).load(function () {\n        \t\t\t\$(target).empty().append(this);\n\t\t\t    })\n\t\t\t    .attr('src', '" . data_entry_helper::$base_url . data_entry_helper::$indicia_upload_path . "med-'+imageData[0].path)\n\t\t\t\t.css('max-width', \$(target).width()).css('max-height', \$(target).height()).css('display', 'block')\n\t\t\t\t.css('vertical-align', 'middle').css('margin-left', 'auto').css('margin-right', 'auto');\n\t\t}\n\t});\n}\n\n// load in any existing incomplete collection.\n// general philosophy is that you are taken back to the stage last verified.\n// Load in the first if there are more than one. Use the internal report which provides my collections.\n// Requires that there is an attribute for completeness, and one for the CMS\n// load the data in the order it is entered, so can stop when get to the point where the user finished.\n// have to reset the entire form first...\njQuery('.poll-section').resetPanel();\n// Default state: hide everything except the collection details block.\njQuery('.poll-section').hidePanel();\njQuery('#cc-1').showPanel();\njQuery('.reinit-button').hide();\naddSession();\n\njQuery.getJSON(\"" . $svcUrl . "\" + \"/report/requestReport?report=poll_my_collections.xml&reportSource=local&mode=json\" +\n\t\t\t\"&auth_token=" . $readAuth['auth_token'] . "&nonce=" . $readAuth["nonce"] . "\" + \n\t\t\t\"&survey_id=" . $args['survey_id'] . "&userID_attr_id=" . $args['uid_attr_id'] . "&userID=" . $uid . "&complete_attr_id=" . $args['complete_attr_id'] . "&callback=?\", function(data) {\n\tif (data.length>0) {\n\t\tvar i;\n       \tfor ( i=0;i<data.length;i++) {\n       \t\tif(data[i].completed == '0'){\n       \t\t    jQuery('#cc-6-consult-collection').attr('href', '" . url('node/' . $args['gallery_node']) . "'+'?collection_id='+data[i].id);\n       \t\t\t// load up collection details: existing ID, location name and protocol\n       \t\t\tjQuery('#cc-1-collection-details,#cc-2').find('input[name=sample\\:id]').val(data[i].id).removeAttr('disabled');\n       \t\t\t// main sample date is only set when collection is completed, so leave default.\n       \t\t\tloadAttributes('sample_attribute_value', 'sample_attribute_id', 'sample_id', 'sample\\:id', data[i].id, 'smpAttr');\n  \t\t\t\t\$.getJSON(\"" . $svcUrl . "/data/location/\" + data[i].location_id +\n          \t\t\t\t\t\"?mode=json&view=detail&nonce=" . $readAuth['nonce'] . "&auth_token=" . $readAuth['auth_token'] . "\" +\n          \t\t\t\t\t\"&callback=?\", function(locationdata) {\n\t\t    \t\tif (locationdata.length>0) {\n\t\t    \t\t\tjQuery('input[name=location\\:id]').val(locationdata[0].id).removeAttr('disabled');\n\t    \t\t\t\tjQuery('input[name=location\\:name]').val(locationdata[0].name);\n       \t\t\t\t\tjQuery('input[name=sample\\:location_name]').val(locationdata[0].name); // make sure the 2 coincide\n\t    \t\t\t\t// NB the location geometry is stored in centroid, due to restrictions in location model.\n\t    \t\t\t\tjQuery('input[name=location\\:centroid_sref]').val(locationdata[0].centroid_sref);\n\t    \t\t\t\tjQuery('input[name=location\\:centroid_sref_system]').val(locationdata[0].centroid_sref_system);\n\t    \t\t\t\tjQuery('input[name=location\\:centroid_geom]').val(locationdata[0].centroid_geom);\n\t    \t\t\t\tjQuery('input[name=locations_website\\:website_id]').attr('disabled', 'disabled');\n\t    \t\t\t\tloadAttributes('location_attribute_value', 'location_attribute_id', 'location_id', 'location\\:id', locationdata[0].id, 'locAttr');\n    \t   \t\t\t\tloadImage('location_image', 'location_id', 'location\\:id', locationdata[0].id, '#cc-2-environment-image');\n\t\t\t\t\t\tjQuery('#imp-sref').change();\n\t\t\t\t        var parts=locationdata[0].centroid_sref.split(' ');\n \t\t\t\t\t\tjQuery('input[name=place\\:lat]').val(parts[0]);\n\t\t\t\t\t\tjQuery('input[name=place\\:long]').val(parts[1]);\n  \t\t\t\t\t}\n  \t\t\t\t});\n  \t\t\t\t\$.getJSON(\"" . $svcUrl . "/data/occurrence/\" +\n          \t\t\t\t\t\"?mode=json&view=detail&nonce=" . $readAuth['nonce'] . "&auth_token=" . $readAuth['auth_token'] . "\" +\n          \t\t\t\t\t\"&sample_id=\"+data[i].id+\"&callback=?\", function(flowerData) {\n          \t\t\t// there will only be an occurrence if the floral station panel has previously been displayed & validated. \n\t\t    \t\tif (flowerData.length>0) {\n  \t\t\t\t\t\t\$('#cc-1').foldPanel();\n  \t\t\t\t\t\t\$('#cc-2').showPanel();\n\t\t    \t\t\tjQuery('form#cc-2-floral-station > input[name=occurrence\\:sample_id]').val(data[i].id);\n\t\t    \t\t\tjQuery('form#cc-2-floral-station > input[name=occurrence\\:id]').val(flowerData[0].id).removeAttr('disabled');\n\t\t    \t\t\tloadAttributes('occurrence_attribute_value', 'occurrence_attribute_id', 'occurrence_id', 'occurrence\\:id', flowerData[0].id, 'occAttr');\n    \t   \t\t\t\tloadImage('occurrence_image', 'occurrence_id', 'occurrence\\:id', flowerData[0].id, '#cc-2-flower-image');\n\n    \t   \t\t\t\t\$.getJSON(\"" . $svcUrl . "/data/determination\" + \n    \t      \t\t\t\t\t\t\"?mode=json&view=list&nonce=" . $readAuth['nonce'] . "&auth_token=" . $readAuth['auth_token'] . "&occurrence_id=\"+flowerData[0].id+\"&deleted=f&callback=?\",\n    \t      \t\t\t\t\tfunction(detData) {\n\t    \t\t\t  \t\tif (detData.length>0) {\n\t\t\t\t\t\t\t\tjQuery('#id-flower-later').removeAttr('checked').attr('disabled', 'disabled');\n\t    \t\t\t  \t\t\tjQuery('form#cc-2-floral-station > input[name=determination\\:id]').val(detData[0].id).removeAttr('disabled');\n\t\t    \t\t\t\t\tjQuery('form#cc-2-floral-station > input[name=determination\\:cms_ref]').val(detData[0].cms_ref);\n\t\t\t\t\t\t\t\tjQuery('form#cc-2-floral-station > input[name=determination\\:email_address]').val(detData[0].email_address);\n\t\t\t\t\t\t\t\tjQuery('form#cc-2-floral-station > input[name=determination\\:person_name]').val(detData[0].person_name);\n\t\t\t\t\t\t\t\tjQuery('select[name=flower\\:taxa_taxon_list_id]').val(detData[0].taxa_taxon_list_id);\n\t\t\t\t\t\t\t\tjQuery('select[name=flower\\:taxon_text_description]').val(detData[0].taxon_text_description);\n  \t\t\t\t\t\t\t} else {\n\t    \t\t\t  \t\t\tjQuery('form#cc-2-floral-station > input[name=determination\\:id]').val('').attr('disabled', 'disabled');\n\t\t\t\t\t\t\t\tjQuery('#id-flower-later').attr('checked', 'checked').removeAttr('disabled');\n\t\t\t\t\t\t\t}\n  \t\t\t\t\t\t});\n\n    \t   \t\t\t\t\$.getJSON(\"" . $svcUrl . "/data/sample\" + \n    \t      \t\t\t\t\t\"?mode=json&view=detail&nonce=" . $readAuth['nonce'] . "&auth_token=" . $readAuth['auth_token'] . "&parent_id=\"+data[i].id+\"&callback=?\", function(sessiondata) {\n\t    \t\t\t  \t\tif (sessiondata.length>0) {\n\t\t\t\t\t\t\t\tjQuery('#cc-2').foldPanel();\n\t\t\t\t\t\t\t\tsessionCounter = 0;\n\t\t\t\t\t\t\t\tjQuery('#cc-3-body').empty();\n \t\t\t\t\t\t\t\t\$('#cc-3').showPanel();\n\t\t\t\t\t\t\t\tfor (var i=0;i<sessiondata.length;i++){\n\t\t\t\t\t\t\t\t\tvar thisSession = addSession();\n\t\t\t\t\t\t\t\t\tjQuery('input[name=sample\\:id]', thisSession).val(sessiondata[i].id).removeAttr('disabled');\n\t\t\t\t\t\t\t\t\tjQuery('input[name=sample\\:date]', thisSession).val(sessiondata[i].date_start);\n       \t\t\t\t\t\t\t\tloadAttributes('sample_attribute_value', 'sample_attribute_id', 'sample_id', 'sample\\:id', sessiondata[i].id, 'smpAttr');\n  \t\t\t\t\t\t\t\t\t// fold this session.\n  \t\t\t\t\t\t\t\t\tthisSession.show();\n\t\t\t\t\t\t\t\t\tthisSession.children(':first').show().children().show();\n\t\t\t\t\t\t\t\t\tthisSession.children().not(':first').hide();\n\t\t\t\t\t\t\t\t\t\$.getJSON(\"" . $svcUrl . "/data/occurrence/\" +\n          \t\t\t\t\t\t\t\t\t\"?mode=json&view=detail&nonce=" . $readAuth['nonce'] . "&auth_token=" . $readAuth['auth_token'] . "&orderby=id\" +\n          \t\t\t\t\t\t\t\t\t\"&sample_id=\"+sessiondata[i].id+\"&callback=?\", function(insectData) {\n\t\t    \t\t\t\t\t\t\tif (insectData.length>0) {\n \t\t\t\t\t\t\t\t\t\t\tfor (var j=0;j<insectData.length;j++){\n\t\t\t\t\t\t\t\t\t\t\t\taddToPhotoReel(insectData[j].id);\n\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t}\n\t\t    \t\t\t\t\t\t});\n\t\t\t\t\t\t\t\t}\n \t\t\t\t\t\t\t\t\$('#cc-3').foldPanel();\n \t\t\t\t\t\t\t\t\$('#cc-4').showPanel();\n\t\t\t\t\t\t\t\tpopulateSessionSelect();\n \t\t\t\t\t  \t\t}\n \t\t\t\t\t  \t\t\$('.loading-panel').remove();\n\t\t\t\t\t\t\t\$('.loading-hide').removeClass('loading-hide');\n\t\t\t\t\t\t});\n    \t   \t\t\t} else {\n    \t   \t\t\t\t\$('.loading-panel').remove();\n\t\t\t\t\t\t\$('.loading-hide').removeClass('loading-hide');\n    \t   \t\t\t}\n  \t\t\t\t});\n\t\t\t\t// only use the first one which is not complete..\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\tif (i >= data.length) {\n\t\t\t\$('.loading-panel').remove();\n\t\t\t\$('.loading-hide').removeClass('loading-hide');\n  \t\t}\n\t} else {\n\t\t\$('.loading-panel').remove();\n\t\t\$('.loading-hide').removeClass('loading-hide');\n\t}\n});\n  \n  ";
        // because of the use of getJson to retrieve the data - which is asynchronous, the use of the normal loading_block_end
        // is not practical - it will do its stuff before the data is loaded, defeating the purpose. Also it uses hide (display:none)
        // which is a no-no in relation to the map. This means we have to dispense with the slow fade in.
        // it is also complicated by the attibutes and images being loaded asynchronously - and non-linearly.
        // Do the best we can!
        data_entry_helper::$onload_javascript .= "jQuery('#map')[0].map.searchLayer.events.register('featuresadded', {}, function(a1){\n\tif(inseeLayer != null)\n\t\tinseeLayer.destroyFeatures();\n});\njQuery('#map')[0].map.editLayer.events.register('featuresadded', {}, function(a1){\n\tif(inseeLayer != null)\n\t\tinseeLayer.destroy();\n\t\t\n  \tvar filter = new OpenLayers.Filter.Spatial({\n  \t\t\ttype: OpenLayers.Filter.Spatial.CONTAINS ,\n    \t\tproperty: 'the_geom',\n    \t\tvalue: jQuery('#map')[0].map.editLayer.features[0].geometry\n  \t\t});\n\n\tvar strategy = new OpenLayers.Strategy.Fixed({preload: false, autoActivate: false});\n\tvar styleMap = new OpenLayers.StyleMap({\n                \"default\": new OpenLayers.Style({\n                    fillColor: \"Red\",\n                    strokeColor: \"Red\",\n                    fillOpacity: 0,\n                    strokeWidth: 1\n                  })\n\t});\n\tinseeLayer = new OpenLayers.Layer.Vector('INSEE Layer', {\n\t\t  styleMap: styleMap,\n          strategies: [strategy],\n          displayInLayerSwitcher: false,\n\t      protocol: new OpenLayers.Protocol.WFS({\n              url:  '" . str_replace("{HOST}", $_SERVER['HTTP_HOST'], $args['INSEE_url']) . "',\n\t          featurePrefix: '" . $args['INSEE_prefix'] . "',\n              featureType: '" . $args['INSEE_type'] . "',\n              geometryName:'the_geom',\n              featureNS: '" . $args['INSEE_ns'] . "',\n              srsName: 'EPSG:900913',\n              version: '1.1.0'                  \n      \t\t  ,propertyNames: ['the_geom', 'NOM', 'INSEE_NEW', 'DEPT_NUM', 'DEPT_NOM', 'REG_NUM', 'REG_NOM']\n  \t\t\t})\n    });\n    inseeLayer.events.register('featuresadded', {}, function(a1){\n    \tjQuery('#cc-2-loc-description').empty();\n    \tjQuery('<span>'+a1.features[0].attributes.NOM+' ('+a1.features[0].attributes.INSEE_NEW+'), '+a1.features[0].attributes.DEPT_NOM+' ('+a1.features[0].attributes.DEPT_NUM+'), '+a1.features[0].attributes.REG_NOM+' ('+a1.features[0].attributes.REG_NUM+')</span>').appendTo('#cc-2-loc-description');\n    });\n\tjQuery('#map')[0].map.addLayer(inseeLayer);\n\tstrategy.load({filter: filter});\n});\n\n";
        global $indicia_templates;
        $r .= $indicia_templates['loading_block_end'];
        return $r;
    }
Ejemplo n.º 23
0
 /**
  * Return the generated form output.
  * @param array $args List of parameter values passed through to the form depending on how the form has been configured.
  * This array always contains a value for language.
  * @param object $node The Drupal node object.
  * @param array $response When this form is reloading after saving a submission, contains the response from the service call.
  * Note this does not apply when redirecting (in this case the details of the saved object are in the $_GET data).
  * @return Form HTML.
  * @todo: Implement this method 
  */
 public static function get_form($args, $node, $response = null)
 {
     if (empty($_GET['group_id'])) {
         return 'This page needs a group_id URL parameter.';
     }
     require_once 'includes/map.php';
     require_once 'includes/groups.php';
     global $indicia_templates;
     iform_load_helpers(array('report_helper', 'map_helper'));
     $conn = iform_get_connection_details($node);
     $readAuth = report_helper::get_read_auth($conn['website_id'], $conn['password']);
     report_helper::$javascript .= "indiciaData.website_id={$conn['website_id']};\n";
     report_helper::$javascript .= "indiciaData.nodeId={$node->nid};\n";
     group_authorise_form($args, $readAuth);
     $group = data_entry_helper::get_population_data(array('table' => 'group', 'extraParams' => $readAuth + array('id' => $_GET['group_id'], 'view' => 'detail')));
     $group = $group[0];
     hostsite_set_page_title("{$group['title']}: {$node->title}");
     $actions = array();
     if (!empty($args['edit_location_path'])) {
         $actions[] = array('caption' => 'edit', 'url' => '{rootFolder}' . $args['edit_location_path'], 'urlParams' => array('group_id' => $_GET['group_id'], 'location_id' => '{location_id}'));
     }
     $actions[] = array('caption' => 'remove', 'javascript' => "remove_location_from_group({groups_location_id});");
     $leftcol = report_helper::report_grid(array('readAuth' => $readAuth, 'dataSource' => 'library/locations/locations_for_groups', 'sendOutputToMap' => true, 'extraParams' => array('group_id' => $_GET['group_id']), 'rowId' => 'location_id', 'columns' => array(array('display' => 'Actions', 'actions' => $actions, 'caption' => 'edit', 'url' => '{rootFolder}'))));
     $leftcol .= '<fieldset><legend>' . lang::Get('Add sites to the group') . '</legend>';
     $leftcol .= '<p>' . lang::get('LANG_Add_Sites_Instruct') . '</p>';
     if (!empty($args['edit_location_path'])) {
         $leftcol .= lang::get('Either') . ' <a class="button" href="' . hostsite_get_url($args['edit_location_path'], array('group_id' => $_GET['group_id'])) . '">' . lang::get('enter details of a new site') . '</a><br/>';
     }
     $leftcol .= data_entry_helper::select(array('label' => lang::get('Or, add an existing site'), 'fieldname' => 'add_existing_location_id', 'report' => 'library/locations/locations_available_for_group', 'caching' => false, 'blankText' => lang::get('<please select>'), 'valueField' => 'location_id', 'captionField' => 'name', 'extraParams' => $readAuth + array('group_id' => $_GET['group_id'], 'user_id' => hostsite_get_user_field('indicia_user_id', 0)), 'afterControl' => '<button id="add-existing">Add</button>'));
     $leftcol .= '</fieldset>';
     // @todo Link existing My Site to group. Need a new report to list sites I created, with sites already in the group
     // removed. Show in a drop down with an add button. Adding must create the groups_locations record, plus refresh
     // the grid and refresh the drop down.
     // @todo set destination after saving added site
     $map = map_helper::map_panel(iform_map_get_map_options($args, $readAuth), iform_map_get_ol_options($args));
     $r = str_replace(array('{col-1}', '{col-2}'), array($leftcol, $map), $indicia_templates['two-col-50']);
     data_entry_helper::$javascript .= "indiciaData.group_id={$_GET['group_id']};\n";
     return $r;
 }
 /**
  * Return the generated form output.
  * @return Form HTML.
  */
 public static function get_form($args)
 {
     iform_load_helpers(array('map_helper', 'data_entry_helper'));
     global $user;
     $readAuth = map_helper::get_read_auth($args['website_id'], $args['password']);
     // setup the map options
     $options = iform_map_get_map_options($args, $readAuth);
     $olOptions = iform_map_get_ol_options($args);
     if (!$args['show_all_species']) {
         if (isset($args['taxon_identifier']) && !empty($args['taxon_identifier'])) {
             // This page is for a predefined species map
             $taxonIdentifier = $args['taxon_identifier'];
         } else {
             if (isset($_GET['taxon'])) {
                 $taxonIdentifier = $_GET['taxon'];
             } else {
                 return lang::get("The distribution map cannot be displayed without a taxon identifier");
             }
         }
         if ($args['external_key'] == true) {
             if (empty($args['taxon_list_id'])) {
                 return lang::get('This form is configured with the Distribution Layer - External Key option ticked, but no species list has been configured to ' . 'lookup the external keys against.');
             }
             // the taxon identifier is an external key, so we need to translate to a meaning ID.
             $fetchOpts = array('table' => 'taxa_taxon_list', 'extraParams' => $readAuth + array('view' => 'detail', 'external_key' => $taxonIdentifier, 'taxon_list_id' => $args['taxon_list_id'], 'preferred' => true));
             $prefRecords = data_entry_helper::get_population_data($fetchOpts);
             // We might have multiple records back, e.g. if there are several photos, but we should have a unique meaning id.
             $meaningId = 0;
             foreach ($prefRecords as $prefRecord) {
                 if ($meaningId != 0 && $meaningId != $prefRecord['taxon_meaning_id']) {
                     // bomb out, as we  don't know which taxon to display
                     return lang::get("The taxon identifier cannot be used to identify a unique taxon.");
                 }
                 $meaningId = $prefRecord['taxon_meaning_id'];
             }
             if ($meaningId == 0) {
                 return lang::get("The taxon identified by the taxon identifier cannot be found.");
             }
             $meaningId = $prefRecords[0]['taxon_meaning_id'];
         } else {
             // the taxon identifier is the meaning ID.
             $meaningId = $taxonIdentifier;
         }
         // We still need to fetch the species record, to get its common name
         $fetchOpts = array('table' => 'taxa_taxon_list', 'extraParams' => $readAuth + array('view' => 'detail', 'language_iso' => iform_lang_iso_639_2(hostsite_get_user_field('language')), 'taxon_meaning_id' => $meaningId));
         $taxonRecords = data_entry_helper::get_population_data($fetchOpts);
     }
     $url = map_helper::$geoserver_url . 'wms';
     // Get the style if there is one selected
     $style = $args["wms_style"] ? ", styles: '" . $args["wms_style"] . "'" : '';
     map_helper::$onload_javascript .= "\n    var filter='website_id=" . $args['website_id'] . "';";
     if ($args['show_all_species']) {
         $layerTitle = lang::get('All species occurrences');
     } else {
         $layerTitle = str_replace('{species}', $taxonRecords[0]['taxon'], $args['layer_title']);
         map_helper::$onload_javascript .= "\n    filter += ' AND taxon_meaning_id={$meaningId}';\n";
     }
     if (!empty($args['cql_filter'])) {
         map_helper::$onload_javascript .= "\n    filter += ' AND(" . str_replace("'", "\\'", $args['cql_filter']) . ")';\n";
     }
     $layerTitle = str_replace("'", "\\'", $layerTitle);
     map_helper::$onload_javascript .= "\n    var distLayer = new OpenLayers.Layer.WMS(\r\n          '" . $layerTitle . "',\r\n          '{$url}',\r\n          {layers: '" . $args["wms_feature_type"] . "', transparent: true, CQL_FILTER: filter {$style}},\r\n          {isBaseLayer: false, sphericalMercator: true, singleTile: true}\r\n    );\n";
     $options['layers'][] = 'distLayer';
     if (isset($args['click_on_occurrences_mode']) && $args['click_on_occurrences_mode'] != 'none') {
         $options['clickableLayersOutputMode'] = $args['click_on_occurrences_mode'];
         $options['clickableLayersOutputDiv'] = 'getinfo-output';
         $options['clickableLayers'][] = 'distLayer';
         if (!empty($args['click_columns'])) {
             // convert the input column list argument to a structured array to pass to the map
             $inputarr = explode("\r\n", $args['click_columns']);
             $outputarr = array();
             foreach ($inputarr as $coldef) {
                 $coldef = explode('=', $coldef);
                 $outputarr[$coldef[0]] = $coldef[1];
             }
             $options['clickableLayersOutputColumns'] = $outputarr;
         }
     }
     // This is not a map used for input
     $options['editLayer'] = false;
     // if in Drupal, and IForm proxy is installed, then use this path as OpenLayers proxy
     if (defined('DRUPAL_BOOTSTRAP_CONFIGURATION') && module_exists('iform_proxy')) {
         global $base_url;
         $options['proxy'] = $base_url . '?q=' . variable_get('iform_proxy_path', 'proxy') . '&url=';
     }
     // output a legend
     if (isset($args['include_layer_list_types'])) {
         $layerTypes = explode(',', $args['include_layer_list_types']);
     } else {
         $layerTypes = array('base', 'overlay');
     }
     $r = '';
     if (!isset($args['include_layer_list']) || $args['include_layer_list']) {
         $r .= map_helper::layer_list(array('includeSwitchers' => isset($args['include_layer_list_switchers']) ? $args['include_layer_list_switchers'] : true, 'includeHiddenLayers' => true, 'layerTypes' => $layerTypes));
     }
     // output a map
     $r .= map_helper::map_panel($options, $olOptions);
     // add an empty div for the output of getinfo requests
     if (isset($args['click_on_occurrences_mode']) && $args['click_on_occurrences_mode'] == 'div') {
         $r .= '<div id="getinfo-output"></div>';
     }
     // Set up a page refresh for dynamic update of the map at set intervals
     if (!empty($args['refresh_timer']) && $args['refresh_timer'] !== 0 && is_numeric($args['refresh_timer'])) {
         // is_int prevents injection
         if (isset($args['load_on_refresh']) && !empty($args['load_on_refresh'])) {
             map_helper::$javascript .= "setTimeout('window.location=\"" . $args['load_on_refresh'] . "\";', " . $args['refresh_timer'] . "*1000 );\n";
         } else {
             map_helper::$javascript .= "setTimeout('window.location.reload( false );', " . $args['refresh_timer'] . "*1000 );\n";
         }
     }
     return $r;
 }
 public static function get_sample_form($args, $node, $response)
 {
     global $user;
     if (!module_exists('iform_ajaxproxy')) {
         return 'This form must be used in Drupal with the Indicia AJAX Proxy module enabled.';
     }
     iform_load_helpers(array('map_helper'));
     $auth = data_entry_helper::get_read_write_auth($args['website_id'], $args['password']);
     $sampleId = isset($_GET['sample_id']) ? $_GET['sample_id'] : null;
     $locationId = null;
     if ($sampleId) {
         data_entry_helper::load_existing_record($auth['read'], 'sample', $sampleId, 'detail', false, true);
         $locationId = data_entry_helper::$entity_to_load['sample:location_id'];
     } else {
         // location ID also might be in the $_POST data after a validation save of a new record
         if (isset($_POST['sample:location_id'])) {
             $locationId = $_POST['sample:location_id'];
         }
     }
     $url = explode('?', $args['my_obs_page'], 2);
     $params = NULL;
     $fragment = NULL;
     // fragment is always at the end.
     if (count($url) > 1) {
         $params = explode('#', $url[1], 2);
         if (count($params) > 1) {
             $fragment = $params[1];
         }
         $params = $params[0];
     } else {
         $url = explode('#', $url[0], 2);
         if (count($url) > 1) {
             $fragment = $url[1];
         }
     }
     $args['my_obs_page'] = url($url[0], array('query' => $params, 'fragment' => $fragment, 'absolute' => TRUE));
     $r = '<form method="post" id="sample">';
     $r .= $auth['write'];
     $r .= '<input type="hidden" name="page" value="mainSample"/>';
     $r .= '<input type="hidden" name="website_id" value="' . $args['website_id'] . '"/>';
     if (isset(data_entry_helper::$entity_to_load['sample:id'])) {
         $r .= '<input type="hidden" name="sample:id" value="' . data_entry_helper::$entity_to_load['sample:id'] . '"/>';
     }
     $r .= '<input type="hidden" name="sample:survey_id" value="' . $args['survey_id'] . '"/>';
     $r .= '<div id="cols" class="ui-helper-clearfix"><div class="left" style="width: ' . (98 - (isset($args['percent_width']) ? $args['percent_width'] : 50)) . '%">';
     // Output only the locations for this website and location type.
     $availableSites = data_entry_helper::get_population_data(array('report' => 'library/locations/locations_list', 'extraParams' => $auth['read'] + array('website_id' => $args['website_id'], 'location_type_id' => $args['locationType'], 'locattrs' => 'CMS User ID', 'attr_location_cms_user_id' => $user->uid), 'nocache' => true));
     // convert the report data to an array for the lookup, plus one to pass to the JS so it can keep the map updated
     $sitesLookup = array();
     $sitesIds = array();
     $sitesJs = array();
     foreach ($availableSites as $site) {
         $sitesLookup[$site['location_id']] = $site['name'];
         $sitesIds[] = $site['location_id'];
     }
     $sites = data_entry_helper::get_population_data(array('table' => 'location', 'extraParams' => $auth['read'] + array('website_id' => $args['website_id'], 'id' => $sitesIds, 'view' => 'detail')));
     foreach ($sites as $site) {
         $sitesJs[$site['id']] = $site;
     }
     data_entry_helper::$javascript .= "indiciaData.sites = " . json_encode($sitesJs) . ";\n";
     if ($locationId) {
         $r .= '<input type="hidden" name="sample:location_id" id="sample_location_id" value="' . $locationId . '"/>';
         // for reload of existing, don't let the user switch the square as that could mess everything up.
         $r .= '<label>' . lang::get('1km square') . ':</label><span>' . $sitesJs[$locationId]['name'] . '</span><br/>' . lang::get('<p class="ui-state-highlight page-notice ui-corner-all">Please use the map to select a more precise location for your timed observation.</p>');
     } else {
         $options = array('label' => lang::get('Select 1km square'), 'validation' => array('required'), 'blankText' => lang::get('Please select'), 'lookupValues' => $sitesLookup, 'id' => "sample_location_id");
         // if ($locationId) $options['default'] = $locationId;
         $r .= data_entry_helper::location_select($options) . lang::get('<p class="ui-state-highlight page-notice ui-corner-all">After selecting the 1km square, use the map to select a more precise location for your timed observation.</p>');
     }
     // [spatial reference]
     $systems = array();
     foreach (explode(',', str_replace(' ', '', $args['spatial_systems'])) as $system) {
         $systems[$system] = lang::get("sref:{$system}");
     }
     $r .= data_entry_helper::sref_and_system(array('label' => lang::get('Grid Ref'), 'systems' => $systems));
     $r .= data_entry_helper::file_box(array('table' => 'sample_image', 'readAuth' => $auth['read'], 'caption' => lang::get('Upload photo(s) of timed search area')));
     $sampleMethods = helper_base::get_termlist_terms($auth, 'indicia:sample_methods', array('Field Observation'));
     $attributes = data_entry_helper::getAttributes(array('id' => $sampleId, 'valuetable' => 'sample_attribute_value', 'attrtable' => 'sample_attribute', 'key' => 'sample_id', 'fieldprefix' => 'smpAttr', 'extraParams' => $auth['read'], 'survey_id' => $args['survey_id'], 'sample_method_id' => $sampleMethods[0]['id']));
     $r .= get_user_profile_hidden_inputs($attributes, $args, '', $auth['read']);
     if (isset($_GET['date'])) {
         $r .= '<input type="hidden" name="sample:date" value="' . $_GET['date'] . '"/>';
         $r .= '<label>' . lang::get('Date') . ':</label> <span class="value-label">' . $_GET['date'] . '</span><br/>';
     } else {
         if (isset(data_entry_helper::$entity_to_load['sample:date']) && preg_match('/^(\\d{4})/', data_entry_helper::$entity_to_load['sample:date'])) {
             // Date has 4 digit year first (ISO style) - convert date to expected output format
             // @todo The date format should be a global configurable option. It should also be applied to reloading of custom date attributes.
             $d = new DateTime(data_entry_helper::$entity_to_load['sample:date']);
             data_entry_helper::$entity_to_load['sample:date'] = $d->format('d/m/Y');
         }
         $r .= data_entry_helper::date_picker(array('label' => lang::get('Date'), 'fieldname' => 'sample:date'));
     }
     // are there any option overrides for the custom attributes?
     if (isset($args['custom_attribute_options']) && $args['custom_attribute_options']) {
         $blockOptions = get_attr_options_array_with_user_data($args['custom_attribute_options']);
     } else {
         $blockOptions = array();
     }
     $r .= get_attribute_html($attributes, $args, array('extraParams' => $auth['read']), null, $blockOptions);
     $r .= '<input type="hidden" name="sample:sample_method_id" value="' . $sampleMethods[0]['id'] . '" />';
     $r .= '<input type="submit" value="' . lang::get('Next') . '" />';
     $r .= '<a href="' . $args['my_obs_page'] . '" class="button">' . lang::get('Cancel') . '</a>';
     if (isset(data_entry_helper::$entity_to_load['sample:id'])) {
         $r .= '<button id="delete-button" type="button" class="ui-state-default ui-corner-all" />' . lang::get('Delete') . '</button>';
     }
     $r .= "</div>";
     // left
     $r .= '<div class="right" style="width: ' . (isset($args['percent_width']) ? $args['percent_width'] : 50) . '%">';
     // [place search]
     $georefOpts = iform_map_get_georef_options($args, $auth['read']);
     $georefOpts['label'] = lang::get('Search for Place on Map');
     // can't use place search without the driver API key
     if ($georefOpts['driver'] == 'geoplanet' && empty(helper_config::$geoplanet_api_key)) {
         $r .= '<span style="display: none;">The form structure includes a place search but needs a geoplanet api key.</span>';
     } else {
         $r .= data_entry_helper::georeference_lookup($georefOpts);
     }
     // [map]
     $options = iform_map_get_map_options($args, $auth['read']);
     if (!empty(data_entry_helper::$entity_to_load['sample:wkt'])) {
         $options['initialFeatureWkt'] = data_entry_helper::$entity_to_load['sample:wkt'];
     }
     $olOptions = iform_map_get_ol_options($args);
     if (!isset($options['standardControls'])) {
         $options['standardControls'] = array('layerSwitcher', 'panZoomBar');
     }
     $r .= map_helper::map_panel($options, $olOptions);
     data_entry_helper::$javascript .= "\nmapInitialisationHooks.push(function(mapdiv) {\n  var defaultStyle = new OpenLayers.Style({pointRadius: 6,fillOpacity: 0,strokeColor: \"Red\",strokeWidth: 1});\n  var SiteStyleMap = new OpenLayers.StyleMap({\"default\": defaultStyle});\n  indiciaData.SiteLayer = new OpenLayers.Layer.Vector('1km square',{styleMap: SiteStyleMap, displayInLayerSwitcher: true});\n  mapdiv.map.addLayer(indiciaData.SiteLayer);\n  if(jQuery('#sample_location_id').length > 0) {\n    if(jQuery('#sample_location_id').val() != ''){\n      var parser = new OpenLayers.Format.WKT();\n      var feature = parser.read(indiciaData.sites[jQuery('#sample_location_id').val()].geom);\n      indiciaData.SiteLayer.addFeatures([feature]);\n      // for existing data we zoom on the site, not this parent location\n    } \n    jQuery('#sample_location_id').change(function(){\n      indiciaData.SiteLayer.destroyFeatures();\n      if(jQuery('#sample_location_id').val() != ''){\n        var parser = new OpenLayers.Format.WKT();\n        var feature = parser.read(indiciaData.sites[jQuery('#sample_location_id').val()].geom);\n        indiciaData.SiteLayer.addFeatures([feature]);\n        var layerBounds = indiciaData.SiteLayer.getDataExtent().clone(); // use a clone\n        indiciaData.SiteLayer.map.zoomToExtent(layerBounds);\n      }\n    });\n  }\n});\n";
     $r .= "</div>";
     // right
     $r .= '</form>';
     // Recorder Name - assume Easy Login uid
     if (function_exists('module_exists') && module_exists('easy_login')) {
         $userId = hostsite_get_user_field('indicia_user_id');
         // For non easy login test only     $userId = 1;
         foreach ($attributes as $attrID => $attr) {
             if (strcasecmp('Recorder Name', $attr["untranslatedCaption"]) == 0 && !empty($userId)) {
                 // determining which you have used is difficult from a services based autocomplete, esp when the created_by_id is not available on the data.
                 data_entry_helper::add_resource('autocomplete');
                 data_entry_helper::$javascript .= "bindRecorderNameAutocomplete(" . $attrID . ", '" . $userId . "', '" . data_entry_helper::$base_url . "', '" . $args['survey_id'] . "', '" . $auth['read']['auth_token'] . "', '" . $auth['read']['nonce'] . "');\n";
             }
         }
     }
     if (isset(data_entry_helper::$entity_to_load['sample:id'])) {
         // allow deletes if sample id is present.
         data_entry_helper::$javascript .= "jQuery('#delete-button').click(function(){\n  if(confirm(\"" . lang::get('Are you sure you want to delete this walk?') . "\")){\n    jQuery('#delete-form').submit();\n  } // else do nothing.\n});\n";
         // note we only require bare minimum in order to flag a sample as deleted.
         $r .= '<form method="post" id="delete-form" style="display: none;">';
         $r .= $auth['write'];
         $r .= '<input type="hidden" name="page" value="delete"/>';
         $r .= '<input type="hidden" name="website_id" value="' . $args['website_id'] . '"/>';
         $r .= '<input type="hidden" name="sample:id" value="' . data_entry_helper::$entity_to_load['sample:id'] . '"/>';
         $r .= '<input type="hidden" name="sample:deleted" value="t"/>';
         $r .= '</form>';
     }
     data_entry_helper::enable_validation('sample');
     return $r;
 }
Ejemplo n.º 26
0
 /**
  * Return the generated output.
  * @param array $args List of parameter values passed through to the form depending on how the form has been configured.
  * This array always contains a value for language.
  * @param object $node The Drupal node object.
  * @param array $response When this form is reloading after saving a submission, contains the response from the service call.
  * Note this does not apply when redirecting (in this case the details of the saved object are in the $_GET data).
  * @return Form HTML.
  */
 public static function get_form($args, $node, $response = null)
 {
     iform_load_helpers(array('report_helper', 'map_helper'));
     $readAuth = report_helper::get_read_auth($args['website_id'], $args['password']);
     $sharing = 'reporting';
     $reportOptions = array_merge(iform_report_get_report_options($args, $readAuth), array('reportGroup' => 'explore', 'rememberParamsReportGroup' => 'explore', 'paramsOnly' => true, 'paramsInMapToolbar' => true, 'sharing' => $sharing, 'paramsFormButtonCaption' => lang::get('Filter'), 'rowId' => 'occurrence_id'));
     iform_report_apply_explore_user_own_preferences($reportOptions);
     $reportOptions['extraParams']['limit'] = 3000;
     $r = report_helper::report_grid($reportOptions);
     $r .= report_helper::report_map(array('readAuth' => $readAuth, 'dataSource' => $args['report_name'], 'extraParams' => $reportOptions['extraParams'], 'paramDefaults' => $reportOptions['paramDefaults'], 'autoParamsForm' => false, 'reportGroup' => 'explore', 'rememberParamsReportGroup' => 'explore', 'clickableLayersOutputMode' => 'report', 'sharing' => $sharing, 'rowId' => 'occurrence_id', 'ajax' => TRUE));
     $options = array_merge(iform_map_get_map_options($args, $readAuth), array('featureIdField' => 'occurrence_id', 'clickForSpatialRef' => false, 'reportGroup' => 'explore', 'toolbarDiv' => 'top'));
     $olOptions = iform_map_get_ol_options($args);
     $r .= map_helper::map_panel($options, $olOptions);
     $allowDownload = !isset($args['downloadOwnDataOnly']) || !$args['downloadOwnDataOnly'] || isset($reportOptions['extraParams']['ownData']) && $reportOptions['extraParams']['ownData'] === 1 || isset($_POST['explore-ownData']) && $_POST['explore-ownData'] === '1' || !(isset($_POST['explore-ownData']) || $_POST['explore-ownData'] === '0') && isset($reportOptions['paramDefaults']['ownData']) && $reportOptions['paramDefaults']['ownData'] === 1;
     $reportOptions = array_merge($reportOptions, array('id' => 'explore-records', 'paramsOnly' => false, 'autoParamsForm' => false, 'downloadLink' => $allowDownload, 'rowClass' => 'certainty{certainty}'));
     if (isset($args['includeEditLink']) && $args['includeEditLink'] && !empty($args['includeEditLinkPath'])) {
         $reportOptions['columns'][] = array('display' => 'Actions', 'actions' => array(array('caption' => 'edit', 'url' => url($args['includeEditLinkPath']), 'urlParams' => array('occurrence_id' => '{occurrence_id}'), 'visibility_field' => 'belongs_to_user')));
     }
     $r .= report_helper::report_grid($reportOptions);
     return $r;
 }
Ejemplo n.º 27
0
 private static function get_template_with_map($args, $readAuth, $extraParams, $paramDefaults)
 {
     $r = '<div id="outer-with-map" class="ui-helper-clearfix">';
     $r .= '<div id="grid" class="left" style="width:65%">{paramsForm}{grid}</div>';
     $r .= '<div id="map-and-record" class="right" style="width: 34%"><div id="summary-map">';
     $options = iform_map_get_map_options($args, $readAuth);
     $olOptions = iform_map_get_ol_options($args);
     // This is used for drawing, so need an editlayer, but not used for input
     $options['editLayer'] = true;
     $options['editLayerInSwitcher'] = true;
     $options['clickForSpatialRef'] = false;
     $options['featureIdField'] = 'occurrence_id';
     $r .= map_helper::map_panel($options, $olOptions);
     $reportMapOpts = array('dataSource' => !empty($args['mapping_report_name']) ? $args['mapping_report_name'] : $args['report_name'], 'mode' => 'report', 'readAuth' => $readAuth, 'autoParamsForm' => false, 'extraParams' => $extraParams, 'paramDefaults' => $paramDefaults, 'reportGroup' => 'verification', 'clickableLayersOutputMode' => 'report', 'rowId' => 'occurrence_id', 'sharing' => 'verification', 'ajax' => TRUE);
     if (!empty($args['mapping_report_name_lores'])) {
         $reportMapOpts['dataSourceLoRes'] = $args['mapping_report_name_lores'];
     }
     $r .= report_helper::report_map($reportMapOpts);
     $r .= '</div>';
     global $user;
     if (function_exists('hostsite_get_user_field') && ($locationId = hostsite_get_user_field('location_expertise', false))) {
         iform_map_zoom_to_location($locationId, $readAuth);
     }
     $r .= '<div id="record-details-wrap" class="ui-widget ui-widget-content">';
     $r .= self::instructions('grid on the left');
     $r .= '<div id="record-details-content" style="display: none">';
     $r .= '<div id="record-details-toolbar">';
     $r .= '<div id="verify-buttons">';
     $r .= '<div id="verify-buttons-inner">';
     $r .= '<label>' . lang::get('Actions:') . '</label>';
     $imgPath = empty(data_entry_helper::$images_path) ? data_entry_helper::relative_client_helper_path() . "../media/images/" : data_entry_helper::$images_path;
     $r .= '<button type="button" id="btn-verify" title="' . lang::get('Verify') . '"><img width="18" height="18" src="' . $imgPath . 'nuvola/ok-16px.png"/></button>';
     $r .= '<button type="button" id="btn-edit-verify" title="' . lang::get('Edit determination then verify') . '"><img width="18" height="18" src="' . $imgPath . 'nuvola/package_editors-16px.png"/>' . '<img width="18" height="18" src="' . $imgPath . 'nuvola/ok-16px.png"/></button>';
     $r .= '<button type="button" id="btn-reject" title="' . lang::get('Reject') . '"><img width="18" height="18" src="' . $imgPath . 'nuvola/cancel-16px.png"/></button>';
     $r .= '<button type="button" id="btn-query" title="' . lang::get('Query') . '"><img width="18" height="18" src="' . $imgPath . 'nuvola/dubious-16px.png"/></button>';
     $r .= '<div id="redet-dropdown-ctnr" style="display: none"><div id="redet-dropdown">';
     $r .= data_entry_helper::species_autocomplete(array('fieldname' => 'redet', 'label' => lang::get('New determination'), 'labelClass' => 'auto', 'helpText' => lang::get('Enter a new determination for this record before verifying it. The previous determination will be stored with the record.'), 'cacheLookup' => true, 'extraParams' => $readAuth + array('taxon_list_id' => 1), 'speciesIncludeBothNames' => true, 'speciesIncludeTaxonGroup' => true));
     $r .= '</div></div>';
     $r .= '</div></div>';
     $r .= '<label>Contact:</label>';
     $r .= '<button type="button" id="btn-email-expert" class="default-button">' . lang::get('Another expert') . '</button>';
     $r .= '<button type="button" id="btn-email-recorder" class="default-button">' . lang::get('Recorder') . '</button>';
     $r .= '</div>';
     $r .= '<div id="record-details-tabs">';
     // note - there is a dependency in the JS that comments is the last tab and media the 2nd to last.
     $r .= data_entry_helper::tab_header(array('tabs' => array('#details-tab' => lang::get('Details'), '#experience-tab' => lang::get('Experience'), '#phenology-tab' => lang::get('Phenology'), '#media-tab' => lang::get('Media'), '#comments-tab' => lang::get('Comments'))));
     data_entry_helper::$javascript .= "indiciaData.detailsTabs = ['details','experience','phenology','media','comments'];\n";
     data_entry_helper::enable_tabs(array('divId' => 'record-details-tabs'));
     $r .= '<div id="details-tab"></div>';
     $r .= self::other_tab_html();
     $r .= '</div></div></div></div></div>';
     return $r;
 }
 protected static function get_control_map($auth, $args, $tabalias, $options)
 {
     iform_load_helpers(array('map_helper', 'report_helper'));
     // $_GET data for standard params can override displayed location
     if (isset($_GET['filter-location_id']) || isset($_GET['filter-indexed_location_id'])) {
         $args['display_user_profile_location'] = false;
         if (!empty($_GET['filter-indexed_location_id'])) {
             $args['location_boundary_id'] = $_GET['filter-indexed_location_id'];
         } elseif (!empty($_GET['filter-location_id'])) {
             $args['location_boundary_id'] = $_GET['filter-location_id'];
         }
     }
     // allow us to call iform_report_get_report_options to get a default report setup, then override report_name
     $args['report_name'] = '';
     $sharing = empty($args['sharing']) ? 'reporting' : $args['sharing'];
     $reportOptions = array_merge(iform_report_get_report_options($args, $auth['read']), array('reportGroup' => 'dynamic', 'autoParamsForm' => false, 'sharing' => $sharing, 'readAuth' => $auth['read'], 'dataSource' => $options['dataSource'], 'reportGroup' => 'dynamic', 'rememberParamsReportGroup' => 'dynamic', 'clickableLayersOutputMode' => 'report', 'rowId' => 'occurrence_id', 'ajax' => TRUE), $options);
     if (self::$applyUserPrefs) {
         iform_report_apply_explore_user_own_preferences($reportOptions);
     }
     $r = report_helper::report_map($reportOptions);
     $options = array_merge(iform_map_get_map_options($args, $auth['read']), array('featureIdField' => 'occurrence_id', 'clickForSpatialRef' => false, 'reportGroup' => 'explore', 'toolbarDiv' => 'top'), $options);
     $olOptions = iform_map_get_ol_options($args);
     $r .= map_helper::map_panel($options, $olOptions);
     return $r;
 }
 /**
  * Return the generated output for the main sample tab.
  * @param array $args List of parameter values passed through to the form depending on how the form has been configured.
  *                    This array always contains a value for language.
  * @param integer $nid The Drupal node object's ID.
  * @param object $auth The full read-write authorisation.
  * @return HTML.
  */
 private static function get_sample_tab($args, $nid, $auth, $attributes, &$packageAttr)
 {
     global $user;
     if (isset(data_entry_helper::$entity_to_load['sample:date']) && preg_match('/^(\\d{4})/', data_entry_helper::$entity_to_load['sample:date'])) {
         // Date has 4 digit year first (ISO style) - convert date to expected output format
         // @todo The date format should be a global configurable option. It should also be applied to reloading of custom date attributes.
         $d = new DateTime(data_entry_helper::$entity_to_load['sample:date']);
         data_entry_helper::$entity_to_load['sample:date'] = $d->format('d/m/Y');
     }
     // are there any option overrides for the custom attributes?
     if (isset($args['custom_attribute_options']) && $args['custom_attribute_options']) {
         $blockOptions = get_attr_options_array_with_user_data($args['custom_attribute_options']);
     } else {
         $blockOptions = array();
     }
     $systems = array();
     $list = explode(',', str_replace(' ', '', $args['spatial_systems']));
     foreach ($list as $system) {
         $systems[$system] = lang::get("sref:{$system}");
     }
     $options = iform_map_get_map_options($args, $auth['read']);
     $olOptions = iform_map_get_ol_options($args);
     if (!empty(data_entry_helper::$entity_to_load['sample:wkt'])) {
         $options['initialFeatureWkt'] = data_entry_helper::$entity_to_load['sample:wkt'];
     }
     if (!isset($options['standardControls'])) {
         $options['standardControls'] = array('layerSwitcher', 'panZoomBar');
     }
     $options['tabDiv'] = 'sample';
     // we pass through the read auth. This makes it possible for the get_submission method to authorise against the warehouse
     // without an additional (expensive) warehouse call, so it can get subsample details.
     $r = '<div id="sample">' . '<input type="hidden" name="website_id" value="' . $args['website_id'] . '"/>' . get_user_profile_hidden_inputs($attributes, $args, isset(data_entry_helper::$entity_to_load['sample:id']), $auth['read']) . data_entry_helper::text_input(array('label' => lang::get('Location Name'), 'fieldname' => 'sample:location_name', 'class' => 'control-width-5', 'validation' => array('required'))) . data_entry_helper::date_picker(array('label' => lang::get('Date'), 'fieldname' => 'sample:date')) . self::_build_package_control($args, $packageAttr) . get_attribute_html($attributes, $args, array('extraParams' => $auth['read']), null, $blockOptions) . data_entry_helper::textarea(array('fieldname' => 'sample:comment', 'label' => lang::get('Overall comment'))) . data_entry_helper::sref_and_system(array('label' => lang::get('Grid Reference'), 'systems' => $systems)) . '<p class="ui-state-highlight page-notice ui-corner-all">' . t('Use the search box to find a nearby town or village, then drag the map to pan and click on the map to set the centre grid reference of the transect. ' . 'Alternatively if you know the grid reference you can enter it in the Grid Ref box above: this will then be drawn automatically on the map.') . '</p>' . (isset(data_entry_helper::$entity_to_load['sample:id']) ? '' : data_entry_helper::georeference_lookup(array('label' => lang::get('Search for place'), 'driver' => $args['georefDriver'], 'georefPreferredArea' => $args['georefPreferredArea'], 'georefCountry' => $args['georefCountry'], 'georefLang' => $args['language'], 'readAuth' => $auth['read']))) . map_helper::map_panel($options, $olOptions) . (self::$readOnly ? '' : '<br/><input type="submit" value="' . lang::get('Save') . '" title="' . lang::get('Saves any data entered across all the tabs.') . '" />') . '</div>';
     return $r;
 }
 /**
  * Return the generated form output.
  * @param array $args List of parameter values passed through to the form depending on how the form has been configured.
  * This array always contains a value for language.
  * @param object $node The Drupal node object.
  * @param array $response When this form is reloading after saving a submission, contains the response from the service call.
  * Note this does not apply when redirecting (in this case the details of the saved object are in the $_GET data).
  * @return Form HTML.
  */
 public static function get_form($args, $node, $response = null)
 {
     $form = '<form action="#" method="POST" id="entry_form">';
     if ($_POST) {
         $auth = data_entry_helper::get_read_write_auth($args['website_id'], $args['password']);
         self::subscribe($args, $auth);
     } else {
         // don't bother with write auth for initial form load, as read auth is cached and faster
         $auth = array('read' => data_entry_helper::get_read_auth($args['website_id'], $args['password']));
     }
     if (!empty($_GET['id'])) {
         data_entry_helper::load_existing_record($auth['read'], 'species_alert', $_GET['id']);
         // enforce permissions
         if (data_entry_helper::$entity_to_load['species_alert:user_id'] != hostsite_get_user_field('indicia_user_id')) {
             return lang::get('You cannot modify a species alert subscription created by someone else');
         }
         $form .= data_entry_helper::hidden_text(array('fieldname' => 'species_alert:id', 'default' => $_GET['id']));
     }
     // if not logged in, then ask for details to register against
     global $user;
     if (!hostsite_get_user_field('id') || !isset($user) || empty($user->mail) || !hostsite_get_user_field('last_name')) {
         $form .= "<fieldset><legend>" . lang::get('Your details') . ":</legend>\n";
         $default = empty($_POST['first_name']) ? hostsite_get_user_field('first_name', '') : $_POST['first_name'];
         $form .= data_entry_helper::text_input(array('label' => lang::get('First name'), 'fieldname' => 'first_name', 'validation' => array('required'), 'default' => $default, 'class' => 'control-width-4'));
         $default = empty($_POST['surname']) ? hostsite_get_user_field('last_name', '') : $_POST['surname'];
         $form .= data_entry_helper::text_input(array('label' => lang::get('Last name'), 'fieldname' => 'surname', 'validation' => array('required'), 'default' => $default, 'class' => 'control-width-4'));
         $default = empty($_POST['email']) ? empty($user->mail) ? '' : $user->mail : $_POST['email'];
         $form .= data_entry_helper::text_input(array('label' => lang::get('Email'), 'fieldname' => 'email', 'validation' => array('required', 'email'), 'default' => $default, 'class' => 'control-width-4'));
         $form .= "</fieldset>\n";
     } else {
         $form .= data_entry_helper::hidden_text(array('fieldname' => 'first_name', 'default' => hostsite_get_user_field('first_name')));
         $form .= data_entry_helper::hidden_text(array('fieldname' => 'surname', 'default' => hostsite_get_user_field('last_name')));
         $form .= data_entry_helper::hidden_text(array('fieldname' => 'email', 'default' => $user->mail));
         $form .= data_entry_helper::hidden_text(array('fieldname' => 'user_id', 'default' => hostsite_get_user_field('indicia_user_id')));
     }
     $form .= "<fieldset><legend>" . lang::get('Alert criteria') . ":</legend>\n";
     // Output the species selection control
     // Default after saving with a validation failure can be pulled direct from the post, but
     // when reloading we don't need a default taxa taxon list ID since we already know the meaning
     // ID or external key.
     $default = empty($_POST['taxa_taxon_list_id']) ? '' : $_POST['taxa_taxon_list_id'];
     if (empty($_POST['taxa_taxon_list_id:taxon'])) {
         $defaultCaption = empty(data_entry_helper::$entity_to_load['species_alert:preferred_taxon']) ? '' : data_entry_helper::$entity_to_load['species_alert:preferred_taxon'];
     } else {
         $defaultCaption = $_POST['taxa_taxon_list_id:taxon'];
     }
     $form .= data_entry_helper::species_autocomplete(array('label' => lang::get('Alert species'), 'helpText' => lang::get('Select the species you are interested in receiving alerts in ' . 'relation to if you want to receive alerts on a single species.'), 'fieldname' => 'taxa_taxon_list_id', 'cacheLookup' => true, 'extraParams' => $auth['read'] + array('taxon_list_id' => $args['list_id']), 'class' => 'control-width-4', 'default' => $default, 'defaultCaption' => $defaultCaption));
     if (empty($default)) {
         // Unless we've searched for the species name then posted (and failed), then the
         // default will be empty. We might therefore be reloading existing data which has
         // a meaning ID or external key.
         if (!empty(data_entry_helper::$entity_to_load['species_alert:external_key'])) {
             $form .= data_entry_helper::hidden_text(array('fieldname' => 'species_alert:external_key', 'default' => data_entry_helper::$entity_to_load['species_alert:external_key']));
         } elseif (!empty(data_entry_helper::$entity_to_load['species_alert:taxon_meaning_id'])) {
             $form .= data_entry_helper::hidden_text(array('fieldname' => 'species_alert:taxon_meaning_id', 'default' => data_entry_helper::$entity_to_load['species_alert:taxon_meaning_id']));
         }
     }
     if (!empty($args['full_lists'])) {
         $form .= data_entry_helper::select(array('label' => lang::get('Select full species lists'), 'helpText' => lang::get('If you want to restrict the alerts to records of any ' . 'species within a species list, then select the list here.'), 'fieldname' => 'species_alert:taxon_list_id', 'blankText' => lang::get('<Select a species list>'), 'table' => 'taxon_list', 'valueField' => 'id', 'captionField' => 'title', 'extraParams' => $auth['read'] + array('id' => $args['full_lists'], 'orderby' => 'title'), 'class' => 'control-width-4'));
     }
     $form .= data_entry_helper::location_select(array('label' => lang::get('Select location'), 'helpText' => lang::get('If you want to restrict the alerts to records within a certain boundary, select it here.'), 'fieldname' => 'species_alert:location_id', 'id' => 'imp-location', 'blankText' => lang::get('<Select boundary>'), 'extraParams' => $auth['read'] + array('location_type_id' => $args['location_type_id'], 'orderby' => 'name'), 'class' => 'control-width-4'));
     $form .= data_entry_helper::checkbox(array('label' => lang::get('Alert on initial entry'), 'helpText' => lang::get('Tick this box if you want to receive a notification when the record is first input into the system.'), 'fieldname' => 'species_alert:alert_on_entry'));
     $form .= data_entry_helper::checkbox(array('label' => lang::get('Alert on verification as correct'), 'helpText' => lang::get('Tick this box if you want to receive a notification when the record has been verified as correct.'), 'fieldname' => 'species_alert:alert_on_verify'));
     $form .= "</fieldset>\n";
     $form .= '<input type="Submit" value="Subscribe" />';
     $form .= '</form>';
     data_entry_helper::enable_validation('entry_form');
     iform_load_helpers(array('map_helper'));
     $mapOptions = iform_map_get_map_options($args, $auth['read']);
     $map = map_helper::map_panel($mapOptions);
     global $indicia_templates;
     return str_replace(array('{col-1}', '{col-2}'), array($form, $map), $indicia_templates['two-col-50']);
 }