/**
  * Get the control for species input, either a grid or a single species input control.
  */
 protected static function get_control_species($auth, $args, $tabAlias, $options)
 {
     global $user;
     $extraParams = $auth['read'];
     $extraParams['preferred'] = "true";
     // Build the configuration options
     if (isset($options['view'])) {
         $extraParams['view'] = $options['view'];
     }
     // There may be options in the form occAttr:n|param => value targetted at specific attributes
     $occAttrOptions = array();
     // make sure that if extraParams is specified as a config option, it does not replace the essential stuff
     if (isset($options['extraParams'])) {
         $options['extraParams'] = array_merge($extraParams, $options['extraParams']);
     }
     $species_ctrl_opts = array_merge(array('occAttrOptions' => $occAttrOptions, 'listId' => $args['list_id'], 'label' => lang::get('occurrence:taxa_taxon_list_id'), 'columns' => 1, 'extraParams' => $extraParams, 'survey_id' => $args['survey_id'], 'language' => iform_lang_iso_639_2(hostsite_get_user_field('language'))), $options);
     if ($groups = hostsite_get_user_field('taxon_groups')) {
         $species_ctrl_opts['usersPreferredGroups'] = unserialize($groups);
     }
     if (isset($args['col_widths']) && $args['col_widths']) {
         $species_ctrl_opts['colWidths'] = explode(',', $args['col_widths']);
     }
     call_user_func(array(self::$called_class, 'build_grid_taxon_label_function'), $args, $options);
     if (self::$mode == self::MODE_CLONE) {
         $species_ctrl_opts['useLoadedExistingRecords'] = true;
     }
     // Start by outputting a hidden value that tells us we are using a grid when the data is posted,
     // then output the grid control
     return '<input type="hidden" value="true" name="gridmode" />' . self::my_species_checklist($species_ctrl_opts);
 }
示例#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;
 }
示例#3
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;
 }
示例#4
0
 /**
  * Get the control for species input, either a grid or a single species input control.
  */
 private static function get_control_species($auth, $args, $tabalias, $options)
 {
     $extraParams = $auth['read'];
     if ($args['species_names_filter'] == 'preferred') {
         $extraParams += array('preferred' => 't');
     }
     if ($args['species_names_filter'] == 'language') {
         $extraParams += array('language' => iform_lang_iso_639_2($user->lang));
     }
     if (self::getGridMode($args)) {
         // multiple species being input via a grid
         $species_ctrl_opts = array_merge(array('listId' => $args['list_id'], 'label' => lang::get('occurrence:taxa_taxon_list_id'), 'columns' => 1, 'extraParams' => $extraParams, 'survey_id' => $args['survey_id'], 'occurrenceComment' => $args['occurrence_comment'], 'occurrenceImages' => $args['occurrence_images'], 'PHPtaxonLabel' => true), $options);
         if ($args['extra_list_id']) {
             $species_ctrl_opts['lookupListId'] = $args['extra_list_id'];
         }
         if (isset($args['col_widths']) && $args['col_widths']) {
             $species_ctrl_opts['colWidths'] = explode(',', $args['col_widths']);
         }
         self::build_grid_taxon_label_function($args);
         self::build_grid_autocomplete_function($args);
         // Start by outputting a hidden value that tells us we are using a grid when the data is posted,
         // then output the grid control
         return '<input type="hidden" value="true" name="gridmode" />' . data_entry_helper::species_checklist($species_ctrl_opts);
     } else {
         // A single species entry control of some kind
         if (count(self::$occurrenceIds) == 1) {
             // output a hidden input to contain the occurrence id
             $r .= '<input type="hidden" name="occurrence:id" value="' . self::$occurrenceIds[0] . '" />' . "\n";
         }
         if ($args['extra_list_id'] == '') {
             $extraParams['taxon_list_id'] = $args['list_id'];
         } elseif ($args['species_ctrl'] == 'autocomplete') {
             $extraParams['taxon_list_id'] = $args['extra_list_id'];
         } else {
             $extraParams['taxon_list_id'] = array($args['list_id'], $args['extra_list_id']);
         }
         $species_ctrl_opts = array_merge(array('label' => lang::get('occurrence:taxa_taxon_list_id'), 'fieldname' => 'occurrence:taxa_taxon_list_id', 'table' => 'taxa_taxon_list', 'captionField' => 'taxon', 'valueField' => 'id', 'columns' => 2, 'parentField' => 'parent_id', 'extraParams' => $extraParams), $options);
         if ($args['species_ctrl'] == 'tree_browser') {
             // change the node template to include images
             global $indicia_templates;
             $indicia_templates['tree_browser_node'] = '<div>' . '<img src="' . data_entry_helper::$base_url . '/upload/thumb-{image_path}" alt="Image of {caption}" width="80" /></div>' . '<span>{caption}</span>';
         }
         // Dynamically generate the species selection control required.
         return call_user_func(array('data_entry_helper', $args['species_ctrl']), $species_ctrl_opts);
     }
 }
 /**
  * Get the control for species input, either a grid or a single species input control.
  */
 protected static function get_control_species($auth, $args, $tabalias, $options)
 {
     global $user;
     $extraParams = $auth['read'];
     $fieldPrefix = !empty($options['fieldprefix']) ? $options['fieldprefix'] : '';
     if (!empty($args['taxon_filter_field']) && !empty($args['taxon_filter'])) {
         $filterLines = helper_base::explode_lines($args['taxon_filter']);
         if ($args['multiple_subject_observation_mode'] !== 'single' && $args['taxon_filter_field'] !== 'taxon_group' && count($filterLines) === 1) {
             // The form is configured for filtering by taxon name or meaning id. If there is only one specified then the form
             // cannot display a species checklist, as there is no point. So, convert our preferred taxon name or meaning ID to find the
             // preferred taxa_taxon_list_id from the selected checklist, and then output a hidden ID.
             if (empty($args['list_id'])) {
                 throw new exception(lang::get('Please configure the Initial Species List parameter to define which list the species to record is selected from.'));
             }
             $filter = array('preferred' => 't', 'taxon_list_id' => $args['list_id']);
             if ($args['taxon_filter_field'] == 'preferred_name') {
                 $filter['taxon'] = $filterLines[0];
             } else {
                 $filter[$args['taxon_filter_field']] = $filterLines[0];
             }
             $options = array('table' => 'taxa_taxon_list', 'extraParams' => $auth['read'] + $filter);
             $response = data_entry_helper::get_population_data($options);
             if (count($response) === 0) {
                 throw new exception(lang::get('Failed to find the single species that this form is setup to record in the defined list.'));
             }
             if (count($response) > 1) {
                 throw new exception(lang::get('This form is setup for single species recording, but more than one species with the same name exists in the list.'));
             }
             return '<input type="hidden" name="' . $fieldPrefix . 'occurrence:taxa_taxon_list_id" value="' . $response[0]['id'] . "\"/>\n";
         }
     }
     if (call_user_func(array(get_called_class(), 'getGridMode'), $args)) {
         // multiple species being input via a grid
         $species_ctrl_opts = array_merge(array('listId' => $args['list_id'], 'label' => lang::get('occurrence:taxa_taxon_list_id'), 'columns' => 1, 'extraParams' => $extraParams, 'survey_id' => $args['survey_id'], 'occurrenceComment' => $args['occurrence_comment'], 'occurrenceSensitivity' => isset($args['subject_observation_confidential']) ? $args['subject_observation_confidential'] : false, 'occurrenceImages' => $args['observation_images'], 'PHPtaxonLabel' => true, 'language' => iform_lang_iso_639_2(hostsite_get_user_field('language')), 'cacheLookup' => isset($args['cache_lookup']) && $args['cache_lookup'], 'speciesNameFilterMode' => self::getSpeciesNameFilterMode($args)), $options);
         if ($args['extra_list_id']) {
             $species_ctrl_opts['lookupListId'] = $args['extra_list_id'];
         }
         if (!empty($args['taxon_filter_field']) && !empty($args['taxon_filter'])) {
             $species_ctrl_opts['taxonFilterField'] = $args['taxon_filter_field'];
             $species_ctrl_opts['taxonFilter'] = $filterLines;
         }
         if (isset($args['col_widths']) && $args['col_widths']) {
             $species_ctrl_opts['colWidths'] = explode(',', $args['col_widths']);
         }
         call_user_func(array(get_called_class(), 'build_grid_taxon_label_function'), $args);
         call_user_func(array(get_called_class(), 'build_grid_autocomplete_function'), $args);
         // Start by outputting a hidden value that tells us we are using a grid when the data is posted,
         // then output the grid control
         return '<input type="hidden" value="true" name="gridmode" />' . data_entry_helper::species_checklist($species_ctrl_opts);
     } else {
         // A single species entry control of some kind
         if ($args['extra_list_id'] == '') {
             $extraParams['taxon_list_id'] = $args['list_id'];
         } elseif ($args['species_ctrl'] == 'autocomplete') {
             $extraParams['taxon_list_id'] = empty($args['extra_list_id']) ? $args['list_id'] : $args['extra_list_id'];
         } else {
             $extraParams['taxon_list_id'] = array($args['list_id'], $args['extra_list_id']);
         }
         if (!empty($args['taxon_filter_field']) && !empty($args['taxon_filter'])) {
             // filter the taxa available to record
             $query = array('in' => array($args['taxon_filter_field'], helper_base::explode_lines($args['taxon_filter'])));
         } else {
             $query = array();
         }
         // Apply the species names filter to the single species picker control
         if (isset($args['species_names_filter'])) {
             $languageFieldName = isset($args['cache_lookup']) && $args['cache_lookup'] ? 'language_iso' : 'language';
             switch ($args['species_names_filter']) {
                 case 'preferred':
                     $extraParams += array('preferred' => 't');
                     break;
                 case 'currentLanguage':
                     if (isset($options['language'])) {
                         $extraParams += array($languageFieldName => $options['language']);
                     }
                     break;
                 case 'excludeSynonyms':
                     $query['where'] = array("(preferred='t' OR {$languageFieldName}<>'lat')");
                     break;
             }
         }
         if (count($query)) {
             $extraParams['query'] = json_encode($query);
         }
         $species_ctrl_opts = array_merge(array('label' => lang::get('occurrence:taxa_taxon_list_id'), 'fieldname' => $fieldPrefix . 'occurrence:taxa_taxon_list_id', 'table' => 'taxa_taxon_list', 'captionField' => 'taxon', 'valueField' => 'id', 'columns' => 2, 'parentField' => 'parent_id', 'extraParams' => $extraParams, 'blankText' => 'Please select'), $options);
         if (isset($args['cache_lookup']) && $args['cache_lookup']) {
             $species_ctrl_opts['extraParams']['view'] = 'cache';
         }
         global $indicia_templates;
         if (isset($args['species_include_both_names']) && $args['species_include_both_names']) {
             if ($args['species_names_filter'] == 'all') {
                 $indicia_templates['species_caption'] = '{taxon}';
             } elseif ($args['species_names_filter'] == 'language') {
                 $indicia_templates['species_caption'] = '{taxon} - {preferred_name}';
             } else {
                 $indicia_templates['species_caption'] = '{taxon} - {common}';
             }
             $species_ctrl_opts['captionTemplate'] = 'species_caption';
         }
         if ($args['species_ctrl'] == 'tree_browser') {
             // change the node template to include images
             $indicia_templates['tree_browser_node'] = '<div>' . '<img src="' . self::warehouseUrl() . '/upload/thumb-{image_path}" alt="Image of {caption}" width="80" /></div>' . '<span>{caption}</span>';
         }
         // Dynamically generate the species selection control required.
         return call_user_func(array('data_entry_helper', $args['species_ctrl']), $species_ctrl_opts);
     }
 }
示例#6
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;
    }
 /**
  * Private utility function to extract the fields which need filtering against, plus any complex
  * SQL where clauses, required to do a species name filter according to the current mode (e.g.
  * preferred names only, all names etc).
  * @param array $options Species_checklist options array.
  * @param array $filterFields Pass an array in - this will be populated with the keys and values
  * of any fields than need to be filtered.
  * @param array $filterWheres Pass an array in - this will be populated with a list of any complex
  * where clauses (to put into a service request's query parameter).
  */
 private static function parse_species_name_filter_mode($options, &$filterFields, &$filterWheres)
 {
     if (isset($options['speciesNameFilterMode'])) {
         $colLanguage = $options['cacheLookup'] ? 'language_iso' : 'language';
         switch ($options['speciesNameFilterMode']) {
             case 'preferred':
                 $filterFields += array('preferred' => 't');
                 break;
             case 'currentLanguage':
                 // look for Drupal user variable. Will degrade gracefully if it doesn't exist
                 global $user;
                 if (isset($options['language'])) {
                     $filterFields += array($colLanguage => $options['language']);
                 } elseif (isset($user) && function_exists('hostsite_get_user_field')) {
                     // if in Drupal we can use the user's language
                     require_once 'prebuilt_forms/includes/language_utils.php';
                     $filterFields += array($colLanguage => iform_lang_iso_639_2(hostsite_get_user_field('language')));
                 }
                 break;
             case 'excludeSynonyms':
                 $filterWheres[] = "(preferred='t' or {$colLanguage}<>'lat')";
                 break;
         }
     }
 }
   /**
    * 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;
   }
示例#9
0
 /**
  * Get the block of custom attributes at the location level
  */
 protected static function get_control_locationattributes($auth, $args, $tabalias, $options)
 {
     $attrArgs = array('valuetable' => 'location_attribute_value', 'attrtable' => 'location_attribute', 'key' => 'location_id', 'fieldprefix' => 'locAttr', 'extraParams' => $auth['read'], 'survey_id' => $args['survey_id']);
     $tabName = isset($options['tabNameFilter']) ? $options['tabNameFilter'] : null;
     if (array_key_exists('location:id', data_entry_helper::$entity_to_load) && data_entry_helper::$entity_to_load['location:id'] != "") {
         // if we have location Id to load, use it to get attribute values
         $attrArgs['id'] = data_entry_helper::$entity_to_load['location:id'];
     }
     $locationAttributes = data_entry_helper::getAttributes($attrArgs, false);
     $defAttrOptions = array_merge(array('extraParams' => array_merge($auth['read'], array('view' => 'detail')), 'language' => iform_lang_iso_639_2($args['language'])), $options);
     $r = self::bats_get_attribute_html($locationAttributes, $args, $defAttrOptions, $tabName);
     return $r;
 }
示例#10
0
 /**
  * Get the control for species input, either a grid or a single species input control.
  */
 protected static function get_control_species($auth, $args, $tabalias, $options)
 {
     data_entry_helper::$javascript .= "\n// Main table existing entries\njQuery('.scCommentLabelCell').each(function(idx,elem){\n  jQuery(this).css('width',jQuery(this).find('label').css('width'));\n});\nspeciesRows = jQuery('.mnhnl-species-grid > tbody').find('tr');\n";
     if (self::$mode !== self::MODE_EXISTING_RO) {
         data_entry_helper::$javascript .= "\nfor(var j=0; j<speciesRows.length; j++){\n  occAttrs = jQuery(speciesRows[j]).find('.scOccAttrCell');\n  occAttrs.find('input').not(':hidden').addClass('fillgroup');\n  occAttrs.find('select').addClass('required').after('<span class=\"deh-required\">*</span>');\n}\nhook_species_checklist_pre_delete_row=function(e) {\n  return confirm(\"" . lang::get('Are you sure you want to delete this row?') . "\");\n};\n";
     }
     $extraParams = $auth['read'];
     // we want all languages, so dont filter
     // multiple species being input via a grid
     $myLanguage = iform_lang_iso_639_2($args['language']);
     if ($myLanguage != 'fra') {
         $myLanguage = 'eng';
     }
     // forced, used for termlists in attributes
     $species_ctrl_opts = array_merge(array("extra_list_id" => $args["extra_list_id"], 'listId' => $args['list_id'], 'label' => lang::get('occurrence:taxa_taxon_list_id'), 'columns' => 1, 'extraParams' => $extraParams, 'survey_id' => $args['survey_id'], 'occurrenceComment' => $args['occurrence_comment'], 'occurrenceImages' => $args['occurrence_images'], 'PHPtaxonLabel' => true, 'language' => $myLanguage, "max_species_ids" => $args["max_species_ids"]), $options);
     if ($args['extra_list_id']) {
         $species_ctrl_opts['lookupListId'] = $args['extra_list_id'];
     }
     if (isset($args['col_widths']) && $args['col_widths']) {
         $species_ctrl_opts['colWidths'] = explode(',', $args['col_widths']);
     }
     call_user_func(array(get_called_class(), 'build_grid_taxon_label_function'), $args, array());
     // Start by outputting a hidden value that tells us we are using a grid when the data is posted,
     // then output the grid control
     return '<input type="hidden" value="true" name="gridmode" />' . self::mnhnl_bats_species_checklist($species_ctrl_opts);
 }
 /**
  * Get the control for species input, either a grid or a single species input control.
  * User Interface options:
  * speciesListID
  * mapPosition = [top|side]
  * maxSpeciesIDs = The maximum number of taxa to be returned by the autocomplete drop down at any one time: OPTIONAL, default 25
  * includeOccurrenceComment = boolean to determine if occurrence_comments are included in the species grid, on a separate line
  */
 protected static function get_control_species($auth, $args, $tabalias, $options)
 {
     global $indicia_templates;
     $indicia_templates['check_or_radio_group'] = '<span {class}>{items}</span>';
     $indicia_templates['check_or_radio_group_item'] = '<span><input type="{type}" name="{fieldname}" id="{itemId}" value="{value}"{class}{checked} {disabled}/><label for="{itemId}">{caption}</label></span>{sep}';
     //  	$indicia_templates['check_or_radio_group'] = self::$check_or_radio_group_template;
     //  	$indicia_templates['check_or_radio_group_item'] = self::$check_or_radio_group_item_template;
     data_entry_helper::$javascript .= "\n// Main table existing entries\nspeciesRows = jQuery('.mnhnl-species-grid > tbody').find('tr');\nfor(var j=0; j<speciesRows.length; j++){\n\toccAttrs = jQuery(speciesRows[j]).find('.scOccAttrCell');\n";
     if (isset($options['unitSpeciesMeaning'])) {
         data_entry_helper::$javascript .= "\n\tif(jQuery(speciesRows[j]).hasClass('scMeaning-" . $options['unitSpeciesMeaning'] . "')){\n\t\tvar units = occAttrs.find('.scUnits');\n\t\tif(units.length > 0){\n\t\t  if(units.find('option').filter(':selected')[0].text=='m2')\n\t\t    occAttrs.find('.scNumber').removeClass('integer').attr('min',0);\n\t\t  units.change(function(){\n\t\t    jQuery('.ui-state-error').removeClass('ui-state-error');\n\t\t    jQuery('.inline-error').remove();\n\t\t    if(jQuery(this).find('option').filter(':selected')[0].text=='m2')\n\t\t      jQuery(this).closest('tr').find('.scNumber').removeClass('integer').attr('min',0);\n\t\t    else\n\t\t      jQuery(this).closest('tr').find('.scNumber').addClass('integer').attr('min',1);\n\t\t  });\n\t\t}\n\t} else {\n\t\toccAttrs.find('.scNumber').addClass('integer');\n\t\toccAttrs.find('.scUnits').find('option').each(function(index, elem){\n\t\t  if(elem.text == 'm2' || elem.value == '') jQuery(elem).remove();\n\t\t});\n\t}\n";
     }
     data_entry_helper::$javascript .= "\n}\nhook_species_checklist_pre_delete_row=function(e) {\n    return confirm(\"" . lang::get('Are you sure you want to delete this row?') . "\");\n};\n";
     $extraParams = $auth['read'];
     // multiple species being input via a grid
     $myLanguage = iform_lang_iso_639_2($args['language']);
     $species_ctrl_opts = array_merge(array('speciesListID' => $options['speciesListID'], 'label' => lang::get('occurrence:taxa_taxon_list_id'), 'columns' => 1, 'extraParams' => $extraParams, 'readAuth' => $extraParams, 'survey_id' => $args['survey_id'], 'includeSubSample' => isset($options['includeSubSample']), 'subsample_method_id' => $args['subsample_method_id'], 'separateCells' => isset($options['separateCells']), 'useCaptionsInHeader' => isset($options['useCaptionsInHeader']) && $options['useCaptionsInHeader'] == 'true', 'useCaptionsInPreRow' => isset($options['useCaptionsInPreRow']) && $options['useCaptionsInPreRow'] == 'true', 'resizeRadioGroup' => isset($options['resizeRadioGroup']) && $options['resizeRadioGroup'] == 'true', 'includeOccurrenceComment' => isset($options['includeOccurrenceComment']) && $options['includeOccurrenceComment'] == 'true', 'PHPtaxonLabel' => true, 'language' => $myLanguage, 'args' => $args), $options);
     $species_ctrl_opts['mapPosition'] = isset($options['mapPosition']) ? $options['mapPosition'] : 'top';
     call_user_func(array(get_called_class(), 'build_grid_taxon_label_function'), $args, $options);
     return self::species_checklist($species_ctrl_opts);
 }
 /**
  * Return the generated form output.
  * @return Form HTML.
  */
 public static function get_form($args, $node, $response = null)
 {
     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';
     $presetLayers = array();
     // read out the activated preset layers
     if (isset($args['preset_layers'])) {
         foreach ($args['preset_layers'] as $layer => $active) {
             if ($active !== 0) {
                 $presetLayers[] = $layer;
             }
         }
     }
     // When invoked by GET there are the following modes:
     // Not logged in: Display an information message.
     // No additional arguments: display the survey selector.
     // Additional argument - newSample: display the main page, no occurrence or occurrence list tabs. Survey tab active.
     // Additional argument - sample_id=<id>: display the main page, fill in the main sample details, "Add Occurrence" tab present, survey tab active.
     // Additional argument - occurrence_id=<id>: display the main page, fill in the main sample details, "Add Occurrence" tab active.
     $mode = 0;
     // default mode : display survey selector
     // mode 1: display new sample: no occurrence list or add occurrence tabs. Survey tab active
     // mode 2: display existing sample. Survey tab active. No occurence details filled in.
     // mode 3: display existing occurrence. Add Occurrence tab active. Occurence details filled in.
     // mode 4: NO LONGER USED. display Occurrence List. Occurrence List tab active. No occurence details filled in.
     $readOnly = 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();
     $parentErrors = null;
     $parentLoadID = null;
     $childSample = array();
     $childErrors = null;
     $childLoadID = null;
     $saveErrors = data_entry_helper::$validation_errors;
     $thisOccID = -1;
     // IDs have to be >0, so this is outside the valid range
     $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 (array_key_exists('website_id', $_POST)) {
             // Indicia POST, already handled.
             if (array_key_exists('newSample', $_GET)) {
                 if (!is_null(data_entry_helper::$entity_to_load)) {
                     $mode = 1;
                     // errors with new sample, entity populated with post, so display this data.
                     $parentSample = data_entry_helper::$entity_to_load;
                     $parentErrors = $saveErrors;
                 } else {
                     // else new sample just saved, so reload it ready to add occurrences
                     // OR, child sample/occurrence saved against new parent sample, in which case parent sample is in the post.
                     $mode = 2;
                     $parentLoadID = array_key_exists('sample:parent_id', $_POST) ? $_POST['sample:parent_id'] : $response['outer_id'];
                 }
             } else {
                 // could have saved parent sample or child sample/occurrence pair.
                 if (array_key_exists('sample:parent_id', $_POST)) {
                     // have saved child sample/occurrence pair
                     $parentLoadID = $_POST['sample:parent_id'];
                     // load the parent sample.
                     $mode = 3;
                     if (isset(data_entry_helper::$entity_to_load)) {
                         // errors so display Edit Occurrence page.
                         $childSample = data_entry_helper::$entity_to_load;
                         $childErrors = $saveErrors;
                         $displayThisOcc = false;
                         if ($childSample['occurrence:id']) {
                             $thisOccID = $childSample['occurrence:id'];
                         }
                     }
                 } else {
                     // saved parent record. display updated parent, no child.
                     $mode = 2;
                     // display parent sample details, whether errors or not.
                     if (isset(data_entry_helper::$entity_to_load)) {
                         // errors so use posted data.
                         $parentSample = data_entry_helper::$entity_to_load;
                         $parentErrors = $saveErrors;
                     } else {
                         $parentLoadID = $_POST['sample:id'];
                         // load the parent sample.
                     }
                 }
             }
         } else {
             // 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('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('newSample', $_GET)) {
                     $mode = 1;
                 }
             }
         }
         // else default to mode 0
     }
     // 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";
     $optionArray_1 = array();
     $optionArray_2 = array();
     $options = explode(',', $args['layer1']);
     foreach ($options as $option) {
         $parts = explode(':', $option);
         $optionName = $parts[0];
         unset($parts[0]);
         $optionsArray_1[$optionName] = implode(':', $parts);
     }
     $options = explode(',', $args['layer2']);
     foreach ($options as $option) {
         $parts = explode(':', $option);
         $optionName = $parts[0];
         unset($parts[0]);
         $optionsArray_2[$optionName] = implode(':', $parts);
     }
     data_entry_helper::$javascript .= "\n// Create Layers.\n// Base Layers first.\nvar WMSoptions = {\n          LAYERS: '" . $optionsArray_1['LAYERS'] . "',\n          SERVICE: 'WMS',\n          VERSION: '1.1.0',\n          STYLES: '',\n          SRS: '" . $optionsArray_1['SRS'] . "',\n          FORMAT: '" . $optionsArray_1['FORMAT'] . "'\n    };\nbaseLayer_1 = new OpenLayers.Layer.WMS('" . $optionsArray_1['Name'] . "',\n        '" . iform_proxy_url($optionsArray_1['URL']) . "',\n        WMSoptions, {\n             minScale: " . $optionsArray_1['minScale'] . ",\n            maxScale: " . $optionsArray_1['maxScale'] . ",\n            units: '" . $optionsArray_1['units'] . "',\n            isBaseLayer: true,\n            singleTile: true\n        });\nWMSoptions = {\n          LAYERS: '" . $optionsArray_2['LAYERS'] . "',\n          SERVICE: 'WMS',\n          VERSION: '1.1.0',\n          STYLES: '',\n          SRS: '" . $optionsArray_2['SRS'] . "',\n          FORMAT: '" . $optionsArray_2['FORMAT'] . "'\n    };\nbaseLayer_2 = new OpenLayers.Layer.WMS('" . $optionsArray_2['Name'] . "',\n        '" . iform_proxy_url($optionsArray_2['URL']) . "',\n        WMSoptions, {\n             minScale: " . $optionsArray_2['minScale'] . ",\n            maxScale: " . $optionsArray_2['maxScale'] . ",\n            units: '" . $optionsArray_2['units'] . "',\n            isBaseLayer: true,\n            singleTile: true\n        });\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.2,\n                    strokeWidth: 1\n                  })\n  });\nlocationLayer = new OpenLayers.Layer.Vector(\"" . lang::get("LANG_Location_Layer") . "\",\n                                    {styleMap: locStyleMap});\noccStyleMap = 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          }) });\noccListLayer = new OpenLayers.Layer.Vector(\"" . lang::get("LANG_Occurrence_List_Layer") . "\",\n                                    {styleMap: occStyleMap});\n";
     // Work out list of locations this user can see.
     $locations = iform_loctools_listlocations($node);
     ///////////////////////////////////////////////////////////////////
     // default mode 0 : display survey selector and locations allocator
     ///////////////////////////////////////////////////////////////////
     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\">\n";
             $r .= data_entry_helper::enable_tabs(array('divId' => 'controls', 'active' => '#surveyList'));
             $r .= "<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(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_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 : '" . $args['sample_visit_number_id'] . "', closed_attr_id : '" . $args['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\n", 'inline');
         $r .= '<div id="surveyList" class="mnhnl-btw-datapanel"><div id="smp_grid"></div>';
         $r .= '<form><input type="button" value="' . lang::get('LANG_Add_Survey') . '" onclick="window.location.href=\'' . url('node/' . $node->nid, array('query' => 'newSample')) . '\'"></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">';
             $r .= "<input type=\"hidden\" id=\"mnhnlbtw\" name=\"mnhnlbtw\" value=\"mnhnlbtw\" />\n";
             $url = $svcUrl . '/data/location';
             $url .= "?mode=json&view=detail&auth_token=" . $readAuth['auth_token'] . "&nonce=" . $readAuth["nonce"] . "&parent_id=NULL&orderby=name";
             $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"] . "\">";
                         $r .= "<option value=\"\" >&lt;" . lang::get('LANG_Not_Allocated') . "&gt;</option>";
                         $defaultuserid = iform_loctools_getuser($node, $entity["id"]);
                         foreach ($userlist as $uid => $a_user) {
                             if ($uid == $defaultuserid) {
                                 $selected = 'selected="selected"';
                             } else {
                                 $selected = '';
                             }
                             $r .= "<option value=\"" . $uid . "\" " . $selected . ">" . $a_user->name . "</option>";
                         }
                         $r .= "</select>";
                     }
                 }
             }
             $r .= "<input type=\"submit\" class=\"ui-state-default ui-corner-all\" value=\"" . lang::get('LANG_Save_Location_Allocations') . "\" />\n";
             $r .= "</form></div>";
         }
         // Add the downloader if user has manager (superuser) rights.
         if (iform_loctools_checkaccess($node, 'superuser')) {
             $r .= '<div id="downloads" class="mnhnl-btw-datapanel">';
             $r .= "<form method=\"post\" action=\"" . data_entry_helper::$base_url . "/index.php/services/report/requestReport?report=mnhnl_btw_transect_direction_report.xml&reportSource=local&auth_token=" . $readAuth['auth_token'] . "&nonce=" . $readAuth['nonce'] . "&mode=csv\">";
             $r .= '<p>' . lang::get('LANG_Direction_Report') . '</p>';
             $r .= "<input type=\"hidden\" id=\"params\" name=\"params\" value='{\"survey_id\":" . $args['survey_id'] . ", \"direction_attr_id\":" . $args['sample_walk_direction_id'] . ", \"closed_attr_id\":" . $args['sample_closure_id'] . "}' />";
             $r .= "<input type=\"submit\" class=\"ui-state-default ui-corner-all\" value=\"" . lang::get('LANG_Direction_Report_Button') . "\">";
             $r .= "</form>";
             $r .= "<form method=\"post\" action=\"" . data_entry_helper::$base_url . "/index.php/services/report/requestReport?report=mnhnl_btw_download_report.xml&reportSource=local&auth_token=" . $readAuth['auth_token'] . "&nonce=" . $readAuth['nonce'] . "&mode=csv\">";
             $r .= '<p>' . lang::get('LANG_Initial_Download') . '</p>';
             $r .= "<input type=\"hidden\" id=\"params\" name=\"params\" value='{\"survey_id\":" . $args['survey_id'] . ", \"closed_attr_id\":" . $args['sample_closure_id'] . ", \"download\": \"INITIAL\"}' />";
             $r .= "<input type=\"submit\" class=\"ui-state-default ui-corner-all\" value=\"" . lang::get('LANG_Initial_Download_Button') . "\">";
             $r .= "</form>";
             $r .= "<form method=\"post\" action=\"" . data_entry_helper::$base_url . "/index.php/services/report/requestReport?report=mnhnl_btw_download_report.xml&reportSource=local&auth_token=" . $readAuth['auth_token'] . "&nonce=" . $readAuth['nonce'] . "&mode=csv\">";
             $r .= '<p>' . lang::get('LANG_Confirm_Download') . '</p>';
             $r .= "<input type=\"hidden\" id=\"params\" name=\"params\" value='{\"survey_id\":" . $args['survey_id'] . ", \"closed_attr_id\":" . $args['sample_closure_id'] . ", \"download\": \"CONFIRM\"}' />";
             $r .= "<input type=\"submit\" class=\"ui-state-default ui-corner-all\" value=\"" . lang::get('LANG_Confirm_Download_Button') . "\">";
             $r .= "</form>";
             $r .= "<form method=\"post\" action=\"" . data_entry_helper::$base_url . "/index.php/services/report/requestReport?report=mnhnl_btw_download_report.xml&reportSource=local&auth_token=" . $readAuth['auth_token'] . "&nonce=" . $readAuth['nonce'] . "&mode=csv\">";
             $r .= '<p>' . lang::get('LANG_Final_Download') . '</p>';
             $r .= "<input type=\"hidden\" id=\"params\" name=\"params\" value='{\"survey_id\":" . $args['survey_id'] . ", \"closed_attr_id\":" . $args['sample_closure_id'] . ", \"download\": \"FINAL\"}' />";
             $r .= "<input type=\"submit\" class=\"ui-state-default ui-corner-all\" value=\"" . lang::get('LANG_Final_Download_Button') . "\">";
             $r .= "</form></div>";
         }
         // Create Map
         $r .= "<div class=\"mnhnl-btw-mappanel\">\n";
         $r .= data_entry_helper::map_panel(array('presetLayers' => $presetLayers, 'layers' => array('baseLayer_1', 'baseLayer_2', 'locationLayer'), 'initialFeatureWkt' => null, 'width' => 'auto', 'height' => 490, 'editLayer' => false, 'initial_lat' => $args['map_centroid_lat'], 'initial_long' => $args['map_centroid_long'], 'initial_zoom' => (int) $args['map_zoom'], 'scroll_wheel_zoom' => false), array('projection' => $args['map_projection']));
         // Add locations to the map on the locations layer.
         // Zoom in to area which contains the users locations.
         if ($locations != 'all') {
             data_entry_helper::$javascript .= "locationList = [" . implode(',', $locations) . "];\n";
         }
         data_entry_helper::$javascript .= "\n// upload locations into map.\n// Change the location control requests the location's geometry to place on the map.\n\$.getJSON(\"{$svcUrl}\" + \"/data/location\" +\n          \"?mode=json&view=detail&nonce=" . $readAuth['nonce'] . "&auth_token=" . $readAuth['auth_token'] . "\" +\n          \"&parent_id=NULL&callback=?\", function(data) {\n    // store value in saved field?\n  locationLayer.destroyFeatures();\n    if (data.length>0) {\n      var newFeatures = [];\n      var feature;\n      var parser = new OpenLayers.Format.WKT();\n    for (var i=0;i<data.length;i++)\n    {\n";
         if ($locations != 'all') {
             // include restriction on locations if user does not have full access.
             data_entry_helper::$javascript .= "\n        for(var j=0; j<locationList.length; j++) {\n          if(locationList[j] == data[i].id || locationList[j] == data[i].parent_id) {";
         }
         data_entry_helper::$javascript .= "\n        if(data[i].boundary_geom){\n          " . self::readBoundaryJs('data[i].boundary_geom', $args['map_projection']) . "\n          feature.style = {label: data[i].name,\n                        strokeColor: \"Blue\",\n                      strokeWidth: 2};\n          newFeatures.push(feature);\n        }\n";
         if ($locations != 'all') {
             data_entry_helper::$javascript .= "\n          }\n        }\n";
         }
         data_entry_helper::$javascript .= "\n    }\n    locationLayer.addFeatures(newFeatures);\n    locationLayer.map.zoomToExtent(locationLayer.getDataExtent());\n    }\n});\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";
         $r .= "</div>\n";
         if (count($tabs) > 1) {
             $r .= "</div>";
         }
         return $r;
     }
     ///////////////////////////////////////////////////////////////////
     $occReadOnly = false;
     if ($childLoadID) {
         $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);
         $childSample = array();
         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);
         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.
         $thisOccID = $childLoadID;
         // this will be used to load the occurrence into the editlayer.
         $childSample['taxon'] = $childSample['occurrence:taxon'];
         $parentLoadID = $childSample['sample:parent_id'];
     }
     if ($parentLoadID) {
         $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);
         $parentSample = array();
         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
         // default values for attributes from DB are picked up automatically.
     }
     $childSample['sample:date'] = $parentSample['sample:date'];
     // enforce a match between child and parent sample dates
     data_entry_helper::$entity_to_load = $parentSample;
     data_entry_helper::$validation_errors = $parentErrors;
     $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[$args['sample_closure_id']]['fieldname'];
     $closedFieldValue = data_entry_helper::check_default_value($closedFieldName, array_key_exists('default', $attributes[$args['sample_closure_id']]) ? $attributes[$args['sample_closure_id']]['default'] : '0');
     // default is not closed
     $adminPerm = 'IForm node ' . $node->nid . ' admin';
     if ($closedFieldValue == '1' && !user_access($adminPerm)) {
         // sample has been closed, no admin perms. Everything now set to read only.
         $readOnly = true;
         $disabledText = "disabled=\"disabled\"";
         $defAttrOptions = array('extraParams' => $readAuth, 'disabled' => $disabledText);
     } else {
         // sample open.
         $disabledText = "";
         $defAttrOptions = array('extraParams' => $readAuth);
     }
     data_entry_helper::enable_validation('SurveyForm');
     $r .= "<div id=\"controls\">\n";
     $activeTab = 'survey';
     if ($mode == 3 || $mode == 2) {
         $activeTab = 'occurrence';
     }
     // Set Up form tabs.
     if ($mode == 4) {
         $activeTab = 'occurrenceList';
     }
     $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($readOnly || $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";
     if ($readOnly) {
         $r .= "<strong>" . lang::get('LANG_Read_Only_Survey') . "</strong>";
     }
     $r .= "<form id=\"SurveyForm\" method=\"post\">\n";
     $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";
     $r .= iform_user_get_hidden_inputs($args);
     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";
     }
     $defAttrOptions['validation'] = array('required');
     $defAttrOptions['suffixTemplate'] = 'requiredsuffix';
     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';
         $url .= "?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[$args['sample_walk_direction_id']], $languageFilteredAttrOptions);
     $r .= data_entry_helper::outputAttribute($attributes[$args['sample_reliability_id']], $languageFilteredAttrOptions);
     $r .= data_entry_helper::outputAttribute($attributes[$args['sample_visit_number_id']], array_merge($languageFilteredAttrOptions, array('default' => 1, 'noBlankText' => true)));
     if ($readOnly) {
         $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', 'suffixTemplate' => 'requiredsuffix'));
     }
     $r .= data_entry_helper::outputAttribute($attributes[$args['sample_wind_id']], $languageFilteredAttrOptions);
     $r .= data_entry_helper::outputAttribute($attributes[$args['sample_precipitation_id']], $languageFilteredAttrOptions);
     $r .= data_entry_helper::outputAttribute($attributes[$args['sample_temperature_id']], array_merge($defAttrOptions, array('suffixTemplate' => 'nosuffix')));
     $r .= " degC<span class=\"deh-required\">*</span><br />";
     $r .= data_entry_helper::outputAttribute($attributes[$args['sample_cloud_id']], $defAttrOptions);
     $r .= data_entry_helper::outputAttribute($attributes[$args['sample_start_time_id']], array_merge($defAttrOptions, array('suffixTemplate' => 'nosuffix')));
     $r .= " hh:mm<span class=\"deh-required\">*</span><br />";
     $r .= data_entry_helper::outputAttribute($attributes[$args['sample_end_time_id']], array_merge($defAttrOptions, array('suffixTemplate' => 'nosuffix')));
     $r .= " hh:mm<span class=\"deh-required\">*</span><br />";
     unset($defAttrOptions['suffixTemplate']);
     unset($defAttrOptions['validation']);
     if (user_access($adminPerm)) {
         //  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[$args['sample_closure_id']], $defAttrOptions);
     } else {
         // hidden closed
         $r .= "<input type=\"hidden\" id=\"" . $closedFieldName . "\" name=\"" . $closedFieldName . "\" value=\"" . $closedFieldValue . "\" />\n";
     }
     if (!empty(data_entry_helper::$validation_errors)) {
         $r .= data_entry_helper::dump_remaining_errors();
     }
     $escaped_id = str_replace(':', '\\\\:', $closedFieldName);
     if (!$readOnly) {
         $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('#SurveyForm').submit();\">\n";
         if (!user_access($adminPerm) && $mode != 1) {
             $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('#" . $escaped_id . "').val('1');\n            jQuery('#SurveyForm').submit();\n          };\">\n";
         }
     }
     $r .= "</form>";
     $r .= "</div>\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\">\n";
     if ($mode != 1) {
         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');
         $r .= '<div id="occ_grid"></div>';
         $r .= "<form method=\"post\" action=\"" . data_entry_helper::$base_url . "/index.php/services/report/requestReport?report=mnhnl_btw_occurrences_report.xml&reportSource=local&auth_token=" . $readAuth['auth_token'] . "&nonce=" . $readAuth['nonce'] . "&mode=csv\">";
         $r .= "<input type=\"hidden\" id=\"params\" name=\"params\" value='{\"survey_id\":" . $args['survey_id'] . ", \"sample_id\":" . data_entry_helper::$entity_to_load['sample:id'] . "}' />";
         $r .= "<input type=\"submit\" class=\"ui-state-default ui-corner-all\" value=\"" . lang::get('LANG_Download_Occurrences') . "\">";
         $r .= "</FORM>";
     } else {
         $r .= '<p>' . lang::get('LANG_Page_Not_Available') . '</p>';
     }
     $r .= '</div>';
     // Set up Occurrence tab: don't allow entry of a new occurrence until after top level sample is saved.
     $r .= "<div id=\"occurrence\" class=\"mnhnl-btw-datapanel\">\n";
     if ($mode != 1 && ($mode != 2 && $mode != 4 || $readOnly == false)) {
         data_entry_helper::$entity_to_load = $childSample;
         data_entry_helper::$validation_errors = $childErrors;
         $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));
         if ($occReadOnly) {
             $r .= "<strong>" . lang::get('LANG_Read_Only_Occurrence') . "</strong>";
             $disabledText = "disabled=\"disabled\"";
             $defAttrOptions['disabled'] = $disabledText;
         } else {
             if ($readOnly) {
                 $r .= "<strong>" . lang::get('LANG_Read_Only_Survey') . "</strong>";
             }
         }
         $r .= "<form method=\"post\">\n";
         $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";
         $r .= "<input type=\"hidden\" id=\"sample:parent_id\" name=\"sample:parent_id\" value=\"" . $parentSample['sample:id'] . "\" />\n";
         $r .= "<input type=\"hidden\" id=\"sample:date\" name=\"sample:date\" value=\"" . data_entry_helper::$entity_to_load['sample:date'] . "\" />\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";
         }
         if (array_key_exists('occurrence:id', data_entry_helper::$entity_to_load)) {
             $r .= "<input type=\"hidden\" id=\"occurrence:id\" name=\"occurrence:id\" value=\"" . data_entry_helper::$entity_to_load['occurrence:id'] . "\" />\n";
         }
         $r .= "<input type=\"hidden\" id=\"occurrence:record_status\" name=\"occurrence:record_status\" value=\"C\" />\n";
         $r .= "<input type=\"hidden\" id=\"occurrence:downloaded_flag\" name=\"occurrence:downloaded_flag\" value=\"N\" />\n";
         $extraParams = $readAuth + array('taxon_list_id' => $args['list_id']);
         $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, 'suffixTemplate' => 'requiredsuffix', 'disabled' => $disabledText, 'defaultCaption' => data_entry_helper::$entity_to_load['occurrence:taxon']);
         $r .= data_entry_helper::autocomplete($species_ctrl_args);
         $r .= data_entry_helper::outputAttribute($attributes[$args['occurrence_confidence_id']], array_merge($languageFilteredAttrOptions, array('noBlankText' => '')));
         $r .= data_entry_helper::sref_and_system(array('label' => lang::get('LANG_Spatial_ref'), 'systems' => array('2169' => 'Luref (Gauss Luxembourg)'), 'suffixTemplate' => 'requiredsuffix'));
         $r .= "<p>" . lang::get('LANG_Click_on_map') . "</p>";
         $r .= data_entry_helper::outputAttribute($attributes[$args['occurrence_count_id']], array_merge($defAttrOptions, array('default' => 1, 'suffixTemplate' => 'requiredsuffix')));
         $r .= data_entry_helper::outputAttribute($attributes[$args['occurrence_approximation_id']], $defAttrOptions);
         $r .= data_entry_helper::outputAttribute($attributes[$args['occurrence_territorial_id']], array_merge($defAttrOptions, array('default' => 1)));
         $r .= data_entry_helper::outputAttribute($attributes[$args['occurrence_atlas_code_id']], $languageFilteredAttrOptions);
         $r .= data_entry_helper::outputAttribute($attributes[$args['occurrence_overflying_id']], $defAttrOptions);
         $r .= data_entry_helper::textarea(array('label' => lang::get('LANG_Comment'), 'fieldname' => 'occurrence:comment', 'disabled' => $disabledText));
         if (!empty(data_entry_helper::$validation_errors)) {
             $r .= data_entry_helper::dump_remaining_errors();
         }
         if (!$readOnly && !$occReadOnly) {
             $r .= "<input type=\"submit\" class=\"ui-state-default ui-corner-all\" value=\"" . lang::get('LANG_Save_Occurrence_Details') . "\" />\n";
         }
         $r .= "</form>\n";
         $escaped_terr_id = str_replace(':', '\\\\:', $attributes[$args['occurrence_territorial_id']]['fieldname']);
         $escaped_atlas_id = str_replace(':', '\\\\:', $attributes[$args['occurrence_atlas_code_id']]['fieldname']);
         data_entry_helper::$javascript .= "\nsetAtlasStatus = function() {\n  if (jQuery(\"input[name='" . $escaped_terr_id . "']:checked\").val() == '0') {\n      jQuery('#" . $escaped_atlas_id . "').val('');\n  } else {\n      if(jQuery('#" . $escaped_atlas_id . "').val() == '') {\n        // Find the BB02 option (depends on the language what val it has)\n        var bb02;\n        jQuery.each(jQuery('#" . $escaped_atlas_id . " 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('#" . $escaped_atlas_id . "').val(bb02);\n      }\n  }\n};\nsetAtlasStatus();\njQuery(\"input[name='" . $escaped_terr_id . "']\").change(setAtlasStatus);\n";
     } else {
         $r .= '<p>' . lang::get('LANG_Page_Not_Available') . '</p>';
     }
     $r .= '</div>';
     // add map panel.
     $r .= "<div class=\"mnhnl-btw-mappanel\">\n";
     $r .= data_entry_helper::map_panel(array('presetLayers' => $presetLayers, 'layers' => array('baseLayer_1', 'baseLayer_2', 'locationLayer', 'occListLayer'), 'initialFeatureWkt' => null, 'width' => 'auto', 'height' => 490, 'initial_lat' => $args['map_centroid_lat'], 'initial_long' => $args['map_centroid_long'], 'initial_zoom' => (int) $args['map_zoom'], 'scroll_wheel_zoom' => false), array('projection' => $args['map_projection']));
     // 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 .= "\nvar control = new OpenLayers.Control.SelectFeature(occListLayer);\noccListLayer.map.addControl(control);\nfunction onPopupClose(evt) {\n    // 'this' is the popup.\n    control.unselect(this.feature);\n}\nfunction 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}\nfunction 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\noccListLayer.events.on({\n    'featureselected': onFeatureSelect,\n    'featureunselected': onFeatureUnselect\n});\n\ncontrol.activate();\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);\n";
     if ($mode != 1) {
         data_entry_helper::$onload_javascript .= "\nactivateAddList = 1;\n\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==" . ($readOnly ? 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      if(" . ($displayThisOcc ? 1 : 0) . "){\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    }\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\$('div#occ_grid').indiciaDataGrid('rpt: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 : '" . $args['occurrence_territorial_id'] . "',\n            count_attr_id : '" . $args['occurrence_count_id'] . "'},\n    itemsPerPage : 12,\n    callback : addListFeature ,\n    cssOdd : ''\n  });\n\n// activateAddList = 0;\n\n";
     }
     $r .= "</div><div><form><input type=\"button\" value=\"" . lang::get('LANG_Return') . "\" onclick=\"window.location.href='" . url('node/' . $node->nid, array('query' => 'Main')) . "'\"></form></div></div>\n";
     return $r;
 }
    /**
     *
     */
    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
        data_entry_helper::add_resource('autocomplete');
        $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'];
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
        // The only things that will be editable after the collection is saved will be the identification 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']));
        $uidAttrID = self::getAttrID($readAuth, $args, 'sample', 'CMS User ID');
        $usernameAttrID = self::getAttrID($readAuth, $args, 'sample', 'CMS Username');
        $frontPageAttrID = self::getAttrID($readAuth, $args, 'sample', 'FrontPage');
        $startTimeAttrID = self::getAttrID($readAuth, $args, 'sample', 'Start Time');
        $endTimeAttrID = self::getAttrID($readAuth, $args, 'sample', 'End Time');
        $skyAttrID = self::getAttrID($readAuth, $args, 'sample', 'Sky');
        $temperatureAttrID = self::getAttrID($readAuth, $args, 'sample', 'Temperature');
        $shadeAttrID = self::getAttrID($readAuth, $args, 'sample', 'Shade');
        $windAttrID = self::getAttrID($readAuth, $args, 'sample', 'Wind');
        $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']));
        $flowerTypeAttrID = self::getAttrID($readAuth, $args, 'occurrence', 'Flower Type');
        $foragingAttrID = self::getAttrID($readAuth, $args, 'occurrence', 'Foraging');
        $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']));
        $habitatAttrID = self::getAttrID($readAuth, $args, 'location', 'Habitat');
        $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>";
        }
        $defAttrOptions = array('extraParams' => $readAuth + array('orderby' => 'id'), 'lookUpListCtrl' => 'checkbox_group', 'lookUpKey' => 'meaning_id', 'booleanCtrl' => 'checkbox_group', 'sep' => ' &nbsp; ', 'language' => $language, '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', 'listCaptionSpecialChars' => true, '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'));
        if (isset($args['flower_data_entry_only']) && $args['flower_data_entry_only']) {
            $flower_ctrl_args['extraParams']['allow_data_entry'] = 't';
        }
        $focus_flower_ctrl_args = $flower_ctrl_args;
        $focus_flower_ctrl_args['fieldname'] = 'determination:taxa_taxon_list_id';
        $focus_flower_ctrl_args['extraParams']['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', 'listCaptionSpecialChars' => true, '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'));
        if (isset($args['insect_data_entry_only']) && $args['insect_data_entry_only']) {
            $insect_ctrl_args['extraParams']['allow_data_entry'] = 't';
        }
        $focus_insect_ctrl_args = $insect_ctrl_args;
        $focus_insect_ctrl_args['fieldname'] = 'determination:taxa_taxon_list_id';
        $focus_insect_ctrl_args['extraParams']['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.
        // Switch to degrees, minutes, seconds for lat long.
        $options['latLongFormat'] = 'DMS';
        $options['initialFeatureWkt'] = null;
        $options['proxy'] = '';
        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['height'] = $args['2nd_map_height'];
        if (isset($args['2nd_map_zoom']) && $args['2nd_map_zoom'] != "") {
            $options2['maxZoom'] = $args['2nd_map_zoom'];
        }
        // we are using meaning_ids: services now use ids, so can't just output value - convert raw value
        data_entry_helper::$javascript .= "var terms = {";
        $extraParams = $readAuth + array('view' => 'detail', 'iso' => $language, 'orderby' => 'meaning_id');
        $terms_data_def = array('table' => 'termlists_term', 'extraParams' => $extraParams);
        $terms = data_entry_helper::get_population_data($terms_data_def);
        $first = true;
        foreach ($terms as $term) {
            data_entry_helper::$javascript .= ($first ? '' : ',') . $term['meaning_id'] . ": \"" . htmlSpecialChars($term['term']) . "\"\n";
            $first = false;
        }
        data_entry_helper::$javascript .= "};\nconvertTerm=function(id){\n\tif(typeof terms[id] == 'undefined') return id;\n\treturn terms[id];\n}\nvar 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['taxon_list_id'] = $args['insect_list_id'];
        $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 so no allow_data_entry
        $species_data_def['extraParams'] = $extraParams;
        $taxa = data_entry_helper::get_population_data($species_data_def);
        $first = true;
        foreach ($taxa as $taxon) {
            // 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 .= "];";
        // TBD Breadcrumb
        $r .= '<h1 id="poll-banner"></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')) . '
  		</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\'}" />
		  <label >' . lang::get('LANG_ID_Status') . ':</label>
		  <span class="control-box "><nobr>
		    <span><input type="checkbox" value="X" id="flower_id_status:0" name="flower_id_status[]"><label for="flower_id_status:0">' . lang::get('LANG_ID_Status_Unidentified') . '</label></span></nobr> &nbsp; <nobr>
		    <span><input type="checkbox" value="A" id="flower_id_status:1" name="flower_id_status[]"><label for="flower_id_status:1">' . lang::get('LANG_ID_Status_Initial') . '</label></span></nobr> &nbsp; <nobr>
		    <span><input type="checkbox" value="B" id="flower_id_status:2" name="flower_id_status[]"><label for="flower_id_status:2">' . lang::get('LANG_ID_Status_Doubt') . '</label></span></nobr> &nbsp; <nobr>
		    <span><input type="checkbox" value="C" id="flower_id_status:3" name="flower_id_status[]"><label for="flower_id_status:3">' . lang::get('LANG_ID_Status_Validated') . '</label></span></nobr> &nbsp; 
		  </span>
		  <label >' . lang::get('LANG_ID_Type') . ':</label>
		  <span class="control-box "><nobr>
		    <span><input type="checkbox" value="seul" id="flower_id_type:0" name="flower_id_type[]"><label for="flower_id_type:0">' . lang::get('LANG_ID_Type_Single') . '</label></span></nobr> &nbsp; <nobr>
		    <span><input type="checkbox" value="multi" id="flower_id_type:1" name="flower_id_type[]"><label for="flower_id_type:1">' . lang::get('LANG_ID_Type_Multiple') . '</label></span></nobr> &nbsp; 
		  </span>
          ' . str_replace("\n", "", data_entry_helper::outputAttribute($occurrence_attributes[$flowerTypeAttrID], $defAttrOptions)) . str_replace("\n", "", data_entry_helper::outputAttribute($location_attributes[$habitatAttrID], $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\'}" />
		  <label >' . lang::get('LANG_ID_Status') . ':</label>
		  <span class="control-box "><nobr>
		    <span><input type="checkbox" value="X" id="insect_id_status:0" name="insect_id_status[]"><label for="insect_id_status:0">' . lang::get('LANG_ID_Status_Unidentified') . '</label></span></nobr> &nbsp; <nobr>
		    <span><input type="checkbox" value="A" id="insect_id_status:1" name="insect_id_status[]"><label for="insect_id_status:1">' . lang::get('LANG_ID_Status_Initial') . '</label></span></nobr> &nbsp; <nobr>
		    <span><input type="checkbox" value="B" id="insect_id_status:2" name="insect_id_status[]"><label for="insect_id_status:2">' . lang::get('LANG_ID_Status_Doubt') . '</label></span></nobr> &nbsp; <nobr>
		    <span><input type="checkbox" value="C" id="insect_id_status:3" name="insect_id_status[]"><label for="insect_id_status:3">' . lang::get('LANG_ID_Status_Validated') . '</label></span></nobr> &nbsp; 
		  </span>
		  <label >' . lang::get('LANG_ID_Type') . ':</label>
		  <span class="control-box "><nobr>
		    <span><input type="checkbox" value="seul" id="insect_id_type:0" name="insect_id_type[]"><label for="insect_id_type:0">' . lang::get('LANG_ID_Type_Single') . '</label></span></nobr> &nbsp; <nobr>
		    <span><input type="checkbox" value="multi" id="insect_id_type:1" name="insect_id_type[]"><label for="insect_id_type:1">' . lang::get('LANG_ID_Type_Multiple') . '</label></span></nobr> &nbsp; 
		  </span>
		' . str_replace("\n", "", data_entry_helper::outputAttribute($occurrence_attributes[$foragingAttrID], $defAttrOptions)) . '
		</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[$skyAttrID], $defAttrOptions)) . str_replace("\n", "", data_entry_helper::outputAttribute($sample_attributes[$temperatureAttrID], $defAttrOptions)) . str_replace("\n", "", data_entry_helper::outputAttribute($sample_attributes[$windAttrID], $defAttrOptions)) . str_replace("\n", "", data_entry_helper::outputAttribute($sample_attributes[$shadeAttrID], $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">';
        $searches = explode(';', trim($args['Localisation_spec']));
        if (count($searches) == 1) {
            $parts = explode(':', $searches[0]);
            $r .= '<input type="hidden" id="place:INSEE_Type" name="place:INSEE_Type" value="0"><label for="place:INSEE">' . lang::get('LANG_Search') . ' ' . $parts[0] . '</label>';
        } else {
            $r .= '<label for="place:INSEE_Type">' . lang::get('LANG_Search') . ' </label><select id="place:INSEE_Type" name="place:INSEE_Type">';
            for ($i = 0; $i < count($searches); $i++) {
                $parts = explode(':', $searches[$i]);
                $r .= '<option value="' . $i . '">' . $parts[0] . '</option>';
            }
            $r .= '</select>';
        }
        $r .= '<input type="text" id="place:INSEE" name="place:INSEE" class="INSEE-search" value="' . lang::get('LANG_Enter_Location') . '"
	 		  onclick="if(this.value==\'' . lang::get('LANG_Enter_Location') . '\'){this.value=\'\'; this.style.color=\'#000\'}"  
              onblur="if(this.value==\'\'){this.value=\'' . lang::get('LANG_Enter_Location') . '\'; 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 class="ui-corner-all ui-widget-content ui-helper-hidden" id="imp-insee-div" style="display: none;">
    	      <div id="imp-insee-output-div"></div>
    	      <a id="imp-insee-close-btn" href="#" class="ui-corner-all ui-widget-content ui-state-default indicia-button">' . lang::get('close') . '</a>
    	    </div>
		  </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" style="display: none">
	  <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" style="display: none">
    </div>
	<div id="results-insects-header" class="ui-accordion-header ui-helper-reset ui-state-active ui-corner-top" style="display: none">
	  <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" style="display: none">
    </div>';
        if (user_access('IForm n' . $node->nid . ' insect expert') || user_access('IForm n' . $node->nid . ' flower expert')) {
            $r .= '
	<form id="bulk-validation-form" action="' . iform_ajaxproxy_url($node, 'determination') . '" method="POST" style="display:none;">
		<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="C" />
		<input type="hidden" name="determination:taxon_details" value="" />
		<input type="hidden" name="determination:taxa_taxon_list_id" value="" />
		<input type="hidden" name="determination:comment" value="' . lang::get('LANG_Bulk_Validation_Comment') . '" />
		<input type="hidden" name="determination:taxon_extra_info" value="" />
	</form>
	<div id="results-validate-page" class="ui-accordion-content ui-helper-reset ui-widget-content ui-accordion-content-active ui-corner-all" style="display: none">
	  <div id="validate-page-button" class="ui-state-default ui-corner-all validate-page-button">' . lang::get('LANG_Validate_Page') . '</div>
	  <div id="validate-page-progress"></div>
	  <div id="validate-page-message"></div>
	  <div id="cancel-validate-page" class="ui-state-default ui-corner-all cancel-validate-button">' . lang::get('LANG_Cancel') . '</div>
	</div>
	<div id="results-validate-taxon-outer" style="display: none">
	  <div id="results-validate-taxon" class="ui-accordion-content ui-helper-reset ui-widget-content ui-accordion-content-active ui-corner-all" style="display: none">
		<div id="validate-taxon-button" class="ui-state-default ui-corner-all validate-taxon-button">' . lang::get('LANG_Validate_Taxon') . '</div>
		<div id="validate-taxon-progress"></div>
		<div id="validate-taxon-message"></div>
		<div id="cancel-validate-taxon" class="ui-state-default ui-corner-all cancel-validate-button">' . lang::get('LANG_Cancel') . '</div>
	</div></div>';
        }
        $r .= '
</div>
<div id="focus-collection" class="ui-accordion ui-widget ui-helper-reset" style="display: none">
	<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">
	    <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>';
        if (user_access('IForm n' . $node->nid . ' delete collection')) {
            $r .= '<div id="fc-delete-collection" class="ui-accordion-content ui-helper-reset ui-widget-content ui-accordion-content-active">
		<form id="fc-delete-collection-form" action="' . iform_ajaxproxy_url($node, 'sample') . '" method="POST">
		<input type="hidden" name="website_id" value="' . $args['website_id'] . '" />
		<input type="hidden" name="survey_id" value="' . $args['survey_id'] . '" />
		<input type="hidden" name="sample:id" value="" />
		<input type="hidden" name="sample:deleted" value="t" />
		<input type="submit" id="fc_delete_collection_submit_button" class="ui-state-default ui-corner-all preferred-button" value="' . lang::get('LANG_Submit_delete-collection') . '" />
		</form>
	  </div>';
        }
        $r .= '	<div id="collection-details" class="ui-accordion-content ui-helper-reset ui-widget-content ' . (user_access('IForm n' . $node->nid . ' add preferred collection') ? '' : 'ui-corner-bottom') . ' ui-accordion-content-active" ' . (user_access('IForm n' . $node->nid . ' add preferred collection') ? 'style="border-bottom:none;"' : '') . '>
	  <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[$flowerTypeAttrID]['caption']) . ': <span id="collection-flower-type" class="collection-value"></span></p>
	    <p>' . lang::get($location_attributes[$habitatAttrID]['caption']) . ': <span id="collection-habitat" class="collection-value"></span></p>
	    <br />
	    <p id="collection-user-name"></p>
	    <a id="collection-user-link">' . lang::get('LANG_User_Link') . '</a>
	    <br /><br />
	    <p>' . lang::get('LANG_INSEE_Localisation') . ': <span id="collection-locality"></span></p>
        <br /><p id="fc-new-location-desc">' . lang::get('LANG_Localisation_Desc') . '</p>
	  </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;
        data_entry_helper::$javascript .= "\njQuery('#fc-new-location').find('br').remove();\n";
        $r .= '</div>
      <div id="fc-new-location">
		<form id="fc-new-location-form" action="' . iform_ajaxproxy_url($node, 'location') . '" method="POST">
    		<input type="hidden"                       name="website_id" value="' . $args['website_id'] . '" />
    		<input type="hidden"                       name="survey_id" value="' . $args['survey_id'] . '" />
    		<input type="hidden" id="imp-sref-system"  name="location:centroid_sref_system" value="4326" />
		 	<input type="hidden"                       name="location:name" value="" />
    		<input type="hidden" id="location-id"      name="location:id" value=""/>
    	' . data_entry_helper::sref_textbox(array('srefField' => 'location:centroid_sref', 'systemfield' => 'location:centroid_sref_system', 'fieldname' => 'location:centroid_sref', 'splitLatLong' => true, 'labelLat' => lang::get('Latitude'), 'fieldnameLat' => 'place:lat', 'labelLong' => lang::get('Longitude'), 'fieldnameLong' => 'place:long', 'idLat' => 'imp-sref-lat', 'idLong' => 'imp-sref-long')) . '
            <input type="submit" id="fc_location_submit_button" class="ui-state-default ui-corner-all submit-button" value="' . lang::get('LANG_Submit_Location') . '" />
        </form>
	  </div>
      <div id="fc-new-location-message"></div></div>';
        if (user_access('IForm n' . $node->nid . ' add preferred collection')) {
            $r .= '<div id="preferred-button-container" class="ui-accordion-content ui-helper-reset ui-widget-content ui-corner-bottom ui-accordion-content-active"><span id="fc-add-preferred" class="ui-state-default ui-corner-all preferred-button">' . lang::get('LANG_Add_Preferred_Collection') . '</span></div>';
        }
        if (user_access('IForm n' . $node->nid . ' add to front page')) {
            $r .= '<div id="fc-front-page" class="ui-widget-content ui-corner-all">
    <form id="fc-front-page-form" action="' . iform_ajaxproxy_url($node, 'sample') . '" method="POST">
       <input type="hidden" name="website_id" value="' . $args['website_id'] . '" />
       <input type="hidden" name="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="" />
       <label>' . lang::get('LANG_Front Page') . '</label><div class="control-box "><nobr><span><input type="radio" id="smpAttr:' . $frontPageAttrID . ':0" name="smpAttr:' . $frontPageAttrID . '" value="0" checked="checked" /><label for="smpAttr:' . $frontPageAttrID . ':0">' . lang::get('No') . '</label></span></nobr> &nbsp; <nobr><span><input type="radio" id="smpAttr:' . $frontPageAttrID . ':1" name="smpAttr:' . $frontPageAttrID . '" value="1" /><label for="smpAttr:' . $frontPageAttrID . ':1">' . lang::get('Yes') . '</label></span></nobr></div>
       <input type="submit" id="fc_front_page_submit_button" class="ui-state-default ui-corner-all submit-button" value="' . lang::get('LANG_Submit_Front_Page') . '" />
    </form>
    <div id="fc-front-page-message"></div>
  </div>
';
        }
        $r .= '<div id="collection-insects"></div>';
        if (user_access('IForm n' . $node->nid . ' insect expert')) {
            $r .= '
    <div id="results-validate-collection" class="ui-accordion-content ui-helper-reset ui-widget-content ui-accordion-content-active ui-corner-all">
	  <div id="validate-collection-button" class="ui-state-default ui-corner-all validate-collection-button">' . lang::get('LANG_Validate_Collection') . '</div>
	  <div id="validate-collection-progress"></div>
	  <div id="validate-collection-message"></div>
	  <div id="cancel-validate-collection" class="ui-state-default ui-corner-all cancel-validate-button">' . lang::get('LANG_Cancel') . '</div>
	</div>';
        }
        $r .= '<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')) . '
    		<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" style="display: none">
	<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>';
        if (user_access('IForm n' . $node->nid . ' delete insect')) {
            $r .= '<div id="fo-delete-insect" class="ui-accordion-content ui-helper-reset ui-widget-content ui-accordion-content-active">
		<form id="fo-delete-insect-form" action="' . iform_ajaxproxy_url($node, 'occurrence') . '" method="POST">
		<input type="hidden" name="website_id" value="' . $args['website_id'] . '" />
		<input type="hidden" name="survey_id" value="' . $args['survey_id'] . '" />
		<input type="hidden" name="occurrence:id" value="" />
		<input type="hidden" name="occurrence:deleted" value="t" />
		<input type="submit" id="fo_delete_insect_submit_button" class="ui-state-default ui-corner-all preferred-button" value="' . lang::get('LANG_Submit_delete-insect') . '" />
		</form>
	</div>';
        }
        $r .= '	
	<div id="fo-picture" class="ui-accordion-content ui-helper-reset ui-widget-content ui-corner-bottom ui-accordion-content-active">
	  <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-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-id-history" class="ui-accordion-content ui-helper-reset ui-widget-content ui-corner-bottom ui-accordion-content-active"></div>
    ';
        $new_flower_ctrl_args = $focus_flower_ctrl_args;
        unset($new_flower_ctrl_args['label']);
        $new_flower_ctrl_args['fieldname'] = 'flowerSelect';
        if (isset($args['deleteable_user_id']) && $args['deleteable_user_id'] != '' && $args['deleteable_user_id'] == $user->uid) {
            // need two as they use different species lists.
            $edit_flower_ctrl_args = $focus_flower_ctrl_args;
            $edit_flower_ctrl_args['class'] = 'species-select';
            $edit_flower_ctrl_args['blankText'] = '';
            $edit_flower_ctrl_args['label'] = 'Main Species';
            $edit_flower_ctrl_args['id'] = 'dummy_tag';
            unset($edit_flower_ctrl_args['extraParams']['allow_data_entry']);
            $edit_insect_ctrl_args = $focus_insect_ctrl_args;
            $edit_insect_ctrl_args['class'] = 'species-select';
            $edit_insect_ctrl_args['blankText'] = '';
            $edit_insect_ctrl_args['label'] = 'Main Species';
            $edit_insect_ctrl_args['id'] = 'dummy_tag';
            unset($edit_insect_ctrl_args['extraParams']['allow_data_entry']);
            $r .= '	<div id="fo-edit-insect-id" class="ui-accordion-content ui-helper-reset ui-widget-content ui-corner-all">
	  <p class="title">Modify Existing Insect Determination</p>
	  <form id="fo-edit-insect-id-form" action="' . iform_ajaxproxy_url($node, 'determination') . '" method="POST">
		<input type="hidden" name="website_id" value="' . $args['website_id'] . '" />
		<label class="follow-on">Determination ID : </label><input type="text" name="determination:id" value="" readonly="readonly" /><br />
		<label class="follow-on">Deleted : </label><input type="checkbox" name="determination:deleted" value="t" /><br />
		<label class="follow-on">Occurrence ID : </label><input type="text" name="determination:occurrence_id" value="" readonly="readonly" /><br />
		<label class="follow-on">CMS User Ref ID : </label><input type="text" name="determination:cms_ref" value="" readonly="readonly" /><br />
		<label class="follow-on">CMS Person Name : </label><input type="text" name="determination:person_name" value="" readonly="readonly" /><br />
		<label class="follow-on">CMS Email : </label><input type="text" name="determination:email_address" value="" readonly="readonly" /><br />
		<label class="follow-on">Type : </label><select name="determination:determination_type" /><option value="A">A : Initial</option><option value="B" selected>B : Doubted</option><option value="C" selected>C : Validated</option><option value="X">X : Unknown</option></select><br />
		<label class="follow-on">Taxon Details : </label><input type="text" name="determination:taxon_details" value="" /><br />
		<label class="follow-on">Extra Info : </label><input type="text" name="determination:taxon_extra_info" value="" /><br />
		' . data_entry_helper::select($edit_insect_ctrl_args) . '
		<label>Taxon Array : </label><table id="fo-edit-insect-id-list"><thead><tr><th>Species</th><th>ID</th><th>Remove</th></tr></thead><tbody id="fo-edit-insect-id-list-body" class="fo-edit-id-list-body"><tr id="insectAutocompleteRow1" class="autocompleteRow"><td>' . lang::get('LANG_Add') . ' <input name="insectAutocomplete1" id="insectAutocomplete1" /></td><td></td><td></td></tr></tbody></table>
		<label >Comment : </label><textarea name="determination:comment" class="taxon-comment" rows="3" ></textarea><br />
		<input type="submit" class="ui-state-default ui-corner-all submit-button" value="' . lang::get('LANG_Validate') . '" />
	  </form>
	</div>
	<div id="fo-edit-flower-id" class="ui-accordion-content ui-helper-reset ui-widget-content ui-corner-all">
	  <p class="title">Modify Existing Flower Determination</p>
	  <form id="fo-edit-flower-id-form" action="' . iform_ajaxproxy_url($node, 'determination') . '" method="POST">
		<input type="hidden" name="website_id" value="' . $args['website_id'] . '" />
		<label class="follow-on">Determination ID : </label><input type="text" name="determination:id" value="" readonly="readonly" /><br />
		<label class="follow-on">Deleted : </label><input type="checkbox" name="determination:deleted" value="t" /><br />
		<label class="follow-on">Occurrence ID : </label><input type="text" name="determination:occurrence_id" value="" readonly="readonly" /><br />
		<label class="follow-on">CMS User Ref ID : </label><input type="text" name="determination:cms_ref" value="" readonly="readonly" /><br />
		<label class="follow-on">CMS Person Name : </label><input type="text" name="determination:person_name" value="" readonly="readonly" /><br />
		<label class="follow-on">CMS Email : </label><input type="text" name="determination:email_address" value="" readonly="readonly" /><br />
		<label class="follow-on">Type : </label><select name="determination:determination_type" /><option value="A">A : Initial</option><option value="B" selected>B : Doubted</option><option value="C" selected>C : Validated</option><option value="X">X : Unknown</option></select><br />
		<label class="follow-on">Taxon Details : </label><input type="text" name="determination:taxon_details" value="" /><br />
		<label class="follow-on">Extra Info : </label><input type="text" name="determination:taxon_extra_info" value="" /><br />
		' . data_entry_helper::select($edit_flower_ctrl_args) . '
		<label>Taxon Array : </label><table id="fo-edit-flower-id-list"><thead><tr><th>Species</th><th>ID</th><th>Remove</th></tr></thead><tbody id="fo-edit-flower-id-list-body" class="fo-edit-id-list-body"><tr id="flowerAutocompleteRow1" class="autocompleteRow"><td>Add <input name="flowerAutocomplete1" id="flowerAutocomplete1" /></td><td></td><td></td></tr></tbody></table>
		<label >Comment : </label><textarea name="determination:comment" class="taxon-comment" rows="3" ></textarea><br />
		<input type="submit" class="ui-state-default ui-corner-all submit-button" value="' . lang::get('LANG_Validate') . '" />
	  </form>
	</div>';
        }
        $r .= '	<form id="fo-new-insect-id-form" action="' . iform_ajaxproxy_url($node, 'determination') . '" method="POST" style="display: none;">
      <div id="fo-new-insect-id" class="ui-accordion-content ui-helper-reset ui-widget-content ui-corner-top ui-accordion-content-active">
        <p class="title">' . lang::get('LANG_New_ID') . '</p>  
		<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 .= '		<label for="fo-insect-expert-det-type" class="follow-on">' . lang::get('Status') . ' : </label><select id="fo-insect-expert-det-type" 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" class="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">' . lang::get('LANG_ID_Comment') . ' </label>
          <textarea id="insect:comment" name="determination:comment" class="taxon-comment" rows="3" ></textarea>
        </div>
	  </div>
      <div id="fo-new-insect-id-buttons" class="ui-accordion-content ui-helper-reset ui-widget-content ui-corner-bottom ui-accordion-content-active">
        <input type="submit" id="insect_id_submit_button" class="ui-state-default ui-corner-all submit-button" value="' . lang::get('LANG_Validate') . '" />
      </div>
    </form>
    <form id="fo-new-flower-id-form" action="' . iform_ajaxproxy_url($node, 'determination') . '" method="POST" style="display: none;">
	  <div id="fo-new-flower-id" class="ui-accordion-content ui-helper-reset ui-widget-content ui-corner-top ui-accordion-content-active">
		<p class="title">' . lang::get('LANG_New_ID') . '</p>
		<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 . '" />
		<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" /> 
		' . (user_access('IForm n' . $node->nid . ' flower expert') ? '<p>' . lang::get('Status') . ' : <span id="fo-flower-expert-det-type" ></span></p>' : '') . '
		<input type="hidden" name="determination:determination_type" value="' . (user_access('IForm n' . $node->nid . ' flower expert') ? "C" : "A") . '" />
        <label class="follow-on">' . lang::get('LANG_Known_Species') . ' : </label><input name="flowerAutocomplete2" id="flowerAutocomplete2" />' . data_entry_helper::select($new_flower_ctrl_args) . '
		<div class="id-tool-group">
          <input type="hidden" name="determination:taxon_details" />
          <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_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">' . lang::get('LANG_ID_Comment') . ' </label>
          <textarea id="flower:comment" name="determination:comment" class="taxon-comment" rows="3" ></textarea>
        </div>
	  </div>
      <div id="fo-new-flower-id-buttons" class="ui-accordion-content ui-helper-reset ui-widget-content ui-corner-bottom ui-accordion-content-active">
        <input type="submit" id="flower_id_submit_button" class="ui-state-default ui-corner-all submit-button" value="' . lang::get('LANG_Validate') . '" />
      </div>
	</form>
	<form id="fo-express-doubt-form" action="' . iform_ajaxproxy_url($node, 'determination') . '" method="POST" style="display: none;">
	  <div id="fo-express-doubt" class="ui-accordion-content ui-helper-reset ui-widget-content ui-corner-top ui-accordion-content-active">
	    <p class="title">' . lang::get('LANG_Doubt') . '</p>
		<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">' . lang::get('LANG_Doubt_Comment') . ' </label>
          <textarea id="determination:comment" name="determination:comment" class="taxon-comment" rows="3" ></textarea>
        </div>
      </div>
      <div id="fo-express-doubt-buttons" class="ui-accordion-content ui-helper-reset ui-widget-content ui-corner-bottom ui-accordion-content-active">
        <input type="submit" id="doubt_submit_button" class="ui-state-default ui-corner-all submit-button" value="' . lang::get('LANG_Validate') . '" />
      </div>
    </form>
	<div id="fo-localisation-info" class="ui-accordion-content ui-helper-reset ui-widget-content ui-corner-top ui-accordion-content-active">
	    <span class="addn-info-title">' . lang::get('LANG_INSEE_Localisation') . '</span>
	    <p>' . lang::get('LANG_Locality_Commune') . ' : <span id="fo-locality-commune"></span></p>
	    <p>' . lang::get('LANG_Locality_Department') . ' : <span id="fo-locality-department"></span></p>
	    <p>' . lang::get('LANG_Locality_Region') . ' : <span id="fo-locality-region"></span></p>
    </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[$skyAttrID]['caption'] . ': <span id="fo-insect-sky"></span></p>
	    <p>' . $sample_attributes[$temperatureAttrID]['caption'] . ': <span id="fo-insect-temp"></span></p>
	    <p>' . $sample_attributes[$windAttrID]['caption'] . ': <span id="fo-insect-wind"></span></p>
	    <p>' . $sample_attributes[$shadeAttrID]['caption'] . ': <span id="fo-insect-shade"></span></p>
	    <p>' . $occurrence_attributes[$foragingAttrID]['caption'] . ': <span id="fo-insect-foraging"></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">
	    <span class="addn-info-title">' . lang::get('LANG_Additional_Info_Title') . '</span>
	    <p>' . $occurrence_attributes[$flowerTypeAttrID]['caption'] . ': <span id="focus-flower-type"></span></p>
	    <p>' . $location_attributes[$habitatAttrID]['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\tif(jQuery('#refresh-message').is(':hidden')){\n\t\tvar errorString = \"" . lang::get('LANG_Indicia_Warehouse_Error') . "\";\n\t\tif(data.error){\terrorString = errorString + ' : ' + data.error;\t}\n\t\tif(data.errors){\n\t\t\tfor (var i in data.errors){\n\t\t\t\terrorString = errorString + ' : ' + data.errors[i];\n\t\t\t}\n\t\t}\n\t\t// the most likely cause is authentication failure - eg the read authentication has timed out.\n\t\t// prevent further use of the form:\n\t\tjQuery('#filter,#focus-occurrence,#focus-collection').hide();\n\t\tjQuery('#refresh-message').show();\n\t\talert(errorString);\n\t}\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\\:" . $flowerTypeAttrID . "]').filter('[value=" . $args['flower_type_dont_know'] . "]').parent().remove();\njQuery('[name=location\\:geom]').attr('name', 'location:centroid_geom');\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('#name-filter-header').click(function(evt){\n    if(\$(evt.originalTarget).hasClass('reset-button')){\n        return;\n    }\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('#date-filter-header').click(function(evt){\n    if(\$(evt.originalTarget).hasClass('reset-button')){\n        return;\n    }\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('#flower-filter-body').find('select').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('#flower-filter-header').click(function(evt){\n    if(\$(evt.originalTarget).hasClass('reset-button')){\n        return;\n    }\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('#insect-filter-body').find('select').val('');\n\tjQuery('[name=insect\\:taxon_extra_info]').val(\"" . lang::get('LANG_More_Precise') . "\");\n\tjQuery('#insect-filter-body').find(':checkbox').removeAttr('checked');\n});\njQuery('#insect-filter-header').click(function(evt){\n    if(\$(evt.originalTarget).hasClass('reset-button')){\n        return;\n    }\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});\njQuery('#conditions-filter-header').click(function(evt){\n    if(\$(evt.originalTarget).hasClass('reset-button')){\n        return;\n    }\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(); //georef Layer\n\tif(inseeLayer != null) inseeLayer.destroyFeatures();\n\tinseeLayerStore.destroyFeatures();\n\tjQuery('[name=place\\:INSEE]').val('');\n\tjQuery('#imp-insee-div').hide();\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('#location-filter-header').click(function(evt){\n    if(\$(evt.originalTarget).hasClass('reset-button')){\n        return;\n    }\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,#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\tif(jQuery('#fo-express-doubt-form').filter(':visible').length>0) {\n\t  jQuery('#fo-express-doubt-form').hide();\n\t  if(!jQuery('#fo-id-history').hasClass('empty')){\n\t\tjQuery('#fo-id-history').addClass('ui-accordion-content-active');\n\t\tjQuery('#fo-id-buttons').removeClass('ui-corner-bottom');\n\t  }\n\t} else {\n\t  jQuery('#fo-new-insect-id-form,#fo-new-flower-id-form').hide();\n\t  jQuery('#fo-express-doubt-form [name=determination\\:comment]').val(\"" . lang::get('LANG_Default_Doubt_Comment') . "\");\n\t  jQuery('#fo-express-doubt-form').show();\n\t  if(!jQuery('#fo-id-history').hasClass('empty')){\n\t\tjQuery('#fo-id-history').removeClass('ui-accordion-content-active');\n\t\tjQuery('#fo-id-buttons').addClass('ui-corner-bottom');\n\t  }\n\t}\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    jQuery('#poll-banner').empty();\n    jQuery('#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});\nbulkValidating=false;";
        if (user_access('IForm n' . $node->nid . ' insect expert')) {
            data_entry_helper::$javascript .= "\nbulkCancel=false;\nbulkType='';\njQuery('#validate-taxon-progress').progressbar({value: 0});\njQuery('#validate-page-progress').progressbar({value: 0});\njQuery('#validate-collection-progress').progressbar({value: 0});\njQuery('form#bulk-validation-form').ajaxForm({\n\tdataType:  'json', \n\tbeforeSubmit:   function(data, obj, options){\n\t\tvar list_string = jQuery('#bulk-validation-form').data('taxa_taxon_list_id_list_string');\n\t\tif(list_string == null) list_string='';\n\t\tvar resultsIDs = list_string.substring(1, list_string.length - 1).split(',');\n\t\tif(resultsIDs[0] != '') {\n\t\t\tfor(var i = 0; i<resultsIDs.length; i++)\n\t\t\t\tdata.push({name: 'determination\\:taxa_taxon_list_id_list[]', value: resultsIDs[i]});\n\t\t} else\n\t\t\tdata.push({name: 'determination\\:taxa_taxon_list_id_list[]', value: ''});\n\t\tif(bulkCancel){\n\t\t\tbulkValidateFinish(\"" . lang::get('LANG_Bulk_Validation_Canceled') . "\");\n\t\t\treturn false;\n\t\t}\t\n\t\treturn true;\n\t},\n\tsuccess:   function(data){\n\t\tif(data.error == undefined){\n\t\t\tvar form = jQuery('form#bulk-validation-form');\n\t\t\tjQuery('.filter-insect-container').filter('[occID='+form.find('[name=determination\\:occurrence_id]').val()+']').find('.occurrence-dubious,.insect-ok').removeClass('occurrence-dubious insect-ok').addClass('occurrence-valid');\n\t\t\tjQuery('.collection-insect-container').filter('[occID='+form.find('[name=determination\\:occurrence_id]').val()+']').find('.occurrence-dubious,.insect-ok').removeClass('occurrence-dubious insect-ok').addClass('occurrence-valid');\n\t\t\tjQuery('.collection-flower-determination').filter('[occID='+form.find('[name=determination\\:occurrence_id]').val()+']').find('.flower-dubious,.flower-ok').remove();\n\t\t\tjQuery('.collection-flower-determination').filter('[occID='+form.find('[name=determination\\:occurrence_id]').val()+']').find('p').append('<span class=\"flower-valid\"><img src=\"/misc/watchdog-ok.png\" style=\"vertical-align: middle;\"></span>').find('.flower-dubious').remove();\n\t\t\tuploadValidation();\n\t\t} else {\n\t\t\talert(data.error);\n\t\t\tbulkValidateFinish(\"" . lang::get('LANG_Bulk_Validation_Error') . "\");\n  \t\t}\n\t} \n});\nuploadValidation = function(){\n\tvar occID = false;\n\tvar max = jQuery('#validate-'+bulkType.toLowerCase()+'-progress').data('max');\n\tswitch(bulkType){\n\t  case 'Taxon':\n\t\tvar index = jQuery('#validate-taxon-progress').data('index');\n\t\tjQuery('#validate-taxon-progress').data('index',index+1);\n\t\tjQuery('#validate-taxon-progress').progressbar('option','value',index*100/max);\n\t\tif(index<max){\n\t\t\tif(jQuery('#results-collections-results').filter(':visible').length > 0)\n\t\t\t\toccID=searchResults.features[index].attributes.flower_id;\n\t\t\telse \n\t\t\t\toccID=searchResults.features[index].attributes.insect_id;\n\t\t\tjQuery('#validate-taxon-message').html('<span>'+index+'/'+max+' : '+Math.round(index*100/max)+'%</span>');\n\t\t}\n\t\tbreak;\n\t  case 'Page':\n\t\tvar todolist;\n\t\tif(jQuery('#results-collections-results').filter(':visible').length > 0)\n\t\t\ttodolist =jQuery('.collection-flower-determination').find('.flower-dubious,.flower-ok').parent();\n\t\telse\n\t\t\ttodolist =jQuery('.filter-insect-container').find('.occurrence-dubious,.insect-ok').parent();\n\t\tvar completed = max - todolist.length;\n\t\tjQuery('#validate-page-progress').progressbar('option','value',completed*100/max);\n\t\tif(todolist.length>0){\n\t\t\toccID=jQuery(todolist[0]).parent().attr('occID');\n\t\t\tjQuery('#validate-page-message').html('<span>'+completed+'/'+max+' : '+Math.round(completed*100/max)+'%</span>');\n\t\t}\n\t\tbreak;\n\t  case 'Collection': // insects only\n\t\tvar todolist = jQuery('.collection-insect-container').find('.occurrence-dubious,.insect-ok').parent().parent();\n\t\tvar completed = max - todolist.length;\n\t\tjQuery('#validate-collection-progress').progressbar('option','value',completed*100/max);\n\t\tif(todolist.length>0){\n\t\t\toccID=jQuery(todolist[0]).attr('occID');\n\t\t\tjQuery('#validate-collection-message').html('<span>'+completed+'/'+max+' : '+Math.round(completed*100/max)+'%</span>');\n\t\t}\n\t\tbreak;\n\t}\n\tif(occID && !bulkCancel){\n\t\tajaxStack.push(\$.getJSON(\"" . $svcUrl . "/data/determination\" + \n\t\t\t\t\"?mode=json&view=list&nonce=" . $readAuth['nonce'] . "&auth_token=" . $readAuth['auth_token'] . "\" + \n\t\t\t\t\"&occurrence_id=\" + occID + \"&deleted=f&orderby=id&sortdir=DESC&REMOVEABLEJSONP&callback=?\", function(detData) {\n\t\t\tif(!(detData instanceof Array)){\n   \t\t\t\talertIndiciaError(detData);\n   \t\t\t// taxon based is more complex than page as we do not have the determination stored - check last is 'doubted' or 'original', at this point a taxon has been specified so no 'X'\n   \t\t\t} else if (detData.length>0) {\n\t\t\t\tif(bulkType!='Taxon' || detData[0].determination_type == 'A' || detData[0].determination_type == 'B'){\n\t\t\t\t\t// all reidentified taxon will have either a unidentified or Valid flag, so will not appear in this list, so doesn't matter if the taxon has changed.\n\t\t\t\t\tvar form = jQuery('form#bulk-validation-form');\n\t\t\t\t\tform.find('[name=determination\\:occurrence_id]').val(detData[0].occurrence_id);\n\t\t\t\t\tform.find('[name=determination\\:taxa_taxon_list_id]').val(detData[0].taxa_taxon_list_id);\n\t\t\t\t\tform.data('taxa_taxon_list_id_list_string',detData[0].taxa_taxon_list_id_list);\n\t\t\t\t\tform.find('[name=determination\\:taxon_details]').val(detData[0].taxon_details);\n\t\t\t\t\tform.find('[name=determination\\:taxon_extra_info]').val(detData[0].taxon_extra_info == null ? '' : detData[0].taxon_extra_info);\n\t\t\t\t\tjQuery('form#bulk-validation-form').submit();\n\t\t\t\t} else {\n\t\t\t\t\tuploadValidation();\n\t\t\t\t}\n\t\t\t}}));\n\t} else {\n\t\tbulkValidateFinish(bulkCancel ? \"" . lang::get('LANG_Bulk_Validation_Canceled') . "\" : \"" . lang::get('LANG_Bulk_Page_Validation_Completed') . "\");\n\t}\n}\nbulkValidatePrep=function(type, max){\n\tbulkValidating=true; //switches off afficher insect.\n\tbulkCancel=false;\n\tbulkType=type;\n\tjQuery('#validate-'+bulkType.toLowerCase()+'-button').addClass('loading-button');\n\tjQuery('#validate-'+bulkType.toLowerCase()+'-progress,#cancel-validate-'+bulkType.toLowerCase()).show();\n\tjQuery('#validate-page-message,#validate-taxon-message,#validate-collection-message').empty();\n\tjQuery('#imp-georef-search-btn,#search-insee-button,#search-insects-button,#search-collections-button,#validate-page-button,#validate-taxon-button,#validate-collection-button').attr('disabled','disabled');\n\tjQuery('#validate-'+bulkType.toLowerCase()+'-message').html('<span>0/'+max+' : 0%</span>');\n\tjQuery('#validate-'+bulkType.toLowerCase()+'-progress').data('max',max).data('index',0).progressbar('option','value',0);\n}\nbulkValidateFinish=function(message){\n\tbulkCancel=false;\n\tbulkValidating=false; //switches on afficher insect.\n\tjQuery('#validate-page-button,#validate-taxon-button,#validate-collection-button').removeClass('loading-button');\n\tjQuery('#validate-page-progress,#cancel-validate-page,#validate-taxon-progress,#cancel-validate-taxon,#validate-collection-progress,#cancel-validate-collection').hide();\n\tjQuery('#validate-page-message,#validate-taxon-message,#validate-collection-message').empty();\n\tif(message) jQuery('#validate-'+bulkType.toLowerCase()+'-message').html('<span>'+message+'</span>');\n\tjQuery('#imp-georef-search-btn,#search-insee-button,#search-insects-button,#search-collections-button,#validate-page-button,#validate-taxon-button,#validate-collection-button').removeAttr('disabled');\n}\njQuery('.cancel-validate-button').click(function(){bulkCancel=true;});\njQuery('#validate-page-button').click(function(){\n\t// first of all we only validate insect-ok and occurrence-dubious.\n\tvar max;\n\tif(jQuery('#results-collections-results').filter(':visible').length > 0)\n\t\tmax =jQuery('.collection-flower-determination').find('.flower-dubious,.flower-ok').length;\n\telse\n\t\tmax =jQuery('.filter-insect-container').find('.occurrence-dubious,.insect-ok').length;\n\tbulkValidatePrep('Page', max);\n\tif(max==0){\n\t\tbulkValidateFinish(\"" . lang::get('LANG_Bulk_Page_Nothing_To_Do') . "\");\n\t} else if(!confirm(\"" . lang::get('LANG_Confirm_Bulk_Page_Validation') . "\")){\n\t\tbulkValidateFinish(false);\n\t\treturn;\n\t} else {\n\t\tuploadValidation();\n\t}\n});\njQuery('#validate-taxon-button').click(function(){\n\t// first of all we only validate insect-ok and occurrence-dubious.\n\tvar max=0;\n\tif(searchResults!= null) max=searchResults.features.length;\n\tbulkValidatePrep('Taxon', max);\n\tif(max==0){\n\t\tbulkValidateFinish(\"" . lang::get('LANG_Bulk_Taxon_Nothing_To_Do') . "\");\n\t} else if(!confirm(\"" . lang::get('LANG_Confirm_Bulk_Taxon_Validation') . "\")){\n\t\tbulkValidateFinish(false);\n\t\treturn;\n\t} else {\n\t\tuploadValidation();\n\t}\n});\njQuery('#validate-collection-button').click(function(){\n\t// first of all we only validate insect-ok and occurrence-dubious.\n\tvar max=jQuery('.collection-insect-container').find('.occurrence-dubious,.insect-ok').length;\n\tbulkValidatePrep('Collection', max);\n\tif(max==0){\n\t\tbulkValidateFinish(\"" . lang::get('LANG_Bulk_Collection_Nothing_To_Do') . "\");\n\t} else if(!confirm(\"" . lang::get('LANG_Confirm_Bulk_Collection_Validation') . "\")){\n\t\tbulkValidateFinish(false);\n\t\treturn;\n\t} else {\n\t\tuploadValidation();\n\t}\n});\n";
        }
        data_entry_helper::$javascript .= "\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    jQuery('[name=sample\\:id]').val(id);\n    jQuery('#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\tjQuery('#fc-new-comment').removeClass('ui-accordion-content-active');\n\tjQuery('#fc-new-location,#fc-new-location-desc')." . (user_access('IForm n' . $node->nid . ' edit geolocation') ? "show()" : "hide()") . ";\n\tjQuery('#focus-occurrence,#filter,#fc-next-button,#fc-prev-button').hide();\n\tjQuery('#flower-image,#environment-image').empty().addClass('loading');\n\tjQuery('#collection-insects,#collection-date,#collection-flower-name,#collection-flower-type,#collection-habitat,#collection-user-name').empty();\n\tjQuery('#focus-collection').show();\n\tjQuery('#flower-image,#environment-image').height(jQuery('#flower-image').width()/(" . $args['Flower_Image_Ratio'] . "));\n    jQuery('#fc-front-page-message,#fc-new-location-message').empty();\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    \t" . $map2JS . "\n\t\tjQuery('#map2')[0].map.editLayer.events.register('featuresadded', {}, function(a1){\n\t\t\tjQuery('#fc-new-location-message').empty();\n\t\t\tvar parser = new OpenLayers.Format.WKT();\n\t\t\tvar feature = parser.read(jQuery('#imp-geom').val());\n\t\t\tvar filter = new OpenLayers.Filter.Spatial({\n  \t\t\t\ttype: OpenLayers.Filter.Spatial.CONTAINS ,\n    \t\t\tproperty: 'the_geom',\n    \t\t\tvalue: feature.geometry\n\t\t\t});\n\t\t\tvar locality = jQuery('#collection-locality');\n\t\t\tvar scope = {target: locality};\n\t\t\tinseeProtocol.read({filter: filter, callback: fillLocationDetails, scope: scope});\n\t\t});\n \t};\n\tjQuery('#map2')[0].map.editLayer.clickControl." . (user_access('IForm n' . $node->nid . ' edit geolocation') ? "" : "de") . "activate();\n\tjQuery('#map2')[0].map.editLayer.destroyFeatures();\n//\tjQuery('#map2').width('auto');\n\tjQuery('#flower-image').data('occID', 'none').data('collectionIndex', index);\n\tloadComments(id, '#fc-comment-list', 'sample_comment', 'sample_id', 'sample-comment-block', 'sample-comment-body', true, " . (user_access('IForm n' . $node->nid . ' delete collection comment') ? "true" : "false") . ");\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&sortdir=DESC&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 string = '';\n\t\t\t\t\tif(detData[0].taxon != '' && detData[0].taxon != null){\n\t\t\t\t\t\tstring = htmlspecialchars(detData[0].taxon);\n\t\t  \t\t\t}\n\t\t\t\t\tif(detData[0].taxa_taxon_list_id_list != '' && detData[0].taxa_taxon_list_id_list != null){\n\t\t\t  \t\t\tvar resultsIDs = detData[0].taxa_taxon_list_id_list.substring(1, detData[0].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 + ', ') + htmlspecialchars(flowerTaxa[k].taxon);\n\t\t\t\t\t\t\t\t\t\tbreak;\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[0].taxon_extra_info != '' && detData[0].taxon_extra_info != null && detData[0].taxon_extra_info != 'null'){\n\t\t\t\t\t\tstring = (string == '' ? '' : string + ' ') + '('+htmlspecialchars(detData[0].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\">'+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 + \"&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 " . $flowerTypeAttrID . ":\n\t\t\t\t\t\t\t\t\tjQuery('<span>'+convertTerm(attrdata[i].raw_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}));";
        if (user_access('IForm n' . $node->nid . ' add to front page')) {
            data_entry_helper::$javascript .= "\n\tjQuery('#fc-front-page-form').find('[name^=smpAttr\\:" . $frontPageAttrID . "]')\n\t\t.attr('name', 'smpAttr:" . $frontPageAttrID . "')\n\t\t.filter('[value=0]')\n\t\t.attr('checked', 'checked');";
        }
        data_entry_helper::$javascript .= "\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 " . $usernameAttrID . ":\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 " . $uidAttrID . ":\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\tif(attrdata[i].value == " . $user->uid . ") { // user can edit geolocation of own collections.\n\t\t\t\t\t\t\t\tjQuery('#fc-new-location,#fc-new-location-desc').show();\n\t\t\t\t\t\t\t\tjQuery('#map2')[0].map.editLayer.clickControl.activate();\n\t\t\t\t\t\t\t}\n\t\t\t       \t\t    break;";
        if (user_access('IForm n' . $node->nid . ' add to front page')) {
            data_entry_helper::$javascript .= "\n\t\t\t\t\t\tcase " . $frontPageAttrID . ":\n\t\t\t\t\t\t\tjQuery('#fc-front-page-form').find('[name^=smpAttr\\:" . $frontPageAttrID . "]')\n\t\t\t\t\t\t\t\t.attr('name', 'smpAttr:" . $frontPageAttrID . ":'+attrdata[i].id)\n\t\t\t\t\t\t\t\t.filter('[value='+attrdata[i].raw_value+']')\n\t\t\t\t\t\t\t\t.attr('checked', 'checked');\n\t\t\t\t\t\t\tbreak;";
        }
        $base = base_path();
        if (substr($base, -1) != '/') {
            $base .= '/';
        }
        data_entry_helper::$javascript .= "\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].parent_id != null) {\n   \t\t\t\talertIndiciaError({error: \"" . lang::get('LANG_Bad_Collection_ID') . "\"});\n   \t\t\t\treturn;\n   \t\t\t}\n   \t\t\tjQuery('[name=sample\\:date_start]').val(collectionData[0].date_start);\n   \t\t\tjQuery('[name=sample\\:date_end]').val(collectionData[0].date_end);\n   \t\t\tjQuery('[name=sample\\:date_type]').val(collectionData[0].date_type);\n   \t\t\tjQuery('[name=sample\\:location_id]').val(collectionData[0].location_id);\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    jQuery('#location-id').val(locationData[0].id);\n\t    \t\t\tjQuery('[name=location\\:name]').val(locationData[0].name);\n\t\t\t\t    jQuery('#imp-sref').val(locationData[0].centroid_sref);\n\t\t\t\t\tjQuery('#imp-geom').val(locationData[0].centroid_geom);\n\t\t\t\t\tvar parts=locationData[0].centroid_sref.split(' ');\n\t\t\t\t\tvar refx = parts[0].split(',');\n\t\t\t\t\tjQuery('#imp-sref-lat').val(refx[0]);\n\t\t\t\t\tjQuery('#imp-sref-long').val(parts[1]).change(); // adds location, auto \n\t\t\t\t    loadImage('location_image', 'location_id', locationData[0].id, '#environment-image', " . $args['Environment_Image_Ratio'] . ", function(imageRecord){collection_preferred_object.environment_image_path = imageRecord.path}, 'med-', true);\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 + \"&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\tvar habitat_string = '';\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 " . $habitatAttrID . ":\n\t\t\t\t\t\t\t\t\tif (attrdata[i].raw_value > 0) habitat_string = (habitat_string == '' ? convertTerm(attrdata[i].raw_value) : (habitat_string + ' / ' + convertTerm(attrdata[i].raw_value)));\n\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t}}}\n\t\t\t\t\tjQuery('<span>'+habitat_string+'</span>').appendTo('#collection-habitat');\n  \t\t\t}}));\n\t\t}\n\t}));\n\t// we want to tag end of row picture, 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(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   var n=0;\n\t\t\t\t\t   // there seems to be an upper limit on how many can be done at one time - so restrict to 20 at a time\n\t\t\t\t \t   while(n<insectData.length){\n   \t\t\t\t\t\tvar insectIDs=[];\n\t\t\t\t\t\tfor (var j=0;j<20 && n<insectData.length; j++,n++){\n\t\t\t\t\t\t\tinsectIDs.push(insectData[n].id);\n\t\t\t\t\t\t\tvar insect=jQuery('<div class=\"collection-insect-container\" />').attr('occID', insectData[n].id).appendTo('#collection-insects');\n\t\t\t\t\t\t\tif(n/" . $args['insectsPerRow'] . " == parseInt(n/" . $args['insectsPerRow'] . ")) insect.addClass('start-of-row');\n\t\t\t\t\t\t\tif((n+1)/" . $args['insectsPerRow'] . " == parseInt((n+1)/" . $args['insectsPerRow'] . ")) insect.addClass('end-of-row');\n\t\t\t\t\t\t\tinsect = jQuery('<div class=\"ui-widget-content ui-corner-all collection-insect\" />').appendTo(insect);\n\t\t\t\t\t\t\tjQuery('<p class=\"insect-tag determination-flag centre-flag occurrence-unknown\" />').appendTo(insect);\n\t\t\t\t\t\t\tvar image = jQuery('<div class=\"insect-image empty loading\" />').appendTo(insect).data('occID',insectData[n].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\timage.height(image.width()/(" . $args['Insect_Image_Ratio'] . "));\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[n].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}\n\t\t\t\t\t\tajaxStack.push(\$.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\"&REMOVEABLEJSONP&callback=?&query=\"+escape(escape(JSON.stringify({'in': {'occurrence_id': insectIDs}}))), \n\t\t\t\t\t\t\tfunction(imageData) {\n\t\t\t\t\t\t\t\tif(!(imageData instanceof Array)){\n\t\t\t\t\t\t\t\t\talertIndiciaError(imageData);\n\t\t\t\t\t\t\t\t} else if (imageData.length>0) {\n\t\t\t\t\t\t\t\t\tfor (var k=0;k<imageData.length;k++){\n\t\t\t\t\t\t\t\t\t\tvar target = jQuery('.collection-insect-container').filter('[occID='+imageData[k].occurrence_id+']').find('.insect-image');\n\t\t\t\t\t\t\t\t\t\ttarget.empty().removeClass('empty');\n\t\t\t\t\t\t\t\t\t\tinsertImage('med-', imageData[k].path, target, " . $args['Insect_Image_Ratio'] . ", false, false);\n\t\t\t\t\t\t\t\t\t\tcollection_preferred_object.insects.push({insect_id: imageData[k].occurrence_id, insect_image_path: imageData[k].path})\n\t\t\t\t\t\t\t\t\t}}}));\n\t\t\t\t\t\tajaxStack.push(\$.getJSON(\"" . $svcUrl . "/data/determination\" + \n\t\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\t\"&deleted=f&orderby=id&sortdir=DESC&REMOVEABLEJSONP&callback=?&query=\"+escape(escape(JSON.stringify({'in': {'occurrence_id': insectIDs}}))),\n\t\t\t\t\t\t\t\tfunction(detData) {\n\t\t\t\t\t\t\t\t\tif(!(detData instanceof Array)){\n\t\t\t\t\t\t\t\t\t\talertIndiciaError(detData);\n\t\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\t\tif (detData.length>0) {\n\t\t\t\t\t\t\t\t\t\t\tfor (var k=0;k<detData.length;k++){\n\t\t\t\t\t\t\t\t\t\t\t\tvar insect = jQuery('.collection-insect-container').filter('[occID='+detData[k].occurrence_id+']');\n\t\t\t\t\t\t\t\t\t\t\t\tvar det = insect.find('.insect-determination').filter('.empty');\n\t\t\t\t\t\t\t\t\t\t\t\tif(det.length>0){\n\t\t\t\t\t\t\t\t\t\t\t\t\tvar string = '';\n\t\t\t\t\t\t\t\t\t\t\t\t\tif(detData[k].taxon != '' && detData[k].taxon != null){\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tstring = htmlspecialchars(detData[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\tif(detData[k].taxa_taxon_list_id_list != '' && detData[k].taxa_taxon_list_id_list != null){\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tvar resultsIDs = detData[k].taxa_taxon_list_id_list.substring(1, detData[k].taxa_taxon_list_id_list.length - 1).split(',');\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tif(resultsIDs[0] != '') {\n\t\t\t\t\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\t\t\t\t\tfor(var m = 0; m< insectTaxa.length; m++){\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tif(insectTaxa[m].id == resultsIDs[j]){\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tstring = (string == '' ? '' : string + ', ') + htmlspecialchars(insectTaxa[m].taxon);\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\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\t// we use the short determination data here - no extra info\n\t\t\t\t\t\t\t\t\t\t\t\t\tdet.empty().removeClass('empty');\n\t\t\t\t\t\t\t\t\t\t\t\t\tif(string != '')\n\t\t\t\t\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\t\t\t\t\tvar tag = insect.find('.insect-tag').removeClass('occurrence-unknown');\n\t\t\t\t\t\t\t\t\t\t\t\t\tif(detData[k].determination_type == 'B' || detData[k].determination_type == 'I' || detData[k].determination_type == 'U'){\n\t\t\t\t\t\t\t\t\t\t\t\t\t\ttag.addClass('occurrence-dubious');\n\t\t\t\t\t\t\t\t\t\t\t\t\t} else if(detData[k].determination_type == 'C'){\n\t\t\t\t\t\t\t\t\t\t\t\t\t\ttag.addClass('occurrence-valid');\n\t\t\t\t\t\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\t\t\t\t\t\ttag.addClass('insect-ok');\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}}));\n\t\t\t\t\t  }}\n\t\t\t\t\t}\n\t\t\t\t}));\n\t\t\t\tjQuery('#collection-insects').ajaxStop(function(event){\n\t\t\t\t\tvar group = jQuery('#collection-insects').find('.collection-insect');\n\t\t\t\t\tvar tallest = 0;\n\t\t\t\t\tgroup.each(function(){ tallest = Math.max(\$(this).height(), tallest); });\n\t\t\t\t\tgroup.each(function(){ \$(this).height(Math.max(\$(this).height(), tallest)); }); // have synchronicity problems.\n\t\t\t\t\t\$(this).unbind(event);\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}\nfillOccurrenceLocationDetails = function(a1)\n{\n\tjQuery('#fo-locality-commune,#fo-locality-department,#fo-locality-region').empty();\n\tif(a1.features.length > 0) {\n\t    jQuery('#fo-locality-commune').empty().append(a1.features[0].attributes.NOM+' ('+a1.features[0].attributes.INSEE_NEW+')');\n\t    jQuery('#fo-locality-department').empty().append(a1.features[0].attributes.DEPT_NOM+' ('+a1.features[0].attributes.DEPT_NUM+')');\n\t    jQuery('#fo-locality-region').empty().append(a1.features[0].attributes.REG_NOM+' ('+a1.features[0].attributes.REG_NUM+')');\n\t}\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\" />').attr('collID', attributes.collection_id).attr('index', index).appendTo('#results-collections-results');\n\n\tvar details = jQuery('<div class=\"collection-details\" />').appendTo(collection);\n\tif(attributes.datedebut_txt == attributes.datefin_txt){\n\t  jQuery('<p class=\"collection-date\">'+convertDate(attributes.datedebut_txt,false)+'</p>').appendTo(details);\n    } else {\n\t  jQuery('<p class=\"collection-date\">'+convertDate(attributes.datedebut_txt,false)+' - '+convertDate(attributes.datefin_txt,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 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\tvar scope = {target: locality};\n\tinseeProtocol.read({filter: filter, callback: fillLocationDetails, scope: scope});\n\t\n\tif(typeof attributes.deleted != 'undefined' && attributes.deleted==true) {\n\t\tcollection.css('background-color','#FF0000');\n\t\treturn;\n\t}\n\t\n\tvar flower = jQuery('<div class=\"collection-image collection-flower loading\" />').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\tflower.appendTo(collection);\n\tinsertImage('med-', attributes.image_de_la_fleur, flower, " . $args['Flower_Image_Ratio'] . ", false, false);\n\n\tvar location = jQuery('<div class=\"collection-image collection-environment loading\" />').appendTo(collection);\n\tinsertImage('med-', attributes.image_de_environment, location, " . $args['Environment_Image_Ratio'] . ", false, false);\n\t\n\tjQuery('<div class=\"collection-flower-determination empty\"></div>').data('occID', attributes.flower_id).attr('occID', attributes.flower_id).appendTo(collection);\n\n\tjQuery('<div class=\"collection-photoreel\"></div>').attr('collID', attributes.collection_id).appendTo(collection);\n\t\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\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 {\n   \t\t\tvar sessionIDs=[];\n   \t\t\tfor (var i=0;i<sessiondata.length;i++){\n\t\t\t\tvar photoreel = jQuery('.collection-photoreel').filter('[collID='+sessiondata[i].parent_id+']');\n\t\t\t\tjQuery('<span class=\"photoreel-session\"></span>').attr('sessID', sessiondata[i].id).appendTo(photoreel);\n\t\t\t\tsessionIDs.push(sessiondata[i].id);\n\t\t\t}\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\"&deleted=f&callback=?&query=\"+escape(escape(JSON.stringify({'in': {'sample_id': sessionIDs}}))), 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  var n=0;\n\t\t\t\t  // there seems to be an upper limit on how many can be done at one time - so restrict to 20 at a time\n\t\t\t\t  while(n<insectData.length){\n   \t\t\t\t\tvar insectIDs=[];\n\t\t\t\t\tfor (var j=0;j<20 && n<insectData.length; j++,n++){\n\t\t\t\t\t\tvar container = jQuery('<div/>').addClass('thumb loading').attr('occID', insectData[n].id.toString()).data('collectionIndex',index).data('determination',false).data('image',false).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('.photoreel-session').filter('[sessID='+insectData[n].sample_id+']').append(container);\n\t\t\t\t\t\tinsectIDs.push(insectData[n].id);\n\t\t\t\t\t}\n\t\t\t\t\t// Not all insects will have determinations, but they will all have images\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'] . "\" + \n\t\t\t\t\t\t\t\"&orderby=id&sortdir=DESC&deleted=f&callback=?&query=\"+escape(escape(JSON.stringify({'in': {'occurrence_id': insectIDs}}))), function(detData) {\n\t\t\t\t\t\tif(!(detData instanceof Array)){\n   \t\t\t\t\t\t\talertIndiciaError(detData);\n   \t\t\t\t\t\t} else if (detData.length>0) {\n\t\t\t\t\t\t\tfor (var k=0;k<detData.length;k++){\n\t\t\t\t\t\t\t\tvar container = jQuery('.thumb').filter('[occID='+detData[k].occurrence_id.toString()+']');\n\t\t\t\t\t\t\t\tif(container.length > 0){\n\t\t\t\t\t\t\t\t\tif(container.data('determination')===false) {\n\t\t\t\t\t\t\t\t\t\tcontainer.data('determination',detData[k]);\n\t\t\t\t\t\t\t\t\t\tif(container.data('image')!==false){\n\t\t\t\t\t\t\t\t\t\t\t// image already loaded, but will have been flagged as unknown.\n\t\t\t\t\t\t\t\t\t\t\tvar img = new Image();\n\t\t\t\t\t\t\t\t\t\t\tvar src = '" . data_entry_helper::$base_url . data_entry_helper::$indicia_upload_path . "thumb-'+container.data('image').path;\n\t\t\t\t\t\t\t\t\t\t\tvar background = '';\n\t\t\t\t\t\t\t\t\t\t\tswitch(detData[k].determination_type){\n\t\t\t\t\t\t\t\t\t\t\t\tcase 'B':\n  \t\t\t\t\t\t\t\t\t\t\t\tcase 'I':\n  \t\t\t\t\t\t\t\t\t\t\t\tcase 'U':\n\t\t\t\t\t\t\t\t\t\t\t\t\tbackground=src;\n\t\t\t\t\t\t\t\t\t\t\t\t\tsrc = '" . drupal_get_path('module', 'iform') . "/client_helpers/prebuilt_forms/images/boundary-doubtful.png';\n\t\t\t\t\t\t\t\t\t\t\t\tcase 'A':\n\t\t\t\t\t\t\t\t\t\t\t\tcase 'C':\n\t\t\t\t\t\t\t\t\t\t\t\tcase 'R':\n\t\t\t\t\t\t\t\t\t\t\t\t\tcontainer.empty();  // loading class already removed.\n\t\t\t\t\t\t\t\t\t\t\t\t\timg = jQuery(img).attr('src', src).attr('width', container.width()).attr('height', container.height()).addClass('thumb-image').appendTo(container);\n\t\t\t\t\t\t\t\t\t\t\t\t\tif(background!='') img.css('background', 'url('+background+')').css('background-size','100% 100%');\n\t\t\t\t\t\t\t\t\t\t\t\tcase 'X': // unidentified, leave as is.\n\t\t\t\t\t\t\t\t\t\t\t\t\tbreak;\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}\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n  \t\t\t\t\t}});\n\t\t\t\t\t\$.getJSON(\"" . $svcUrl . "/data/occurrence_image\" +\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\"&orderby=id&sortdir=DESC&callback=?&query=\"+escape(escape(JSON.stringify({'in': {'occurrence_id': insectIDs}}))), function(imageData) {\n\t\t\t\t\t\tif(!(imageData instanceof Array)){\n   \t\t\t\t\t\t\talertIndiciaError(imageData);\n   \t\t\t\t\t\t} else if (imageData.length>0) { // thumbs are fixed in size, and small - dont worry about ratios\n   \t\t\t\t\t\t\tfor (var j=0;j<imageData.length;j++){\n\t\t\t\t\t\t\t\tvar container = jQuery('.thumb').filter('[occID='+imageData[j].occurrence_id.toString()+']');\n\t\t\t\t\t\t\t\tif(container.length > 0){\n\t\t\t\t\t\t\t\t\tif(container.data('image')===false){\n\t\t\t\t\t\t\t\t\t\tcontainer.empty().removeClass('loading').data('image',imageData[j]);\n\t\t\t\t\t\t\t\t\t\tvar img = new Image();\n\t\t\t\t\t\t\t\t\t\tvar background = '" . data_entry_helper::$base_url . data_entry_helper::$indicia_upload_path . "thumb-'+imageData[j].path;\n  \t\t\t\t\t\t\t\t\t\tvar src = '" . drupal_get_path('module', 'iform') . "/client_helpers/prebuilt_forms/images/boundary-unknown.png';\n  \t\t\t\t\t\t\t\t\t\tif(container.data('determination')!==false){\n\t\t\t\t\t\t\t\t\t\t\tswitch(container.data('determination').determination_type){\n\t\t\t\t\t\t\t\t\t\t\t\tcase 'B':\n  \t\t\t\t\t\t\t\t\t\t\t\tcase 'I':\n  \t\t\t\t\t\t\t\t\t\t\t\tcase 'U':\n\t\t\t\t\t\t\t\t\t\t\t\t\tsrc = '" . drupal_get_path('module', 'iform') . "/client_helpers/prebuilt_forms/images/boundary-doubtful.png';\n\t\t\t\t\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\t\t\t\t\tcase 'A':\n\t\t\t\t\t\t\t\t\t\t\t\tcase 'C':\n\t\t\t\t\t\t\t\t\t\t\t\tcase 'R':\n\t\t\t\t\t\t\t\t\t\t\t\t\tsrc=background;\n\t\t\t\t\t\t\t\t\t\t\t\t\tbackground='';\n\t\t\t\t\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\t\t\t\t\tcase 'X': // unidentified, leave as is.\n\t\t\t\t\t\t\t\t\t\t\t\t\tbreak;\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\tcontainer.empty();  // loading class already removed.\n\t\t\t\t\t\t\t\t\t\timg = jQuery(img).attr('src', src).attr('width', container.width()).attr('height', container.height()).addClass('thumb-image').appendTo(container);\n\t\t\t\t\t\t\t\t\t\tif(background!='') img.css('background', 'url('+background+')').css('background-size','100% 100%');\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}}})\n\t\t\t      }; \n\t\t\t}});\n\t\t}});\n\t\$.getJSON(\"" . $svcUrl . "/data/determination\" + \n\t\t\t\"?mode=json&view=list&nonce=" . $readAuth['nonce'] . "&auth_token=" . $readAuth['auth_token'] . "\" + \n\t\t\t\"&reset_timeout=true&deleted=f&orderby=id&sortdir=DESC&deleted=f&callback=?&occurrence_id=\"+attributes.flower_id,\n\t\tfunction(detData) {\n\t\t\tif(!(detData instanceof Array)){\n\t\t\t\talertIndiciaError(detData);\n\t\t\t} else {\n\t\t\t\tif (detData.length>0) {\n\t\t\t\t\tfor(var i=0; i< detData.length; i++){\n\t\t\t\t\t\tvar determination = jQuery('.collection-flower-determination').filter('[occID='+detData[i].occurrence_id+']').filter('.empty');\n\t\t\t\t\t\tif(determination.length > 0){\n\t\t\t\t\t\t\tvar string = '';\n\t\t\t\t\t\t\tif(detData[i].taxon != '' && detData[i].taxon != null){\n\t\t\t\t\t\t\t\tstring = htmlspecialchars(detData[i].taxon);\n\t\t\t\t\t\t\t}\n\t\t\t\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\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\tif(resultsIDs[0] != '') {\n\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\tfor(var k = 0; k< flowerTaxa.length; k++){\n\t\t\t\t\t\t\t\t\t\t\tif(flowerTaxa[k].id == resultsIDs[j]){\n\t\t\t\t\t\t\t\t\t\t\t\tstring = (string == '' ? '' : string + ', ') + htmlspecialchars(flowerTaxa[k].taxon);\n\t\t\t\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t}}}}}\n\t\t\t\t\t\t\tif(detData[i].taxon_extra_info != '' && detData[i].taxon_extra_info != null && detData[i].taxon_extra_info != 'null'){\n\t\t\t\t\t\t\t\tstring = (string == '' ? '' : string + ' ') + '('+htmlspecialchars(detData[i].taxon_extra_info)+')';\n\t\t\t\t\t\t\t}\n\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\tstring='<span class=\"flower-dubious\"><img src=\"" . $base . drupal_get_path('module', 'iform') . "/client_helpers/prebuilt_forms/images/occ_doubtful.png\" style=\"vertical-align: middle;\"></span>'+string;\n\t\t\t\t\t\t\t} else if(detData[i].determination_type == 'C'){\n\t\t\t\t\t\t\t\tstring=string+'<span class=\"flower-valid\"><img src=\"/misc/watchdog-ok.png\" style=\"vertical-align: middle;\"></span>';\n\t\t\t\t\t\t\t} else string=string+'<span class=\"flower-ok\"></span>';\n\t\t\t\t\t\t\tdetermination.empty().removeClass('empty').append('<p>'+string+'</p>');\n\t\t\t\t}}}\n\t}});\n};\naddInsect = function(index, attributes, endOfRow, first){\n\tvar container1=jQuery('<div class=\"filter-insect-container\" />').attr('occID',attributes.insect_id).attr('index', index).appendTo('#results-insects-results');\n\tif(endOfRow) container1.addClass('end-of-row');\n\tvar container=jQuery('<div class=\"ui-widget-content ui-corner-all filter-insect\" />').appendTo(container1);\n\tif(typeof attributes.deleted != 'undefined' && attributes.deleted==true) {\n\t\tcontainer1.css('background-color','#FF0000');\n\t\tjQuery('<div class=\"insect-determinationX empty\" />').attr('occID',attributes.insect_id).appendTo(container).append(\"<p>" . lang::get('LANG_No_Determinations') . "</p>\");\n\t\treturn;\n\t}\n\tjQuery(\"<div class='determination-flag centre-flag occurrence-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}).appendTo(container);\n\tinsect.height(insect.width()/(" . $args['Insect_Image_Ratio'] . "));\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'] . ", false, false);\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};\naddInsectDeterminations = function(insects){\n\t\$.getJSON(\"" . $svcUrl . "/data/determination\" + \n\t\t\t\"?mode=json&view=list&nonce=" . $readAuth['nonce'] . "&auth_token=" . $readAuth['auth_token'] . "\" + \n\t\t\t\"&reset_timeout=true&orderby=id&sortdir=DESC&deleted=f&callback=?&query=\"+escape(escape(JSON.stringify({'in': {'occurrence_id': insects}}))),\n\t\tfunction(detData) {\n\t\t\tif(!(detData instanceof Array)){\n\t\t\t\talertIndiciaError(detData);\n\t\t\t} else {\n\t\t\t\tif (detData.length>0) {\n\t\t\t\t\tfor(var i=0; i< detData.length; i++){\n\t\t\t\t\t\tvar determination = jQuery('.insect-determinationX').filter('[occID='+detData[i].occurrence_id+']').filter('.empty');\n\t\t\t\t\t\tif(determination.length > 0){\n\t\t\t\t\t\t\tvar string = '';\n\t\t\t\t\t\t\tif(detData[i].taxon != '' && detData[i].taxon != null){\n\t\t\t\t\t\t\t\tstring = htmlspecialchars(detData[i].taxon);\n\t\t\t\t\t\t\t}\n\t\t\t\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\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\tif(resultsIDs[0] != '') {\n\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\tfor(var k = 0; k< insectTaxa.length; k++){\n\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\tstring = (string == '' ? '' : string + ', ') + htmlspecialchars(insectTaxa[k].taxon);\n\t\t\t\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t}}}}}\n\t\t\t\t\t\t\tif(detData[i].taxon_extra_info != '' && detData[i].taxon_extra_info != null && detData[i].taxon_extra_info != 'null'){\n\t\t\t\t\t\t\t\tstring = (string == '' ? '' : string + ' ') + '('+htmlspecialchars(detData[i].taxon_extra_info)+')';\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tdetermination.empty().removeClass('empty').append('<p>'+string+'</p>');\n\t\t\t\t\t\t\tvar flag = determination.parent().find('.occurrence-unknown').removeClass('occurrence-unknown');\n\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\tflag.addClass('occurrence-dubious');\n\t\t\t\t\t\t\t} else if(detData[i].determination_type == 'C'){\n\t\t\t\t\t\t\t\tflag.addClass('occurrence-valid');\n\t\t\t\t\t\t\t} else \n\t\t\t\t\t\t\t\tflag.addClass('insect-ok');\n\t\t\t\t}}}\n\t\t\t\tvar group = jQuery('#results-insects-results').find('.filter-insect');\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}});\n};\n\nsetCollectionPage = function(pageNum){\n\tif(bulkValidating) return; //prevent query changing underneath bulk validation\n\tjQuery('#results-collections-results,#validate-page-message,#validate-taxon-message,#validate-collection-message').empty();\n\tvar no_units = 4;\n\tvar no_tens = 2;\n\tvar no_hundreds = 1;\n\tif(searchResults.features.length >= " . $args['max_features'] . "){\n\t\tjQuery(\"<span class='features-warning'>" . lang::get('LANG_Max_Collections_Reached') . "</span>\").appendTo('#results-collections-results');\n\t}\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\tif(pageNum==numPages)\n\t\tjQuery('#results-validate-taxon-outer').show();\n\telse\n\t\tjQuery('#results-validate-taxon-outer').hide();\n}\nsetInsectPage = function(pageNum){\n\tif(bulkValidating) return; //prevent query changing underneath bulk validation\n\tjQuery('#results-insects-results,#validate-page-message,#validate-taxon-message,#validate-collection-message').empty();\n\tif(searchResults.features.length >= " . $args['max_features'] . "){\n\t\tjQuery(\"<span class='features-warning'>" . lang::get('LANG_Max_Insects_Reached') . "</span>\").appendTo('#results-insects-results');\n\t}\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\tvar insectIDs=[];\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\tinsectIDs.push(searchResults.features[i].attributes.insect_id);\n\t}\n\taddInsectDeterminations(insectIDs);\n\tif(numPages > 1) {\n\t\titemList.clone(true).appendTo('#results-insects-results');\n\t}\n\tif(pageNum==numPages)\n\t\tjQuery('#results-validate-taxon-outer').show();\n\telse\n\t\tjQuery('#results-validate-taxon-outer').hide();\n}\n\n// searchLayer in map is used for georeferencing.\n// map editLayer is switched off. TODO: need to switch off click control\n// editlayer left in map2: replaces locationLayer\nsearchResultsLayer = null;\ninseeLayer = null;\npolygonLayer = new OpenLayers.Layer.Vector('Polygon Layer', {\n\tstyleMap: new OpenLayers.StyleMap({\n                \"default\": new OpenLayers.Style({\n                    fillColor: \"" . $args['Polygon_Colour'] . "\",\n                    strokeColor: \"" . $args['Polygon_Colour'] . "\",\n                    fillOpacity: " . $args['Polygon_Opacity'] . ",\n                    strokeWidth: 1\n                  })\n\t}),\n\tdisplayInLayerSwitcher: false\n});\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\tuseKey: false,\n\tname: 'flowerIDstruc',\n\tdeterminationType: '" . (user_access('IForm n' . $node->nid . ' flower expert') ? 'C' : 'A') . "',\n\ttaxaList: flowerTaxa\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\t toolStruct: toolStruct,\n\t success: function(da){ // now jsonp form, so comes in already parsed.\n\t  // How do I check if person has finished? data is filled in...\n\t  pollReset(this.toolStruct);\n\t  var status = da.data.sddversion + ' : ' + JSON.stringify(da.data.history);\n      jQuery(this.toolStruct.mainForm+' [name=determination\\:taxon_details]').val(status); // Stores details how the identification was arrived at within the tool.\n      // Initially galerie will not process da.urlimage\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.mainForm+' [name=determination\\:determination_type]').val('X'); // Unidentified.\n\t  } else {\n\t\tvar resultsIDs = [];\n\t\tvar resultsText = \"" . lang::get('LANG_Taxa_Returned') . "<br />{ \";\n\t\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\tjQuery(this.toolStruct.mainForm).append('<input type=\"hidden\" name=\"determination:taxa_taxon_list_id_list[]\" value=\"'+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  \tif(notFound != ''){\n\t\t\tvar comment = jQuery('[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.sessionID='';\n\ttoolStruct.timeOutTimer = null;\n\ttoolStruct.pollTimer = null;\n};\n\nidButtonPressed = function(toolStruct){\n\tif(!toolStruct.useKey) return;\n\tjQuery(toolStruct.mainForm+' [name=determination\\:determination_type]').val(toolStruct.determinationType);\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.mainForm+' [name=determination\\:taxa_taxon_list_id_list\\[\\]]').remove(); // table removal not required at moment\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+(toolStruct.imagePath != '' ? '&urlimageuser='******'" . data_entry_helper::$base_url . data_entry_helper::$indicia_upload_path . "'+toolStruct.imagePath : '');\n\twindow.open(toolURL);\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\n// an expert can set the determination type to 'X' manually, so reset everything in this case.\nexpertSetUnidentified = function(toolStruct){\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.mainForm+' [name=determination\\:taxa_taxon_list_id_list\\[\\]]').remove();\n\tjQuery(toolStruct.mainForm+' [name=determination\\:comment]').val(\"" . lang::get('LANG_Default_ID_Comment') . "\");\n  };\njQuery('#fo-insect-expert-det-type').change(function(){\n\tif(jQuery(this).val()=='X') expertSetUnidentified(insectIDstruc);\n});\n\ntaxonChosen = function(toolStruct){\n\tjQuery(toolStruct.mainForm+' [name=determination\\:taxon_details]').val('');\n\tjQuery(toolStruct.mainForm+' [name=determination\\:taxa_taxon_list_id_list\\[\\]]').remove();\n\tjQuery('#'+toolStruct.type+'_taxa_list').empty();\n\tjQuery(toolStruct.mainForm+' [name=determination\\:comment]').val('');\n\tjQuery(toolStruct.mainForm+' [name=determination\\:taxon_extra_info]').val('');\n\tjQuery(toolStruct.mainForm+' [name=determination\\:determination_type]').val(toolStruct.determinationType);\n};\n\ninsectIDstruc = {\n\ttype: 'insect',\n\tmainForm: 'form#fo-new-insect-id-form',\n\tuseKey: true,\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\timagePath: '',\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();\n\njQuery('form#fo-new-insect-id-form select[name=determination\\:taxa_taxon_list_id]').change(function(){\n\tpollReset(insectIDstruc);\n\ttaxonChosen(insectIDstruc);\n});\n\$('#imp-insee-close-btn').click(function(e) {\n  \$('#imp-insee-div').hide();\n  if(inseeLayer != null){\n\t\tinseeLayer.destroyFeatures();\n  }\n  inseeLayerStore.destroyFeatures();\n  e.preventDefault();\n});\nvar defaultDiacriticsRemovalMap = [\n    {'base':'A', 'letters':/[\\u0041\\u24B6\\uFF21\\u00C0\\u00C1\\u00C2\\u1EA6\\u1EA4\\u1EAA\\u1EA8\\u00C3\\u0100\\u0102\\u1EB0\\u1EAE\\u1EB4\\u1EB2\\u0226\\u01E0\\u00C4\\u01DE\\u1EA2\\u00C5\\u01FA\\u01CD\\u0200\\u0202\\u1EA0\\u1EAC\\u1EB6\\u1E00\\u0104\\u023A\\u2C6F]/g},\n    {'base':'AA','letters':/[\\uA732]/g},\n    {'base':'AE','letters':/[\\u00C6\\u01FC\\u01E2]/g},\n    {'base':'AO','letters':/[\\uA734]/g},\n    {'base':'AU','letters':/[\\uA736]/g},\n    {'base':'AV','letters':/[\\uA738\\uA73A]/g},\n    {'base':'AY','letters':/[\\uA73C]/g},\n    {'base':'B', 'letters':/[\\u0042\\u24B7\\uFF22\\u1E02\\u1E04\\u1E06\\u0243\\u0182\\u0181]/g},\n    {'base':'C', 'letters':/[\\u0043\\u24B8\\uFF23\\u0106\\u0108\\u010A\\u010C\\u00C7\\u1E08\\u0187\\u023B\\uA73E]/g},\n    {'base':'D', 'letters':/[\\u0044\\u24B9\\uFF24\\u1E0A\\u010E\\u1E0C\\u1E10\\u1E12\\u1E0E\\u0110\\u018B\\u018A\\u0189\\uA779]/g},\n    {'base':'DZ','letters':/[\\u01F1\\u01C4]/g},\n    {'base':'Dz','letters':/[\\u01F2\\u01C5]/g},\n    {'base':'E', 'letters':/[\\u0045\\u24BA\\uFF25\\u00C8\\u00C9\\u00CA\\u1EC0\\u1EBE\\u1EC4\\u1EC2\\u1EBC\\u0112\\u1E14\\u1E16\\u0114\\u0116\\u00CB\\u1EBA\\u011A\\u0204\\u0206\\u1EB8\\u1EC6\\u0228\\u1E1C\\u0118\\u1E18\\u1E1A\\u0190\\u018E]/g},\n    {'base':'F', 'letters':/[\\u0046\\u24BB\\uFF26\\u1E1E\\u0191\\uA77B]/g},\n    {'base':'G', 'letters':/[\\u0047\\u24BC\\uFF27\\u01F4\\u011C\\u1E20\\u011E\\u0120\\u01E6\\u0122\\u01E4\\u0193\\uA7A0\\uA77D\\uA77E]/g},\n    {'base':'H', 'letters':/[\\u0048\\u24BD\\uFF28\\u0124\\u1E22\\u1E26\\u021E\\u1E24\\u1E28\\u1E2A\\u0126\\u2C67\\u2C75\\uA78D]/g},\n    {'base':'I', 'letters':/[\\u0049\\u24BE\\uFF29\\u00CC\\u00CD\\u00CE\\u0128\\u012A\\u012C\\u0130\\u00CF\\u1E2E\\u1EC8\\u01CF\\u0208\\u020A\\u1ECA\\u012E\\u1E2C\\u0197]/g},\n    {'base':'J', 'letters':/[\\u004A\\u24BF\\uFF2A\\u0134\\u0248]/g},\n    {'base':'K', 'letters':/[\\u004B\\u24C0\\uFF2B\\u1E30\\u01E8\\u1E32\\u0136\\u1E34\\u0198\\u2C69\\uA740\\uA742\\uA744\\uA7A2]/g},\n    {'base':'L', 'letters':/[\\u004C\\u24C1\\uFF2C\\u013F\\u0139\\u013D\\u1E36\\u1E38\\u013B\\u1E3C\\u1E3A\\u0141\\u023D\\u2C62\\u2C60\\uA748\\uA746\\uA780]/g},\n    {'base':'LJ','letters':/[\\u01C7]/g},\n    {'base':'Lj','letters':/[\\u01C8]/g},\n    {'base':'M', 'letters':/[\\u004D\\u24C2\\uFF2D\\u1E3E\\u1E40\\u1E42\\u2C6E\\u019C]/g},\n    {'base':'N', 'letters':/[\\u004E\\u24C3\\uFF2E\\u01F8\\u0143\\u00D1\\u1E44\\u0147\\u1E46\\u0145\\u1E4A\\u1E48\\u0220\\u019D\\uA790\\uA7A4]/g},\n    {'base':'NJ','letters':/[\\u01CA]/g},\n    {'base':'Nj','letters':/[\\u01CB]/g},\n    {'base':'O', 'letters':/[\\u004F\\u24C4\\uFF2F\\u00D2\\u00D3\\u00D4\\u1ED2\\u1ED0\\u1ED6\\u1ED4\\u00D5\\u1E4C\\u022C\\u1E4E\\u014C\\u1E50\\u1E52\\u014E\\u022E\\u0230\\u00D6\\u022A\\u1ECE\\u0150\\u01D1\\u020C\\u020E\\u01A0\\u1EDC\\u1EDA\\u1EE0\\u1EDE\\u1EE2\\u1ECC\\u1ED8\\u01EA\\u01EC\\u00D8\\u01FE\\u0186\\u019F\\uA74A\\uA74C]/g},\n    {'base':'OI','letters':/[\\u01A2]/g},\n    {'base':'OO','letters':/[\\uA74E]/g},\n    {'base':'OU','letters':/[\\u0222]/g},\n    {'base':'P', 'letters':/[\\u0050\\u24C5\\uFF30\\u1E54\\u1E56\\u01A4\\u2C63\\uA750\\uA752\\uA754]/g},\n    {'base':'Q', 'letters':/[\\u0051\\u24C6\\uFF31\\uA756\\uA758\\u024A]/g},\n    {'base':'R', 'letters':/[\\u0052\\u24C7\\uFF32\\u0154\\u1E58\\u0158\\u0210\\u0212\\u1E5A\\u1E5C\\u0156\\u1E5E\\u024C\\u2C64\\uA75A\\uA7A6\\uA782]/g},\n    {'base':'S', 'letters':/[\\u0053\\u24C8\\uFF33\\u1E9E\\u015A\\u1E64\\u015C\\u1E60\\u0160\\u1E66\\u1E62\\u1E68\\u0218\\u015E\\u2C7E\\uA7A8\\uA784]/g},\n    {'base':'T', 'letters':/[\\u0054\\u24C9\\uFF34\\u1E6A\\u0164\\u1E6C\\u021A\\u0162\\u1E70\\u1E6E\\u0166\\u01AC\\u01AE\\u023E\\uA786]/g},\n    {'base':'TZ','letters':/[\\uA728]/g},\n    {'base':'U', 'letters':/[\\u0055\\u24CA\\uFF35\\u00D9\\u00DA\\u00DB\\u0168\\u1E78\\u016A\\u1E7A\\u016C\\u00DC\\u01DB\\u01D7\\u01D5\\u01D9\\u1EE6\\u016E\\u0170\\u01D3\\u0214\\u0216\\u01AF\\u1EEA\\u1EE8\\u1EEE\\u1EEC\\u1EF0\\u1EE4\\u1E72\\u0172\\u1E76\\u1E74\\u0244]/g},\n    {'base':'V', 'letters':/[\\u0056\\u24CB\\uFF36\\u1E7C\\u1E7E\\u01B2\\uA75E\\u0245]/g},\n    {'base':'VY','letters':/[\\uA760]/g},\n    {'base':'W', 'letters':/[\\u0057\\u24CC\\uFF37\\u1E80\\u1E82\\u0174\\u1E86\\u1E84\\u1E88\\u2C72]/g},\n    {'base':'X', 'letters':/[\\u0058\\u24CD\\uFF38\\u1E8A\\u1E8C]/g},\n    {'base':'Y', 'letters':/[\\u0059\\u24CE\\uFF39\\u1EF2\\u00DD\\u0176\\u1EF8\\u0232\\u1E8E\\u0178\\u1EF6\\u1EF4\\u01B3\\u024E\\u1EFE]/g},\n    {'base':'Z', 'letters':/[\\u005A\\u24CF\\uFF3A\\u0179\\u1E90\\u017B\\u017D\\u1E92\\u1E94\\u01B5\\u0224\\u2C7F\\u2C6B\\uA762]/g},\n    {'base':'a', 'letters':/[\\u0061\\u24D0\\uFF41\\u1E9A\\u00E0\\u00E1\\u00E2\\u1EA7\\u1EA5\\u1EAB\\u1EA9\\u00E3\\u0101\\u0103\\u1EB1\\u1EAF\\u1EB5\\u1EB3\\u0227\\u01E1\\u00E4\\u01DF\\u1EA3\\u00E5\\u01FB\\u01CE\\u0201\\u0203\\u1EA1\\u1EAD\\u1EB7\\u1E01\\u0105\\u2C65\\u0250]/g},\n    {'base':'aa','letters':/[\\uA733]/g},\n    {'base':'ae','letters':/[\\u00E6\\u01FD\\u01E3]/g},\n    {'base':'ao','letters':/[\\uA735]/g},\n    {'base':'au','letters':/[\\uA737]/g},\n    {'base':'av','letters':/[\\uA739\\uA73B]/g},\n    {'base':'ay','letters':/[\\uA73D]/g},\n    {'base':'b', 'letters':/[\\u0062\\u24D1\\uFF42\\u1E03\\u1E05\\u1E07\\u0180\\u0183\\u0253]/g},\n    {'base':'c', 'letters':/[\\u0063\\u24D2\\uFF43\\u0107\\u0109\\u010B\\u010D\\u00E7\\u1E09\\u0188\\u023C\\uA73F\\u2184]/g},\n    {'base':'d', 'letters':/[\\u0064\\u24D3\\uFF44\\u1E0B\\u010F\\u1E0D\\u1E11\\u1E13\\u1E0F\\u0111\\u018C\\u0256\\u0257\\uA77A]/g},\n    {'base':'dz','letters':/[\\u01F3\\u01C6]/g},\n    {'base':'e', 'letters':/[\\u0065\\u24D4\\uFF45\\u00E8\\u00E9\\u00EA\\u1EC1\\u1EBF\\u1EC5\\u1EC3\\u1EBD\\u0113\\u1E15\\u1E17\\u0115\\u0117\\u00EB\\u1EBB\\u011B\\u0205\\u0207\\u1EB9\\u1EC7\\u0229\\u1E1D\\u0119\\u1E19\\u1E1B\\u0247\\u025B\\u01DD]/g},\n    {'base':'f', 'letters':/[\\u0066\\u24D5\\uFF46\\u1E1F\\u0192\\uA77C]/g},\n    {'base':'g', 'letters':/[\\u0067\\u24D6\\uFF47\\u01F5\\u011D\\u1E21\\u011F\\u0121\\u01E7\\u0123\\u01E5\\u0260\\uA7A1\\u1D79\\uA77F]/g},\n    {'base':'h', 'letters':/[\\u0068\\u24D7\\uFF48\\u0125\\u1E23\\u1E27\\u021F\\u1E25\\u1E29\\u1E2B\\u1E96\\u0127\\u2C68\\u2C76\\u0265]/g},\n    {'base':'hv','letters':/[\\u0195]/g},\n    {'base':'i', 'letters':/[\\u0069\\u24D8\\uFF49\\u00EC\\u00ED\\u00EE\\u0129\\u012B\\u012D\\u00EF\\u1E2F\\u1EC9\\u01D0\\u0209\\u020B\\u1ECB\\u012F\\u1E2D\\u0268\\u0131]/g},\n    {'base':'j', 'letters':/[\\u006A\\u24D9\\uFF4A\\u0135\\u01F0\\u0249]/g},\n    {'base':'k', 'letters':/[\\u006B\\u24DA\\uFF4B\\u1E31\\u01E9\\u1E33\\u0137\\u1E35\\u0199\\u2C6A\\uA741\\uA743\\uA745\\uA7A3]/g},\n    {'base':'l', 'letters':/[\\u006C\\u24DB\\uFF4C\\u0140\\u013A\\u013E\\u1E37\\u1E39\\u013C\\u1E3D\\u1E3B\\u017F\\u0142\\u019A\\u026B\\u2C61\\uA749\\uA781\\uA747]/g},\n    {'base':'lj','letters':/[\\u01C9]/g},\n    {'base':'m', 'letters':/[\\u006D\\u24DC\\uFF4D\\u1E3F\\u1E41\\u1E43\\u0271\\u026F]/g},\n    {'base':'n', 'letters':/[\\u006E\\u24DD\\uFF4E\\u01F9\\u0144\\u00F1\\u1E45\\u0148\\u1E47\\u0146\\u1E4B\\u1E49\\u019E\\u0272\\u0149\\uA791\\uA7A5]/g},\n    {'base':'nj','letters':/[\\u01CC]/g},\n    {'base':'o', 'letters':/[\\u006F\\u24DE\\uFF4F\\u00F2\\u00F3\\u00F4\\u1ED3\\u1ED1\\u1ED7\\u1ED5\\u00F5\\u1E4D\\u022D\\u1E4F\\u014D\\u1E51\\u1E53\\u014F\\u022F\\u0231\\u00F6\\u022B\\u1ECF\\u0151\\u01D2\\u020D\\u020F\\u01A1\\u1EDD\\u1EDB\\u1EE1\\u1EDF\\u1EE3\\u1ECD\\u1ED9\\u01EB\\u01ED\\u00F8\\u01FF\\u0254\\uA74B\\uA74D\\u0275]/g},\n    {'base':'oi','letters':/[\\u01A3]/g},\n    {'base':'ou','letters':/[\\u0223]/g},\n    {'base':'oo','letters':/[\\uA74F]/g},\n    {'base':'p','letters':/[\\u0070\\u24DF\\uFF50\\u1E55\\u1E57\\u01A5\\u1D7D\\uA751\\uA753\\uA755]/g},\n    {'base':'q','letters':/[\\u0071\\u24E0\\uFF51\\u024B\\uA757\\uA759]/g},\n    {'base':'r','letters':/[\\u0072\\u24E1\\uFF52\\u0155\\u1E59\\u0159\\u0211\\u0213\\u1E5B\\u1E5D\\u0157\\u1E5F\\u024D\\u027D\\uA75B\\uA7A7\\uA783]/g},\n    {'base':'s','letters':/[\\u0073\\u24E2\\uFF53\\u00DF\\u015B\\u1E65\\u015D\\u1E61\\u0161\\u1E67\\u1E63\\u1E69\\u0219\\u015F\\u023F\\uA7A9\\uA785\\u1E9B]/g},\n    {'base':'t','letters':/[\\u0074\\u24E3\\uFF54\\u1E6B\\u1E97\\u0165\\u1E6D\\u021B\\u0163\\u1E71\\u1E6F\\u0167\\u01AD\\u0288\\u2C66\\uA787]/g},\n    {'base':'tz','letters':/[\\uA729]/g},\n    {'base':'u','letters':/[\\u0075\\u24E4\\uFF55\\u00F9\\u00FA\\u00FB\\u0169\\u1E79\\u016B\\u1E7B\\u016D\\u00FC\\u01DC\\u01D8\\u01D6\\u01DA\\u1EE7\\u016F\\u0171\\u01D4\\u0215\\u0217\\u01B0\\u1EEB\\u1EE9\\u1EEF\\u1EED\\u1EF1\\u1EE5\\u1E73\\u0173\\u1E77\\u1E75\\u0289]/g},\n    {'base':'v','letters':/[\\u0076\\u24E5\\uFF56\\u1E7D\\u1E7F\\u028B\\uA75F\\u028C]/g},\n    {'base':'vy','letters':/[\\uA761]/g},\n    {'base':'w','letters':/[\\u0077\\u24E6\\uFF57\\u1E81\\u1E83\\u0175\\u1E87\\u1E85\\u1E98\\u1E89\\u2C73]/g},\n    {'base':'x','letters':/[\\u0078\\u24E7\\uFF58\\u1E8B\\u1E8D]/g},\n    {'base':'y','letters':/[\\u0079\\u24E8\\uFF59\\u1EF3\\u00FD\\u0177\\u1EF9\\u0233\\u1E8F\\u00FF\\u1EF7\\u1E99\\u1EF5\\u01B4\\u024F\\u1EFF]/g},\n    {'base':'z','letters':/[\\u007A\\u24E9\\uFF5A\\u017A\\u1E91\\u017C\\u017E\\u1E93\\u1E95\\u01B6\\u0225\\u0240\\u2C6C\\uA763]/g}\n];\nfunction removeDiacritics (str) {\n    var changes = defaultDiacriticsRemovalMap;\n    for(var i=0; i<changes.length; i++) {\n        str = str.replace(changes[i].letters, changes[i].base);\n    }\n    return str;\n}\ninseeLayerStore = new OpenLayers.Layer.Vector('INSEE Layer Store', {displayInLayerSwitcher: false});\njQuery('#search-insee-button').click(function(){\n\tif(inseeLayer != null){\n\t\tinseeLayer.destroyFeatures();\n\t\tinseeLayer.destroy();\n\t}\n\tinseeLayerStore.destroyFeatures();\n\tjQuery('#imp-insee-div').hide();\n\tpolygonLayer.map.searchLayer.destroyFeatures();\n\tpolygonLayer.destroyFeatures();\n\tvar filters = [];\n\tvar myGeometryName;\n\tvar myFeatureType;\n\tvar myDisplayField;\n\tvar myExtraDataField;\n\tvar myINSEELookUpMaxFeatures;\n\tvar place = removeDiacritics(jQuery('input[name=place\\:INSEE]').val());\n\tplace = place.toUpperCase();\n\twhile(place!='' && place.substring(0,1)=='*'){place=place.substring(1);}\n\twhile(place!='' && place.substring(place.length-1)=='*'){place=place.substring(0,place.length-1);}\n\tif(place == \"" . lang::get('LANG_Enter_Location') . "\") return;\n\tjQuery('#search-insee-button').addClass('loading-button');\n\tswitch(jQuery('[name=place\\:INSEE_Type]').val()){";
        $searches = explode(';', trim($args['Localisation_spec']));
        for ($i = 0; $i < count($searches); $i++) {
            $parts = explode(':', $searches[$i]);
            data_entry_helper::$javascript .= "case \"" . $i . "\": myFeatureType=\"" . $parts[1] . "\";myGeometryName=\"" . $parts[2] . "\";myDisplayField=\"" . $parts[3] . "\";myExtraDataField=\"" . $parts[4] . "\";myINSEELookUpMaxFeatures=\"" . $parts[5] . "\";mySearchINSEEfeaturesLimit=\"" . $parts[6] . "\";";
            for ($j = 7; $j < count($parts); $j = $j + 2) {
                data_entry_helper::$javascript .= "\n\tfilters.push(new OpenLayers.Filter.Comparison({\n\t\ttype: " . ($parts[$j + 1] == 'equal' ? 'OpenLayers.Filter.Comparison.EQUAL_TO' : 'OpenLayers.Filter.Comparison.LIKE') . ",\n\t\tproperty: '" . $parts[$j] . "',\n\t\tvalue: " . ($parts[$j + 1] == '*like*' ? '"*"+' : '') . "place" . ($parts[$j + 1] == 'equal' ? '' : '+"*"') . "\n\t}));";
            }
            data_entry_helper::$javascript .= "break;";
        }
        data_entry_helper::$javascript .= "\n\t}\n\tvar strategy = new OpenLayers.Strategy.Fixed({preload: false, autoActivate: false});\n\tvar styleMap = new OpenLayers.StyleMap({\n                \"default\": new OpenLayers.Style({\n                    fillColor: \"" . $args['Feature_Colour'] . "\",\n                    strokeColor: \"" . $args['Feature_Colour'] . "\",\n                    fillOpacity: " . $args['Feature_Opacity'] . ",\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: myFeatureType,\n              geometryName: myGeometryName,\n              featureNS: '" . $args['INSEE_ns'] . "',\n              srsName: 'EPSG:900913',\n              version: '1.1.0'                  \n              ,maxFeatures: myINSEELookUpMaxFeatures\n              ,propertyNames: (myExtraDataField=='' ? [myGeometryName, myDisplayField] : [myGeometryName, myDisplayField, myExtraDataField])\n          }),\n          filter: new OpenLayers.Filter.Logical({\n\t\t      type: OpenLayers.Filter.Logical.OR,\n\t\t      filters: filters\n\t\t  \t  })\n    });\n    inseeLayer.events.register('featuresadded', {}, function(a1){\n\t\tvar div = jQuery('#map')[0];\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\tjQuery('#search-insee-button').removeClass('loading-button');\n\t\tif(inseeLayer.features.length == 0){\n\t\t\tjQuery('#imp-insee-div').show();\n\t\t\tjQuery('#imp-insee-output-div').empty().append(\"<span>" . lang::get('LANG_NO_INSEE') . "</span>\");\n\t\t} else if(inseeLayer.features.length > 1){\n\t\t\tjQuery('#imp-insee-output-div').empty();\n\t\t\tjQuery('#imp-insee-div').show();\n\t\t\tif(inseeLayer.features.length == myINSEELookUpMaxFeatures)\n\t\t\t\tjQuery('#imp-insee-output-div').append('<span>'+\"" . lang::get('LANG_Max_INSEE_Features') . "\".replace('<>',myINSEELookUpMaxFeatures)+'</span> ');\n\t\t\tif(inseeLayer.features.length > mySearchINSEEfeaturesLimit)\n\t\t\t\tjQuery('#imp-insee-output-div').append('<span>'+\"" . lang::get('LANG_INSEE_Search_Limit') . "\".replace('<>',mySearchINSEEfeaturesLimit)+'</span>');\n\t\t\tvar ol=jQuery('<ol></ol>');\n\t\t\tjQuery('#imp-insee-output-div').append(ol);\n\t\t\tfor(var i = 0; i< inseeLayer.features.length; i++){\n\t\t\t\tvar text = inseeLayer.features[i].data[myDisplayField]+(myExtraDataField=='' ? '' : ' ('+inseeLayer.features[i].data[myExtraDataField]+')');\n\t\t\t\tol.append(jQuery('<li>').append(jQuery(\"<a href='#'>\" + text + '</a>')\n                  .click(function(e) {e.preventDefault();})\n                  .click((// use closures to persist the values of feature\n                    function(feature){\n                      return function() {\n                        var removeList = [];\n                        for(var i=0; i< inseeLayer.features.length; i++){removeList.push(inseeLayer.features[i]);}\n                        if(removeList.length) {\n                        \tinseeLayer.removeFeatures(removeList);\n                        \tinseeLayerStore.addFeatures(removeList);\n                        }\n                        inseeLayerStore.removeFeatures([feature]);\n                        inseeLayer.addFeatures([feature]);\n                      };\n                    })(inseeLayer.features[i]))));\n\t\t\t}\n\t\t}\n    });\n    jQuery('#map')[0].map.addLayer(inseeLayer);\n    strategy.load({});\n});\n\njQuery('#search-collections-button').click(function(){\n\tif(bulkValidating) return; //prevent results changing underneath bulk validation\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\tif(bulkValidating) return; //prevent results changing underneath bulk validation\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 && inseeLayer.features.length <= mySearchINSEEfeaturesLimit)\n\t\tfeatures = inseeLayer.features;\n\telse if(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', featureNS: 'user', featurePrefix: 'user'});\n    var features=format.read(string);\n\tif(inseeLayer != null) inseeLayer.destroyFeatures();\n\tinseeLayerStore.destroyFeatures();\n\tjQuery('#imp-insee-div').hide();\n\tpolygonLayer.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}\nmySearchINSEEfeaturesLimit=1;\nfunction pad(number, length) {\n    var str = '' + number;\n    while (str.length < length) {\n        str = '0' + str;\n    }\n    return str;\n}\nrunSearch = function(forCollections){\n\tif(bulkValidating) return; //prevent query changing underneath bulk validation\n  \tvar ORgroup = [];\n  \tif(searchResultsLayer != null)\n\t\tsearchResultsLayer.destroy();\n    jQuery('#results-collections-results,#results-insects-results,#validate-page-message,#validate-taxon-message,#validate-collection-message,#collection-insects').empty();\n\tjQuery('#focus-occurrence,#focus-collection').hide();\n\tjQuery('#validate-taxon-progress,#validate-page-progress,,#validate-collection-progress,#cancel-validate-page,#cancel-validate-taxon,#cancel-validate-collection').hide();\n  \tjQuery('#results-validate-taxon,#results-validate-page,#results-validate-taxon-outer').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\tif(inseeLayer != null){\n  \t\tif(inseeLayer.features.length > 0 && inseeLayer.features.length<=mySearchINSEEfeaturesLimit){\n\t\t\tORgroup = [];\n\t\t\tfor(i=0; i< inseeLayer.features.length; i++)\n\t\t\t\tORgroup.push(new OpenLayers.Filter.Spatial({type: OpenLayers.Filter.Spatial.WITHIN, property: 'geom', value: inseeLayer.features[i].geometry}));\n\t\t\tif(ORgroup.length >= 1) filters.push(combineOR(ORgroup));}}\n\tif(polygonLayer.features.length > 0){\n\t\tORgroup = [];\n\t\tfor(i=0; i< polygonLayer.features.length; i++)\n\t\t\tORgroup.push(new OpenLayers.Filter.Spatial({type: OpenLayers.Filter.Spatial.WITHIN, property: 'geom', value: polygonLayer.features[i].geometry}));\n\t\tif(ORgroup.length >= 1) filters.push(combineOR(ORgroup));\n\t}\n\t\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 != '') {\n  \t\tvar flower_taxon_filter = new OpenLayers.Filter.Comparison({type: OpenLayers.Filter.Comparison.LIKE, property: 'flower_taxon_ids', value: '*|'+flower+'|*'});\n  \t\tif(jQuery('select[name=flower\\:taxa_taxon_list_id] option:selected').text().substring(0,13) == 'Taxon inconnu'){\n  \t\t\tORgroup = [];\n  \t\t\tORgroup.push(flower_taxon_filter);\n//  \t\t\tORgroup.push(new OpenLayers.Filter.Comparison({type: OpenLayers.Filter.Comparison.EQUAL_TO, property: 'status_fleur_code', value: 'X'}));\n  \t\t\tfilters.push(combineOR(ORgroup));\n  \t\t} else {\n  \t\t\tif(forCollections)\n\t\t\t\tjQuery('#results-validate-taxon,#results-validate-page').show();\n  \t\t\tfilters.push(flower_taxon_filter);\n  \t\t}\n  \t}\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\tORgroup = [];\n  \tjQuery('#flower-filter-body').find('[name=flower_id_status\\[\\]]').filter('[checked]').each(function(index, elem){\n  \t\tORgroup.push(new OpenLayers.Filter.Comparison({type: OpenLayers.Filter.Comparison.EQUAL_TO, property: 'status_fleur_code', value: elem.value}));\n  \t});\n  \tif(ORgroup.length >= 1) filters.push(combineOR(ORgroup));\n\tORgroup = [];\n  \tjQuery('#flower-filter-body').find('[name=flower_id_type\\[\\]]').filter('[checked]').each(function(index, elem){\n  \t\tORgroup.push(new OpenLayers.Filter.Comparison({type: OpenLayers.Filter.Comparison.EQUAL_TO, property: 'flower_taxon_type', value: elem.value}));\n  \t});\n  \tif(ORgroup.length >= 1) filters.push(combineOR(ORgroup));\n\t\t\n\tORgroup = [];\n  \tjQuery('#flower-filter-body').find('[name^=occAttr:" . $flowerTypeAttrID . "]').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:" . $habitatAttrID . "]').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  \t\n\tvar insect = jQuery('select[name=insect\\:taxa_taxon_list_id]').val();\n\tvar insect_name = jQuery('select[name=insect\\:taxa_taxon_list_id] option:selected').text()\n\tvar insect_statuses = jQuery('[name=insect_id_status\\[\\]]').filter('[checked]');\n\tvar insect_taxon_types = jQuery('[name=insect_id_type\\[\\]]').filter('[checked]');\n\tvar foraging = jQuery('#insect-filter-body').find('[name^=occAttr:" . $foragingAttrID . "]').filter('[checked]');\n\tif(forCollections){\n\t\tvar foundSome = false;\n\t\tvar queries = [];\n//\t\tif(insect_name.substring(0,13) == 'Taxon inconnu'){\n//\t\t\tif((insect_statuses.length == 1 && insect_statuses[0].val() == 'X') || insect_statuses.length == 0){\n//\t\t\t\tqueries.push({status: 'X'});\n//\t\t\t\tqueries.push({taxon: insect});\n//\t\t\t} else {\n//\t\t\t\tinsect_statuses.each(function(index, elem){\n//\t\t\t\t\tqueries.push({status: elem.value, taxon: insect});\n//\t\t\t\t});\n//\t\t\t}\n//\t\t} else \n\t\tif(insect != ''){\n\t\t\tif(insect_statuses.length > 0){\n\t\t\t\tinsect_statuses.each(function(index, elem){\n\t\t\t\t\tqueries.push({status: elem.value, taxon: insect});\n\t\t\t\t});\n\t\t\t} else {\n\t\t\t\tqueries.push({taxon: insect});\n\t\t\t}\n\t\t} else if(insect_statuses.length > 0){\n\t\t\tinsect_statuses.each(function(index, elem){\n\t\t\t\tqueries.push({status: elem.value});\n\t\t\t});\n\t\t}\n\t\tif(insect_taxon_types.length>0){\n\t\t\tif(queries.length == 0){\n\t\t\t\tinsect_taxon_types.each(function(index, elem){\n\t\t\t\t\tqueries.push({type: elem.value});\n\t\t\t\t});\n\t\t\t} else {\n\t\t\t\tvar newQueries = [];\n\t\t\t\tfor(var i=0; i< insect_taxon_types.length; i++){\n\t\t\t\t\tfor(var j=0; j< queries.length; j++){\n\t\t\t\t\t\tvar newObject = jQuery.extend({}, queries[j]);\n\t\t\t\t\t\tnewObject.type = jQuery(insect_taxon_types[i]).val();\n\t\t\t\t\t\tnewQueries.push(newObject);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tqueries = newQueries;\n\t\t\t}\n\t\t}\n\t\tif(foraging.length>0){\n\t\t\tif(queries.length == 0){\n\t\t\t\tfor(var i=0; i< foraging.length; i++)\n\t\t\t\t\tqueries.push({foraging: jQuery(foraging[i]).val()});\n\t\t\t} else {\n\t\t\t\tvar newQueries = [];\n\t\t\t\tfor(var i=0; i< foraging.length; i++){\n\t\t\t\t\tfor(var j=0; j< queries.length; j++){\n\t\t\t\t\t\tvar newObject = jQuery.extend({}, queries[j]);\n\t\t\t\t\t\tnewObject.foraging = jQuery(foraging[i]).val();\n\t\t\t\t\t\tnewQueries.push(newObject);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tqueries = newQueries;\n\t\t\t}\n\t\t}\n\t\tif(queries.length > 0){\n\t\t\tORgroup = []\n\t\t\tfor(var j=0; j< queries.length; j++){\n\t\t\t\tvar query='*|'+\n\t\t\t\t\t(typeof queries[j].status == 'undefined' ? '.' : queries[j].status) + ':' +\n\t\t\t\t\t(typeof queries[j].type == 'undefined' ? '.' : queries[j].type.charAt(0).toUpperCase()) + ':' +\n\t\t\t\t\t(typeof queries[j].foraging == 'undefined' ? '.' : queries[j].foraging) + ':' +\n\t\t\t\t\t(typeof queries[j].taxon == 'undefined' ? '.....' : pad(queries[j].taxon,5)) + '|*';\n\t\t\t\tORgroup.push(new OpenLayers.Filter.Comparison({type: OpenLayers.Filter.Comparison.LIKE, property: 'insect_search', value: query}));\n\t\t\t}\n\t\t\tfilters.push(combineOR(ORgroup));\n\t\t}\n\t} else {\n\t\tif(insect != '') {\n\t\t\tvar insect_taxon_filter = new OpenLayers.Filter.Comparison({type: OpenLayers.Filter.Comparison.LIKE, property: 'insect_taxon_ids', value: '*|'+insect+'|*'});\n\t\t\tif(insect_name.substring(0,13) == 'Taxon inconnu'){\n\t\t\t\tORgroup = [];\n\t\t\t\tORgroup.push(insect_taxon_filter);\n//\t\t\t\tORgroup.push(new OpenLayers.Filter.Comparison({type: OpenLayers.Filter.Comparison.LIKE, property: 'status_insecte_code', value: '*X*'}));\n\t\t\t\tfilters.push(combineOR(ORgroup));\n\t\t\t} else {\n\t\t\t\tjQuery('#results-validate-taxon,#results-validate-page').show();\n\t\t\t\tfilters.push(insect_taxon_filter);\n\t\t\t}\n\t\t}\n\t\tORgroup = [];\n\t\tinsect_statuses.each(function(index, elem){\n\t\t\tORgroup.push(new OpenLayers.Filter.Comparison({type: OpenLayers.Filter.Comparison.EQUAL_TO, property: 'status_insecte_code', value: elem.value}));\n\t\t});\n\t\tif(ORgroup.length >= 1) filters.push(combineOR(ORgroup));\n\t\tORgroup = [];\n\t\tinsect_taxon_types.each(function(index, elem){\n\t\t\tORgroup.push(new OpenLayers.Filter.Comparison({type: OpenLayers.Filter.Comparison.EQUAL_TO, property: 'insect_taxon_type', value: elem.value}));\n\t\t});\n\t\tif(ORgroup.length >= 1) filters.push(combineOR(ORgroup));\n\t\tORgroup = []\n\t\tforaging.each(function(index, elem){\n\t\t\tORgroup.push(new OpenLayers.Filter.Comparison({type: OpenLayers.Filter.Comparison.EQUAL_TO, property: 'notonaflower_id', value: elem.value}));\n\t\t});\n\t\tif(ORgroup.length >= 1) filters.push(combineOR(ORgroup));\n\t}\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\t\n  \tORgroup = [];\n  \tjQuery('#conditions-filter-body').find('[name^=smpAttr:" . $skyAttrID . "]').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:" . $temperatureAttrID . "]').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:" . $windAttrID . "]').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:" . $shadeAttrID . "]').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_txt','datefin_txt','geom','nom','image_de_environment','image_de_la_fleur','flower_id']\n\t\tfeature = '" . $args['search_collections_layer'] . "';\n  \t} else {\n  \t\tfeature = '" . $args['search_insects_layer'] . "';\n  \t\tproperties = ['insect_id','collection_id','geom','image_d_insecte'];\n  \t}\n  \t\n    var style = new OpenLayers.Style({\n                    pointRadius: '\${radius}',\n                    fillColor: '#ffcc66',\n                    fillOpacity: 0.8,\n                    strokeColor: '#cc6633',\n                    strokeWidth: 2,\n                    strokeOpacity: 1\n       }, {context: {radius: function(feature) {\n                     if(feature.attributes.count>=10) return 10;\n                     if(feature.attributes.count>=5) return 8;\n                     if(feature.attributes.count>1) return 6;\n                     return 4;}}\n    });\n    var styleMap = new OpenLayers.StyleMap({\"default\": style});\n\tsearchResults = null;  \n\tvar strategy = new OpenLayers.Strategy.Fixed({preload: false, autoActivate: false});\n\tclusterStrategy = new OpenLayers.Strategy.Cluster();\n\tsearchResultsLayer = new OpenLayers.Layer.Vector('Search Layer', {\n\t\t  styleMap: styleMap,\n\t      strategies: [strategy, clusterStrategy],\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\t  filter: new OpenLayers.Filter.Logical({type: OpenLayers.Filter.Logical.AND, filters: filters})\n\t});\n\tif(forCollections) {\n\t\tjQuery('#results-collections-results').empty().append('<div class=\"collection-loading-panel\" ><img src=\"" . $base . drupal_get_path('module', 'iform') . "/media/images/ajax-loader2.gif\" />" . lang::get('loading') . "...</div>');\n\t\tsearchResultsLayer.events.register('featuresadded', {}, function(a1){\n\t\t\tsearchResultsLayer.events.remove('featuresadded');\n\t\t\tsearchResults = clusterStrategy;\n\t\t\tsearchResults.type = 'C';\n\t\t\tsetCollectionPage(1);\n\t\t});\n\t\tsearchResultsLayer.events.register('loadend', {}, function(){\n\t\t\tif(searchResultsLayer.features.length == 0){\n\t\t\t\tjQuery('#results-validate-taxon,#results-validate-page').hide();\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=\"" . $base . drupal_get_path('module', 'iform') . "/media/images/ajax-loader2.gif\" />" . lang::get('loading') . "...</div>');\n\t\tsearchResultsLayer.events.register('featuresadded', {}, function(a1){\n\t\t\tsearchResultsLayer.events.remove('featuresadded');\n\t\t\tsearchResults = clusterStrategy;\n\t\t\tsearchResults.type = 'I';\n\t\t\tsetInsectPage(1);\n\t\t});\n\t\tsearchResultsLayer.events.register('loadend', {}, function(){\n\t\t\tif(searchResultsLayer.features.length == 0){\n\t\t\t\tjQuery('#results-validate-taxon,#results-validate-page').hide();\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(searchResultsLayer);\n\tstrategy.load({});\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\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-form').hide();\n\t\t\tloadDeterminations(jQuery('[name=determination\\:occurrence_id]').val(), 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\tjQuery('.filter-insect-container').filter('[occID='+jQuery('form#fo-express-doubt-form').find('[name=determination\\:occurrence_id]').val()+']').find('.insect-ok').removeClass('insect-ok').addClass('occurrence-dubious');\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-edit-insect-id-form').ajaxForm({ // no alerts\n\tasync: false,\n\tdataType:  'json', \n\tbeforeSubmit:   function(data, obj, options){\n\t\tclearErrors('form#fo-edit-insect-id-form');\n\t\tif (!jQuery('form#fo-edit-insect-id-form input').valid()) {\n\t\t\tmyScrollToError();\n\t\t\treturn false;\n\t\t};\n\t\tvar found=jQuery('#fo-edit-insect-id-form .fo-edit-id-list-entry').length>0;\n\t\tjQuery('form#fo-edit-insect-id-form').find('[name=determination\\:deleted]').removeAttr('checked');\n\t\tif(!found)\n\t\t\tdata.push({name: 'determination\\:taxa_taxon_list_id_list[]', value: ''});\n   \t\treturn true;\n\t},\n\tsuccess:   function(data){\n\t\tif(data.error == undefined){\n\t\t\tloadDeterminations(jQuery('[name=determination\\:occurrence_id]').val(), 'form#fo-new-insect-id-form', function(args, type){\n  \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});\n\njQuery('form#fo-edit-flower-id-form').ajaxForm({ // no tool attached, no alerts\n\tasync: false,\n\tdataType:  'json', \n\tbeforeSubmit:   function(data, obj, options){\n\t\tclearErrors('form#fo-edit-flower-id-form');\n\t\tif (!jQuery('form#fo-edit-flower-id-form input').valid()) {\n\t\t\tmyScrollToError();\n\t\t\treturn false;\n\t\t};\n\t\tvar found=jQuery('#fo-edit-flower-id-form .fo-edit-id-list-entry').length>0;\n\t\tjQuery('form#fo-edit-flower-id-form').find('[name=determination\\:deleted]').removeAttr('checked');\n\t\tif(!found) // if no array fields there, ensure array is blanked out.\n\t\t\tdata.push({name: 'determination\\:taxa_taxon_list_id_list[]', value: ''});\n\t\treturn true;\n\t},\n\tsuccess:   function(data){\n\t\tif(data.error == undefined){\n\t\t\tloadDeterminations(jQuery('[name=determination\\:occurrence_id]').val(), 'form#fo-new-flower-id-form', function(args, type){\n\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});\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\t// All new determinations are stored as list, even if only one\n\t\t// TODO in future, if only have one put it in the ttlid.\n\t\tif (jQuery('form#fo-new-insect-id-form [name=determination\\:taxa_taxon_list_id]').val() == '' &&\n\t\t\t\tjQuery('form#fo-new-insect-id-form [name=determination\\:taxa_taxon_list_id_list\\[\\]]').length == 0 &&\n\t\t\t\tjQuery('form#fo-new-insect-id-form [name=determination\\:determination_type]').val() != 'X') {\n\t\t\tvalid = false;\n\t\t\tvar label = \$('<p/>')\n\t\t\t\t.addClass('inline-error')\n\t\t\t\t.html(\$.validator.messages.required);\n\t\t\tlabel.insertBefore('form#fo-new-insect-id-form [name=determination\\:taxa_taxon_list_id]');\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('.filter-insect-container').filter('[occID='+jQuery('form#fo-express-doubt-form').find('[name=determination\\:occurrence_id]').val()+']')\n\t\t\t\t.find('.insect-ok').removeClass('insect-ok')\n\t\t\t\t.addClass(jQuery(insectIDstruc.mainForm+' [name=determination\\:determination_type]').val() == 'X' ? 'occurrence-dubious' : 'occurrence-valid');\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(insectIDstruc.mainForm +' [name=determination\\:taxa_taxon_list_id_list\\[\\]]').remove();\n\t\t\tjQuery('#fo-new-insect-id-form').hide();\n\t\t\tjQuery('#fo-edit-insect-id').addClass('ui-accordion-content-active');\n\t\t\tloadDeterminations(jQuery('[name=determination\\:occurrence_id]').val(), '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\t// All new determinations are stored as list, even if only one\n\t\t// TODO in future, if only have one put it in the ttlid.\n\t\tif (jQuery('form#fo-new-flower-id-form [name=determination\\:taxa_taxon_list_id_list\\[\\]]').length == 0 &&\n\t\t\t\tjQuery('form#fo-new-flower-id-form [name=determination\\:determination_type]').val() != 'X') {\n\t\t\tvalid = false;\n\t\t\tvar label = \$('<p/>')\n\t\t\t\t.addClass('inline-error')\n\t\t\t\t.html(\$.validator.messages.required);\n\t\t\tlabel.insertBefore('#flower-species-list');\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-form').hide();\n\t\t\tif(!jQuery('#fo-id-history').hasClass('empty')){\n\t\t\t\tjQuery('#fo-id-history').addClass('ui-accordion-content-active');\n\t\t\t\tjQuery('#fo-id-buttons').removeClass('ui-corner-bottom');\n\t\t\t}\n\t  \t\tjQuery('#fo-edit-flower-id').addClass('ui-accordion-content-active');\t\t\n\t\t\t  \t\t\t\t\t\n\t\t\tloadDeterminations(jQuery('[name=determination\\:occurrence_id]').val(), '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});\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, false);\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, " . (user_access('IForm n' . $node->nid . ' delete collection comment') ? "true" : "false") . ");\n  \t\t} else {\n\t\t\talert(data.error);\n\t\t}\n\t} \n});\n";
        if (user_access('IForm n' . $node->nid . ' delete collection')) {
            data_entry_helper::$javascript .= "\njQuery('#fc-delete-collection-form').ajaxForm({\n\t\tasync: false,\n\t\tdataType:  'json',\n\t\tbeforeSubmit:   function(data, obj, options){\n\t\t\tif(!confirm(\"" . lang::get('LANG_Collection_Delete_Confirmation') . "\")){\n\t\t\t\treturn false;\n\t\t\t}\t\n\t\t\tjQuery('#fc_delete_collection_submit_button').addClass('loading-button');\n\t\t\treturn true;\n\t\t},\n\t\tsuccess:   function(data){\n\t\t\tif(data.error != undefined){\n\t\t\t\talert(data.error);\n\t\t\t} else {\n\t\t\t\t// blank out collection in collection list.\n\t\t\t\tjQuery('.filter-collection').filter('[collID='+collection_preferred_object.collection_id+']').each(function(idx, collection){\n\t\t\t\t\tsearchResults.features[jQuery(collection).attr('index')].attributes.deleted= true;\n\t\t\t\t\tjQuery(collection).css('background-color','#FF0000');\n\t\t\t\t\tjQuery(collection).find('.collection-image,.collection-flower-determination,.collection-photoreel,.collection-buttons').remove();\n\t\t\t\t});\n\t\t\t\t// return to filter page\n\t\t\t\tjQuery('#fc-filter-button').click();\n\t\t}},\n\t\tcomplete: function (){\n\t\t\tjQuery('.loading-button').removeClass('loading-button');\n\t\t}\n\t});";
        }
        if (user_access('IForm n' . $node->nid . ' delete insect')) {
            data_entry_helper::$javascript .= "\njQuery('#fo-delete-insect-form').ajaxForm({\n\t\tasync: false,\n\t\tdataType:  'json',\n\t\tbeforeSubmit:   function(data, obj, options){\n\t\t\tif(!confirm(\"" . lang::get('LANG_Insect_Delete_Confirmation') . "\")){\n\t\t\t\treturn false;\n\t\t\t}\t\n\t\t\tjQuery('#fo_delete_insect_submit_button').addClass('loading-button');\n\t\t\treturn true;\n\t\t},\n\t\tsuccess:   function(data){\n\t\t\tif(data.error != undefined){\n\t\t\t\talert(data.error);\n\t\t\t} else {\n\t\t\t\t// blank out insect in gallery search insect list.\n\t\t\t\tjQuery('.filter-insect-container').filter('[occID='+insect_alert_object.insect_id+']').each(function(idx, insect){\n\t\t\t\t\tsearchResults.features[jQuery(insect).attr('index')].attributes.deleted= true;\n\t\t\t\t\tjQuery(insect).children().css('background-color','#FF0000').css('height','');\n\t\t\t\t\tjQuery(insect).find('.determination-flag,.insect-image,.display-button').remove();\n\t\t\t\t});\n\t\t\t\t// remove insect from gallery search collection insect photoreel.\n\t\t\t\tjQuery('.collection-photoreel .thumb').filter('[occID='+insect_alert_object.insect_id+']').remove();\n\t\t\t\t// no need to blank out insect in collection insect list as the collection is refetched when it is redisplayed.\n\t\t\t\t// return to filter search or collection page\n\t\t\t\tif(jQuery('.collection-insect-container').filter('[occID='+insect_alert_object.insect_id+']').length > 0) {\n\t\t\t\t\tjQuery('#fo-collection-button').click();\n\t\t\t\t} else {\n\t\t\t\t\tjQuery('#fo-filter-button').click();\n\t\t\t\t}\n\t\t}},\n\t\tcomplete: function (){\n\t\t\tjQuery('.loading-button').removeClass('loading-button');\n\t\t}\n\t});";
        }
        if (user_access('IForm n' . $node->nid . ' add to front page')) {
            data_entry_helper::$javascript .= "\njQuery('#fc-front-page-form').ajaxForm({ \n\tasync: false,\n\tdataType:  'json', \n\tbeforeSubmit:   function(data, obj, options){\n\t\tif (!jQuery('form#fc-front-page-form').valid()) { return false; }\n  \t\tjQuery('#fc_front_page_submit_button').addClass('loading-button');\n\t\treturn true;\n\t},\n\tsuccess:   function(data){\n\t\tif(data.error != undefined){\n\t\t\talert(data.error);\n\t\t} else {\n\t\t\tif(jQuery('#fc-front-page-form').find('[name^=smpAttr\\:" . $frontPageAttrID . "]')\n\t\t\t\t\t\t.filter('[checked]').val() == '1')\n\t\t\t\tjQuery('#fc-front-page-message').empty().append(\"<span>" . lang::get('LANG_Included_In_Front_Page') . "<span>\");\n\t\t\telse\n\t\t\t\tjQuery('#fc-front-page-message').empty().append(\"<span>" . lang::get('LANG_Removed_From_Front_Page') . "<span>\");\n\t\t\tajaxStack.push(\n\t\t\t\tjQuery.ajax({ \n\t\t\t\t\ttype: \"GET\", \n\t\t\t\t\turl: \"" . $svcUrl . "/data/sample_attribute_value\"  +\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\"&sample_id=\" + data.outer_id + \"&REMOVEABLEJSONP&callback=?\",\n\t\t\t\t\tdataType: 'json',\n\t\t\t\t\tsuccess: function(attrdata) {\n\t\t\t\t\t\tif(!(attrdata instanceof Array)){\n\t\t\t\t\t\t\talertIndiciaError(attrdata);\n\t\t\t\t\t\t} else if (attrdata.length>0) {\n\t\t\t\t\t\t\tfor(i=0; i< attrdata.length; i++){\n\t\t\t\t\t\t\t\tif (attrdata[i].id){\n\t\t\t\t\t\t\t\t\tswitch(parseInt(attrdata[i].sample_attribute_id)){\n\t\t\t\t\t\t\t\t\t\tcase " . $frontPageAttrID . ":\n\t\t\t\t\t\t\t\t\t\t\tjQuery('#fc-front-page-form').find('[name^=smpAttr\\:" . $frontPageAttrID . "]')\n\t\t\t\t\t\t\t\t\t\t\t\t.attr('name', 'smpAttr:" . $frontPageAttrID . ":'+attrdata[i].id)\n\t\t\t\t\t\t\t\t\t\t\t\t.filter('[value='+attrdata[i].raw_value+']')\n\t\t\t\t\t\t\t\t\t\t\t\t.attr('checked', 'checked');\n\t\t\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t}}}}}));\n\t\t\tajaxStack.push(\n\t\t\t\tjQuery.ajax({ \n\t\t\t\t\ttype: \"GET\", \n\t\t\t\t\turl: \"" . $svcUrl . "/data/sample_attribute_value\"  +\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\"&sample_attribute_id=" . $frontPageAttrID . "&value=1&REMOVEABLEJSONP&callback=?\",\n\t\t\t\t\tdataType: 'json',\n\t\t\t\t\tsuccess: function(attrdata) {\n\t\t\t\t\t\tif(!(attrdata instanceof Array)){\n\t\t\t\t\t\t\talertIndiciaError(attrdata);\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tjQuery('#fc-front-page-message').append(\"<br /><span>" . lang::get('LANG_Number_In_Front_Page') . "\"+attrdata.length+\".<span>\");\n\t\t\t\t\t\t}}}));\n    }},\n\tcomplete: function (){\n  \t\tjQuery('.loading-button').removeClass('loading-button');\n  \t}\n});";
        }
        data_entry_helper::$javascript .= "\njQuery('#fc-new-location-form').ajaxForm({ \n\tasync: false,\n\tdataType:  'json', \n\tbeforeSubmit:   function(data, obj, options){\n\t\tif(!confirm(\"" . lang::get('LANG_Localisation_Confirm') . "\")) { return false; }\n\t\tif (!jQuery('form#fc-new-location-form').valid()) { return false; }\n  \t\tjQuery('#fc_location_submit_button').addClass('loading-button');\n\t\treturn true;\n\t},\n\tsuccess:   function(data){\n\t\tif(data.error != undefined){\n\t\t\talert(data.error);\n\t\t} else {\n\t\t\tjQuery('#fc-new-location-message').empty().append(\"<span>" . lang::get('LANG_Location_Updated') . "<span>\");\n\t\t}\n\t},\n\tcomplete: function (){\n  \t\tjQuery('.loading-button').removeClass('loading-button');\n  \t}\n});\n// Boolean attributes: not present = 0;\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\tjQuery('#fo-insect-shade').append(\"" . lang::get('No') . "\"); // default with no attribute is 'No'\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 " . $startTimeAttrID . ":\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 " . $endTimeAttrID . ":\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 " . $skyAttrID . ":\n\t\t\t\t\t\t\tjQuery('#fo-insect-sky').append(convertTerm(attrdata[i].raw_value));\n\t\t\t\t\t\t\tbreak;\n  \t\t\t\t\t\tcase " . $temperatureAttrID . ":\n\t\t\t\t\t\t\tjQuery('#fo-insect-temp').append(convertTerm(attrdata[i].raw_value));\n\t\t\t\t\t\t\tbreak;\n  \t\t\t\t\t\tcase " . $windAttrID . ":\n\t\t\t\t\t\t\tjQuery('#fo-insect-wind').append(convertTerm(attrdata[i].raw_value));\n\t\t\t\t\t\t\tbreak;\n  \t\t\t\t\t\tcase " . $shadeAttrID . ":\n  \t\t\t\t\t\t\tif(attrdata[i].value == '1'){\n\t\t\t\t\t\t\t\tjQuery('#fo-insect-shade').empty().append(\"" . lang::get('Yes') . "\");\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,#fo-insect-foraging').empty();\n\tjQuery('#fo-insect-foraging').append(\"" . lang::get('No') . "\");\n    ajaxStack.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 + \"&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  if (attrdata[i].id){\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 " . $flowerTypeAttrID . ":\n\t\t\t\t\t\t\tjQuery('<span>'+convertTerm(attrdata[i].raw_value)+'</span>').appendTo('#focus-flower-type');\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tcase " . $foragingAttrID . ":\n  \t\t\t\t\t\t\tif(attrdata[i].value == '1'){\n\t\t\t\t\t\t\t\tjQuery('#fo-insect-foraging').empty().append(\"" . lang::get('Yes') . "\");\n  \t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tbreak;\n  }}}}}}));\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 + \"&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 " . $habitatAttrID . ":\n\t\t\t\t\t\t\tif (attrdata[i].raw_value > 0) habitat_string = (habitat_string == '' ? convertTerm(attrdata[i].raw_value) : (habitat_string + ', ' + convertTerm(attrdata[i].raw_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(prepend, path, target, ratio, allowFull, callback){\n    var img = new Image();\n\tvar item = jQuery(img).load(function () {\n\t\ttarget.removeClass('loading').height('').append(this);\n\t\ttarget.append(this);\n\t\tif(this.width/this.height > ratio){\n\t\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\t\tjQuery(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) callback(this);\n\t}).attr('src', '" . data_entry_helper::$base_url . data_entry_helper::$indicia_upload_path . "'+prepend+path);\n\tif(allowFull)\n\t\titem.click(function(){\n\t\t\twindow.open ('" . data_entry_helper::$base_url . data_entry_helper::$indicia_upload_path . "'+path, 'newwindow', config='toolbar=no, menubar=no, location=no, directories=no, status=no')\n\t\t});\n}\n\nloadImage = function(imageTable, key, keyValue, target, imageRatio, callback, prepend, allowfull){\n    jQuery(target).empty();\n    ajaxStack.push(jQuery.ajax({ \n        type: \"GET\",\n        myTarget: target,\n        myRatio: imageRatio,\n        myCallback: callback,\n        myPrepend: prepend,\n        myAllowfull: allowfull,\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), this.myRatio, this.myAllowfull, this.myImgCallback);\n\t\t\tif(this.myCallback) this.myCallback(imageData[0]);\n\t\t  }},\n\t\tdataType: 'json'\n\t}));\n}\n\nsetIDButtons = function (expert, owner, reidentifiable, can_doubt, type){\n  if(expert === true) jQuery('#fo-id-buttons').addClass('expert');\n  else if(expert===false) jQuery('#fo-id-buttons').removeClass('expert'); // leave possiblity of 'other' which does nothing\n\n  if(owner === true) jQuery('#fo-id-buttons').addClass('owner');\n  else if(owner===false) jQuery('#fo-id-buttons').removeClass('owner'); // leave possiblity of 'other' which does nothing\n\n  if(reidentifiable === true) jQuery('#fo-id-buttons').addClass('reidentifiable');\n  else if(reidentifiable===false) jQuery('#fo-id-buttons').removeClass('reidentifiable'); // leave possiblity of 'other' which does nothing\n\n  if(can_doubt === true) {\n    jQuery('#fo-id-buttons').addClass('can_doubt');\n    jQuery('#fo-doubt-button').show();\n  } else if(can_doubt === false) {\n    jQuery('#fo-id-buttons').removeClass('can_doubt');\n    jQuery('#fo-doubt-button').hide();\n  }  // leave possiblity of 'other' which does nothing\n\n  if(jQuery('#fo-id-buttons').hasClass('expert') ||\n      (jQuery('#fo-id-buttons').hasClass('owner') && jQuery('#fo-id-buttons').hasClass('reidentifiable'))){\n    jQuery(type=='I'?'#fo-new-insect-id-button':'#fo-new-flower-id-button').show();\n  } else {\n    jQuery(type=='I'?'#fo-new-insect-id-button':'#fo-new-flower-id-button').hide();\n  }\n\n  if(jQuery('#fo-id-buttons').hasClass('expert') ||\n      jQuery('#fo-id-buttons').hasClass('can_doubt') || \n      (jQuery('#fo-id-buttons').hasClass('owner') && jQuery('#fo-id-buttons').hasClass('reidentifiable'))){\n    if(jQuery('#fo-id-history:visible').length>0)\n      jQuery('#fo-id-buttons').show().removeClass('ui-corner-bottom'); // history is visible so current ID will not have this class\n    else {\n      jQuery('#fo-id-buttons').show().addClass('ui-corner-bottom'); // history is visible\n      jQuery('#fo-current-id').removeClass('ui-corner-bottom');\n    }\n  } else {\n    jQuery('#fo-id-buttons').hide();\n    if(jQuery('#fo-id-history:visible').length==0)\n      jQuery('#fo-current-id').addClass('ui-corner-bottom');\n  }\n}\n\njQuery('.removeRow').live('click', function (){\n  jQuery(this).closest('tr').remove();\n});\n\n// this function is called to reset the page after a doubt is emitted, an insect or flower is reidentified, a determination is changed\n// The data is loaded into the current-id section, with historic data displayed i reverse chronological order in the relevant history section.\n// In addition the express doubt form is loaded with the current data, as is the direct modificaton form.\n// If an expert, the data is copied down to the new id form to allow it to be validated, otherwise this is blanked out.\nloadDeterminations = function(keyValue, newIDForm, callback, isExpert, canDoubt, taxaList, type){\n    jQuery('#fo-id-history').show().empty().append('<strong>" . lang::get('LANG_History_Title') . "</strong>').addClass('empty');\n\tjQuery('#fo-current-id').empty().removeClass('ui-corner-bottom');\n\tjQuery('#poll-banner').empty();\n\tsetIDButtons(null, null, null, false, type);\n\t// doubt comment is reset when the button is pressed.\n\t// NB all occurrence ids are set by loadInsect or loadFlower. doubt generates a new record\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-express-doubt-form').find('[name=determination\\:taxa_taxon_list_id_list\\[\\]]').remove();\n\tjQuery('#fo-doubt-button').hide();\n\tjQuery(newIDForm).find('[name=determination\\:taxa_taxon_list_id]').val(''); // ttlidlist added below.\n\tjQuery(newIDForm).find('[name=determination\\:taxon_extra_info]').val('');\n\tjQuery(newIDForm).find('[name=determination\\:taxon_details]').val(''); // TODO NOT SURE IF NEEDED.\n\tjQuery(newIDForm).find('[name=determination\\:taxa_taxon_list_id_list\\[\\]]').remove(); // needed for insects: not needed for flowers\n\tjQuery(newIDForm).find('.flower-species-list-entry').remove();\n\tif(isExpert) {\n\t\tjQuery(newIDForm).find('[name=determination\\:determination_type]').val('C'); // for expert, default to confirmed.\n\t\tjQuery('#fo-flower-expert-det-type').html('" . lang::get('LANG_Det_Type_C') . "');\n\t} else {\n\t\tjQuery(newIDForm).find('[name=determination\\:determination_type]').val('A');\n\t}\n\tjQuery('#id-flower-unknown').removeAttr('checked');\n\t\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&deleted=f&orderby=id&REMOVEABLEJSONP&callback=?&occurrence_id=\" + keyValue,\n\t\tparams: {newIDForm: newIDForm,\n\t\t\t\tcallback: callback,\n\t\t\t\tisExpert: isExpert,\n\t\t\t\tcanDoubt: canDoubt,\n\t\t\t\ttaxaList: taxaList,\n\t\t\t\ttype: type},\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\t// potentially 3 forms to populate.\n   \t\t\t// 1) General new identification form\n   \t\t\t// 2) Express a doubt form\n   \t\t\t// 3) Special direct determination modification form\n   \t\t\t// Also need to set up the means to Delete the determination.\n\t\t\tif(detData.length==1){\n\t\t\t\tjQuery('#fo-id-history').hide();\n\t\t\t\tjQuery(jQuery('#fo-id-buttons:visible').length>0?'#fo-id-buttons':'#fo-current-id').addClass('ui-corner-bottom');\n\t\t\t} else\n\t\t\t\tjQuery(jQuery('#fo-id-buttons:visible').length>0?'#fo-id-buttons':'#fo-current-id').removeClass('ui-corner-bottom');\n\t\t\tvar i = detData.length-1;\n\t\t\t// list is returned as array with braces - convert to square barckets\n\t\t\t\n" . (isset($args['deleteable_user_id']) && $args['deleteable_user_id'] != '' && $args['deleteable_user_id'] == $user->uid ? "\t\t\t//*******************************************************\n\t\t\t// fill in the special direct determination modification form\n\t\t\t// has table for ttlidlist.\n\t\t\tvar mF = jQuery(this.params.type=='I'?'#fo-edit-insect-id':'#fo-edit-flower-id');\n\t\t\tmF.find('[name=determination\\:id]').val(detData[i].id);\n\t\t\tmF.find('[name=determination\\:deleted]').removeAttr('checked');\n\t\t\tmF.find('[name=determination\\:cms_ref]').val(detData[i].cms_ref);\n\t\t\tmF.find('[name=determination\\:person_name]').val(detData[i].person_name);\n\t\t\tmF.find('[name=determination\\:email_address]').val(detData[i].email_address);\n\t\t\tmF.find('[name=determination\\:determination_type]').val(detData[i].determination_type);\n\t\t\tmF.find('[name=determination\\:taxon_details]').val(detData[i].taxon_details==null?'':detData[i].taxon_details);\n\t\t\tmF.find('[name=determination\\:taxon_extra_info]').val(detData[i].taxon_extra_info==null?'':detData[i].taxon_extra_info);\n\t\t\tmF.find('[name=determination\\:comment]').val(detData[i].comment==null?'':detData[i].comment);\n\t\t\tmF.find('[name=determination\\:taxa_taxon_list_id]').val(detData[i].taxa_taxon_list_id==null?'':detData[i].taxa_taxon_list_id);\n\t\t\tmF.find('.fo-edit-id-list-entry').remove();\n" : "\t\t\tvar mF = false;\n") . "\t\t\t// thorughout the following section the callback data is setup: this is for alerting.\n\t\t\tvar callbackEntry = {date: detData[i].updated_on, user_id: detData[i].cms_ref, taxa: []};\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 = htmlspecialchars(detData[i].taxon);\n\t\t\t\tcallbackEntry.taxa.push(detData[i].taxon);\n  \t\t\t}\n\t\t\t//*******************************************************\n\t\t\t// fill in the express doubt form: note that has been cleared down above: no determination ID as generating a new record.\n\t\t\t// ttlidlist are added as hidden fields. Doubt is expressed on existing data.\n\t\t\tjQuery('#fo-express-doubt-form').find('[name=determination\\:taxa_taxon_list_id]').val(detData[i].taxa_taxon_list_id); // ttlidlist added below.\n\t\t\tjQuery('#fo-express-doubt-form').find('[name=determination\\:taxon_extra_info]').val(detData[i].taxon_extra_info==null ? '' : detData[i].taxon_extra_info);\n\t\t\t// TODO\t\t\tjQuery('#fo-express-doubt-form').find('[name=determination\\:taxon_details]').val(detData[i].taxon_details); NOT SURE IF NEEDED.\n\t\t\t//*******************************************************\n\t\t\t// fill in the new ID form : all occurrence_ids set by load* functions.\n\t\t\tif(isExpert) {\n\t\t\t\tif(this.params.type == 'I')\n\t\t\t\t\tjQuery(this.params.newIDForm).find('[name=determination:taxa_taxon_list_id]').val(detData[i].taxa_taxon_list_id);\n\t\t\t\telse {\n\t\t\t\t\tjQuery(this.params.newIDForm).find('[name=determination:taxa_taxon_list_id]').val('');\n\t\t\t\t\tif(detData[i].taxa_taxon_list_id!='' && detData[i].taxa_taxon_list_id != null) // for flowers convert to table list format\n\t\t\t\t\t\tjQuery('#flower-species-list-body').append('<tr class=\"flower-species-list-entry\"><td>'+htmlspecialchars(detData[i].taxon)+'<input type=\"hidden\" name=\"determination:taxa_taxon_list_id_list[]\" value=\"'+detData[i].taxa_taxon_list_id+'\"></td><td><img class=\"removeRow\" src=\"/misc/watchdog-error.png\" alt=\"" . lang::get('Remove this entry') . "\" title=\"" . lang::get('Remove this entry') . "\"/></td></tr>');\n\t\t\t\t}\n\t\t\t\tjQuery(this.params.newIDForm).find('[name=determination\\:taxon_extra_info]').val(detData[i].taxon_extra_info==null ? '' : detData[i].taxon_extra_info);\n\t\t\t\tjQuery(this.params.newIDForm).find('[name=determination\\:taxon_details]').val(detData[i].taxon_details);\n\t\t\t}\n\t\t\t//*******************************************************\n\t\t\t// work out the multitaxon situation, and store in the 3 forms.\n\t\t\tvar decoded = (detData[i].taxa_taxon_list_id_list != null && detData[i].taxa_taxon_list_id_list != '' && detData[i].taxa_taxon_list_id_list != '{}') ? JSON.parse(detData[i].taxa_taxon_list_id_list.replace('{','[').replace('}',']')) : [];\n\t\t\tif(decoded.length>0){\n\t\t\t\tfor(var j=0; j < decoded.length; j++){\n\t\t\t\t\tvar species='';\n\t\t\t\t\tfor(var k = 0; k< this.params.taxaList.length; k++)\n\t\t\t\t\t\tif(this.params.taxaList[k].id == decoded[j]) {\n\t\t\t\t\t\t\tstring = (string == '' ? '' : string + ', ') + htmlspecialchars(this.params.taxaList[k].taxon);\n\t\t\t\t\t\t\tspecies = htmlspecialchars(this.params.taxaList[k].taxon);\n\t\t\t\t\t\t\tresultsText = resultsText + (j == 0 ? '' : '<br />&nbsp;&nbsp;') + htmlspecialchars(this.params.taxaList[k].taxon);\n\t\t\t\t\t\t\tcallbackEntry.taxa.push(this.params.taxaList[k].taxon);\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\tif(mF) mF.find('.autocompleteRow').before('<tr class=\"fo-edit-id-list-entry\"><td>'+species+'</td><td><input type=\"hidden\" name=\"determination:taxa_taxon_list_id_list[]\" value=\"'+decoded[j]+'\">'+decoded[j]+'</td><td><img class=\"removeRow\" src=\"/misc/watchdog-error.png\" alt=\"" . lang::get('Remove this entry') . "\" title=\"" . lang::get('Remove this entry') . "\"/></td></tr>');\n\t\t\t\t\tjQuery('#fo-express-doubt-form').append('<input type=\"hidden\" name=\"determination:taxa_taxon_list_id_list[]\" value=\"'+decoded[j]+'\" />');\n\t\t\t\t\tif(isExpert){\n\t\t\t\t\t\tif(this.params.type == 'I')\n\t\t\t\t\t\t\tjQuery(this.params.newIDForm).append('<input type=\"hidden\" name=\"determination:taxa_taxon_list_id_list[]\" value=\"'+decoded[j]+'\"/>');\n\t\t\t\t\t\telse\n\t\t\t\t\t\t\tjQuery('#flower-species-list-body').append('<tr class=\"flower-species-list-entry\"><td>'+species+'<input type=\"hidden\" name=\"determination:taxa_taxon_list_id_list[]\" value=\"'+decoded[j]+'\"></td><td><img class=\"removeRow\" src=\"/misc/watchdog-error.png\" alt=\"" . lang::get('Remove this entry') . "\" title=\"" . lang::get('Remove this entry') . "\"/></td></tr>');\n\t\t\t\t\t}\n  \t\t\t\t}\n\t\t\t\tif(isExpert)\n\t\t\t\t\tjQuery('.taxa_list').append(resultsText+ ' }');\n\t\t\t}\n\t\t\tcallbackArgs.push(callbackEntry);\n\t\t\tjQuery('#poll-banner').append(string); // dont include extra info in banner\n\t\t\tif(detData[i].taxon_extra_info != '' && detData[i].taxon_extra_info != null && detData[i].taxon_extra_info != 'null'){\n\t\t\t\tstring = (string == '' ? '' : string + ' ') + '('+htmlspecialchars(detData[i].taxon_extra_info)+')';\n\t\t\t}\n\t\t\tjQuery(this.params.newIDForm).find('[name=determination:taxon_extra_info]').val(detData[i].taxon_extra_info==null ? '' : detData[i].taxon_extra_info);\n\t\t\t//*******************************************************\n\t\t\t// Optionally add delete button to current identification.\n\t\t\tif((this.params.type == 'I' && " . (user_access('IForm n' . $node->nid . ' delete insect determination') ? 'true' : 'false') . ") || \n\t\t\t\t\t(this.params.type == 'F' && " . (user_access('IForm n' . $node->nid . ' delete flower determination') ? 'true' : 'false') . " && detData.length>1)){ // can't delete the flower determination if it is the only one\n\t\t\t\tvar delButton = jQuery('<span class=\"main-determination-delete-button\" style=\"float: right;\"><img src=\"/misc/watchdog-error.png\" style=\"vertical-align: middle;\"></span>').appendTo('#fo-current-id');\n\t\t\t\tvar delForm = jQuery('<form action=\"" . iform_ajaxproxy_url($node, 'determination') . "\" method=\"POST\" style=\"display: none;\"><input type=\"hidden\" name=\"website_id\" value=\"" . $args['website_id'] . "\" /><input type=\"hidden\" name=\"determination:id\" value=\"'+detData[i].id+'\" /><input type=\"hidden\" name=\"determination:deleted\" value=\"t\" /></form>').appendTo(delButton);\n\t\t\t\tdelForm.ajaxForm({\n\t\t\t\t\tasync: false,\n\t\t\t\t\tdataType:  'json',\n\t\t\t\t\tparams: {occID: detData[i].occurrence_id, // these persist\n\t\t\t\t\t\t\tnewIDForm: this.params.newIDForm,\n\t\t\t\t\t\t\tisExpert: this.params.isExpert,\n\t\t\t\t\t\t\tcanDoubt: this.params.canDoubt,\n\t\t\t\t\t\t\ttaxaList: this.params.taxaList,\n\t\t\t\t\t\t\ttype: this.params.type},\n\t\t\t\t\tsuccess:   function(data){\n\t\t\t\t\t\tif(data.error == undefined){\n\t\t\t\t\t\t\tif(this.params.type == 'I'){\n\t\t\t\t\t\t\t\t// flag out insect in gallery search insect list as modified.\n\t\t\t\t\t\t\t\tjQuery('.filter-insect-container').filter('[occID='+this.params.occID+']').each(function(idx, insect){\n\t\t\t\t\t\t\t\t\tsearchResults.features[jQuery(insect).attr('index')].attributes.modified= true;\n\t\t\t\t\t\t\t\t\tjQuery(insect).css('background-color','#00FFFF');\n\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\t// gallery search collection insect photoreel doesn't need to change.\n\t\t\t\t\t\t\t\t// no need to change insect in collection insect list as the collection is refetched when it is redisplayed.\n\t\t\t\t\t\t\t} else { //type == 'F' Flower\n\t\t\t\t\t\t\t\t// flag flower in gallery search collection list as modified.\n\t\t\t\t\t\t\t\tjQuery('.collection-flower-determination').filter('[occID='+this.params.occID+']').css('background-color','#00FFFF');\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tloadDeterminations(this.params.occID, this.params.newIDForm, null, this.params.isExpert, this.params.canDoubt, this.params.taxaList, this.params.type); // no alert\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\talert(data.error);\n\t\t\t\t\t\t}\n\t\t\t\t\t} \n\t\t\t\t});\n\t\t\t\tdelButton.click(function(e){\n\t\t\t\t  e.preventDefault();\n\t\t\t\t  if(!confirm(\"" . lang::get('LANG_Determination_Delete_Confirmation') . "\")) return;\n\t\t\t\t  var me = \$(e.target.parentNode);\n\t\t\t\t  me.find('form').submit();\n\t\t\t\t});\n\t\t\t}\n\t\t\t//*******************************************************\n\t\t\tjQuery('<p>' + (string != '' ? '<strong>'+string+ '</strong> ' : '') + '" . lang::get('LANG_Comment_By') . "' + detData[i].person_name + ' ' + convertDate(detData[i].updated_on,false) + '</p>').appendTo('#fo-current-id');\n\t\t\tsetIDButtons(null, null, detData[i].determination_type != 'C', this.params.canDoubt && detData[i].determination_type == 'A', this.params.type);\n\t\t\t//*******************************************************\n\t\t\t// Add relevant text and flags to current identification.\n\t\t\t// Type 'A' - do nothing\n\t\t\tif(detData[i].determination_type == 'B'){\n\t\t\t\tjQuery(\"<p>" . lang::get('LANG_Doubt_Expressed') . "</p>\").appendTo('#fo-current-id');\n\t\t\t\tjQuery('#fo-current-id').prepend(\"<div class='determination-flag occurrence-dubious'></div>\");\n\t\t\t} else if(detData[i].determination_type == 'C'){\n\t\t\t\t// This has been set by an expert. If it is the same as the previous determination, then it has been confirmed,\n\t\t\t\t// If different then it is has been corrected. Use different messages.\n\t\t\t\t// Ideally could be able to tell if bulk validation - but cant!\n\t\t\t\tjQuery('#fo-current-id').prepend(\"<div class='determination-flag occurrence-valid'></div>\");\n\t\t\t\tif(i==0 || (detData[i].taxon == detData[i-1].taxon && detData[i].taxa_taxon_list_id_list == detData[i-1].taxa_taxon_list_id_list))\n\t\t\t\t  jQuery(\"<p>" . lang::get('LANG_Determination_Valid') . "</p>\").appendTo('#fo-current-id');\n\t\t\t\telse\n\t\t\t\t  jQuery(\"<p>" . lang::get('LANG_Determination_Corrected') . "</p>\").appendTo('#fo-current-id');\n\t\t\t} else if(detData[i].determination_type == 'I'){\n\t\t\t\tjQuery(\"<p>" . lang::get('LANG_Determination_Incorrect') . "</p>\").appendTo('#fo-current-id');\n\t\t\t\tjQuery('#fo-current-id').prepend(\"<div class='determination-flag occurrence-dubious'></div>\");\n\t\t\t} else if(detData[i].determination_type == 'U'){\n\t\t\t\tjQuery(\"<p>" . lang::get('LANG_Determination_Unconfirmed') . "</p>\").appendTo('#fo-current-id');\n\t\t\t\tjQuery('#fo-current-id').prepend(\"<div class='determination-flag occurrence-dubious'></div>\");\n\t\t\t} else if(detData[i].determination_type == 'X'){\n\t\t\t\tjQuery(\"<p>" . lang::get('LANG_Determination_Unknown') . "</p>\").appendTo('#fo-current-id');\n//\t\t\t\tjQuery('#fo-current-id').prepend(\"<div class='determination-flag occurrence-unknown'></div>\");\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('#fo-current-id');\n\t\t\t}\n\t\t\t//*******************************************************\n\t\t\t// fill in identification history, with optional delete buttons\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\tjQuery('#fo-id-history').removeClass('empty');\n\t\t\t\tvar item = jQuery('<div></div>').attr('detID',detData[i].id).addClass('history-item').appendTo('#fo-id-history');\n\t\t\t\tif((this.params.type == 'I' && " . (user_access('IForm n' . $node->nid . ' delete insect determination') ? 'true' : 'false') . ") || \n\t\t\t\t\t\t(this.params.type == 'F' && " . (user_access('IForm n' . $node->nid . ' delete flower determination') ? 'true' : 'false') . ")){\n\t\t\t\t\tvar delButton = jQuery('<span style=\"float: right;\"><img src=\"/misc/watchdog-error.png\" style=\"vertical-align: middle;\"></span>').appendTo(item);\n\t\t\t\t\tvar delForm = jQuery('<form action=\"" . iform_ajaxproxy_url($node, 'determination') . "\" method=\"POST\" style=\"display: none;\"><input type=\"hidden\" name=\"website_id\" value=\"" . $args['website_id'] . "\" /><input type=\"hidden\" name=\"determination:id\" value=\"'+detData[i].id+'\" /><input type=\"hidden\" name=\"determination:deleted\" value=\"t\" /></form>').appendTo(delButton);\n\t\t\t\t\tdelForm.ajaxForm({\n\t\t\t\t\t\tasync:    false,\n\t\t\t\t\t\tdataType: 'json',\n\t\t\t\t\t\tparams: {occID: detData[i].occurrence_id, // these persist\n\t\t\t\t\t\t\ttype: this.params.type},\n\t\t\t\t\t\tsuccess:  function(data){\n\t\t\t\t\t\t\tif(data.error == undefined){\n\t\t\t\t\t\t\t\t// we're just about to remove the historic ID: if there is only one, that means this will leave the main\n\t\t\t\t\t\t\t\t// ID as the only one: for flowers we can't remove the last ID.\n\t\t\t\t\t\t\t\tif(this.params.type == 'F' && jQuery('.history-item').length == 1){\n\t\t\t\t\t\t\t\t\tjQuery('.main-determination-delete-button').remove();\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tjQuery('.history-item').filter('[detID='+data.outer_id+']').remove();\n\t\t\t\t\t\t\t} else { alert(data.error); }\n\t\t\t\t\t\t} \n\t\t\t\t\t});\n\t\t\t\t\tdelButton.click(function(e){\n\t\t\t\t\t  e.preventDefault();\n\t\t\t\t\t  if(!confirm(\"" . lang::get('LANG_Determination_Delete_Confirmation') . "\")) return;\n\t\t\t\t\t  var me = \$(e.target.parentNode);\n\t\t\t\t\t  me.find('form').submit();\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t\tif(detData[i].taxon != '' && detData[i].taxon != null){\n\t\t\t\t\tstring = htmlspecialchars(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< this.params.taxaList.length; k++)\n\t\t\t\t\t\t\tif(this.params.taxaList[k].id == resultsIDs[j]) {\n\t\t\t\t\t\t\t\tstring = (string == '' ? '' : string + ', ') + htmlspecialchars(this.params.taxaList[k].taxon);\n\t\t\t\t\t\t\t\tcallbackEntry.taxa.push(this.params.taxaList[k].taxon);\n\t\t\t\t\t\t\t\tbreak;\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 && detData[i].taxon_extra_info != 'null'){\n\t\t\t\t\tstring = (string == '' ? '' : string + ' ') + '('+htmlspecialchars(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-id-history').hide();\n\t\t\tjQuery(jQuery('#fo-id-buttons:visible').length>0?'#fo-id-buttons':'#fo-current-id').addClass('ui-corner-bottom');\n\t\t\tjQuery(this.params.type=='I'?'#fo-edit-insect-id':'#fo-edit-flower-id').removeClass('ui-accordion-content-active');\n\t\t\tjQuery('#fo-current-id').append(\"<div class='determination-flag occurrence-unknown'></div><p>" . lang::get('LANG_No_Determinations') . "</p>\");\n\t\t\tsetIDButtons(null, null, true, false, this.params.type); // can re-identify unidentified species \n\t\t\tjQuery('#poll-banner').append(\"" . lang::get('LANG_No_Determinations') . "\");\n\t\t\tif(isExpert) {\n\t\t\t\tjQuery(this.params.newIDForm).find('[name=determination\\:determination_type]').val('X');\n\t\t\t\tjQuery('#fo-flower-expert-det-type').html('" . lang::get('LANG_Det_Type_X') . "');\n\t\t\t\tjQuery('#id-flower-unknown').attr('checked','checked');\n\t\t\t}\n\t\t  }\n\t\t  if(this.params.callback) this.params.callback(callbackArgs, this.params.type);\n\t\t}  \n\t}));\n\t// when the occurrence is loaded (eg in loadInsect) all determination:occurrence_ids are set.\n\tjQuery(newIDForm).find('[name=determination\\:determination_type]').val(isExpert ? 'C' : 'A');\n};\n// direct determination form autocompletes\njQuery('input#insectAutocomplete1').autocomplete(insectTaxa,\n      { matchContains: true,\n        parse: function(data)\n        {\n          var results = [];\n          jQuery.each(data, function(i, item) {\n            results[results.length] = { 'data' : item, 'result' : item.id, 'value' : item.taxon };\n          });\n          return results;\n        },\n      formatItem: function(item) { return item.taxon; }\n      // {max}\n});\njQuery('input#insectAutocomplete1').result(function(event, data) {\n  jQuery('input#insectAutocomplete1').val('');\n  jQuery('#fo-edit-insect-id').find('.autocompleteRow').before('<tr class=\"fo-edit-id-list-entry\"><td>'+htmlspecialchars(data.taxon)+'</td><td><input type=\"hidden\" name=\"determination:taxa_taxon_list_id_list[]\" value=\"'+data.id+'\">'+data.id+'</td><td><img class=\"removeRow\" src=\"/misc/watchdog-error.png\" alt=\"" . lang::get('Remove this entry') . "\" title=\"" . lang::get('Remove this entry') . "\"/></td></tr>');\n});\njQuery('input#flowerAutocomplete1').autocomplete(flowerTaxa,\n      { matchContains: true,\n        parse: function(data)\n        {\n          var results = [];\n          jQuery.each(data, function(i, item) {\n            results[results.length] = { 'data' : item, 'result' : item.id, 'value' : item.taxon };\n          });\n          return results;\n        },\n      formatItem: function(item) { return item.taxon; }\n      // {max}\n});\njQuery('input#flowerAutocomplete1').result(function(event, data) {\n  jQuery('input#flowerAutocomplete1').val('');\n  jQuery('#fo-edit-flower-id').find('.autocompleteRow').before('<tr class=\"fo-edit-id-list-entry\"><td>'+htmlspecialchars(data.taxon)+'</td><td><input type=\"hidden\" name=\"determination:taxa_taxon_list_id_list[]\" value=\"'+data.id+'\">'+data.id+'</td><td><img class=\"removeRow\" src=\"/misc/watchdog-error.png\" alt=\"" . lang::get('Remove this entry') . "\" title=\"" . lang::get('Remove this entry') . "\"/></td></tr>');\n});\n// new Flower ID form autocompletes\njQuery('input#flowerAutocomplete2').autocomplete(flowerTaxa,\n      { matchContains: true,\n        parse: function(data)\n        {\n          var results = [];\n          jQuery.each(data, function(i, item) {\n            results[results.length] = { 'data' : item, 'result' : item.id, 'value' : item.taxon };\n          });\n          return results;\n        },\n      formatItem: function(item) { return item.taxon; }\n      // {max}\n});\njQuery('input#flowerAutocomplete2').result(function(event, data) {\n  jQuery('input#flowerAutocomplete2').val('');\n  if(jQuery('#flower-species-list input[value='+data.id+']').length > 0) return;\n  jQuery('#flower-species-list-body').append('<tr class=\"flower-species-list-entry\"><td>'+htmlspecialchars(data.taxon)+'<input type=\"hidden\" name=\"determination:taxa_taxon_list_id_list[]\" value=\"'+data.id+'\"></td><td><img class=\"removeRow\" src=\"/misc/watchdog-error.png\" alt=\"" . lang::get('Remove this entry') . "\" title=\"" . lang::get('Remove this entry') . "\"/></td></tr>');\n  jQuery('#fo-new-flower-id-form [name=determination\\:determination_type]').val('" . (user_access('IForm n' . $node->nid . ' flower expert') ? "C" : "A") . "');\n  jQuery('#fo-flower-expert-det-type').html('" . lang::get('LANG_Det_Type_' . (user_access('IForm n' . $node->nid . ' flower expert') ? "C" : "A")) . "');\n  jQuery('#id-flower-unknown').removeAttr('checked');\n});\njQuery('select#flowerSelect').change(function() {\n  if(jQuery('#flower-species-list input[value='+jQuery(this).val()+']').length > 0) return;\n  jQuery('#flower-species-list-body').append('<tr class=\"flower-species-list-entry\"><td><input type=\"hidden\" name=\"determination: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>');\n  jQuery('#fo-new-flower-id-form [name=determination\\:determination_type]').val('" . (user_access('IForm n' . $node->nid . ' flower expert') ? "C" : "A") . "');\n  jQuery('#fo-flower-expert-det-type').html('" . lang::get('LANG_Det_Type_' . (user_access('IForm n' . $node->nid . ' flower expert') ? "C" : "A")) . "');\n  jQuery('select#flowerSelect').val('');\n  jQuery('#id-flower-unknown').removeAttr('checked');\n});\n\njQuery('#id-flower-unknown').change(function (){\n  clearErrors('form#fo-new-flower-id-form');\n  if (jQuery('#id-flower-unknown').attr('checked') != '') {\n    jQuery('#fo-new-flower-id-form [name=determination\\:determination_type]').val('X');\n    jQuery('#fo-flower-expert-det-type').html('" . lang::get('LANG_Det_Type_X') . "');\n    jQuery('.flower-species-list-entry').remove();\n    jQuery('#fo-new-flower-id-form [name=determination\\:taxon_details]').val('');\n    jQuery('#fo-new-flower-id-form [name=determination\\:taxa_taxon_list_id]').val('');\n    jQuery('#fo-new-flower-id-form [name=determination\\:taxon_extra_info]').val(''); // more precise info\n//    jQuery('#fo-new-flower-id-form [name=determination\\:comment]').val('');\n  } else {\n    jQuery('#fo-new-flower-id-form [name=determination\\:determination_type]').val('" . (user_access('IForm n' . $node->nid . ' flower expert') ? "C" : "A") . "');\n    jQuery('#fo-flower-expert-det-type').html('" . lang::get('LANG_Det_Type_' . (user_access('IForm n' . $node->nid . ' flower expert') ? "C" : "A")) . "');\n  }\n});\nloadComments = function(keyValue, block, table, key, blockClass, bodyClass, reset_timeout, addDelete){\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        params: {keyValue: keyValue,\n        \t\t block: block,\n        \t\t table: table,\n        \t\t key: key, \n        \t\t blockClass: blockClass,\n        \t\t bodyClass: bodyClass,\n        \t\t addDelete: addDelete},\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.params.blockClass+'\"/>').appendTo(block);\n\t\t\t\tif (this.params.addDelete){\n\t\t\t\t\tvar delButton = jQuery('<span style=\"float: right;\"><img src=\"/misc/watchdog-error.png\" style=\"vertical-align: middle;\"></span>').appendTo(newCommentDetails);\n\t\t\t\t\tvar delForm = jQuery('<form action=\"'+(this.params.table == 'sample_comment' ? '" . iform_ajaxproxy_url($node, 'smp-comment') . "' : '" . iform_ajaxproxy_url($node, 'occ-comment') . "')+'\" method=\"POST\" style=\"display: none;\"><input type=\"hidden\" name=\"website_id\" value=\"" . $args['website_id'] . "\" /><input type=\"hidden\" name=\"'+this.params.table+':id\" value=\"'+commentData[i].id+'\" /><input type=\"hidden\" name=\"'+this.params.table+':deleted\" value=\"t\" /></form>').appendTo(delButton);\n\t\t\t\t\tdelForm.ajaxForm({\n\t\t\t\t\t\tasync: false,\n\t\t\t\t\t\tdataType:  'json',\n\t\t\t\t\t\tsuccess:   function(data){\n\t\t\t\t\t\t\tif(data.error == undefined){\n\t\t\t\t\t\t\t\tloadComments(this.params.keyValue, this.params.block, this.params.table, this.params.key, this.params.blockClass, this.params.bodyClass, true, this.params.addDelete);\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\talert(data.error);\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\tdelButton.click(function(e){\n\t\t\t\t\t  e.preventDefault();\n\t\t\t\t\t  if(!confirm(\"" . lang::get('LANG_Comment_Delete_Confirmation') . "\")) return;\n\t\t\t\t\t  var me = \$(e.target.parentNode);\n\t\t\t\t\t  me.find('form').submit();\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t\tjQuery('<span>" . lang::get('LANG_Comment_By') . "' + commentData[i].person_name + ' ' + convertDate(commentData[i].updated_on,false) + '</span>').appendTo(newCommentDetails);\n\t   \t\t\tvar newComment = jQuery('<div class=\"'+this.params.blockClass+'\"/>').appendTo(this.params.block);\n\t\t\t\tjQuery('<p>' + commentData[i].comment + '</p>').appendTo(newComment);\n\t\t\t}\n\t\t  } else {\n\t\t\tjQuery('<p>" . lang::get('LANG_No_Comments') . "</p>').appendTo(this.params.block);\n\t\t  }\n\t\t}\n    }));\n};\n\ncollectionProcessing = function(keyValue, type){\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 " . $uidAttrID . ":\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\tsetIDButtons(null, parseInt(attrdata[i].value) == " . $uid . ", null, null, type);\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    loadOccurrenceAttributes(keyValue);\n\tajaxStack.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\tif(smpData[0].parent_id == null) {\n   \t\t\t\t\t\talertIndiciaError({error: \"" . lang::get('LANG_Bad_Insect_ID') . "\"});\n   \t\t\t\t\t\treturn;\n\t\t   \t\t\t}\n   \t\t\t\t\tcollection = smpData[0].parent_id;\n\t\t\t\t\tcollectionProcessing(collection, 'I');\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\tajaxStack.push(\$.getJSON(\"" . $svcUrl . "/data/location/\" +smpData[0].location_id +\n\t\t\t\t\t\t\t\"?mode=json&view=detail&nonce=" . $readAuth['nonce'] . "&auth_token=" . $readAuth['auth_token'] . "\" +\n\t\t\t\t\t\t\t\"&REMOVEABLEJSONP&callback=?\", function(locationData) {\n\t\t\t\t\t\tif(!(locationData instanceof Array)){\n\t\t\t\t\t\t\talertIndiciaError(locationData);\n\t\t\t\t\t\t} else if (locationData.length>0) {\n\t\t\t\t\t\t\tvar parser = new OpenLayers.Format.WKT();\n\t\t\t\t\t\t\tvar feature = parser.read(locationData[0].centroid_geom);\n\t\t\t\t\t\t\tvar filter = new OpenLayers.Filter.Spatial({\n  \t\t\t\t\t\t\t\ttype: OpenLayers.Filter.Spatial.CONTAINS ,\n    \t\t\t\t\t\t\tproperty: 'the_geom',\n    \t\t\t\t\t\t\tvalue: feature.geometry\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\tinseeProtocol.read({filter: filter, callback: fillOccurrenceLocationDetails});\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}\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, 'F');\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\tif(collection[0].parent_id != null) {\n   \t\t\t\t\t\talertIndiciaError({error: \"" . lang::get('LANG_Bad_Flower_ID') . "\"});\n   \t\t\t\t\t\treturn;\n\t\t   \t\t\t}\n   \t\t\t\t\tloadLocationAttributes(collection[0].location_id);\n   \t\t\t\t\tajaxStack.push(\$.getJSON(\"" . $svcUrl . "/data/location/\" +collection[0].location_id +\n\t\t\t\t\t\t\t\"?mode=json&view=detail&nonce=" . $readAuth['nonce'] . "&auth_token=" . $readAuth['auth_token'] . "\" +\n\t\t\t\t\t\t\t\"&REMOVEABLEJSONP&callback=?\", function(locationData) {\n\t\t\t\t\t\tif(!(locationData instanceof Array)){\n\t\t\t\t\t\t\talertIndiciaError(locationData);\n\t\t\t\t\t\t} else if (locationData.length>0) {\n\t\t\t\t\t\t\tvar parser = new OpenLayers.Format.WKT();\n\t\t\t\t\t\t\tvar feature = parser.read(locationData[0].centroid_geom);\n\t\t\t\t\t\t\tvar filter = new OpenLayers.Filter.Spatial({\n  \t\t\t\t\t\t\t\ttype: OpenLayers.Filter.Spatial.CONTAINS ,\n    \t\t\t\t\t\t\tproperty: 'the_geom',\n    \t\t\t\t\t\t\tvalue: feature.geometry\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\tinseeProtocol.read({filter: filter, callback: fillOccurrenceLocationDetails});\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}\n    }));\n}\n\nloadInsect = function(insectID, collectionIndex, insectIndex, type){\n\tif(bulkValidating) return; // don't do anything if bulk validating.\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-container').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-container').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\tinsectIDstruc.imagePath = '';\n\tjQuery('#focus-collection,#filter,#fo-flower-addn-info').hide();\n\tjQuery('#fo-image').empty();\n    jQuery('#focus-occurrence,#fo-addn-info-header,#fo-insect-addn-info').show();\n\tjQuery('#fo-edit-insect-id,#fo-delete-insect').addClass('ui-accordion-content-active');\n\tjQuery('#fo-edit-flower-id,#fo-new-comment').removeClass('ui-accordion-content-active');\n\tjQuery('#fo-image').height(jQuery('#fo-image').width()/(" . $args['Insect_Image_Ratio'] . "));\n    jQuery('[name=determination\\:occurrence_id],[name=occurrence_comment\\:occurrence_id],[name=occurrence\\:id]').val(insectID);\n\tjQuery('#fo-new-insect-id-form,#fo-new-flower-id-form,#fo-express-doubt-form,#fo-new-flower-id-button').hide();\n\tsetIDButtons(" . (user_access('IForm n' . $node->nid . ' insect expert') ? 'true' : 'false') . ", false, false, false, 'I');\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, '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; insectIDstruc.imagePath = imageRecord.path}, '', true);\n\tloadInsectAddnInfo(insectID, collectionIndex);\n\tloadComments(insectID, '#fo-comment-list', 'occurrence_comment', 'occurrence_id', 'occurrence-comment-block', 'occurrence-comment-body', false, " . (user_access('IForm n' . $node->nid . ' delete insect comment') ? "true" : "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('#fo-image').empty();\n\tjQuery('#fo-edit-flower-id').addClass('ui-accordion-content-active');\n\tjQuery('#fo-edit-insect-id,#fo-delete-insect,#fo-new-comment').removeClass('ui-accordion-content-active');\n\tjQuery('#focus-occurrence,#fo-addn-info-header,#fo-flower-addn-info').show();\n\tjQuery('#fo-image').height(jQuery('#fo-image').width()/(" . $args['Flower_Image_Ratio'] . "));\n\tjQuery('#fo-new-insect-id-form,#fo-new-flower-id-form,#fo-express-doubt-form').hide();\n\tjQuery('[name=determination\\:occurrence_id],[name=occurrence_comment\\:occurrence_id]').val(flowerID);\n\tjQuery('[name=occurrence\\:id]').val('');\n\tjQuery('#fo-new-insect-id-button').hide();\n\tsetIDButtons(" . (user_access('IForm n' . $node->nid . ' flower expert') ? 'true' : 'false') . ", false, false, false, 'F');\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, '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}, '', true);\n\tloadFlowerAddnInfo(flowerID, collectionIndex);\n\tloadComments(flowerID, '#fo-comment-list', 'occurrence_comment', 'occurrence_id', 'occurrence-comment-block', 'occurrence-comment-body', false, " . (user_access('IForm n' . $node->nid . ' delete flower comment') ? "true" : "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\tpolygonLayer.map.searchLayer.destroyFeatures();\n\tjQuery('#imp-insee-div').hide();\n\tif(inseeLayer != null) inseeLayer.destroyFeatures();\n\tinseeLayerStore.destroyFeatures();\n};\nOpenLayers.Control.ClearLayer = OpenLayers.Class(OpenLayers.Control, {\n    destroy: function() {\n        this.deactivate();        \n        OpenLayers.Control.prototype.destroy.apply(this, arguments);\n    },\n    activate: function() {\n      jQuery('#imp-insee-div').hide();\n      if(inseeLayer != null) inseeLayer.destroyFeatures();\n      inseeLayerStore.destroyFeatures();\n      polygonLayer.destroyFeatures();\n      polygonLayer.map.searchLayer.destroyFeatures();\n      return false;\n    },\n    CLASS_NAME: \"OpenLayers.Control.ClearLayer\"\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([]);\n\t\t\t\tvar controls=[new OpenLayers.Control.Navigation(),\n\t\t\t\t\tnew OpenLayers.Control.DrawFeature(layer,OpenLayers.Handler.Polygon,{'displayClass':'olControlDrawFeaturePolygon', drawFeature: addDrawnGeomToSelection}),\n\t\t\t\t\tnew OpenLayers.Control.ClearLayer({'displayClass':'olControlClearLayer', title: '" . lang::get('LANG_ClearTooltip') . "'})];\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// a move may be associated with a zoom as well.\nlastZoom=0;\nreQuery = function(){\n\tlastZoom = jQuery('#map')[0].map.getZoom();\n\tif(jQuery('#results-collections-results').filter(':visible').length > 0)\n\t\trunSearch(true);\n\telse if(jQuery('#results-insects-results').filter(':visible').length > 0)\n\t\trunSearch(false);\n};\nmoveEnd = function(){\n\tif(lastZoom == jQuery('#map')[0].map.getZoom()) reQuery();\n};\nloadFilter = function(){\n    if(jQuery('#map').children().length == 0) {\n\t\tmapInitialisationHooks.push(function(mapdiv) {\n\t\t\tvar editControl = new MyEditingToolbar(polygonLayer, {'displayClass':'olControlEditingToolbar'});\n\t\t\tmapdiv.map.addControl(editControl);\n\t\t\teditControl.activate();\n\t\t\tmapdiv.map.events.on({'zoomend': reQuery, 'dragend': reQuery, 'moveend': moveEnd});\n\t\t});\n    \t" . $map1JS . "\n\t\tmapInitialisationHooks=[];\n\t\tpolygonLayer.map.searchLayer.events.register('featuresadded', {}, function(a1){\n\t\t\t// draw a square defining the bounds for the georeffed location.\n\t\t\tpolygonLayer.destroyFeatures();\n\t\t\tif(inseeLayer != null) inseeLayer.destroyFeatures();\n\t\t\tvar searchLayer = polygonLayer.map.searchLayer;\n\t\t\tvar bounds=searchLayer.getDataExtent();\n\t\t\tvar feature = new OpenLayers.Feature.Vector(bounds.toGeometry())\n\t\t\tpolygonLayer.addFeatures([feature]);\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-form').hide();\n\tjQuery('#fo-new-insect-id-form [name=determination\\:comment]').val(\"" . lang::get('LANG_Default_ID_Comment') . "\");\n\tif(jQuery('#fo-new-insect-id-form').filter(':visible').length>0) {\n\t  jQuery('#fo-new-insect-id-form').hide();\n\t  if(!jQuery('#fo-id-history').hasClass('empty')){\n\t\tjQuery('#fo-id-history').addClass('ui-accordion-content-active');\n\t\tjQuery('#fo-id-buttons').removeClass('ui-corner-bottom');\n\t  }\n\t  jQuery('#fo-edit-insect-id').addClass('ui-accordion-content-active');\n \t} else {\n\t  jQuery('#fo-new-insect-id-form').show();\n\t  if(!jQuery('#fo-id-history').hasClass('empty')){\n\t\tjQuery('#fo-id-history').removeClass('ui-accordion-content-active');\n\t\tjQuery('#fo-id-buttons').addClass('ui-corner-bottom');\n\t  }\n\t  jQuery('#fo-edit-insect-id').removeClass('ui-accordion-content-active');\n\t}\n});\njQuery('#fo-new-flower-id-button').click(function(){ \n\tjQuery('#fo-express-doubt-form').hide();\n\tjQuery('#fo-new-flower-id-form [name=determination\\:comment]').val(\"" . lang::get('LANG_Default_ID_Comment') . "\");\n\tif(jQuery('#fo-new-flower-id-form').filter(':visible').length>0) {\n\t  jQuery('#fo-new-flower-id-form').hide();\n\t  if(!jQuery('#fo-id-history').hasClass('empty')){\n\t\tjQuery('#fo-id-history').addClass('ui-accordion-content-active');\n\t\tjQuery('#fo-id-buttons').removeClass('ui-corner-bottom');\n\t  }\n\t  jQuery('#fo-edit-flower-id').addClass('ui-accordion-content-active');\n\t} else {\n\t  jQuery('#fo-new-flower-id-form').show();\n\t  if(!jQuery('#fo-id-history').hasClass('empty')){\n\t\tjQuery('#fo-id-history').removeClass('ui-accordion-content-active');\n\t\tjQuery('#fo-id-buttons').addClass('ui-corner-bottom');\n\t  }\n\t  jQuery('#fo-edit-flower-id').removeClass('ui-accordion-content-active');\n\t}\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\n\$('#username').autocomplete([";
        /* warning Drupal specific code */
        $userList = array();
        if (!($userList = self::_fetchDBCache())) {
            $results = db_query('SELECT uid, name FROM {users} ORDER BY name');
            while ($result = db_fetch_object($results)) {
                $account = user_load($result->uid);
                if ($account->uid != 1) {
                    // && user_access('IForm loctools node '.$node->nid.' user', $account)){
                    $userList[] = '"' . str_replace('"', '\\"', $account->name) . '"';
                }
            }
            self::_cacheResponse($userList);
        }
        data_entry_helper::$javascript .= implode(',', $userList) . "]);\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;
    }
   /**
    * 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.
       $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';
       $presetLayers = array();
       // read out the activated preset layers
       if (isset($args['preset_layers'])) {
           foreach ($args['preset_layers'] as $layer => $active) {
               if ($active !== 0) {
                   $presetLayers[] = $layer;
               }
           }
       }
       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']);
       }
       // 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 - newSample: mode 1.
       // Additional argument - sample_id=<id>: mode 2.
       // Additional argument - occurrence_id=<id>: mode 3.
       $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 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
       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('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('newSample', $_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";
       $optionArray_1 = array();
       $optionArray_2 = array();
       $optionArray_Location = array();
       $options = explode(',', $args['layer1']);
       foreach ($options as $option) {
           $parts = explode(':', $option);
           $optionName = $parts[0];
           unset($parts[0]);
           $optionsArray_1[$optionName] = implode(':', $parts);
       }
       $options = explode(',', $args['layer2']);
       foreach ($options as $option) {
           $parts = explode(':', $option);
           $optionName = $parts[0];
           unset($parts[0]);
           $optionsArray_2[$optionName] = implode(':', $parts);
       }
       $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 .= "locationList = [" . implode(',', $locations) . "];\n";
       }
       data_entry_helper::$javascript .= "\n// Create Layers.\n// Base Layers first.\nvar WMSoptions = {\n          LAYERS: '" . $optionsArray_1['LAYERS'] . "',\n          SERVICE: 'WMS',\n          VERSION: '1.1.0',\n          STYLES: '',\n          SRS: '" . $optionsArray_1['SRS'] . "',\n          FORMAT: '" . $optionsArray_1['FORMAT'] . "'\n    };\nbaseLayer_1 = new OpenLayers.Layer.WMS('" . $optionsArray_1['Name'] . "',\n        '" . iform_proxy_url($optionsArray_1['URL']) . "',\n        WMSoptions, {\n             minScale: " . $optionsArray_1['minScale'] . ",\n            maxScale: " . $optionsArray_1['maxScale'] . ",\n            units: '" . $optionsArray_1['units'] . "',\n            isBaseLayer: true,\n            singleTile: true\n        });\nWMSoptions = {\n          LAYERS: '" . $optionsArray_2['LAYERS'] . "',\n          SERVICE: 'WMS',\n          VERSION: '1.1.0',\n          STYLES: '',\n          SRS: '" . $optionsArray_2['SRS'] . "',\n          FORMAT: '" . $optionsArray_2['FORMAT'] . "'\n    };\nbaseLayer_2 = new OpenLayers.Layer.WMS('" . $optionsArray_2['Name'] . "',\n        '" . iform_proxy_url($optionsArray_2['URL']) . "',\n        WMSoptions, {\n             minScale: " . $optionsArray_2['minScale'] . ",\n            maxScale: " . $optionsArray_2['maxScale'] . ",\n            units: '" . $optionsArray_2['units'] . "',\n            isBaseLayer: true,\n            singleTile: true\n        });\nWMSoptions = {\n          SERVICE: 'WMS',\n          VERSION: '1.1.0',\n          STYLES: '',\n          SRS: '" . $optionsArray_Location['SRS'] . "',\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.
           $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 .= "\n        LAYERS: '" . $optionsArray_Location['LAYERS'] . "'";
       }
       data_entry_helper::$javascript .= "\n    };\nlocationListLayer = new OpenLayers.Layer.WMS('" . $optionArray_Location['Name'] . "',\n        '" . iform_proxy_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// 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.2,\n                    strokeWidth: 1\n                  })\n  });\nlocationLayer = new OpenLayers.Layer.Vector(\"" . lang::get("LANG_Location_Layer") . "\",\n                                    {styleMap: locStyleMap});\noccStyleMap = 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          }) });\noccListLayer = new OpenLayers.Layer.Vector(\"" . lang::get("LANG_Occurrence_List_Layer") . "\",\n                                    {styleMap: occStyleMap});\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');
       // 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: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 : '" . $args['sample_visit_number_id'] . "', closed_attr_id : '" . $args['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');
           $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' => 'newSample')) . '\'"></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" />\\n';
               $url = $svcUrl . '/data/location?mode=json&view=detail&auth_token=' . $readAuth['auth_token'] . "&nonce=" . $readAuth["nonce"] . "&parent_id=NULL&orderby=name";
               $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('LANG_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=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" id="params" name="params" value=\'{"survey_id":' . $args['survey_id'] . ', "direction_attr_id":' . $args['sample_walk_direction_id'] . ', "closed_attr_id":' . $args['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=mnhnl_btw_download_report.xml&reportSource=local&auth_token=' . $readAuth['auth_token'] . '&nonce=' . $readAuth['nonce'] . '&mode=csv\\">
     <p>' . lang::get('LANG_Initial_Download') . '</p>
     <input type="hidden" id="params" name="params" value=\'{"survey_id":' . $args['survey_id'] . ', "closed_attr_id":' . $args['sample_closure_id'] . ', "download": "INITIAL"}\' />
     <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=mnhnl_btw_download_report.xml&reportSource=local&auth_token=' . $readAuth['auth_token'] . '&nonce=' . $readAuth['nonce'] . '&mode=csv\\">
     <p>' . lang::get('LANG_Confirm_Download') . '</p>
     <input type="hidden" id="params" name="params" value=\'{"survey_id":' . $args['survey_id'] . ', "closed_attr_id":' . $args['sample_closure_id'] . ', "download": "CONFIRM"}\' />
     <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=mnhnl_btw_download_report.xml&reportSource=local&auth_token=' . $readAuth['auth_token'] . '&nonce=' . $readAuth['nonce'] . '&mode=csv\\">
     <p>' . lang::get('LANG_Final_Download') . '</p>
     <input type="hidden" id="params" name="params" value=\'{"survey_id":' . $args['survey_id'] . ', "closed_attr_id":' . $args['sample_closure_id'] . ', "download": "FINAL"}\' />
     <input type="submit" class="ui-state-default ui-corner-all" value="' . lang::get('LANG_Final_Download_Button') . '">
   </form>
 </div>';
           }
           // Create Map
           $r .= "<div class=\"mnhnl-btw-mappanel\">\n" . data_entry_helper::map_panel(array('presetLayers' => $presetLayers, 'layers' => array('baseLayer_1', 'baseLayer_2', 'locationListLayer'), 'initialFeatureWkt' => null, 'width' => 'auto', 'height' => 490, 'editLayer' => false, 'initial_lat' => $args['map_centroid_lat'], 'initial_long' => $args['map_centroid_long'], 'initial_zoom' => (int) $args['map_zoom'], 'scroll_wheel_zoom' => false), array('projection' => $args['map_projection'])) . "</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>";
           }
           return $r;
       }
       ///////////////////////////////////////////////////////////////////
       $occReadOnly = false;
       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);
           $childSample = array();
           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);
           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.
           $thisOccID = $childLoadID;
           // this will be used to load the occurrence into the editlayer.
           $childSample['taxon'] = $childSample['occurrence:taxon'];
           $parentLoadID = $childSample['sample:parent_id'];
       }
       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);
           $parentSample = array();
           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
           // default values for attributes from DB are picked up automatically.
       }
       $childSample['sample:date'] = $parentSample['sample:date'];
       // enforce a match between child and parent sample dates
       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[$args['sample_closure_id']]['fieldname'];
       $closedFieldValue = data_entry_helper::check_default_value($closedFieldName, array_key_exists('default', $attributes[$args['sample_closure_id']]) ? $attributes[$args['sample_closure_id']]['default'] : '0');
       // default is not closed
       $adminPerm = 'IForm node ' . $node->nid . ' admin';
       if ($closedFieldValue == '1' && !user_access($adminPerm)) {
           // 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 open.
           $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('DummyForm');
       $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>\n  <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'] . "\" />\n    " . iform_user_get_hidden_inputs($args);
       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";
       }
       $defAttrOptions['validation'] = array('required');
       $defAttrOptions['suffixTemplate'] = 'requiredsuffix';
       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[$args['sample_walk_direction_id']], $languageFilteredAttrOptions) . data_entry_helper::outputAttribute($attributes[$args['sample_reliability_id']], $languageFilteredAttrOptions) . data_entry_helper::outputAttribute($attributes[$args['sample_visit_number_id']], array_merge($languageFilteredAttrOptions, array('default' => 1, 'noBlankText' => true)));
       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', 'suffixTemplate' => 'requiredsuffix'));
       }
       $r .= data_entry_helper::outputAttribute($attributes[$args['sample_wind_id']], $languageFilteredAttrOptions) . data_entry_helper::outputAttribute($attributes[$args['sample_precipitation_id']], $languageFilteredAttrOptions) . data_entry_helper::outputAttribute($attributes[$args['sample_temperature_id']], array_merge($defAttrOptions, array('suffixTemplate' => 'nosuffix'))) . " degC<span class=\"deh-required\">*</span><br />" . data_entry_helper::outputAttribute($attributes[$args['sample_cloud_id']], $defAttrOptions) . data_entry_helper::outputAttribute($attributes[$args['sample_start_time_id']], array_merge($defAttrOptions, array('suffixTemplate' => 'nosuffix'))) . " hh:mm<span class=\"deh-required\">*</span><br />" . data_entry_helper::outputAttribute($attributes[$args['sample_end_time_id']], array_merge($defAttrOptions, array('suffixTemplate' => 'nosuffix'))) . " hh:mm<span class=\"deh-required\">*</span><br />";
       unset($defAttrOptions['suffixTemplate']);
       unset($defAttrOptions['validation']);
       if (user_access($adminPerm)) {
           //  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[$args['sample_closure_id']], $defAttrOptions);
       } else {
           // hidden closed
           $r .= "<input type=\"hidden\" id=\"" . $closedFieldName . "\" name=\"" . $closedFieldName . "\" value=\"" . $closedFieldValue . "\" />\n";
       }
       $escaped_id = str_replace(':', '\\\\:', $closedFieldName);
       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($adminPerm)) {
               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('#" . $escaped_id . "').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}\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\$('.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\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            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            jQuery('#occ-form').show();\n            jQuery('#na-occ-warn').hide();";
       if (!user_access($adminPerm)) {
           data_entry_helper::$javascript .= "\n\t\t\tif(jQuery('#" . $escaped_id . "').val() == '1'){\n\t\t\t\tjQuery('#read-only-survey').show();\n\t\t\t\tjQuery('#close1').hide();\n\t\t\t\tjQuery('#close2').hide();\n\t\t\t};\n";
       }
       data_entry_helper::$javascript .= "\n\t\t\tswitch(\"" . $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:\n\t\t\t\t\tvar a = \$('ul.ui-tabs-nav a')[1];\n\t\t\t\t\t\$(a).click();\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/>')\n\t\t\t\t\t\t\t\t.addClass('inline-error')\n\t\t\t\t\t\t\t\t.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});";
       // 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=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, 'suffixTemplate' => 'requiredsuffix', 'disabled' => $disabledText, 'defaultCaption' => data_entry_helper::$entity_to_load['occurrence:taxon']);
       $escaped_terr_id = str_replace(':', '\\\\:', $attributes[$args['occurrence_territorial_id']]['fieldname']);
       $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=\"C\" />\n    <input type=\"hidden\" id=\"occurrence:downloaded_flag\" name=\"occurrence:downloaded_flag\" value=\"N\" />\n    " . data_entry_helper::autocomplete($species_ctrl_args) . "\n    " . data_entry_helper::outputAttribute($attributes[$args['occurrence_confidence_id']], array_merge($languageFilteredAttrOptions, array('noBlankText' => ''))) . "\n    " . data_entry_helper::sref_and_system(array('label' => lang::get('LANG_Spatial_ref'), 'systems' => array('2169' => 'Luref (Gauss Luxembourg)'), 'suffixTemplate' => 'requiredsuffix')) . "\n    <p>" . lang::get('LANG_Click_on_map') . "</p>\n    " . data_entry_helper::outputAttribute($attributes[$args['occurrence_count_id']], array_merge($defAttrOptions, array('default' => 1, 'suffixTemplate' => 'requiredsuffix'))) . "\n    " . data_entry_helper::outputAttribute($attributes[$args['occurrence_approximation_id']], $defAttrOptions) . "\n    " . data_entry_helper::outputAttribute($attributes[$args['occurrence_territorial_id']], array_merge($defAttrOptions, array('default' => 1))) . "\n    " . data_entry_helper::outputAttribute($attributes[$args['occurrence_atlas_code_id']], $languageFilteredAttrOptions) . "\n    " . data_entry_helper::outputAttribute($attributes[$args['occurrence_overflying_id']], $defAttrOptions) . "\n    " . data_entry_helper::textarea(array('label' => lang::get('LANG_Comment'), 'fieldname' => 'occurrence:comment', 'disabled' => $disabledText));
       if (!$surveyReadOnly && !$occReadOnly) {
           $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: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 : '" . $args['occurrence_territorial_id'] . "',\n            count_attr_id : '" . $args['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\\:" . $args['occurrence_confidence_id'] . "]').find('option').removeAttr('selected');\n\t\t\tjQuery('form#occ-form').find('[name=occAttr\\:" . $args['occurrence_count_id'] . "]').val('1');\n\t\t\tjQuery('form#occ-form').find('input[name=occAttr\\:" . $args['occurrence_approximation_id'] . "],input[name=occAttr\\:" . $args['occurrence_overflying_id'] . "]').filter('[value=0]').attr('checked','checked');\n\t\t\tjQuery('form#occ-form').find('input[name=occAttr\\:" . $args['occurrence_territorial_id'] . "]').filter('[value=1]').attr('checked','checked');\n\t\t\tjQuery('form#occ-form').find('select[name=occAttr\\:" . $args['occurrence_atlas_code_id'] . "]').val('');\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/>')\n\t\t\t\t\t\t\t\t.addClass('inline-error')\n\t\t\t\t\t\t\t\t.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(\"input[name=occAttr\\:" . $args['occurrence_territorial_id'] . "]:checked,input[name^=occAttr\\:" . $args['occurrence_territorial_id'] . "\\:]:checked\").val() == '0') {\n      jQuery(\"select[name=occAttr\\:" . $args['occurrence_atlas_code_id'] . "],select[name^=occAttr\\:" . $args['occurrence_atlas_code_id'] . "\\:]\").val('');\n  } else {\n      if(jQuery(\"select[name=occAttr\\:" . $args['occurrence_atlas_code_id'] . "],select[name^=occAttr\\:" . $args['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\\:" . $args['occurrence_atlas_code_id'] . "],select[name^=occAttr\\:" . $args['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\\:" . $args['occurrence_atlas_code_id'] . "],select[name^=occAttr\\:" . $args['occurrence_atlas_code_id'] . "\\:]\").val(bb02);\n      }\n  }\n};\njQuery(\"input[name='" . $escaped_terr_id . "']\").change(setAtlasStatus);\n";
       $r .= '</div>';
       // add map panel.
       $r .= "<div class=\"mnhnl-btw-mappanel\">\n";
       $r .= data_entry_helper::map_panel(array('presetLayers' => $presetLayers, 'layers' => array('baseLayer_1', 'baseLayer_2', 'locationLayer', 'occListLayer'), 'initialFeatureWkt' => null, 'width' => 'auto', 'height' => 490, 'initial_lat' => $args['map_centroid_lat'], 'initial_long' => $args['map_centroid_long'], 'initial_zoom' => (int) $args['map_zoom'], 'scroll_wheel_zoom' => false), array('projection' => $args['map_projection']));
       // 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 .= "\nvar control = new OpenLayers.Control.SelectFeature(occListLayer);\noccListLayer.map.addControl(control);\nfunction onPopupClose(evt) {\n    // 'this' is the popup.\n    control.unselect(this.feature);\n}\nfunction 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}\nfunction 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\noccListLayer.events.on({\n    'featureselected': onFeatureSelect,\n    'featureunselected': onFeatureUnselect\n});\n\ncontrol.activate();\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);\n";
       if ($mode != 1) {
           data_entry_helper::$onload_javascript .= "\nactivateAddList = 1;\nthisOccID = " . $thisOccID . ";\n\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\$('div#occ_grid').indiciaDataGrid('rpt: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 : '" . $args['occurrence_territorial_id'] . "',\n            count_attr_id : '" . $args['occurrence_count_id'] . "'},\n    itemsPerPage : 12,\n    callback : addListFeature ,\n    cssOdd : ''\n  });\n\n// activateAddList = 0;\n\n";
       }
       $r .= "</div><div><form><input type=\"button\" value=\"" . lang::get('LANG_Return') . "\" onclick=\"window.location.href='" . url('node/' . $node->nid, array('query' => 'Main')) . "'\"></form></div></div>\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;
 }
示例#16
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');
        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']));
        $defNRAttrOptions = array('extraParams' => $readAuth + array('orderby' => 'id'), 'lookUpListCtrl' => 'radio_group', 'lookUpKey' => 'meaning_id', 'language' => iform_lang_iso_639_2($args['language']), 'containerClass' => 'group-control-box', 'sep' => ' &nbsp; ', 'suffixTemplate' => 'nosuffix');
        $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>';
        $r .= data_entry_helper::loading_block_start();
        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 .= "];";
        // 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="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="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=""/>
 	' . 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 id="cc-1-valid-button" class="ui-state-default ui-corner-all save-button">' . lang::get('LANG_Validate') . '</div>
  </div>
  <div id="cc-1-trailer" class="poll-section-trailer">
    <div id="cc-1-trailer-image" ><img src="' . helper_config::$base_url . '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');\njQuery('.loading-hide').hide().addClass('my-loading-hide').removeClass('loading-hide');\n// can't use shuffle to side as dynamic generated code does like it in IE7\n\n\$.fn.foldPanel = function(){\n\tthis.children('.poll-section-body').hide();\n\tthis.children('.poll-section-footer,.poll-section-trailer').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').show();\n\tthis.children('.poll-section-footer,.poll-section-trailer').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\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').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\t// TODO Map\n\tthis.find('.thumb').filter('not(.blankPhoto)').remove();\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('.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');\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  };\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\$('.loading-hide').removeClass('loading-hide');\n\tjQuery('#cc-1').hide();\n\tjQuery('#refresh-message').show();\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};\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 = '" . str_replace("{HOST}", $_SERVER['HTTP_HOST'], $args['ID_tool_insect_poll_dir']) . "'+insectSess;\n\tvar flowerURL = '" . str_replace("{HOST}", $_SERVER['HTTP_HOST'], $args['ID_tool_flower_poll_dir']) . "'+flowerSess;\n\tif(settings.url != flowerURL && settings.url != insectURL){\n\t   alert(\"" . lang::get('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_date') . "');\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        \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[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  \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('#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 instanceof Array)){\n   \t\t\t\t\t\talertIndiciaError(data);\n   \t\t\t\t\t} else if (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', true);\n\t\t\t\t\t\t}\n\t\t\t\t});\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[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  \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(flowerIDstruc);\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\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';
        $options['suffixTemplate'] = 'nosuffix';
        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('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' => $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>
          <input type="hidden" id="flower:taxon_details" name="flower:taxon_details" />
          <input type="hidden" name="flower:determination_type" value="A" />  
   	      <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>
 	      <p id="flower_taxa_list"></p>
 	    </div>
 	    <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>
 	    <div class="id-specified-group">
 	      ' . data_entry_helper::select($species_ctrl_args) . '
          <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" class="follow-on">' . lang::get('LANG_ID_Comment') . ' </label>
        <textarea id="flower:comment" name="flower:comment" class="taxon-comment" rows="5" columns="80"></textarea>
      </div>
    </div>
    <div class="poll-break"></div>
 	<div id="cc-2-environment">
	  <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" 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_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="" />
      ' . 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['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)) . '
    	<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="' . 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', 'suffixTemplate' => 'nosuffix')) . '
 	  </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 .= "\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});\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({filter: filter});\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\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\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\t\$.get(toolStruct.pollURL+toolStruct.pollFile, function(data){\n\t  pollReset(toolStruct);\n\t  var da = data.split('\\n');\n      jQuery(toolStruct.selector+' [name='+toolStruct.type+'\\: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('#'+toolStruct.type+'_taxa_list').append(\"" . lang::get('LANG_Taxa_Unknown_In_Tool') . "\");\n\t  \tjQuery(toolStruct.selector+' [name='+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\titemText = items[j].replace(/</g, '&lt;').replace(/>/g, '&gt;');\n\t\t\tvar found = false;\n\t\t\tfor(i = 0; i< toolStruct.taxaList.length; i++){\n  \t\t\t\tif(toolStruct.taxaList[i].taxon == itemText){\n\t  \t\t\t\tresultsIDs.push(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('#'+toolStruct.type+'_taxa_list').append(resultsText+ ' }');\n\t\tjQuery('#'+toolStruct.type+'-id-button').data('toolRetValues', resultsIDs);\n\t  \tif(notFound != ''){\n\t\t\tvar comment = jQuery(toolStruct.selector+' [name='+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\tjQuery('#'+toolStruct.type+'-id-button').data('toolRetValues', []);\n\tjQuery(toolStruct.selector+' [name='+toolStruct.type+'\\:taxon_details]').val('');\n\tjQuery('#'+toolStruct.type+'_taxa_list').empty();\n\ttoolStruct.pollFile='';\n\ttoolStruct.timeOutTimer = null;\n\ttoolStruct.pollTimer = null;\n};\n\nidButtonPressed = function(toolStruct){\n\tjQuery(toolStruct.selector+' [name='+toolStruct.type+'\\:determination_type]').val('A');\n\tjQuery('#id-'+toolStruct.type+'-later').removeAttr('checked');\n\tjQuery('#'+toolStruct.type+'-id-button').data('toolRetValues', []);\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.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('#id-'+toolStruct.type+'-later').removeAttr('checked');\n\tjQuery('#'+toolStruct.type+'-id-button').data('toolRetValues', []);\n\tjQuery(toolStruct.selector+' [name='+toolStruct.type+'\\:taxon_details]').val('');\n\tjQuery('#'+toolStruct.type+'_taxa_list').empty();\n\tjQuery(toolStruct.selector+' [name='+toolStruct.type+'\\:comment]').val('');\n  \tjQuery(toolStruct.selector+' [name='+toolStruct.type+'\\:determination_type]').val('A');\n};\njQuery('#cc-2-flower-identify select[name=flower\\:taxa_taxon_list_id]').change(function(){\n\tpollReset(flowerIDstruc);\n\ttaxonChosen(flowerIDstruc);\n});\n\nidLater = function (toolStruct){\n\tif (jQuery('#id-'+toolStruct.type+'later').attr('checked') != '') {\n\t  \tjQuery(toolStruct.selector+' [name='+toolStruct.type+'\\:determination_type]').val('A');\n\t\tjQuery('#'+toolStruct.type+'-id-button').data('toolRetValues', []);\n\t\tjQuery(toolStruct.selector+' [name='+toolStruct.type+'\\:taxon_details]').val('');\n\t\tjQuery('#'+toolStruct.type+'_taxa_list').empty();\n\t\tjQuery(toolStruct.selector+' [name='+toolStruct.type+'\\:taxa_taxon_list_id]').val('');\n\t\tjQuery(toolStruct.selector+' [name='+toolStruct.type+'\\:taxon_extra_info]').val(''); // more precise info\n\t\tjQuery(toolStruct.selector+' [name='+toolStruct.type+'\\:comment]').val('');\n\t}\n};\njQuery('#id-flower-later').change(function (){\n\tpollReset(flowerIDstruc);\n\tidLater(flowerIDstruc);\n});\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    });\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\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('#cc-2-flower-identify select[name=flower\\:taxa_taxon_list_id]').val() == '' &&\n\t\t\tjQuery('[name=flower\\:taxon_details]').val() == '' &&\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\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') == '' &&\t jQuery('[name=flower\\:taxon_details]').val() == ''){\n\t\tif(!validateRequiredField('flower\\:taxa_taxon_list_id', '#cc-2-flower-identify')) { valid = 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 (!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   \t\t\t\treturn false;\n   \t\t\t}\n        \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]);\n\t        \tinsertImage('med-'+data.files[0], jQuery('#cc-2-flower-image'), " . $args['Flower_Image_Ratio'] . ");\n\t\t\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]);\n\t        \tinsertImage('med-'+data.files[0], 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 (!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\tdata[findID('determination:taxa_taxon_list_id', data)].value = jQuery('#cc-2-flower-identify select[name=flower\\:taxa_taxon_list_id]').val();\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 (jQuery('#cc-2-flower-identify [name=flower\\:taxon_details]').val() == ''){\n\t\t\t\tif (!validateRequiredField('flower\\:taxa_taxon_list_id', '#cc-2-flower-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 = jQuery('#flower-id-button').data('toolRetValues');\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\tdata.splice(10,8); // remove determination entries.\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    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', true);\n       \t\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+\"&deleted=f&callback=?\", function(occdata) {\n\t\t\t\tif(!(occdata instanceof Array)){\n   \t\t\t\t\talertIndiciaError(occdata);\n   \t\t\t\t} else if (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', false);\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 instanceof Array)){\n   \t\t\t\t\t\t\talertIndiciaError(imgdata);\n   \t\t\t\t\t\t} else 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\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 instanceof Array)){\n   \t\t\t\t\talertIndiciaError(data);\n   \t\t\t\t} else if (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        }  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        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        \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}\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    if (!jQuery(this).children('input').valid()) { valid = false; }\n   \t\tif (!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 (!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) {\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);";
        }
        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']], $defNRAttrOptions)) . "').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\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\t// shade is a boolean, and will always have one set, default no\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('sample_attribute_value', 'sample_attribute_id', 'sample_id', 'sample\\:id', data.outer_id, 'smpAttr', 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    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\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\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', 'valueField' => 'id', 'columns' => 2, '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 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" class="follow-on">' . lang::get('LANG_ID_Comment') . ' </label>
        <textarea id="insect:comment" name="insect:comment" class="taxon-desc" rows="5" columns="80" ></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" />
	    <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')) . 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']], $defNRAttrOptions)) . '
    </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 .= "\n\ninsectIDstruc = {\n\ttype: 'insect',\n\tselector: '#cc-4-insect-identify',\n\tmainForm: '#cc-4-main-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\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('#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]);\n\t        \tinsertImage('med-'+data.files[0], 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\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 = jQuery('#insect-id-button').data('toolRetValues');\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\tdata.splice(4,8); // remove determination entries.\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\tupdatePhotoReel(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\tjQuery('#insect-id-button').data('toolRetValues',[]);\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\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    populateSessionSelect();\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('occurrence_attribute_value', 'occurrence_attribute_id', 'occurrence_id', 'occurrence\\:id', id, 'occAttr', true);\n\tloadImage('occurrence_image', 'occurrence_id', 'occurrence\\:id', id, '#cc-4-insect-image', " . $args['Insect_Image_Ratio'] . ");\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}\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\nupdatePhotoReel = 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 () {setInsect(occId)});\n\telse\n\t\tcontainer.empty();\n\tjQuery('<span>?</span>').addClass('thumb-text').appendTo(container);\n\t// the picture can be async but the determination can'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        data: {}, \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\tcontainer.find('.thumb-text').remove();\n\t    \t}\n  \t\t}, \n    \tdataType: 'json', \n\t    async: false \n    });\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\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}\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\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\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(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\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('.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="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-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 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  \t\t\tjQuery('#cc-5-complete-collection').addClass('loading-button');\n        \tdata[2].value = jQuery('#cc-1-collection-details input[name=sample\\:id]').val();\n\t\t\tdata[3].value = '';\n\t\t\tdata[4].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(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[3].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[4].value = sessDate;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t});\n\t\t\tif(data[3].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\tif(data[3].value == data[4].value){\n\t       \t\tdata[5].value = 'D';\n\t       \t} else {\n\t       \t\tdata[5].value = 'DD';\n  \t\t\t}\n\t       \tjQuery('#cc-1-collection-details,#cc-2').find('[name=sample\\:date]:hidden').val(data[3].value);\n  \t\t\tdata[6].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>';
        data_entry_helper::$javascript .= "\n \t\t\t\nloadAttributes = function(attributeTable, attributeKey, key, keyName, keyValue, prefix, reset_timeout){\n\tvar form = jQuery('input[name='+keyName+'][value='+keyValue+']').parents('form');\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    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        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\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\t  checkProtocolStatus('leave');\n\t\t  populateSessionSelect();\n\t\t},\n\t\tdataType: 'json', \n\t    async: false  \n\t});\n}\n\nloadImage = function(imageTable, key, keyName, keyValue, target, ratio){\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}\n\t});\n}\n\nloadDetermination = function(detData, toolStruc){\n\tjQuery('#'+toolStruc.type+'_taxa_list').empty();\n\tjQuery('#'+toolStruc.type+'-id-button').data('toolRetValues', []);\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);\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;') + 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\tjQuery('#'+toolStruc.type+'-id-button').data('toolRetValues', resultsIDs);\n  \t\t}\n\t} else {\n\t\tjQuery('#id-'+toolStruc.type+'-later').attr('checked', 'checked');\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();\njQuery('#flower-id-button').data('toolRetValues',[]);\njQuery('#insect-id-button').data('toolRetValues',[]);\njQuery('#flower_taxa_list').empty();\njQuery('#insect_taxa_list').empty();\n\t\njQuery.ajax({ \n    type: 'GET', \n    url: \"" . $svcUrl . "\" + \"/report/requestReport?report=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    dataType: 'json', \n    success: function(data) {\n\t  if(!(data instanceof Array)){\n   \t\talertIndiciaError(data);\n   \t  } else if (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', false);\n  \t\t\t\tvar locData = [];\n  \t\t\t\tjQuery.ajax({ \n\t\t\t\t\ttype: 'GET', \n\t\t\t\t\turl: \"" . $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=?\", \n\t\t\t\t\tdataType: 'json', \n\t\t\t\t\tsuccess: function(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\t    locData = locationdata;\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\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', " . $args['Environment_Image_Ratio'] . ", false);\n  \t\t\t\t\t  }\n  \t\t\t\t\t}, \n\t\t\t\t\tdata: {}, \n\t\t\t\t\tasync: false \n\t\t\t\t});\n  \t\t\t\tjQuery.ajax({ \n\t\t\t\t\ttype: 'GET', \n\t\t\t\t\turl: \"" . $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+\"&deleted=f&callback=?\", \n\t\t\t\t\tdataType: 'json', \n\t\t\t\t\tsuccess: 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\t  if(!(flowerData instanceof Array)){\n\t\t\t\t\t\talertIndiciaError(flowerData);\n\t\t\t\t\t  } else if (flowerData.length>0) {\n\t\t\t\t\t\t// The location only holds a valid place if the floral station has been saved: because \n\t\t\t\t\t\t// the location is saved on cc-1 (due to FK constraints), we use the presence of the flower\n\t\t\t\t\t\t// occurrence as the indicator of FS saving. Only load location location at this point.\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\tjQuery('input[name=location\\:centroid_sref]').val(locData[0].centroid_sref);\n\t\t\t\t\t\tjQuery('input[name=location\\:centroid_sref_system]').val(locData[0].centroid_sref_system);\n\t\t\t\t\t\tjQuery('input[name=location\\:centroid_geom]').val(locData[0].centroid_geom);\n\t\t\t\t\t\tjQuery('#imp-sref').change();\n\t\t\t\t\t\tvar parts=locData[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\n\t\t\t\t\t\t\$('#cc-1').foldPanel();\n\t\t\t\t\t\tcheckProtocolStatus(true);\n\t\t\t\t\t\t\$('#cc-2').showPanel();\n\t\t\t\t\t\tjQuery('form#cc-2-floral-station > input[name=occurrence\\:sample_id]').val(data[i].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\t\tloadAttributes('occurrence_attribute_value', 'occurrence_attribute_id', 'occurrence_id', 'occurrence\\:id', flowerData[0].id, 'occAttr', false);\n\t\t\t\t\t\tloadImage('occurrence_image', 'occurrence_id', 'occurrence\\:id', flowerData[0].id, '#cc-2-flower-image', " . $args['Flower_Image_Ratio'] . ");\n\n\t\t\t\t\t\tjQuery.ajax({ \n\t\t\t\t\t\t\ttype: 'GET', \n\t\t\t\t\t\t\turl: \"" . $svcUrl . "/data/determination\" + \n\t\t\t\t\t\t\t\t\t\"?mode=json&view=list&nonce=" . $readAuth['nonce'] . "&auth_token=" . $readAuth['auth_token'] . "&occurrence_id=\"+flowerData[0].id+\"&orderby=id&deleted=f&callback=?\", \n\t\t\t\t\t\t\tdataType: 'json', \n\t\t\t\t\t\t\tsuccess: function(detData) {\n\t\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 loadDetermination(detData, flowerIDstruc);\n  \t\t\t\t\t\t\t}, \n\t\t\t\t\t\t\tdata: {}, \n\t\t\t\t\t\t\tasync: false \n\t\t\t\t\t\t});\n    \t      \t\t\t\t  \n    \t   \t\t\t\tjQuery.ajax({ \n\t\t\t\t\t\t\ttype: 'GET', \n\t\t\t\t\t\t\turl: \"" . $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=?\", \n\t\t\t\t\t\t\tdataType: 'json', \n\t\t\t\t\t\t\tsuccess: function(sessiondata) {\n\t    \t\t\t  \t\t  if(!(sessiondata instanceof Array)){\n   \t\t\t\t\t\t\t\talertIndiciaError(sessiondata);\n   \t\t\t\t\t  \t\t  } else if (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\t\tjQuery('input[name=dummy_date]', thisSession).datepicker('disable').datepicker('setDate', new Date(sessiondata[i].date_start)).datepicker('enable');\n\t\t\t\t\t\t\t\t\tloadAttributes('sample_attribute_value', 'sample_attribute_id', 'sample_id', 'sample\\:id', sessiondata[i].id, 'smpAttr', false);\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+\"&deleted=f&callback=?\", function(insectData) {\n\t\t    \t\t\t\t\t\t\tif(!(insectData instanceof Array)){\n   \t\t\t\t\t\t\t\t\t\t\talertIndiciaError(insectData);\n   \t\t\t\t\t  \t\t  \t\t\t} else if (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\tupdatePhotoReel(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}, \n\t\t\t\t\t\t\tdata: {}, \n\t\t\t\t\t\t\tasync: false \n\t\t\t\t\t\t});\n    \t   \t\t\t  }\n  \t\t\t\t\t}, \n\t\t\t\t\tdata: {}, \n\t\t\t\t\tasync: false \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  }}, \n    data: {}, \n    async: false \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::loading_block_end();
        data_entry_helper::$onload_javascript = "jQuery('.my-loading-hide').addClass('loading-hide').removeClass('my-loading-hide');\n" . data_entry_helper::$onload_javascript . "\nbuildMap();";
        return $r;
    }
示例#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::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;
    }
 /**
  * Return the generated form output.
  * @return Form HTML.
  */
 public static function get_form($args)
 {
     global $user;
     $logged_in = $user->uid > 0;
     // 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'];
     // enable image viewing with FancyBox - only required if the file box is enabled
     //data_entry_helper::$javascript .= "jQuery(\"a.fancybox\").fancybox();\n";
     $r = "\n<form method=\"post\" id=\"entry_form\">\n";
     if (isset($_GET['taxa_taxon_list_id']) || isset($_GET['taxon_external_key'])) {
         if (isset($_GET['taxa_taxon_list_id'])) {
             $filter = array('id' => $_GET['taxa_taxon_list_id']);
         } else {
             $filter = array('external_key' => $_GET['taxon_external_key']);
         }
         $species = data_entry_helper::get_population_data(array('table' => 'taxa_taxon_list', 'extraParams' => $readAuth + $filter + array('taxon_list_id' => $args['list_id'], 'view' => 'detail', 'preferred' => 't')));
         // we need only one result, but there could be more than one picture, therefore multiple rows
         $uniqueMeaning = false;
         if (count($species) == 1) {
             $uniqueMeaning = $species[0]['taxon_meaning_id'];
         }
         if (count($species) > 1) {
             $uniqueMeaning = $species[0]['taxon_meaning_id'];
             foreach ($species as $item) {
                 if ($item['taxon_meaning_id'] != $uniqueMeaning) {
                     $uniqueMeaning = false;
                 }
             }
         }
         if ($uniqueMeaning) {
             // now we have the meaning_id, we need to fetch the actual species in the chosen common name
             $speciesCommon = data_entry_helper::get_population_data(array('table' => 'taxa_taxon_list', 'extraParams' => $readAuth + array('taxon_meaning_id' => $uniqueMeaning, 'language_iso' => iform_lang_iso_639_2($user->lang), 'view' => 'detail')));
             $r .= '<div class="ui-widget ui-widget-content ui-corner-all page-notice ui-helper-clearfix">';
             $nameString = ($species[0]['language_iso'] == 'lat' ? '<em>' : '') . $species[0]['taxon'] . ($species[0]['language_iso'] == 'lat' ? '</em>' : '');
             if (count($speciesCommon) >= 1) {
                 // use a common name if we have one
                 $nameString = $speciesCommon[0]['taxon'] . ' (' . $nameString . ')';
             }
             if (!empty($species[0]['description_in_list'])) {
                 $r .= '<div class="page-notice">' . lang::get('you are recording a', $nameString) . '</div>';
             }
             $taxa_taxon_list_id = $species[0]['id'];
             $images_path = data_entry_helper::$base_url . (isset(data_entry_helper::$indicia_upload_path) ? data_entry_helper::$indicia_upload_path : 'upload/');
             foreach ($species as $item) {
                 if (!empty($item['image_path'])) {
                     $r .= '<a class="fancybox left" href="' . $images_path . $item['image_path'] . '" style="margin: 0 1em 1em;">';
                     $r .= '<img width="100" src="' . $images_path . 'thumb-' . $item['image_path'] . '" />';
                     $r .= '</a>';
                 }
             }
             if (!empty($species[0]['description_in_list'])) {
                 $r .= '<p>' . $species[0]['description_in_list'] . "</p>";
             } else {
                 $r .= '<p>' . lang::get('you are recording a', $nameString) . '</p>';
             }
             $r .= "</div>\n";
         } else {
             $r .= "<p>The species not be identified uniquely from the URL parameters.</p>\n";
         }
     }
     // request automatic JS validation
     data_entry_helper::enable_validation('entry_form');
     $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('about you') . "</span></a></li>\n";
         }
         if (!isset($taxa_taxon_list_id)) {
             $r .= '  <li><a href="#species"><span>' . lang::get('what did you see') . "</span></a></li>\n";
         }
         $r .= '  <li><a href="#place"><span>' . lang::get('where was it') . "</span></a></li>\n";
         $r .= '  <li><a href="#other"><span>' . lang::get('other information') . "</span></a></li>\n";
         $r .= "</ul>\n";
         data_entry_helper::enable_tabs(array('divId' => 'controls', 'style' => $args['interface']));
     }
     if ($user->uid == 0) {
         $r .= "<fieldset id=\"about_you\">\n";
         $r .= '<p class="page-notice ui-state-highlight ui-corner-all">' . lang::get('about you tab instructions') . "</p>";
         $r .= data_entry_helper::text_input(array('label' => lang::get('first name'), 'fieldname' => 'smpAttr:' . $args['first_name_attr_id'], 'class' => 'control-width-4'));
         $r .= data_entry_helper::text_input(array('label' => lang::get('surname'), 'fieldname' => 'smpAttr:' . $args['surname_attr_id'], 'class' => 'control-width-4'));
         $r .= data_entry_helper::text_input(array('label' => lang::get('email'), 'fieldname' => 'smpAttr:' . $args['email_attr_id'], 'class' => 'control-width-4'));
         $r .= data_entry_helper::text_input(array('label' => lang::get('phone number'), 'fieldname' => 'smpAttr:' . $args['phone_attr_id'], 'class' => 'control-width-4'));
         if ($args['interface'] == 'wizard') {
             $r .= data_entry_helper::wizard_buttons(array('divId' => 'controls', 'page' => 'first'));
         }
         $r .= "</fieldset>\n";
     }
     // the species tab is ommitted if the page is called with a taxon in the querystring parameters
     if (isset($taxa_taxon_list_id)) {
         $r .= "<input type=\"hidden\" name=\"occurrence:taxa_taxon_list_id\" value=\"{$taxa_taxon_list_id}\"/>\n";
     } else {
         $r .= "<fieldset id=\"species\">\n";
         $r .= '<p class="page-notice ui-state-highlight ui-corner-all">' . lang::get('species tab instructions') . "</p>";
         $extraParams = $readAuth + array('taxon_list_id' => $args['list_id']);
         if ($args['preferred']) {
             $extraParams += array('preferred' => 't');
         }
         if ($args['restrict_species_to_users_lang']) {
             $extraParams += array('language_iso' => iform_lang_iso_639_2($user->lang));
         }
         $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' => 2, 'view' => 'detail', 'parentField' => 'parent_id', 'extraParams' => $extraParams);
         if ($args['species_ctrl'] == 'tree_browser') {
             // change the node template to include images
             global $indicia_templates;
             $indicia_templates['tree_browser_node'] = '<div>' . '<img src="' . data_entry_helper::$base_url . '/upload/thumb-{image_path}" alt="Image of {caption}" width="80" /></div>' . '<span>{caption}</span>';
         }
         // Dynamically generate the species selection control required.
         $r .= call_user_func(array('data_entry_helper', $args['species_ctrl']), $species_list_args);
         if ($args['interface'] == 'wizard') {
             $r .= data_entry_helper::wizard_buttons(array('divId' => 'controls', 'page' => $user->id == 0 ? 'first' : 'middle'));
         }
         $r .= "</fieldset>\n";
     }
     $r .= "<fieldset id=\"place\">\n";
     // Output all our hidden data here, because this tab is always present
     $r .= $auth['write'];
     if ($logged_in) {
         // If logged in, output some hidden data about the user
         $r .= iform_user_get_hidden_inputs($args);
     }
     // if the species being recorded is a fixed species defined in the URL, then output a hidden
     if (isset($taxa_taxon_list_id)) {
         $r .= "<input type=\"hidden\" name=\"occurrence:taxa_taxon_list_id'\" value=\"" . $taxa_taxon_list_id . "\" />\n";
     }
     $r .= "<input type=\"hidden\" name=\"website_id\" value=\"" . $args['website_id'] . "\" />\n";
     $r .= "<input type=\"hidden\" name=\"survey_id\" value=\"" . $args['survey_id'] . "\" />\n";
     $r .= "<input type=\"hidden\" name=\"record_status\" value=\"" . $args['record_status'] . "\" />\n";
     $r .= '<p class="page-notice ui-state-highlight ui-corner-all">' . lang::get('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::georeference_lookup(iform_map_get_georef_options($args, $auth['read']));
     $r .= data_entry_helper::sref_and_system(array('label' => lang::get('sample:entered_sref'), 'systems' => $systems));
     // retrieve options for the IndiciaMapPanel, and optionally options for OpenLayers.
     $options = iform_map_get_map_options($args, $readAuth);
     $options['tabDiv'] = 'place';
     $olOptions = iform_map_get_ol_options($args);
     $options['scroll_wheel_zoom'] = false;
     $r .= data_entry_helper::map_panel($options, $olOptions);
     if ($args['interface'] == 'wizard') {
         $r .= data_entry_helper::wizard_buttons(array('divId' => 'controls', 'page' => $user->id == 0 && isset($taxa_taxon_list_id) ? 'first' : 'middle'));
     }
     $r .= "</fieldset>\n";
     $r .= "<fieldset id=\"other\">\n";
     $r .= '<p class="page-notice ui-state-highlight ui-corner-all">' . lang::get('other tab instructions') . "</p>";
     $r .= data_entry_helper::date_picker(array('label' => lang::get('Date'), 'fieldname' => 'sample:date'));
     $r .= data_entry_helper::file_box(array('caption' => 'Upload your photos', 'readAuth' => $readAuth, 'resizeWidth' => 1024, 'resizeHeight' => 768, 'table' => 'occurrence_image', 'tabDiv' => 'other', 'runtimes' => array('html5', 'html4')));
     // Dynamically create a control for the abundance, unless overridden for this species
     if (isset($species) && count($species) > 0 && trim($args['abundance_overrides']) !== '') {
         $overrides = explode("\n", $args['abundance_overrides']);
         foreach ($overrides as $override) {
             $tokens = explode(':', $override);
             if ($tokens[0] == $species[0]['taxon']) {
                 // remove the default abundance attribute behaviour
                 $args['abundance_attr_id'] = '';
                 if (trim($tokens[1]) !== '') {
                     $attrIds = explode(',', $tokens[1]);
                     $attributes = data_entry_helper::getAttributes(array('id' => null, 'valuetable' => 'occurrence_attribute_value', 'attrtable' => 'occurrence_attribute', 'key' => 'occurrence_id', 'fieldprefix' => "occAttr", 'extraParams' => $readAuth + array('query' => urlencode(json_encode(array('in' => array('id', $attrIds))))), 'survey_id' => $args['survey_id']));
                     foreach ($attributes as $attribute) {
                         $r .= data_entry_helper::outputAttribute($attribute, array('language' => iform_lang_iso_639_2($user->lang), 'booleanCtrl' => 'checkbox'));
                     }
                 }
             }
         }
     }
     if (!empty($args['abundance_attr_id'])) {
         $abundance_args = array('label' => lang::get('abundance'), 'fieldname' => 'occAttr:' . $args['abundance_attr_id'], 'table' => 'termlists_term', 'captionField' => 'term', 'valueField' => 'id', 'extraParams' => $readAuth + array('termlist_id' => $args['abundance_termlist_id']), 'size' => 6, 'sep' => '<br/>');
         $r .= call_user_func(array('data_entry_helper', $args['abundance_ctrl']), $abundance_args);
     }
     $r .= data_entry_helper::textarea(array('label' => lang::get('sample:comment'), 'fieldname' => 'sample:comment', 'class' => 'wide'));
     $r .= '<div class="footer">' . data_entry_helper::checkbox(array('label' => lang::get('happy for contact'), 'labelClass' => 'auto', 'fieldname' => 'smpAttr:' . $args['contact_attr_id'])) . '</div>';
     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=\"Save\" />\n";
     }
     $r .= "</fieldset>\n";
     $r .= "</div>\n";
     $r .= "</form>";
     return $r;
 }
示例#19
0
function iform_mnhnl_locationattributes($auth, $args, $tabalias, $options)
{
    $creatorAttr = iform_mnhnl_getAttrID($auth, $args, 'location', 'Creator');
    if ($creatorAttr) {
        data_entry_helper::$javascript .= "\njQuery('[name=locAttr:" . $creatorAttr . "],[name^=locAttr:" . $creatorAttr . ":]').removeClass('wide').attr('readonly','readonly');";
    }
    $attrArgs = array('valuetable' => 'location_attribute_value', 'attrtable' => 'location_attribute', 'key' => 'location_id', 'fieldprefix' => 'locAttr', 'extraParams' => $auth['read'], 'survey_id' => $args['survey_id']);
    //    if($options['read_only']===true) $attrArgs['read_only']='read_only';
    $tabName = isset($options['tabNameFilter']) && isset($options['tabNameFilter']) != '' ? $options['tabNameFilter'] : '';
    if (array_key_exists('location:id', data_entry_helper::$entity_to_load) && data_entry_helper::$entity_to_load['location:id'] != "") {
        // if we have location Id to load, use it to get attribute values
        $attrArgs['id'] = data_entry_helper::$entity_to_load['location:id'];
    }
    $locationAttributes = data_entry_helper::getAttributes($attrArgs, false);
    $defAttrOptions = array_merge(array('extraParams' => array_merge($auth['read'], array('view' => 'detail')), 'language' => iform_lang_iso_639_2($args['language'])), $options);
    $r = '';
    foreach ($locationAttributes as $attribute) {
        if ($tabName == '' && $attribute['inner_structure_block'] != "Filter" || strcasecmp($tabName, $attribute['inner_structure_block']) == 0) {
            $opt = $defAttrOptions + get_attr_validation($attribute, $args);
            $r .= data_entry_helper::outputAttribute($attribute, $opt);
        }
    }
    return $r;
}
示例#20
0
 /**
  * Return the generated form output.
  * @return Form HTML.
  */
 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 (!$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) {
             // 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($user->lang), 'taxon_meaning_id' => $meaningId));
         $taxonRecords = data_entry_helper::get_population_data($fetchOpts);
     }
     $url = data_entry_helper::$geoserver_url . 'wms';
     // Get the style if there is one selected
     $style = $args["wms_style"] ? ", styles: '" . $args["wms_style"] . "'" : '';
     data_entry_helper::$onload_javascript .= "\n    var filter='website_id=" . $args['website_id'] . "';";
     if (!$args['show_all_species']) {
         data_entry_helper::$onload_javascript .= "\n    filter += ' AND taxon_meaning_id={$meaningId}';\n";
     }
     data_entry_helper::$onload_javascript .= "\n    var distLayer = new OpenLayers.Layer.WMS(\n\t        '" . $args['layer_title'] . "',\n\t        '{$url}',\n\t        {layers: '" . $args["wms_feature_type"] . "', transparent: true, CQL_FILTER: filter {$style}},\n\t        {isBaseLayer: false, sphericalMercator: true, singleTile: true}\n      );\n";
     $options['layers'][] = 'distLayer';
     // output a legend
     if ($args['show_all_species']) {
         $layerTitle = lang::get('All species occurrences');
     } else {
         $layerTitle = str_replace('{species}', $taxonRecords[0]['taxon'], $args['layer_title']);
     }
     $r .= '<div id="legend" class="ui-widget ui-widget-content ui-corner-all">';
     $r .= '<div><img src="' . data_entry_helper::$geoserver_url . 'wms?SERVICE=WMS&VERSION=1.1.1&REQUEST=GetLegendGraphic&LAYER=' . $args['wms_feature_type'] . '&Format=image/jpeg' . '&STYLE=' . $args["wms_style"] . '" alt=""/>' . $layerTitle . '</div>';
     $r .= '</div>';
     // output a map
     $r .= data_entry_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'])) {
             data_entry_helper::$javascript .= "setTimeout('window.location=\"" . $args['load_on_refresh'] . "\";', " . $args['refresh_timer'] . "*1000 );\n";
         } else {
             data_entry_helper::$javascript .= "setTimeout('window.location.reload( false );', " . $args['refresh_timer'] . "*1000 );\n";
         }
     }
     return $r;
 }
 /**
  * Returns the species checklist input control.
  * @param array $auth Read authorisation tokens
  * @param array $args Form configuration
  * @param array $extraParams Extra parameters array, pre-configured with filters for taxa and name types.
  * @param array $options additional options for the control, e.g. those configured in the form structure.
  * @return HTML for the species_checklist control.
  */
 protected static function get_control_species_checklist($auth, $args, $extraParams, $options)
 {
     global $user;
     // Build the configuration options
     if (isset($options['view'])) {
         $extraParams['view'] = $options['view'];
     }
     // There may be options in the form occAttr:n|param => value targetted at specific attributes
     $occAttrOptions = array();
     $optionToUnset = array();
     foreach ($options as $option => $value) {
         // split the id of the option into the attribute name and option name.
         $optionParts = explode('|', $option);
         if ($optionParts[0] != $option) {
             // an occurrence attribute option was found
             $attrName = $optionParts[0];
             $optName = $optionParts[1];
             // split the attribute name into the type and id (type will always be occAttr)
             $attrParts = explode(':', $attrName);
             $attrId = $attrParts[1];
             if (!isset($occAttrOptions[$attrId])) {
                 $occAttrOptions[$attrId] = array();
             }
             $occAttrOptions[$attrId][$optName] = apply_user_replacements($value);
             $optionToUnset[] = $option;
         }
     }
     // tidy up options array
     foreach ($optionToUnset as $value) {
         unset($options[$value]);
     }
     // make sure that if extraParams is specified as a config option, it does not replace the essential stuff
     if (isset($options['extraParams'])) {
         $options['extraParams'] = array_merge($extraParams, $options['extraParams']);
     }
     $species_ctrl_opts = array_merge(array('occAttrOptions' => $occAttrOptions, 'listId' => $args['list_id'], 'label' => lang::get('occurrence:taxa_taxon_list_id'), 'columns' => 1, 'extraParams' => $extraParams, 'survey_id' => $args['survey_id'], 'occurrenceComment' => $args['occurrence_comment'], 'occurrenceSensitivity' => isset($args['occurrence_sensitivity']) ? $args['occurrence_sensitivity'] : false, 'occurrenceImages' => $args['occurrence_images'], 'PHPtaxonLabel' => true, 'language' => iform_lang_iso_639_2(hostsite_get_user_field('language')), 'cacheLookup' => $args['cache_lookup'], 'speciesNameFilterMode' => self::getSpeciesNameFilterMode($args), 'userControlsTaxonFilter' => isset($args['user_controls_taxon_filter']) ? $args['user_controls_taxon_filter'] : false, 'subSpeciesColumn' => $args['sub_species_column'], 'copyDataFromPreviousRow' => !empty($args['copy_species_row_data_to_new_rows']) && $args['copy_species_row_data_to_new_rows'], 'previousRowColumnsToInclude' => empty($args['previous_row_columns_to_include']) ? '' : $args['previous_row_columns_to_include'], 'editTaxaNames' => !empty($args['edit_taxa_names']) && $args['edit_taxa_names'], 'includeSpeciesGridLinkPage' => !empty($args['include_species_grid_link_page']) && $args['include_species_grid_link_page'], 'speciesGridPageLinkUrl' => $args['species_grid_page_link_url'], 'speciesGridPageLinkParameter' => $args['species_grid_page_link_parameter'], 'speciesGridPageLinkTooltip' => $args['species_grid_page_link_tooltip']), $options);
     if ($groups = hostsite_get_user_field('taxon_groups')) {
         $species_ctrl_opts['usersPreferredGroups'] = unserialize($groups);
     }
     if ($args['extra_list_id']) {
         $species_ctrl_opts['lookupListId'] = $args['extra_list_id'];
     }
     //We only do the work to setup the filter if the user has specified a filter in the box
     if (!empty($args['taxon_filter_field']) && !empty($args['taxon_filter'])) {
         $species_ctrl_opts['taxonFilterField'] = $args['taxon_filter_field'];
         $filterLines = helper_base::explode_lines($args['taxon_filter']);
         $species_ctrl_opts['taxonFilter'] = $filterLines;
     }
     if (isset($args['col_widths']) && $args['col_widths']) {
         $species_ctrl_opts['colWidths'] = explode(',', $args['col_widths']);
     }
     call_user_func(array(self::$called_class, 'build_grid_taxon_label_function'), $args, $options);
     if (self::$mode == self::MODE_CLONE) {
         $species_ctrl_opts['useLoadedExistingRecords'] = true;
     }
     // Start by outputting a hidden value that tells us we are using a grid when the data is posted,
     // then output the grid control
     return '<input type="hidden" value="true" name="gridmode" />' . data_entry_helper::species_checklist($species_ctrl_opts);
 }
 /**
  * Returns the species checklist input control.
  * @param array $auth Read authorisation tokens
  * @param array $args Form configuration
  * @param array $extraParams Extra parameters array, pre-configured with filters for taxa and name types.
  * @param array $options additional options for the control, e.g. those configured in the form structure.
  * @return HTML for the species_checklist control.
  */
 protected static function get_control_species_checklist($auth, $args, $extraParams, $options)
 {
     global $user;
     // Build the configuration options
     if (isset($options['view'])) {
         $extraParams['view'] = $options['view'];
     }
     // make sure that if extraParams is specified as a config option, it does not replace the essential stuff
     if (isset($options['extraParams'])) {
         $options['extraParams'] = array_merge($extraParams, $options['extraParams']);
     }
     $species_ctrl_opts = array_merge(array('occAttrOptions' => array(), 'listId' => '', 'label' => lang::get('occurrence:taxa_taxon_list_id'), 'columns' => 1, 'extraParams' => $extraParams, 'survey_id' => $args['survey_id'], 'occurrenceComment' => $args['occurrence_comment'], 'occurrenceSensitivity' => isset($args['occurrence_sensitivity']) ? $args['occurrence_sensitivity'] : false, 'occurrenceImages' => $args['occurrence_images'], 'PHPtaxonLabel' => true, 'language' => iform_lang_iso_639_2(hostsite_get_user_field('language')), 'cacheLookup' => $args['cache_lookup'], 'speciesNameFilterMode' => self::getSpeciesNameFilterMode($args), 'userControlsTaxonFilter' => false, 'subSpeciesColumn' => false, 'copyDataFromPreviousRow' => false, 'editTaxaNames' => !empty($args['edit_taxa_names']) && $args['edit_taxa_names']), $options);
     if ($groups = hostsite_get_user_field('taxon_groups')) {
         $species_ctrl_opts['usersPreferredGroups'] = unserialize($groups);
     }
     if ($args['map_taxon_list_id']) {
         $species_ctrl_opts['lookupListId'] = $args['map_taxon_list_id'];
     }
     //We only do the work to setup the filter if the user has specified a filter in the box
     if (!empty($args['map_taxon_filter_field']) && !empty($args['map_taxon_filter'])) {
         $species_ctrl_opts['taxonFilterField'] = $args['map_taxon_filter_field'];
         $filterLines = helper_base::explode_lines($args['map_taxon_filter']);
         $species_ctrl_opts['taxonFilter'] = $filterLines;
     }
     if (isset($args['col_widths']) && $args['col_widths']) {
         $species_ctrl_opts['colWidths'] = explode(',', $args['col_widths']);
     }
     self::build_grid_taxon_label_function($args, $options);
     // Start by outputting a hidden value that tells us we are using a grid when the data is posted,
     // then output the grid control
     return '<input type="hidden" value="true" name="gridmode" />' . data_entry_helper::species_checklist($species_ctrl_opts);
 }
示例#23
0
 protected static function get_control_sectionlist($auth, $args, $tabalias, $options)
 {
     $numAttrs = count($options['smpAttr']);
     $attributes = data_entry_helper::getAttributes(array('valuetable' => 'sample_attribute_value', 'attrtable' => 'sample_attribute', 'key' => 'sample_id', 'fieldprefix' => 'smpAttr', 'extraParams' => $auth['read'], 'survey_id' => $args['survey_id']));
     /* We will make the assumption that only one of these will be put onto a form.
      * A lot of this is copied from the species control and has the same features. */
     $extraParams = $auth['read'] + array('view' => 'detail', 'reset_timeout' => 'true');
     if ($args['species_names_filter'] == 'preferred') {
         $extraParams += array('preferred' => 't');
     }
     if ($args['species_names_filter'] == 'language') {
         $extraParams += array('language_iso' => iform_lang_iso_639_2($user->lang));
     }
     // A single species entry control of some kind
     if ($args['extra_list_id'] == '') {
         $extraParams['taxon_list_id'] = $args['list_id'];
     } elseif ($args['species_ctrl'] == 'autocomplete') {
         $extraParams['taxon_list_id'] = $args['extra_list_id'];
     } else {
         $extraParams['taxon_list_id'] = array($args['list_id'], $args['extra_list_id']);
     }
     $species_list_args = array_merge(array('fieldname' => 'sectionlist_taxa_taxon_list_id', 'id' => 'sectionlist_taxa_taxon_list_id', 'table' => 'taxa_taxon_list', 'captionField' => 'taxon', 'valueField' => 'taxon_meaning_id', 'columns' => 2, 'parentField' => 'parent_id', 'extraParams' => $extraParams, 'numValues' => $args['max_species_ids']), $options);
     $defNRAttrOptions = array('extraParams' => $auth['read'] + array('orderby' => 'id'), 'lookUpKey' => 'meaning_id', 'suffixTemplate' => 'nosuffix');
     $defAttrOptions = $defNRAttrOptions;
     $defAttrOptions['validation'] = array('required');
     // do not allow tree browser
     if ($args['species_ctrl'] == 'tree_browser') {
         return '<p>Can not use tree browser in this context</p>';
     }
     data_entry_helper::$javascript .= "\nvar numAttrs = " . $numAttrs . ";\ndelete_section_species_row = function(row){\n  if(confirm(\"" . lang::get('sectionlist:confirmremove') . "\"+row.find('.seclistspecname')[0].textContent+\"?\")){\n    row.find('input').each(function(){\n      // Fieldname is SL:speciesID:section:SectionsampleID:OccID:AttrValID\n      var parts = jQuery(this).attr('name').split(':');\n      if(parts[4] != '-'){\n        var delList = jQuery('#SLDEL').val();\n        jQuery('#SLDEL').val((delList == '' ? '' : delList+',')+parts[4]);\n      }\n    });\n    row.remove();\n    // recalc the aucune checkboxes.\n    for(var i=1; i<= " . $args['max_number_sections'] . "; i++){\n      if(jQuery('.sectionlist').find('[section='+i+']').length > 0) {\n        section_column_changed(i);\n      }\n    }\n  }\n};\nremove_section_columns = function(from, to){\n  var rows=jQuery('.sectionlist').find('tr');\n  for(var i=0; i< rows.length; i++){\n    for(var j=to; j>= from; j--){\n      var cell = jQuery(rows[i]).children(':eq('+j+')');\n      cell.find('input').each(function(){\n        // Fieldname is SL:speciesID:section:SectionsampleID:OccID:AttrValID\n        var parts = jQuery(this).attr('name').split(':');\n        if(parts[4] != '-'){\n          var delList = jQuery('#SLDEL').val();\n          jQuery('#SLDEL').val((delList == '' ? '' : delList+',')+parts[4]);\n        }\n      });\n      cell.remove();\n    }\n  }\n};\n// at this point, the species ID should hold the preferred taxon id.\nadd_section_species_row = function(speciesID){\n  // first check if already set up. If yes do nothing.\n  if(jQuery('.sectionlist').find('[taxonID='+speciesID+']').length > 0) return;\n  var remButton = jQuery('<img src=\"/misc/watchdog-error.png\" alt=\"Delete\"/>').click(function(){\n    delete_section_species_row(jQuery(this).parent().parent()); // image, td, tr\n  });\n  var name = jQuery('<span class=\"seclistspecname\"></span>').attr('taxonID',speciesID);\n  var cell = jQuery('<td></td>').append(remButton).append(name);\n  var row = jQuery('<tr></tr>').data('taxonID',speciesID).insertBefore('.seclistspecrow').append(cell);\n  for(var i=1; i<= " . $args['max_number_sections'] . "; i++){\n    if(jQuery('.sectionlist').find('[section='+i+']').length > 0) {\n      var sampleID = jQuery('.sectionlist').find('tr:eq(0)').find('th:eq('+i+')').data('sampleID');\n      add_section_value(row, i, sampleID);  // these are all empty, so aucune value stays unchanged.\n    }\n  }\n  jQuery.getJSON(\"" . self::$svcUrl . "/data/taxa_taxon_list/\"+speciesID +\n\t\t\"?mode=json&view=detail&auth_token=" . $auth['read']['auth_token'] . "&nonce=" . $auth['read']["nonce"] . "\" +\n\t\t\t\"&callback=?\", function(data) {\n        if (data.length>0) {\n          // we are assuming that this is the preferred ID\n          jQuery('.seclistspecname').filter('[taxonID='+data[0].id+']').empty().attr('meaningID', data[0].taxon_meaning_id).append('<b>'+data[0].taxon+'</b>');\n        }}\n  );\n};\nsection_column_changed = function(column){\n  var aucuneControl = jQuery(':checkbox[name^=\"SLA\\:'+column+'\\:\"]').filter('[name\$=\"\\:" . $args['aucune_attr_id'] . "\"]').attr('disabled', false);\n  var rows = jQuery('.sectionlist').find('tr');\n  for(var j = 1; j < (rows.length-" . ($numAttrs + 1) . "); j++){\n    if(jQuery(rows[j]).find('td').filter(':eq('+column+')').find('[value!=\"\"]').length > 0)\n      aucuneControl.attr('checked', false).attr('disabled', true);\n  };\n};\nsection_data_changed = function(){\n  section_column_changed(jQuery(this).attr('name').split(':')[2]);\n};\n\nadd_section_value = function(row, column, sampleID){\n  // Fieldname is SL:speciesID:section:SectionsampleID:OccID:AttrID\n  var taxonID = jQuery(row).find('.seclistspecname').attr('taxonID');\n  var ctrl = jQuery('<input type=\"text\" name=\"SL:'+taxonID+':'+column+':'+sampleID+':-:-\" class=\"sl-input digits\" value=\"\" />').change(section_data_changed);\n  jQuery('<td></td>').append(ctrl).appendTo(row);\n};\n\nadd_section_column = function(column, sampleID){\n  var rows=jQuery('.sectionlist').find('tr');\n  for(var i=1; i<= column; i++){\n    if(jQuery('.sectionlist').find('[section='+i+']').length == 0) {\n    \tfor(var j = 0; j < rows.length; j++){\n    \t\tif(j==0){ //header\n    \t\t  var header = jQuery('<span class=\"sectionlist-column-header\">" . lang::get('sectionlist:section') . " '+i+'</span>').attr('section',i);\n    \t\t  jQuery('<th></th>').data('sampleID', i==column ? sampleID : '-').append(header).appendTo(rows[j]);\n    \t\t} else if(j == (rows.length-" . (1 + $numAttrs) . ")) {// species selection row has no data.\n    \t\t  jQuery('<td></td>').appendTo(rows[j]);";
     global $indicia_templates;
     $tempLabel = $indicia_templates['label'];
     $indicia_templates['label'] = '';
     // we don't want labels in the cell
     // Fieldname is SLA:section:SectionsampleID:AttrValID:AttrID
     for ($i = 0; $i < $numAttrs; $i++) {
         data_entry_helper::$javascript .= "\n    \t\t} else if(j == (rows.length-" . ($numAttrs - $i) . ")) { // section sample attribute rows.\n    \t\t  var newName = 'SLA:'+i+':'+(i==column ? sampleID : '-')+':-'; //this will replace the smpAttr, so the AttrID is left alone at the end.\n    \t\t  var attr = '" . str_replace("\n", "", data_entry_helper::outputAttribute($attributes[$options['smpAttr'][$i]], $attributes[$options['smpAttr'][$i]]['data_type'] == 'Boolean' || $attributes[$options['smpAttr'][$i]]['data_type'] == 'B' ? $defNRAttrOptions : $defAttrOptions)) . "';\n    \t\t  jQuery('<td>'+attr.replace(/smpAttr/g, newName)+'</td>').appendTo(rows[j]);";
     }
     $indicia_templates['label'] = $tempLabel;
     data_entry_helper::$javascript .= "\n            } else\n              add_section_value(rows[j], i, (i==column ? sampleID : '-'));\n    \t}\n    } else if (i==column && jQuery(rows[0]).find('th:eq('+i+')').data('sampleID') == '-' && sampleID != '-'){\n      jQuery(rows[0]).find('th:eq('+i+')').data('sampleID', sampleID);\n      for(var j = 1; j < rows.length; j++){\n        var input = jQuery(rows[j]).find('td:eq('+i+')').find('input,select');\n        if(input.length > 0) {\n          var parts = input.attr('name').split(':');\n          if(parts[0]=='SL')\n            input.attr('name','SL:'+parts[1]+':'+i+':'+sampleID+':'+parts[4]+':'+parts[5]);\n          else if(parts[0]=='SLA')\n            input.attr('name','SLA:'+i+':'+sampleID+':'+parts[3]+':'+parts[4]);\n        }\n      }\n    }\n  }\n  if(jQuery('#sectionlist_number').val() < column) jQuery('#sectionlist_number').val(column);\n  section_column_changed(column);\n};\njQuery('#sectionlist_number').change(function(){\n  // initially we put in the restriction that it is only possible to increase the number of sections.\n  var currentCols = jQuery('.sectionlist-column-header').length;\n  if(currentCols > jQuery('#sectionlist_number').val()){\n    if(!confirm(\"" . lang::get('sectionlist:confirmremovecolumns') . "\")) return;\n    remove_section_columns(parseInt(jQuery('#sectionlist_number').val())+1, currentCols);\n  }\n  add_section_column(jQuery('#sectionlist_number').val(),'-');\n});\nadd_section_species = function(speciesID, section, sectionSampleID, occurrenceID, attributeID, value){\n  add_section_column(section, sectionSampleID);\n  add_section_species_row(speciesID);\n  jQuery('[name^=\"SL\\:'+speciesID+'\\:'+section+'\\:\"]').attr('name','SL:'+speciesID+':'+section+':'+sectionSampleID+':'+occurrenceID+':'+attributeID).val(value).change()\n  section_column_changed(section);\n};\nadd_section_attribute = function(section, sectionSampleID, attrValID, attributeID, value){\n  // Fieldname is SLA:section:SectionsampleID:AttrValID:AttrID\n  add_section_column(section, sectionSampleID);\n  jQuery('[name^=\"SLA\\:'+section+'\\:\"]').each(function(){\n    var parts = jQuery(this).attr('name').split(':');\n    if(attributeID == parts[4]) {\n      var myName = jQuery(this).attr('name');\n      var checkboxes = jQuery('[name=\"'+myName+'\"]:checkbox');\n      if(checkboxes.length > 0){\n        checkboxes.attr('checked', value == '1' ? true : false);\n      } else {\n        jQuery(this).val(value);\n      }\n      jQuery(this).attr('name','SLA:'+section+':'+sectionSampleID+':'+attrValID+':'+attributeID);\n    }\n  });\n};\njQuery('#sectionlist_taxa_taxon_list_id').change(function(){\n  // when this is called the value stored is the taxon_meaning_id: .\n  // Initially check that row does not already exist:\n  var existRows = jQuery('.seclistspecname').filter('[meaningID='+jQuery('#sectionlist_taxa_taxon_list_id').val()+']');\n  if(existRows.length>0)\n    alert(\"" . lang::get('sectionlist:rowexists') . "\"+existRows[0].textContent);\n  else\n    // Next convert to the preferred ID\n    jQuery.getJSON(\"" . self::$svcUrl . "/data/taxa_taxon_list/\" +\n\t\t\"?mode=json&view=detail&auth_token=" . $auth['read']['auth_token'] . "&nonce=" . $auth['read']["nonce"] . "&preferred=true&taxon_meaning_id=\" + jQuery('#sectionlist_taxa_taxon_list_id').val() +\n\t\t\t\"&callback=?\", function(data) {\n        if (data.length>0) {\n  \t\t\tadd_section_species_row(data[0].id);\n        }});\n  jQuery('#sectionlist_taxa_taxon_list_id\\\\:taxon').val('');\n});\njQuery('#sectionlist_number').change();\n";
     if ($args['init_species_ids'] != '') {
         $init_species = explode(',', $args['init_species_ids']);
         foreach ($init_species as $toAdd) {
             data_entry_helper::$javascript .= "add_section_species_row(" . $toAdd . ");\n";
         }
     }
     $myHidden = '';
     // here put in a load of JS calls to build the grids
     if (isset(data_entry_helper::$entity_to_load['auth_token'])) {
         // post failed
         foreach (data_entry_helper::$entity_to_load as $key => $value) {
             $parts = explode(':', $key);
             if ($parts[0] == 'SL' && $value != '') {
                 data_entry_helper::$javascript .= "add_section_species(" . $parts[1] . "," . $parts[2] . ",\"" . $parts[3] . "\",\"" . $parts[4] . "\",\"" . $parts[5] . "\",\"" . $value . "\");\n";
             } else {
                 if ($parts[0] == 'SLS' || $parts[0] == 'SLDEL') {
                     $myHidden .= '<input type="hidden" name="' . $key . '" value="' . $value . '">';
                 } else {
                     if ($parts[0] == 'SLA' && $value != '') {
                         data_entry_helper::$javascript .= "add_section_attribute(" . $parts[1] . "," . $parts[2] . ",\"" . $parts[3] . "\",\"" . $parts[4] . "\",\"" . $value . "\");\n";
                     }
                 }
             }
         }
     } else {
         if (isset(data_entry_helper::$entity_to_load['sample:id'])) {
             //sample specified
             $myHidden = '<input type="hidden" id="SLDEL" name="SLDEL" value="" >';
             data_entry_helper::$javascript .= "jQuery('#SLDEL').val('');";
             $url = self::$svcUrl . '/data/sample?parent_id=' . data_entry_helper::$entity_to_load['sample:id'];
             $url .= "&mode=json&view=detail&auth_token=" . $auth['read']['auth_token'] . "&nonce=" . $auth['read']["nonce"];
             $session = curl_init($url);
             curl_setopt($session, CURLOPT_RETURNTRANSFER, true);
             $entities = json_decode(curl_exec($session), true);
             foreach ($entities as $entity) {
                 if (substr($entity['location_name'], 0, 3) == 'SL ') {
                     $section = explode(' ', $entity['location_name']);
                     $section = $section[2];
                     $myHidden .= '<input type="hidden" name="SLS:' . $section . '" value="' . $entity['id'] . '">';
                     $url = self::$svcUrl . '/data/occurrence?sample_id=' . $entity['id'];
                     $url .= "&mode=json&view=detail&auth_token=" . $auth['read']['auth_token'] . "&nonce=" . $auth['read']["nonce"];
                     $session = curl_init($url);
                     curl_setopt($session, CURLOPT_RETURNTRANSFER, true);
                     $OCCentities = json_decode(curl_exec($session), true);
                     foreach ($OCCentities as $OCCentity) {
                         $url = self::$svcUrl . '/data/occurrence_attribute_value?mode=json&view=list&nonce=' . $auth['read']["nonce"] . '&auth_token=' . $auth['read']['auth_token'] . '&deleted=f&occurrence_id=' . $OCCentity['id'] . '&occurrence_attribute_id=' . $args['quant_dist_attr_id'];
                         $session = curl_init($url);
                         curl_setopt($session, CURLOPT_RETURNTRANSFER, true);
                         $ATTRentities = json_decode(curl_exec($session), true);
                         foreach ($ATTRentities as $ATTRentity) {
                             data_entry_helper::$javascript .= "\nadd_section_species(" . $OCCentity['taxa_taxon_list_id'] . "," . $section . "," . $OCCentity['sample_id'] . "," . $ATTRentity['occurrence_id'] . "," . (isset($ATTRentity['id']) ? $ATTRentity['id'] : "\"-\"") . "," . ($ATTRentity['raw_value'] == '' ? "\"\"" : $ATTRentity['raw_value']) . ");";
                         }
                     }
                     // TBS SLA
                     $url = self::$svcUrl . '/data/sample_attribute_value?mode=json&view=list&nonce=' . $auth['read']["nonce"] . '&auth_token=' . $auth['read']['auth_token'] . '&deleted=f&sample_id=' . $entity['id'];
                     $session = curl_init($url);
                     curl_setopt($session, CURLOPT_RETURNTRANSFER, true);
                     $ATTRentities = json_decode(curl_exec($session), true);
                     foreach ($ATTRentities as $ATTRentity) {
                         // Fieldname is SLA:section:SectionsampleID:AttrValID:AttrID
                         if ($ATTRentity['id'] != '') {
                             data_entry_helper::$javascript .= "\nadd_section_attribute(" . $section . "," . $entity['id'] . "," . $ATTRentity['id'] . "," . $ATTRentity['sample_attribute_id'] . "," . $ATTRentity['raw_value'] . ");";
                         }
                     }
                 }
             }
         }
     }
     $retVal = $myHidden . '<div class="sectionlist"><table border="1" ><tr><th>' . lang::get('sectionlist:species') . '</th></tr><tr class="seclistspecrow" ><td>' . call_user_func(array('data_entry_helper', $args['species_ctrl']), $species_list_args) . '</td></tr>';
     for ($i = 0; $i < $numAttrs; $i++) {
         $retVal .= '<tr><td>' . $attributes[$options['smpAttr'][$i]]['caption'] . '</td></tr>';
     }
     $retVal .= '</table></div>';
     data_entry_helper::$javascript .= "\n// override the default results function - doesn't seem to use value field.\njQuery('input#sectionlist_taxa_taxon_list_id\\\\:taxon').unbind(\"result\");\njQuery('input#sectionlist_taxa_taxon_list_id\\\\:taxon').result(function(event, data, value) {\n      jQuery('input#sectionlist_taxa_taxon_list_id').attr('value', value);\n      jQuery('input#sectionlist_taxa_taxon_list_id').change();\n});\n";
     return $retVal;
 }
示例#24
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('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']));
        $language = iform_lang_iso_639_2($args['language']);
        $defAttrOptions = array('extraParams' => $readAuth, 'lookUpListCtrl' => 'checkbox_group', 'booleanCtrl' => 'checkbox', '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 packages the post into the correct format
        $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'], 'orderby' => 'taxon'), 'suffixTemplate' => 'nosuffix');
        $focus_flower_ctrl_args = $flower_ctrl_args;
        $focus_flower_ctrl_args['fieldname'] = 'determination:taxa_taxon_list_id';
        $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'], 'orderby' => 'taxon'), 'suffixTemplate' => 'nosuffix');
        $focus_insect_ctrl_args = $insect_ctrl_args;
        $focus_insect_ctrl_args['fieldname'] = 'determination:taxa_taxon_list_id';
        $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';
        $options2 = $options;
        $options['searchLayer'] = 'true';
        $options['editLayer'] = 'false';
        $options['layers'] = array('polygonLayer');
        $options2['divId'] = "map2";
        $options2['layers'] = array('locationLayer');
        // TBD Breadcrumb
        $r .= '
<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>
	<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-active ui-corner-all">
	  		<div id="fold-name-button" class="ui-state-default ui-corner-all fold-button">&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-accordion-content-active 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-active ui-corner-all">
	  		<div id="fold-date-button" class="ui-state-default ui-corner-all fold-button">&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-accordion-content-active 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') . '" />
       		<label for="start_date" >' . lang::get('LANG_And') . ':</label>
  			<input type="text" size="10" id="end_date" name="end_date" value="' . lang::get('click here') . '" />
  		</div>
  		<div id="flower-filter-header" class="ui-accordion-header ui-helper-reset ui-state-active ui-corner-all">
	  		<div id="fold-flower-button" class="ui-state-default ui-corner-all fold-button">&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-accordion-content-active ui-corner-all">
		  ' . data_entry_helper::select($flower_ctrl_args) . data_entry_helper::outputAttribute($occurrence_attributes[$args['flower_type_attr_id']], $defAttrOptions) . 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-active ui-corner-all">
	  		<div id="fold-insect-button" class="ui-state-default ui-corner-all fold-button">&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-accordion-content-active ui-corner-all">
		  ' . data_entry_helper::select($insect_ctrl_args) . data_entry_helper::outputAttribute($sample_attributes[$args['sky_state_attr_id']], $defAttrOptions) . data_entry_helper::outputAttribute($sample_attributes[$args['temperature_attr_id']], $defAttrOptions) . data_entry_helper::outputAttribute($sample_attributes[$args['wind_attr_id']], $defAttrOptions) . 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(array('label' => lang::get('LANG_Georef_Label'), 'georefPreferredArea' => $args['georefPreferredArea'], 'georefCountry' => $args['georefCountry'], 'georefLang' => $args['language'], 'suffixTemplate' => 'nosuffix')) . '
 	        <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" />
 	      </div>
	  		' . data_entry_helper::map_panel($options, $olOptions) . '
		</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="collection-header" class="ui-accordion-header ui-helper-reset ui-state-active ui-corner-all">
	  <div id="collection-title">
	  	<span> </span>
      </div>
	</div>
	<div id="collection-details" class="ui-accordion-content ui-helper-reset ui-widget-content ui-accordion-content-active ui-corner-top">
	  <div id="flower-image">
      </div>
	  <div id="collection-description">
	    <p id="collection-date"></p>
	    <p id="collection-name"></p>
	    <p id="collection-flower-name"></p>
	    <p>' . $occurrence_attributes[$args['flower_type_attr_id']]['caption'] . ': <span id="collection-flower-type"></span></p>
	    <p>' . $location_attributes[$args['habitat_attr_id']]['caption'] . ': <span id="collection-habitat"></span></p>
	    <p id="collection-locality"></p>
	    <p id="collection-user-name"></p>
	  </div>
	  <div id="environment-image">
      </div>
      <div id="map2_container">' . data_entry_helper::map_panel($options2, $olOptions) . '
      </div>
    </div>
	<div id="collection-insects" class="ui-accordion-content ui-helper-reset ui-widget-content ui-accordion-content-active ui-corner-bottom">
    </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">
	<h1 id="fo-taxon"></h1>
	<div id="fo-header" class="ui-accordion-header ui-helper-reset ui-state-active ui-corner-all">
	  <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>
	  </div>
	  <div id="fo-breadcrumb">
	  	<span> </span>
      </div>
	</div>
	<div id="fo-warning" class="ui-accordion-content ui-helper-reset ui-widget-content ui-corner-top ui-accordion-content-active"></div>
	<div id="fo-picture" class="ui-accordion-content ui-helper-reset ui-widget-content ui-accordion-content-active">
	  <div id="fo-image">
      </div>
    </div>
	<div id="fo-identification" class="ui-accordion-header ui-helper-reset ui-state-active">';
        if (user_access('IForm n' . $node->nid . ' insect expert')) {
            $r .= '<div id="fo-new-insect-id-button" class="ui-state-default ui-corner-all new-id-button">' . lang::get('LANG_New_ID') . '</div>';
        }
        if (user_access('IForm n' . $node->nid . ' flower expert')) {
            $r .= '<div id="fo-new-flower-id-button" class="ui-state-default ui-corner-all new-id-button">' . lang::get('LANG_New_ID') . '</div>';
        }
        $r .= ' 
	  <div id="fo-doubt-button" class="ui-state-default ui-corner-all doubt-button">' . lang::get('LANG_Doubt') . '</div>
	  <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>';
        if (user_access('IForm n' . $node->nid . ' insect expert')) {
            $r .= '
	<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 . '" />
		' . ($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($focus_insect_ctrl_args) . '
        <input type="submit" id="id_submit_button" class="ui-state-default ui-corner-all submit-button" value="' . lang::get('LANG_Validate') . '" />
      </form>
	</div>';
        }
        if (user_access('IForm n' . $node->nid . ' flower expert')) {
            $r .= '
    <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 . '" />
		' . ($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($focus_flower_ctrl_args) . '
        <input type="submit" id="id_submit_button" class="ui-state-default ui-corner-all submit-button" value="' . lang::get('LANG_Validate') . '" />
      </form>
	</div>';
        }
        $r .= '
	<div id="fo-id-history" class="ui-accordion-content ui-helper-reset ui-widget-content ui-corner-bottom ui-accordion-content-active">
	</div>
	<div id="fo-addn-info-header" class="ui-accordion-header ui-helper-reset ui-state-active ui-corner-all">
	  <div id="fo-addn-info-title">
	  	<span>' . lang::get('LANG_Additional_Info_Title') . '</span>
      </div>
	</div>
	<div id="fo-insect-addn-info" class="ui-accordion-content ui-helper-reset ui-widget-content ui-corner-all ui-accordion-content-active">
	    <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-date"></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-sahed"></span></p>
	</div>
	<div id="fo-flower-addn-info" class="ui-accordion-content ui-helper-reset ui-widget-content ui-corner-all 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-all">
	    <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-corner-all 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-all ui-accordion-content-active">
	</div>
	<div style="display:none" />
      <form id="fo-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:id" value="" />
    	<input type="hidden" name="determination:dubious" value="Y" />
      </form>
    </div>	
</div>
';
        data_entry_helper::$javascript .= "\n\$.validator.messages.required = \"" . lang::get('validation_required') . "\";\njQuery('#start_date').datepicker({\n  dateFormat : 'yy-mm-dd',\n  constrainInput: false,\n  maxDate: '0'\n});\njQuery('#end_date').datepicker({\n  dateFormat : 'yy-mm-dd',\n  constrainInput: false,\n  maxDate: '0'\n});\n  \njQuery('#filter-header').click(function(){\n    jQuery('#filter-header').addClass('ui-state-active').removeClass('ui-state-default').addClass('ui-corner-top').removeClass('ui-corner-all');\n\tjQuery('#filter-spec,#filter-footer').removeClass('filter-hide');\n    jQuery('#results-collections-header,#results-insects-header').removeClass('ui-state-active').addClass('ui-state-default');\n    jQuery('#focus-occurrence,#focus-flower,#focus-collection,#results-insects-results,#results-collections-results').addClass('filter-hide');\n});\njQuery('#results-collections-header').click(function(){\n    jQuery('#results-collections-header').addClass('ui-state-active').removeClass('ui-state-default');\n\tjQuery('#results-collections-results').removeClass('filter-hide');\n    jQuery('#filter-header').removeClass('ui-state-active').addClass('ui-state-default').removeClass('ui-corner-top').addClass('ui-corner-all');\n\tjQuery('#filter-spec,#filter-footer,#focus-occurrence,#focus-flower,#focus-collection,#results-insects-results').addClass('filter-hide');\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('filter-hide');\n});\njQuery('#reset-date-button').click(function(){\n\tjQuery('[name=start_date]').val('" . lang::get('click here') . "');\n\tjQuery('[name=end_date]').val('" . lang::get('click here') . "');\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('filter-hide');\n});\n\njQuery('#reset-flower-button').click(function(){\n\tjQuery('[name=flower\\:taxa_taxon_list_id]').val('');\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('filter-hide');\n});\n\njQuery('#reset-insect-button').click(function(){\n\tjQuery('[name=insect\\:taxa_taxon_list_id]').val('');\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('filter-hide');\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});\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('filter-hide');\n});\n\njQuery('#flower-image').click(function(){\n\tif(jQuery('#flower-image').attr('occID') != 'none'){\n\t\tloadFlower(jQuery('#flower-image').attr('occID'));\n\t}\n});\n\njQuery('#fo-doubt-button').click(function(){\n\tif(confirm(\"" . lang::get('LANG_Confirm_Express_Doubt') . "\")){\n\t\tjQuery('#fo-doubt-form').submit();\n\t}\n});\n\n\n\nloadCollection = function(id){\n    jQuery('[name=sample_comment\\:sample_id]').val(id);\n    locationLayer.destroyFeatures();\n\tjQuery('#fc-new-comment-button')." . (user_access('IForm n' . $node->nid . ' create collection comment') ? "show()" : "hide()") . ";\n    jQuery('#focus-occurrence,#filter-spec,#filter-footer,#results-insects-header,#results-insects-results,#results-collections-results').addClass('filter-hide');\n    jQuery('#filter-header').removeClass('ui-state-active').addClass('ui-state-default').removeClass('ui-corner-top').addClass('ui-corner-all');\n    jQuery('#focus-collection').removeClass('filter-hide');\n\tjQuery('#map2').width(jQuery('#map2_container').width());\n\tjQuery('#flower-image').attr('occID', 'none');\n\tjQuery('#collection-insects,#collection-date,#collection-name,#collection-flower-name,#collection-flower-type,#collection-habitat,#collection-user-name').empty();\n\t// this has a fixed target so can be done asynchronously.\n\t\$.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+\"&callback=?\", function(flowerData) {\n   \t\tif (flowerData.length>0) {\n\t\t\tloadImage('occurrence_image', 'occurrence_id', flowerData[0].id, '#flower-image');\n\t\t\tjQuery('#flower-image').attr('occID', flowerData[0].id);\n\t\t\t\$.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&callback=?\", function(detData) {\n   \t\t\t\tif (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 = string + detData[i].taxon + ', ';\n\t\t\t\t\t}\n\t\t\t\t\tif(detData[i].taxon_text_description != '' && detData[i].taxon_text_description != null){\n\t\t\t\t\t\tstring = string + detData[i].taxon_text_description + ', ';\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 + detData[i].taxon_extra_info;\n\t\t\t\t\t}\n\t\t\t\t\tjQuery('<span>" . lang::get('LANG_Flower_Name') . ": '+string+'</span>').appendTo('#collection-flower-name');\n\t\t\t\t}});\n\t\t\t\$.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 . "&callback=?\", function(attrdata) {\n\t\t\t\tif (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\t\$.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 + \"&callback=?\", function(attrdata) {\n\t\tif (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}}}}});\n  \t\n\t// this has a fixed target so can be done asynchronously.\n\t\$.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\"&callback=?\", function(collectionData) {\n   \t\tif (collectionData.length>0) {\n\t\t\tif(collectionData[0].date_start == collectionData[0].date_end){\n\t  \t\t\tjQuery('<span>'+collectionData[0].date_start.substring(0,10)+'</span>').appendTo('#collection-date');\n    \t\t} else {\n\t  \t\t\tjQuery('<span>'+collectionData[0].date_start+' - '+collectionData[0].date_end+'</span>').appendTo('#collection-date');\n    \t\t}\n\t  \t\tjQuery('<span>'+collectionData[0].location_name+'</span>').appendTo('#collection-name');\n   \t\t    \$.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\"&callback=?\", function(locationData) {\n   \t\t\t\tif (locationData.length>0) {\n\t\t\t\t\tloadImage('location_image', 'location_id', locationData[0].id, '#environment-image');\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        locationLayer.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: test, scope: scope, async: false});\n\t\t\t\t}\n\t\t\t});\n\t\t\t\$.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 . "&callback=?\", function(attrdata) {\n\t\t\t\tif (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\$.getJSON(\"" . $svcUrl . "/data/sample\" + \n\t\t\t\"?mode=json&view=detail&nonce=" . $readAuth['nonce'] . "&auth_token=" . $readAuth['auth_token'] . "&parent_id=\"+id+\"&callback=?\", function(sessiondata) {\n  \t\tif (sessiondata.length>0) {\n\t\t\tfor (var i=0;i<sessiondata.length;i++){\n\t\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'] . "\" +\n\t\t\t\t\t\t\"&sample_id=\"+sessiondata[i].id+\"&orderby=id&callback=?\", function(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\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\tjQuery('<p class=\"insect-tag insect-unknown\" />').appendTo(insect);\n\t\t\t\t\t\t\tvar image = jQuery('<div class=\"insect-image\" />').appendTo(insect);\n\t\t\t\t\t\t\tjQuery('<p class=\"insect-determination\" />').appendTo(insect);\n\t\t\t\t\t\t\tvar displayButton = jQuery('<div class=\"ui-state-default ui-corner-all display-button\">" . lang::get('LANG_Display') . "</div>')\n\t\t\t\t\t\t\t\t.appendTo(insect).attr('value',insectData[j].id);\n\t\t\t\t\t\t\tdisplayButton.click(function(){\n\t\t\t\t\t\t\t\tloadInsect(jQuery(this).attr('value'));\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\tloadImage('occurrence_image', 'occurrence_id', insectData[j].id, image);\n\t\t\t\t\t\t\t// have to do this synchronously due to multiple targets\n\t\t\t\t\t\t\t\$.getJSON(\"" . $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&callback=?\", function(detData) {\n   \t\t\t\t\t\t\t\tif (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 = string + 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].taxon_text_description != '' && detData[i].taxon_text_description != null){\n\t\t\t\t\t\t\t\t\t\tstring = string + detData[i].taxon_text_description + ', ';\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\tif(detData[i].taxon_extra_info != '' && detData[i].taxon_extra_info != null){\n\t\t\t\t\t\t\t\t\t\tstring = string + detData[i].taxon_extra_info;\n\t\t\t\t\t\t\t\t\t}\n\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].dubious == 'Y'){\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}});  \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}\n\t});\n\tloadComments(id, '#fc-comment-list', 'sample_comment', 'sample_id', 'sample-comment-block', 'sample-comment-body');\n};\ntest = function(a1)\n{\n\tjQuery(this.target).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(this.target);\n}\naddCollection = function(attributes, geom){\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\" />').attr('occID', attributes.flower_id).click(function(){\n\t\tloadFlower(jQuery(this).attr('occID'));\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\tvar img = new Image();\n\t\$(img).load(function () {flower.append(this);})\n\t    .attr('src', '" . data_entry_helper::$base_url . data_entry_helper::$indicia_upload_path . "med-'+attributes.flower_image_path)\n\t    .css('max-width', flower.width()).css('max-height', flower.height())\n\t    .css('vertical-align', 'middle').css('margin-left', 'auto').css('margin-right', 'auto').css('display', 'block');\n\tvar location = jQuery('<div class=\"collection-image collection-environment\" />').appendTo(collection);\n\timg = new Image();\n\t\$(img).load(function () {location.append(this)})\n\t    .attr('src', '" . data_entry_helper::$base_url . data_entry_helper::$indicia_upload_path . "med-'+attributes.location_image_path)\n\t    .css('max-width', location.width()).css('max-height', location.height())\n\t    .css('vertical-align', 'middle').css('margin-left', 'auto').css('margin-right', 'auto').css('display', 'block');\n\tvar photoReel = jQuery('<div class=\"collection-photoreel\"></div>').appendTo(collection);\n\tvar displayButtonContainer = jQuery('<div class=\"collection-buttons\"></div>').appendTo(collection);\n\tvar displayButton = jQuery('<div class=\"ui-state-default ui-corner-all display-button\">" . lang::get('LANG_Display') . "</div>');\n\tdisplayButton.click(function(){\n\t\tloadCollection(jQuery(this).attr('value'));\n\t}).appendTo(displayButtonContainer).attr('value',attributes.collection_id);\n\tif(attributes.date_start == attributes.date_end){\n\t  jQuery('<p class=\"collection-date\">'+attributes.date_start.substring(0,10)+'</p>').appendTo(details);\n    } else {\n\t  jQuery('<p class=\"collection-date\">'+attributes.date_start+' - '+attributes.date_end+'</p>').appendTo(details);\n    }\n\tjQuery('<p class=\"collection-name\">'+attributes.location_name+'</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: test, scope: scope, async: false});\n    \$.getJSON(\"" . $svcUrl . "/data/sample\" + \n    \t\t\"?mode=json&view=detail&nonce=" . $readAuth['nonce'] . "&auth_token=" . $readAuth['auth_token'] . "&parent_id=\"+attributes.collection_id+\"&callback=?\", function(sessiondata) {\n\t\tfor (var i=0;i<sessiondata.length;i++){\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+\"&callback=?\", function(insectData) {\n\t\t    \tif (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()).click(function () {loadInsect(jQuery(this).attr('occId'));});\n\t\t\t\t\t\tjQuery('<span>" . lang::get('LANG_Unknown') . "</span>').addClass('thumb-text').appendTo(container);\n\t\t\t\t\t\tphotoReel.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.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\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 + \"&deleted=f&callback=?\", function(detData) {\n\t\t\t\t\t\t      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        container.find('.thumb-text').remove();\n\t\t\t\t\t\t        if(detData[detData.length-1].dubious == 'Y'){\n\t\t\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}\n  \t\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(attributes){\n\tvar container=jQuery('<div class=\"ui-widget-content ui-corner-all filter-insect\" />').appendTo('#results-insects-results');\n\tvar flag = jQuery('<div />').addClass('insect-ok').appendTo(container);\n\tvar insect = jQuery('<div class=\"insect-image\" />').attr('occID', attributes.insect_id).click(function(){\n\t\tloadInsect(jQuery(this).attr('occID'));\n\t});\n\tinsect.appendTo(container);\n\tvar img = new Image();\n\t\$(img).load(function () {insect.append(this);})\n\t    .attr('src', '" . data_entry_helper::$base_url . data_entry_helper::$indicia_upload_path . "med-'+attributes.insect_image_path)\n\t\t.css('max-width', insect.width()).css('max-height', insect.width()*imageRatio)\n\t    .css('vertical-align', 'middle').css('margin-left', 'auto').css('margin-right', 'auto').css('display', 'block');\n\t\$.getJSON(\"" . $svcUrl . "/data/determination\" +\n   \t\t\t\"?mode=json&view=list&nonce=" . $readAuth['nonce'] . "&auth_token=" . $readAuth['auth_token'] . "\" +\n   \t\t\t\"&occurrence_id=\" + attributes.insect_id + \"&callback=?\", function(detData) {\n   \t\tif (detData.length>0) {\n\t\t\tvar i = detData.length-1;\n   \t\t\tvar string = '';\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].taxon_text_description != '' && detData[i].taxon_text_description != null){\n\t\t\t\tstring = (string == '' ? '' : string + ', ') + detData[i].taxon_text_description;\n\t\t\t}\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('<p>'+string+'</p>').appendTo(container)\n\t\t\tif(detData[i].dubious == 'Y'){\n\t\t\t\tjQuery(flag).removeClass('insect-ok').addClass('insect-dubious');\n\t\t\t}\n\t\t} else {\n\t\t\tjQuery(flag).removeClass('insect-ok').addClass('insect-unknown');\n\t\t\tjQuery(\"<p>" . lang::get('LANG_No_Determinations') . "</p>\")\n\t\t\t\t\t.appendTo(container);\n\t\t}\n\t});\n\tvar displayButton = jQuery('<div class=\"ui-state-default ui-corner-all display-button\">" . lang::get('LANG_Display') . "</div>');\n\tdisplayButton.click(function(){\n\t\tloadInsect(jQuery(this).attr('value'));\n\t}).appendTo(container).attr('value',attributes.insect_id);\n};\n\n\nsetCollectionPage = function(pageNum){\n\tjQuery('#results-collections-results').empty();\n\tvar numPages = Math.ceil(searchResults.features.length/" . $args['collectionsPerPage'] . ");\n\tif(numPages > 1) {\n\t\tvar pageCtrl = jQuery('<div>').addClass('page-control').appendTo('#results-collections-results');\n\t\tvar pageCtrl2 = jQuery('<div>').addClass('page-control');\n\t\tvar first = true;\n\t\tfor (var j = (pageNum < 6  ? 1 : pageNum - 5); j <= numPages && j <= (pageNum + 5); j++){\n\t\t\tif (first != true){\n\t\t\t\tjQuery('<span>|</span>').appendTo(pageCtrl);\n\t\t\t\tjQuery('<span>|</span>').appendTo(pageCtrl2);\n  \t\t\t}\n  \t\t\tfirst = false;\n\t\t\tif( j != pageNum) {\n\t\t\t\tjQuery('<a>'+j+'</a>').attr('value',j).click(function(){setCollectionPage(jQuery(this).attr('value'))}).appendTo(pageCtrl);\n\t\t\t\tjQuery('<a>'+j+'</a>').attr('value',j).click(function(){setCollectionPage(jQuery(this).attr('value'))}).appendTo(pageCtrl2);\n  \t\t\t} else {\n\t\t\t\tjQuery('<span>'+j+'</span>').appendTo(pageCtrl);\n\t\t\t\tjQuery('<span>'+j+'</span>').appendTo(pageCtrl2);\n  \t\t\t}\n\t    }\n\t}\n    for (var i = (pageNum-1)*" . $args['collectionsPerPage'] . "; i < searchResults.features.length && i < pageNum*" . $args['collectionsPerPage'] . "; i++){\n\t\taddCollection(searchResults.features[i].attributes,searchResults.features[i].geometry);\n\t}\n\tif(numPages > 1) {\n\t\tpageCtrl2.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['insectsPerPage'] . ");\n\tif(numPages > 1) {\n\t\tvar pageCtrl = jQuery('<div>').addClass('page-control').appendTo('#results-insects-results');\n\t\tvar pageCtrl2 = jQuery('<div>').addClass('page-control');\n\t\tvar first = true;\n\t\tfor (var j = (pageNum < 6  ? 1 : pageNum - 5); j <= numPages && j <= (pageNum + 5); j++){\n\t\t\tif (first != true){\n\t\t\t\tjQuery('<span>|</span>').appendTo(pageCtrl);\n\t\t\t\tjQuery('<span>|</span>').appendTo(pageCtrl2);\n  \t\t\t}\n  \t\t\tfirst = false;\n\t\t\tif( j != pageNum) {\n\t\t\t\tjQuery('<a>'+j+'</a>').attr('value',j).click(function(){setInsectPage(jQuery(this).attr('value'))}).appendTo(pageCtrl);\n\t\t\t\tjQuery('<a>'+j+'</a>').attr('value',j).click(function(){setInsectPage(jQuery(this).attr('value'))}).appendTo(pageCtrl2);\n  \t\t\t} else {\n\t\t\t\tjQuery('<span>'+j+'</span>').appendTo(pageCtrl);\n\t\t\t\tjQuery('<span>'+j+'</span>').appendTo(pageCtrl2);\n  \t\t\t}\n\t    }\n\t}\n    for (var i = (pageNum-1)*" . $args['insectsPerPage'] . "; i < searchResults.features.length && i < pageNum*" . $args['insectsPerPage'] . "; i++){\n\t\taddInsect(searchResults.features[i].attributes);\n\t}\n\tif(numPages > 1) {\n\t\tpageCtrl2.appendTo('#results-insects-results');\n\t}\n}\n\n// searchLayer in map is used for georeferencing.\n// map editLayer is switched off.\nsearchLayer = null;\ninseeLayer = null;\npolygonLayer = new OpenLayers.Layer.Vector('Polygon Layer', {\n\tstyleMap: new OpenLayers.StyleMap({\n                \"default\": new OpenLayers.Style({\n                    fillColor: \"Red\",\n                    strokeColor: \"Red\",\n                    fillOpacity: 0,\n                    strokeWidth: 1\n                  })\n\t}),\n\tdisplayInLayerSwitcher: false\n});\npolygonLayer.events.register('featuresadded', {}, function(a1){\n\tpolygonLayer.map.searchLayer.destroyFeatures();\n\tif(inseeLayer != null)\n\t\tinseeLayer.destroyFeatures();\n});          \nlocationLayer = new OpenLayers.Layer.Vector('Location Layer',\n\t{displayInLayerSwitcher: false});\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  \t\t\t});\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').addClass('filter-hide');\n\tjQuery('#results-collections-header,#results-collections-results').removeClass('filter-hide');\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').addClass('filter-hide');\n\tjQuery('#results-insects-header,#results-insects-results').removeClass('filter-hide');\n\tjQuery('#results-insects-header').addClass('ui-state-active').removeClass('ui-state-default');\n\trunSearch(false);\n});\n\nrunSearch = function(forCollections){\n  \tvar ORgroup = [];\n\t\n  \tif(searchLayer != null)\n\t\tsearchLayer.destroy();\n\t\t\n\tvar use_insects = false;\n    jQuery('#results-collections-results,#results-insects-results').empty();\n\tjQuery('#focus-occurrence,#focus-collection').addClass('filter-hide');\n\tvar filters = [];\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){\n\t  filters.push(new OpenLayers.Filter.Spatial({\n    \ttype: OpenLayers.Filter.Spatial.BBOX,\n    \tproperty: 'geom',\n    \tvalue: mapBounds\n  \t  }));\n  \t}\n  \tif(inseeLayer != null){\n  \t\tif(inseeLayer.features.length > 0){\n  \t\t\t// should only be one entry in the inseeLayer\n\t\t\tfilters.push(new OpenLayers.Filter.Spatial({\n    \t\t\ttype: OpenLayers.Filter.Spatial.WITHIN,\n    \t\t\tproperty: 'geom',\n    \t\t\tvalue: inseeLayer.features[0].geometry\n\t\t  \t}));\n  \t\t}\n  \t}\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({\n    \t\t\t\ttype: OpenLayers.Filter.Spatial.WITHIN,\n\t    \t\t\tproperty: 'geom',\n    \t\t\t\tvalue: polygonLayer.features[i].geometry\n\t\t  \t\t}));\n  \t\t\t}\n\t\t  \tif(ORgroup.length > 1){\n\t\t\t\tfilters.push(new OpenLayers.Filter.Logical({\n\t\t\t\t\ttype: OpenLayers.Filter.Logical.OR,\n\t\t\t\t\tfilters: ORgroup\n\t\t\t\t}));\n\t\t\t} else {\n  \t\t\t\tif(ORgroup.length == 1){\n\t\t\t \t\tfilters.push(ORgroup[0]);\n\t \t\t\t}\n\t\t  \t} \t\n  \t\t}\n  \t}\n  \t// Only deal with completed collections on our survey.\n  \tfilters.push(new OpenLayers.Filter.Comparison({\n  \t\ttype: OpenLayers.Filter.Comparison.LIKE,\n    \tproperty: 'collection_attributes',\n    \tvalue: '*{|" . $args['complete_attr_id'] . "|,1}*'\n  \t}));\n  \tfilters.push(new OpenLayers.Filter.Comparison({\n  \t\ttype: OpenLayers.Filter.Comparison.EQUAL_TO,\n    \tproperty: 'survey_id',\n    \tvalue: '" . $args['survey_id'] . "'\n  \t}));\n  \t\n  \tvar user = jQuery('input[name=username]').val();\n  \tif(user != ''){\n  \t\tfilters.push(new OpenLayers.Filter.Comparison({\n  \t\t\ttype: OpenLayers.Filter.Comparison.LIKE,\n    \t\tproperty: 'collection_attributes',\n    \t\tvalue: '*{|" . $args['username_attr_id'] . "|,'+user+'}*'\n  \t\t}));\n  \t}\n  \t\n  \tvar start_date = jQuery('input[name=start_date]').val();\n  \tvar end_date = jQuery('input[name=end_date]').val();\n  \tif(start_date != '" . lang::get('click here') . "' && start_date != ''){\n  \t\tfilters.push(new OpenLayers.Filter.Comparison({\n  \t\t\ttype: OpenLayers.Filter.Comparison.GREATER_THAN  ,\n    \t\tproperty: 'date_end',\n    \t\tvalue: start_date\n  \t\t}));\n  \t}\n  \tif(end_date != '" . lang::get('click here') . "' && end_date != ''){\n  \t\tfilters.push(new OpenLayers.Filter.Comparison({\n  \t\t\ttype: OpenLayers.Filter.Comparison.LESS_THAN  ,\n    \t\tproperty: 'date_start',\n    \t\tvalue: end_date\n  \t\t}));\n  \t}\n  \t\n  \tvar flower = jQuery('select[name=flower\\:taxa_taxon_list_id]').val();\n  \tif(flower != ''){\n  \t\tfilters.push(new OpenLayers.Filter.Comparison({\n  \t\t\ttype: OpenLayers.Filter.Comparison.LIKE ,\n    \t\tproperty: 'flower_taxon',\n    \t\tvalue: '*|'+flower+'|*'\n  \t\t}));\n  \t}\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({\n  \t\t\ttype: OpenLayers.Filter.Comparison.LIKE ,\n    \t\tproperty: 'flower_attributes',\n    \t\tvalue: '*{|" . $args['flower_type_attr_id'] . "|,'+elem.value+'}*'\n  \t\t}));\n  \t});\n  \tif(ORgroup.length > 1){\n\t\tfilters.push(new OpenLayers.Filter.Logical({\n\t\t\ttype: OpenLayers.Filter.Logical.OR,\n\t\t\tfilters: ORgroup\n\t\t}));\n\t} else {\n  \t\tif(ORgroup.length == 1){\n\t \t\tfilters.push(ORgroup[0]);\n\t \t}\n  \t}\n \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({\n  \t\t\ttype: OpenLayers.Filter.Comparison.LIKE ,\n    \t\tproperty: 'location_attributes',\n    \t\tvalue: '*{|" . $args['habitat_attr_id'] . "|,'+elem.value+'}*'\n  \t\t}));\n  \t});\n  \tif(ORgroup.length > 1){\n\t\tfilters.push(new OpenLayers.Filter.Logical({\n\t\t\ttype: OpenLayers.Filter.Logical.OR,\n\t\t\tfilters: ORgroup\n\t\t}));\n\t} else {\n  \t\tif(ORgroup.length == 1){\n\t \t\tfilters.push(ORgroup[0]);\n\t \t}\n  \t}\n  \t\n  \tvar insect = jQuery('select[name=insect\\:taxa_taxon_list_id]').val();\n  \tif(insect != ''){\n  \t\tuse_insects = true;\n  \t\tfilters.push(new OpenLayers.Filter.Comparison({\n  \t\t\ttype: OpenLayers.Filter.Comparison.LIKE ,\n    \t\tproperty: forCollections ? 'insects' : 'insect_taxon',\n    \t\tvalue: '*|'+insect+'|*'\n  \t\t}));\n  \t}\n\n  \tORgroup = [];\n  \tjQuery('#insect-filter-body').find('[name^=smpAttr:" . $args['sky_state_attr_id'] . "]').filter('[checked]').each(function(index, elem){\n  \t\tuse_insects = true;\n  \t\tORgroup.push(new OpenLayers.Filter.Comparison({\n  \t\t\ttype: OpenLayers.Filter.Comparison.LIKE ,\n    \t\tproperty: 'session_attributes',\n    \t\tvalue: '*{|" . $args['sky_state_attr_id'] . "|,'+elem.value+'}*'\n  \t\t}));\n  \t});\n  \tif(ORgroup.length > 1){\n\t\tfilters.push(new OpenLayers.Filter.Logical({\n\t\t\ttype: OpenLayers.Filter.Logical.OR,\n\t\t\tfilters: ORgroup\n\t\t}));\n\t} else {\n  \t\tif(ORgroup.length == 1){\n\t \t\tfilters.push(ORgroup[0]);\n\t \t}\n  \t}\n\n  \tORgroup = [];\n  \tjQuery('#insect-filter-body').find('[name^=smpAttr:" . $args['temperature_attr_id'] . "]').filter('[checked]').each(function(index, elem){\n  \t\tuse_insects = true;\n  \t\tORgroup.push(new OpenLayers.Filter.Comparison({\n  \t\t\ttype: OpenLayers.Filter.Comparison.LIKE ,\n    \t\tproperty: 'session_attributes',\n    \t\tvalue: '*{|" . $args['temperature_attr_id'] . "|,'+elem.value+'}*'\n  \t\t}));\n  \t});\n  \tif(ORgroup.length > 1){\n\t\tfilters.push(new OpenLayers.Filter.Logical({\n\t\t\ttype: OpenLayers.Filter.Logical.OR,\n\t\t\tfilters: ORgroup\n\t\t}));\n\t} else {\n  \t\tif(ORgroup.length == 1){\n\t \t\tfilters.push(ORgroup[0]);\n\t \t}\n  \t}\n\n  \tORgroup = [];\n  \tjQuery('#insect-filter-body').find('[name^=smpAttr:" . $args['wind_attr_id'] . "]').filter('[checked]').each(function(index, elem){\n  \t\tuse_insects = true;\n  \t\tORgroup.push(new OpenLayers.Filter.Comparison({\n  \t\t\ttype: OpenLayers.Filter.Comparison.LIKE ,\n    \t\tproperty: 'session_attributes',\n    \t\tvalue: '*{|" . $args['wind_attr_id'] . "|,'+elem.value+'}*'\n  \t\t}));\n  \t});\n  \tif(ORgroup.length > 1){\n\t\tfilters.push(new OpenLayers.Filter.Logical({\n\t\t\ttype: OpenLayers.Filter.Logical.OR,\n\t\t\tfilters: ORgroup\n\t\t}));\n\t} else {\n  \t\tif(ORgroup.length == 1){\n\t \t\tfilters.push(ORgroup[0]);\n\t \t}\n  \t}\n\n\t// TODO need to do shade : this needs to be altered so that the attribute is a termlist\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: forCollections ? (use_insects ? 'poll_collection_insects' : 'poll_collections') : 'poll_insects',\n              geometryName:'geom',\n              featureNS: '" . $args['search_ns'] . "',\n              srsName: 'EPSG:900913',\n              version: '1.1.0',   \n              maxFeatures: " . $args['max_features'] . ",               \n//      \t\t  propertyNames: forCollections ? ['collection_id','date_start','date_end','geom','location_name','location_image_path','flower_image_path','flower_id','flower_taxon','collection_attributes','location_attributes','flower_attributes']\n              propertyNames: forCollections ? ['collection_id','date_start','date_end','geom','location_name','location_image_path','flower_image_path','flower_id','flower_taxon','collection_attributes','location_attributes','flower_attributes']\n      \t\t  \t\t\t\t\t\t\t: ['insect_id','collection_id','geom','insect_image_path']\n\t\t  })\n\t});\n\tif(forCollections) {\n\t\tsearchLayer.events.register('featuresadded', {}, function(a1){\n\t\t\tsearchResults = a1;\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} else {\n\t\tsearchLayer.events.register('featuresadded', {}, function(a1){\n\t\t\tsearchResults = a1;\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}\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\njQuery('form#fo-doubt-form').ajaxForm({ \n\tdataType:  'json', \n\tsuccess:   function(data){\n\t\tif(data.error == undefined){\n\t\t\tloadDeterminations(jQuery('[name=determination\\:occurrence_id]').val(), '#fo-id-history', '#fo-current-id');\n\t\t\tjQuery('[name=occurrence_comment\\:comment]').val(\"" . lang::get('LANG_Doubt_Comment') . "\");\n\t\t\tjQuery('#fo-new-comment-button').click();\n\t\t} else {\n\t\t\talert(data.error);\n\t\t}\n\t} \n});\njQuery('form#fo-new-insect-id-form').ajaxForm({ \n\tdataType:  'json', \n\tbeforeSubmit:   function(data, obj, options){\n\t\tif (!jQuery('form#fo-new-insect-id-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=determination\\:taxa_taxon_list_id]').val('');\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');\n\t\t} else {\n\t\t\talert(data.error);\n\t\t}\n\t} \n});\njQuery('form#fo-new-flower-id-form').ajaxForm({ \n\tdataType:  'json', \n\tbeforeSubmit:   function(data, obj, options){\n\t\tif (!jQuery('form#fo-new-flower-id-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=determination\\:taxa_taxon_list_id]').val('');\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');\n\t\t} else {\n\t\t\talert(data.error);\n\t\t}\n\t} \n});\njQuery('#fo-new-comment-form').ajaxForm({ \n\t// dataType identifies the expected content type of the server response \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');\n  \t\t} else {\n\t\t\talert(data.error);\n\t\t}\n\t} \n});\njQuery('#fc-new-comment-form').ajaxForm({ \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');\n  \t\t} else {\n\t\t\talert(data.error);\n\t\t}\n\t} \n});\n\nloadSampleAttributes = function(keyValue){\n\tjQuery('#fo-insect-start-time,#fo-insect-end-time,#fo-insect-sky,#fo-insect-temp,#fo-insect-wind,#fo-insect-shade').empty();\n\t\$.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 + \"&callback=?\", function(attrdata) {\n\t\tif (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\tjQuery('#fo-insect-shade').append(attrdata[i].value);\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\tjQuery('#focus-flower-type').empty();\n\t\$.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 . "&callback=?\", function(attrdata) {\n\t\tif (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\tjQuery('#focus-habitat').empty();\n\thabitat_string = '';\n\t\$.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 . "&callback=?\", function(attrdata) {\n\t\tif (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].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] : (habitat_string + ' | ' + attrdata[i]));\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}\nimageRatio = 3/4;\n\nloadImage = function(imageTable, key, keyValue, target){\n\tjQuery(target).empty();\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 img = new Image();\n\t\t\tjQuery(img)\n        \t\t.load(function () {\n        \t\t\tjQuery(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 . "'+imageData[0].path)\n\t\t\t\t.css('max-width', \$(target).width()).css('max-height', \$(target).width()*imageRatio)\n\t\t\t\t.css('vertical-align', 'middle').css('margin-left', 'auto').css('margin-right', 'auto').css('display', 'block');\n\t\t}\n\t});\n}\n\nloadDeterminations = function(keyValue, historyID, currentID){\n\tjQuery(historyID).empty().append('<strong>" . lang::get('LANG_History_Title') . "</strong>');\n\tjQuery(currentID).empty();\n\tjQuery('#fo-taxon').empty();\n\tjQuery('#fo-warning').addClass('insect-ok').removeClass('insect-dubious').removeClass('insect-unknown');\n\t\$.getJSON(\"" . $svcUrl . "/data/determination\" +\n   \t\t\t\"?mode=json&view=list&nonce=" . $readAuth['nonce'] . "&auth_token=" . $readAuth['auth_token'] . "\" +\n   \t\t\t\"&occurrence_id=\" + keyValue + \"&callback=?\", function(detData) {\n   \t\tif (detData.length>0) {\n\t\t\tvar i = detData.length-1;\n   \t\t\tjQuery('#fo-doubt-form').find('[name=determination\\:id]').val(detData[i].id);\n   \t\t\tjQuery('#fo-doubt-form').find('[name=determination\\:occurrence_id]').val(detData[i].occurrence_id);\n   \t\t\tvar string = '';\n\t\t\tif(detData[i].taxon != '' && detData[i].taxon != null){\n\t\t\t\tstring = detData[i].taxon;\n\t\t\t\tjQuery('#fo-taxon').append(detData[i].taxon);\n  \t\t\t}\n\t\t\tif(detData[i].taxon_text_description != '' && detData[i].taxon_text_description != null){\n\t\t\t\tstring = (string == '' ? '' : string + ', ') + detData[i].taxon_text_description;\n\t\t\t}\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_text_description;\n\t\t\t}\n\t\t\tjQuery('<p><strong>'+string+ '</strong> " . lang::get('LANG_Comment_By') . "' + detData[i].person_name + ' ' + detData[i].updated_on + '</p>').appendTo(currentID)\n\t\t\tif(detData[i].dubious == 'Y'){\n\t\t\t\tjQuery(\"<p>" . lang::get('LANG_Doubt_Expressed') . "</p>\").appendTo(currentID)\n\t\t\t\tjQuery('#fo-warning').removeClass('insect-ok').addClass('insect-dubious');\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\tvar string = detData[i].updated_on + ' : ';\n\t\t\t\tif(detData[i].taxon != '' && detData[i].taxon != null){\n\t\t\t\t\tstring = string + detData[i].taxon + ', ';\n\t\t\t\t}\n\t\t\t\tif(detData[i].taxon_text_description != '' && detData[i].taxon_text_description != null){\n\t\t\t\t\tstring = string + detData[i].taxon_text_description + ', ';\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 + detData[i].taxon_text_description ;\n\t\t\t\t}\n\t\t\t\tjQuery('<p>'+string+ ' " . lang::get('LANG_Comment_By') . "' + detData[i].person_name+'</p>').appendTo(historyID)\n\t\t\t}\n\t\t} else {\n\t\t\tjQuery('#fo-doubt-button').hide();\n\t\t\tjQuery('#fo-warning').removeClass('insect-ok').addClass('insect-unknown');\n\t\t\tjQuery('<p>" . lang::get('LANG_No_Determinations') . "</p>')\n\t\t\t\t\t.appendTo(historyID);\n\t\t\tjQuery('<p>" . lang::get('LANG_No_Determinations') . "</p>')\n\t\t\t\t\t.appendTo(currentID);\n\t\t}\n\t});\n};\nloadComments = function(keyValue, block, table, key, blockClass, bodyClass){\n\tjQuery(block).empty();\n\t\$.getJSON(\"" . $svcUrl . "/data/\" + table +\n   \t\t\t\"?mode=json&view=list&nonce=" . $readAuth['nonce'] . "&auth_token=" . $readAuth['auth_token'] . "\" +\n   \t\t\t\"&\" + key + \"=\" + keyValue + \"&callback=?\", function(commentData) {\n   \t\tif (commentData.length>0) {\n   \t\t\tfor(i=commentData.length - 1; i >= 0; i--){\n\t   \t\t\tvar newCommentDetails = jQuery('<div class=\"'+blockClass+'\"/>')\n\t\t\t\t\t.appendTo(block);\n\t\t\t\tjQuery('<span>" . lang::get('LANG_Comment_By') . "' + commentData[i].person_name + ' ' + commentData[i].updated_on + '</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(block);\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(block);\n\t\t}\n\t});\n};\n\nloadInsectAddnInfo = function(keyValue){\n\t// TODO convert buttons into thumbnails\n\tcollection = '';\n\tjQuery('#fo-prev-button,#fo-next-button').hide();\n\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\t\$.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\"&callback=?\", function(occData) {\n   \t\tif (occData.length > 0) {\n\t\t\t\$.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\"&callback=?\", function(smpData) {\n   \t\t\t\tif (smpData.length > 0) {\n   \t\t\t\t\tcollection = smpData[0].parent_id;\n\t\t\t\t\tjQuery('#fo-insect-date').empty().append(smpData[0].date_start);\n\t\t\t\t\tloadSampleAttributes(smpData[0].id);\n\t\t\t\t\tjQuery('#fo-collection-button').attr('smpID',smpData[0].parent_id).show();\n\t\t\t\t\t\$.getJSON(\"" . $svcUrl . "/data/sample/\" +\n   \t\t\t\t\t\t\t\"?mode=json&view=detail&nonce=" . $readAuth['nonce'] . "&auth_token=" . $readAuth['auth_token'] . "\" +\n   \t\t\t\t\t\t\t\"&parent_id=\" + smpData[0].parent_id + \"&callback=?\", function(smpList) {\n   \t\t\t\t\t\tif (smpList.length > 0) {\n   \t\t\t\t\t\t\tfor(j=0; j< smpList.length; j++){\n\t\t   \t\t\t\t\t\t\$.getJSON(\"" . $svcUrl . "/data/occurrence\" +\n   \t\t\t\t\t\t\t\t\t\t\"?mode=json&view=detail&nonce=" . $readAuth['nonce'] . "&auth_token=" . $readAuth['auth_token'] . "\" +\n   \t\t\t\t\t\t\t\t\t\t\"&sample_id=\" + smpList[j].id + \"&orderby=id&callback=?\", function(occList) {\n\t   \t\t\t\t\t\t\t\tif(occList.length > 0){\n   \t\t\t\t\t\t\t\t\t\tfor(i=0; i< occList.length; i++){\n   \t\t\t\t\t\t\t\t\t\t\tif(parseInt(occList[i].id) == parseInt(keyValue)){\n   \t\t\t\t\t\t\t\t\t\t\t\tif(i>0){\n\t\t\t\t\t\t\t\t\t\t\t\t\tjQuery('#fo-prev-button').attr('occID',occList[i-1].id).show();\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\tif(i< occList.length-1){\n\t\t\t\t\t\t\t\t\t\t\t\t\tjQuery('#fo-next-button').attr('occID',occList[i+1].id).show();\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}\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}\n   \t\t   \t});\n   \t\t}\n   \t});\n}\nloadFlowerAddnInfo = function(keyValue){\n\t// fetch occurrence details first to get the collection id.\n\tloadOccurrenceAttributes(keyValue);\n\t\$.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\"&callback=?\", function(occData) {\n   \t\tif (occData.length > 0) {\n\t\t\tjQuery('#fo-collection-button').attr('smpID',occData[0].sample_id).show();\n   \t\t\t\$.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\"&callback=?\", function(collection) {\n   \t\t\t\tif (collection.length > 0) {\n\t\t\t\t\tloadLocationAttributes(collection.location_id);\n  \t\t\t\t}\n   \t\t   \t});\n   \t\t}\n   \t});\n}\n\nloadInsect = function(insectID){\n    jQuery('#focus-collection,#filter-spec,#filter-footer,#results-insects-header,#results-collections-header,#results-insects-header,#results-insects-results,#results-collections-results,#fo-flower-addn-info').addClass('filter-hide');\n    jQuery('#filter-header').removeClass('ui-state-active').addClass('ui-state-default').removeClass('ui-corner-top').addClass('ui-corner-all');\n    jQuery('#focus-occurrence,#fo-addn-info-header,#fo-insect-addn-info').removeClass('filter-hide');\n\tjQuery('[name=determination\\:occurrence_id]').val(insectID);\n\tjQuery('[name=occurrence_comment\\:occurrence_id]').val(insectID);\n\tjQuery('#fo-new-comment,#fo-new-id').removeClass('ui-accordion-content-active');\n\tjQuery('#fo-new-insect-id-button').show();\n\tjQuery('#fo-new-flower-id-button').hide();\n\tjQuery('#fo-doubt-button')." . (user_access('IForm n' . $node->nid . ' insect expert') || user_access('IForm n' . $node->nid . ' flag dubious insect') ? "show()" : "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\tloadImage('occurrence_image', 'occurrence_id', insectID, '#fo-image');\n\tloadDeterminations(insectID, '#fo-id-history', '#fo-current-id');\n\tloadInsectAddnInfo(insectID);\n\tloadComments(insectID, '#fo-comment-list', 'occurrence_comment', 'occurrence_id', 'occurrence-comment-block', 'occurrence-comment-body');\n}\nloadFlower = function(flowerID){\n\tjQuery('#fo-prev-button,#fo-next-button').hide();\n\tjQuery('#focus-collection,#filter-spec,#filter-footer,#results-insects-header,#results-collections-header,#results-insects-header,#results-insects-results,#results-collections-results,#fo-insect-addn-info').addClass('filter-hide');\n    jQuery('#filter-header').removeClass('ui-state-active').addClass('ui-state-default').removeClass('ui-corner-top').addClass('ui-corner-all');\n\tjQuery('#focus-occurrence,#fo-addn-info-header,#fo-flower-addn-info').removeClass('filter-hide');\n\tjQuery('#fo-new-comment,#fo-new-id').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-doubt-button')." . (user_access('IForm n' . $node->nid . ' flower expert') || user_access('IForm n' . $node->nid . ' flag dubious flower') ? "show()" : "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\tloadImage('occurrence_image', 'occurrence_id', flowerID, '#fo-image');\n\tloadDeterminations(flowerID, '#fo-id-history', '#fo-current-id');\n\tloadFlowerAddnInfo(flowerID);\n\tloadComments(flowerID, '#fo-comment-list', 'occurrence_comment', 'occurrence_id', 'occurrence-comment-block', 'occurrence-comment-body');\n}\n\njQuery('#fo-new-comment-button').click(function(){ \n\tjQuery('#fo-new-comment').toggleClass('ui-accordion-content-active');\n});\njQuery('#fc-new-comment-button').click(function(){ \n\tjQuery('#fc-new-comment').toggleClass('ui-accordion-content-active');\n});\njQuery('#fo-new-insect-id-button').click(function(){ \n\tjQuery('#fo-new-insect-id').toggleClass('ui-accordion-content-active');\n});\njQuery('#fo-new-flower-id-button').click(function(){ \n\tjQuery('#fo-new-flower-id').toggleClass('ui-accordion-content-active');\n});\njQuery('#fo-collection-button').click(function(){\n\tloadCollection(jQuery(this).attr('smpID'));\n});\njQuery('#fo-prev-button').click(function(){\n\tloadInsect(jQuery(this).attr('occID'));\n});\njQuery('#fo-next-button').click(function(){\n\tloadInsect(jQuery(this).attr('occID'));\n});\n  ";
        data_entry_helper::$onload_javascript .= "\n\tfunction addDrawnGeomToSelection (geometry) {\n    \t// Create the polygon as drawn\n    \tvar feature = new OpenLayers.Feature.Vector(geometry, {});\n    \tpolygonLayer.addFeatures([feature]);\n\t};\n    \n\tpolygonControl = new OpenLayers.Control.DrawFeature(polygonLayer, OpenLayers.Handler.Polygon, {drawFeature: addDrawnGeomToSelection});\n\tpolygonLayer.map.addControl(this.polygonControl);\n\tpolygonControl.activate();\n\tpolygonLayer.map.searchLayer.events.register('featuresadded', {}, function(a1){\n\t\tif(inseeLayer != null)\n\t\t\tinseeLayer.destroyFeatures();\n\t\tpolygonLayer.destroyFeatures();\n\t});          \n";
        switch ($mode) {
            case 'INSECT':
                data_entry_helper::$onload_javascript .= "loadInsect(" . $occID . ");\n\t\t\t";
                break;
            case 'FLOWER':
                data_entry_helper::$onload_javascript .= "loadFlower(" . $occID . ");\n\t\t\t";
                break;
            case 'COLLECTION':
                data_entry_helper::$onload_javascript .= "\n    \t\tjQuery('#focus-occurrence,#filter-spec,#filter-footer,#results-insects-header,#results-collections-header,#results-insects-results,#results-collections-results').addClass('filter-hide');\n    \t\tjQuery('#filter-header').removeClass('ui-state-active').addClass('ui-state-default').removeClass('ui-corner-top').addClass('ui-corner-all');\n    \t\tloadCollection(" . $smpID . ");\n    \t\t";
                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').addClass('filter-hide');\n    \t\t";
                if ($userID != '') {
                    $thisuser = user_load($userID);
                    data_entry_helper::$onload_javascript .= "\n    \t\t\tjQuery('[name=username]').val('" . $thisuser->name . "');\n    \t\t\tjQuery('#search-collections-button').click();\n    \t\t\t";
                }
                break;
        }
        return $r;
    }
示例#25
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;
    }
示例#26
0
 /**
  * Get the custom species control.
  */
 protected static function get_control_species($auth, $args, $tabalias, $options)
 {
     $surveyMethodIdAttr = iform_mnhnl_getAttrID($auth, $args, 'sample', 'Bats2SurveyMethod');
     if (!$surveyMethodIdAttr) {
         return 'get_control_species : This Species control must be used with a survey that has the Bats2SurveyMethod attribute associated with it.';
     }
     $list = data_entry_helper::get_population_data(array('table' => 'termlist', 'extraParams' => $auth['read'] + array('external_key' => $options['surveyMethodTermList'])));
     if (count($list) == 0) {
         return "get_control_species : Termlist " . $options['surveyMethodTermList'] . " not available on the Warehouse";
     }
     if (count($list) > 1) {
         return "get_control_species : Multiple termlists identified by " . $options['surveyMethodTermList'] . " found on the Warehouse";
     }
     $termlist = $list[0]['id'];
     $extraParams = $auth['read'] + array('termlist_id' => $termlist, 'view' => 'detail');
     $surveyMethods = data_entry_helper::get_population_data(array('table' => 'termlists_term', 'extraParams' => $extraParams));
     data_entry_helper::$javascript .= "\nhook_species_checklist_pre_delete_row=function(e) {\n    return confirm(\"" . lang::get('Are you sure you want to delete this row?') . "\");\n};\n";
     $extraParams = $auth['read'];
     if ($args['species_names_filter'] == 'preferred') {
         $extraParams += array('preferred' => 't');
     }
     if ($args['species_names_filter'] == 'language') {
         $extraParams += array('language' => iform_lang_iso_639_2($user->lang));
     }
     // multiple species being input via a grid
     $species_ctrl_opts = array_merge(array("extra_list_id" => $args["extra_list_id"], 'listId' => $args['list_id'], 'label' => lang::get('occurrence:taxa_taxon_list_id'), 'columns' => 1, 'readAuth' => $auth['read'], 'extraParams' => $extraParams, 'survey_id' => $args['survey_id'], 'PHPtaxonLabel' => true, 'language' => iform_lang_iso_639_2($user->lang), 'max_species_ids' => $args['max_species_ids'], 'surveyMethodAttrId' => $surveyMethodIdAttr, 'surveyMethods' => $surveyMethods), $options);
     if ($args['extra_list_id']) {
         $species_ctrl_opts['lookupListId'] = $args['extra_list_id'];
     }
     if (isset($args['col_widths']) && $args['col_widths']) {
         $species_ctrl_opts['colWidths'] = explode(',', $args['col_widths']);
     }
     call_user_func(array(get_called_class(), 'build_grid_taxon_label_function'), $args, array());
     // Start by outputting a hidden value that tells us we are using a grid when the data is posted,
     // then output the grid control
     return self::mnhnl_bats2_species_checklist($args, $species_ctrl_opts);
 }
 protected static function get_control_targetspeciesgrid($auth, $args, $tabalias, $options)
 {
     $targetSpeciesAttr = iform_mnhnl_getAttr($auth, $args, 'sample', $args['targetSpeciesAttr']);
     if (!$targetSpeciesAttr) {
         return lang::get('The Target Species Grid control must be used with a survey that has the ' . $args['targetSpeciesAttr'] . ' attribute associated with it.');
     }
     // the target species grid is based on a grouping of samples determined by the
     // 1) the termlist id of the list of target species: argument targetSpeciesTermList
     // 2) a default set of attributes to be loaded: visit, Unsuitablity
     // 3) Overrides for specific target species: Common wall disabled second survey
     $termlist = $targetSpeciesAttr["termlist_id"];
     $extraParams = $auth['read'] + array('termlist_id' => $termlist, 'view' => 'detail');
     $targetSpecies = data_entry_helper::get_population_data(array('table' => 'termlists_term', 'extraParams' => $extraParams));
     $smpAttributes = data_entry_helper::getAttributes(array('attrtable' => 'sample_attribute', 'key' => 'sample_id', 'fieldprefix' => '{MyPrefix}:smpAttr', 'extraParams' => $auth['read'], 'survey_id' => $args['survey_id']), true);
     $retval = '<br /><table class="target-species-grid"><tr><th colspan=2>' . lang::get('Target Species') . '</th>';
     $attrList = explode(',', $args['targetSpeciesAttrList']);
     $attrIDs = array();
     foreach ($attrList as $attr) {
         $cell = "";
         // $retval .= '<th></th>'; // blank headings: will put captions in table itself.
         if (is_numeric($attr)) {
             $cell = $smpAttributes[intval($attr)]['caption'];
             $attrIDs[] = intval($attr);
         } else {
             foreach ($smpAttributes as $id => $sattr) {
                 if ($attr == $sattr['untranslatedCaption']) {
                     $cell = $sattr['caption'];
                     $attrIDs[] = $id;
                 }
             }
             if ($cell == "") {
                 $retval = lang::get('The configuration of the Target Species Grid includes a ' . $attr . ' samples attribute, which is not associated with this survey.') . '<br/>' . $retval;
             }
         }
         if (!isset($options['useCaptionsInHeader'])) {
             $cell = "";
         }
         $retval .= '<th class="targ-grid-cell">' . $cell . '</th>';
     }
     $retval .= '</tr>';
     if (isset($options['useCaptionsInHeader'])) {
         foreach ($smpAttributes as $id => $sattr) {
             unset($smpAttributes[$id]['caption']);
         }
     }
     $subSamples = array();
     $subSamplesAttrs = array();
     if (isset(data_entry_helper::$entity_to_load['sample:id'])) {
         $smpOptions = array('table' => 'sample', 'nocache' => true, 'extraParams' => $auth['read'] + array('view' => 'detail', 'parent_id' => data_entry_helper::$entity_to_load['sample:id']));
         $subSamples = data_entry_helper::get_population_data($smpOptions);
         foreach ($subSamples as $sample) {
             $subSamplesAttrs[$sample['id']] = data_entry_helper::getAttributes(array('attrtable' => 'sample_attribute', 'valuetable' => 'sample_attribute_value', 'id' => $sample['id'], 'key' => 'sample_id', 'fieldprefix' => '{MyPrefix}:smpAttr', 'extraParams' => $auth['read'], 'survey_id' => $args['survey_id']), true);
         }
     }
     // targ:sampleID:termlist_meaning_id:presence|smpAttr:attrdetails.
     foreach ($targetSpecies as $target) {
         $smpID = false;
         $fieldname = '{MyPrefix}:presence:' . $targetSpeciesAttr["attributeId"];
         $present = '';
         $attrOpts = array('lookUpKey' => 'meaning_id', 'extraParams' => $auth['read'], 'language' => iform_lang_iso_639_2($args['language']), 'disabled' => 'disabled');
         foreach ($subSamples as $subSample) {
             foreach ($subSamplesAttrs[$subSample['id']] as $id => $attr) {
                 if (isset($options['useCaptionsInHeader'])) {
                     unset($subSamplesAttrs[$subSample['id']][$id]['caption']);
                 }
                 if ($attr['attributeId'] == $targetSpeciesAttr["attributeId"] && $attr['default'] == $target['meaning_id']) {
                     $smpID = $subSample['id'];
                     $fieldname = str_replace('smpAttr', 'presence', $attr["fieldname"]);
                     $present = " checked=\"checked\" ";
                     unset($attrOpts['disabled']);
                 }
             }
         }
         $fieldprefix = 'targ:' . ($smpID ? $smpID : '-') . ':' . $target['meaning_id'];
         $retval .= str_replace('{MyPrefix}', $fieldprefix, '<tr><td>' . $target['term'] . '</td><td><input type="hidden" name="' . $fieldname . '" class="targ-presence" value=0><input type="checkbox" class="targ-presence" name="' . $fieldname . '" value=1 ' . $present . '></td>');
         foreach ($attrIDs as $attrID) {
             $retval .= str_replace('{MyPrefix}', $fieldprefix, '<td class="targ-grid-cell">' . data_entry_helper::outputAttribute($smpID ? $subSamplesAttrs[$smpID][$attrID] : $smpAttributes[$attrID], $attrOpts) . '</td>');
         }
         $retval .= '</tr>';
     }
     $retval .= '</table><br />';
     data_entry_helper::$javascript .= "// JS for target species grid control.\r\njQuery('.targ-presence').change(function(){\r\n  var myTR = jQuery(this).closest('tr');\r\n  if(jQuery(this).filter('[checked]').length>0) {\r\n    myTR.find('input').filter('[name*=\\:smpAttr\\:]').removeAttr('disabled');\r\n    myTR.find('select').removeAttr('disabled').addClass('required').after('<span class=\"deh-required\">*</span>');\r\n  } else {\r\n    myTR.find('.deh-required,.inline-error').remove();\r\n    myTR.find('.required').removeClass('ui-state-error required');\r\n    myTR.find('input').filter('[name*=\\:smpAttr\\:]').attr('disabled','disabled').removeAttr('checked');\r\n    myTR.find('select').attr('disabled','disabled').val('');\r\n  }\r\n});";
     if (isset($options['disableOptions'])) {
         $disableControls = explode(';', $options['disableOptions']);
         foreach ($disableControls as $disableControl) {
             $disableList = explode(',', $disableControl);
             data_entry_helper::$javascript .= "\njQuery('.target-species-grid').find('[name*=\\:" . $disableList[0] . "\\:smpAttr\\:]').find('option').filter('";
             for ($i = 1; $i < count($disableList); $i++) {
                 data_entry_helper::$javascript .= ($i > 1 ? ',' : '') . "[value=" . $disableList[$i] . "]";
             }
             data_entry_helper::$javascript .= "').attr('disabled','disabled');\n";
         }
     }
     data_entry_helper::$late_javascript .= "// JS for target species grid control.\r\n\$.validator.addMethod('targ-presence', function(value, element){\r\n\treturn jQuery('.targ-presence').filter('[checked]').length > 0;\r\n},\r\n  \"" . lang::get('validation_targ-presence') . "\");\r\n";
     return $retval;
 }
示例#28
0
 protected static function get_tab_content($auth, $args, $tab, $tabContent, $tabalias, &$attributes, &$hasControls)
 {
     // cols array used if we find | splitters
     $cols = array();
     $defAttrOptions = array('extraParams' => $auth['read']);
     if (isset($args['attribute_termlist_language_filter']) && $args['attribute_termlist_language_filter']) {
         $defAttrOptions['language'] = iform_lang_iso_639_2($args['language']);
     }
     //create array of attribute field names to test against later
     $attribNames = array();
     foreach ($attributes as $key => $attrib) {
         $attribNames[$key] = $attrib['id'];
     }
     $html = '';
     // Now output the content of the tab. Use a for loop, not each, so we can treat several rows as one object
     for ($i = 0; $i < count($tabContent); $i++) {
         $component = trim($tabContent[$i]);
         if (preg_match('/\\A\\?[^�]*\\?\\z/', $component) === 1) {
             // Component surrounded by ? so represents a help text
             $helpText = substr($component, 1, -1);
             $html .= '<div class="page-notice ui-state-highlight ui-corner-all">' . lang::get($helpText) . "</div>";
         } elseif (preg_match('/\\A\\[[^�]*\\]\\z/', $component) === 1) {
             // Component surrounded by [] so represents a control or control block
             // Anything following the component that starts with @ is an option to pass to the control
             $options = array();
             while ($i < count($tabContent) - 1 && substr($tabContent[$i + 1], 0, 1) == '@' || trim($tabContent[$i]) === '') {
                 $i++;
                 // ignore empty lines
                 if (trim($tabContent[$i]) !== '') {
                     $option = explode('=', substr($tabContent[$i], 1), 2);
                     if (!isset($option[1]) || $option[1] === 'false') {
                         $options[$option[0]] = FALSE;
                     } else {
                         $options[$option[0]] = json_decode($option[1], TRUE);
                         // if not json then need to use option value as it is
                         if ($options[$option[0]] == '') {
                             $options[$option[0]] = $option[1];
                         }
                     }
                     // urlParam is special as it loads the control's default value from $_GET
                     if ($option[0] === 'urlParam' && isset($_GET[$option[1]])) {
                         $options['default'] = $_GET[$option[1]];
                     }
                 }
             }
             // if @permission specified as an option, then check that the user has access to this control
             if (!empty($options['permission']) && !user_access($options['permission'])) {
                 continue;
             }
             $parts = explode('.', str_replace(array('[', ']'), '', $component));
             $method = 'get_control_' . preg_replace('/[^a-zA-Z0-9]/', '', strtolower($component));
             if (!empty($args['high_volume']) && $args['high_volume']) {
                 // enable control level report caching when in high_volume mode
                 $options['caching'] = empty($options['caching']) ? true : $options['caching'];
                 $options['cachetimeout'] = empty($options['cachetimeout']) ? HIGH_VOLUME_CONTROL_CACHE_TIMEOUT : $options['cachetimeout'];
             }
             // allow user settings to override the control - see iform_user_ui_options.module
             if (isset(data_entry_helper::$data['structureControlOverrides']) && !empty(data_entry_helper::$data['structureControlOverrides'][$component])) {
                 $options = array_merge($options, data_entry_helper::$data['structureControlOverrides'][$component]);
             }
             if (count($parts) === 1 && method_exists(self::$called_class, $method)) {
                 //outputs a control for which a specific output function has been written.
                 $html .= call_user_func(array(self::$called_class, $method), $auth, $args, $tabalias, $options);
                 $hasControls = true;
             } elseif (count($parts) === 2) {
                 require_once dirname($_SERVER['SCRIPT_FILENAME']) . '/' . data_entry_helper::relative_client_helper_path() . '/prebuilt_forms/extensions/' . $parts[0] . '.php';
                 if (method_exists('extension_' . $parts[0], $parts[1])) {
                     //outputs a control for which a specific extension function has been written.
                     $path = call_user_func(array(self::$called_class, 'getReloadPath'));
                     //pass the classname of the form through to the extension control method to allow access to calling class functions and variables
                     $args["calling_class"] = 'iform_' . self::$node->iform;
                     $html .= call_user_func(array('extension_' . $parts[0], $parts[1]), $auth, $args, $tabalias, $options, $path, $attributes);
                     $hasControls = true;
                     // auto-add JavaScript for the extension
                     if (file_exists(iform_client_helpers_path() . 'prebuilt_forms/extensions/' . $parts[0] . '.js')) {
                         drupal_add_js(iform_client_helpers_path() . 'prebuilt_forms/extensions/' . $parts[0] . '.js', array('preprocess' => FALSE));
                     }
                     if (file_exists(iform_client_helpers_path() . 'prebuilt_forms/extensions/' . $parts[0] . '.css')) {
                         drupal_add_css(iform_client_helpers_path() . 'prebuilt_forms/extensions/' . $parts[0] . '.css', array('preprocess' => FALSE));
                     }
                 } else {
                     $html .= lang::get("The {$component} extension cannot be found.");
                 }
             } elseif (($attribKey = array_search(substr($component, 1, -1), $attribNames)) !== false || preg_match('/^\\[[a-zA-Z]+:(?P<ctrlId>[0-9]+)\\]/', $component, $matches)) {
                 // control is a smpAttr or other attr control.
                 if (empty($options['extraParams'])) {
                     $options['extraParams'] = array_merge($defAttrOptions['extraParams']);
                 } else {
                     $options['extraParams'] = array_merge($defAttrOptions['extraParams'], (array) $options['extraParams']);
                 }
                 //merge extraParams first so we don't loose authentication
                 $options = array_merge($defAttrOptions, $options);
                 foreach ($options as $key => &$value) {
                     $value = apply_user_replacements($value);
                 }
                 if ($attribKey !== false) {
                     // a smpAttr control
                     $html .= data_entry_helper::outputAttribute($attributes[$attribKey], $options);
                     $attributes[$attribKey]['handled'] = true;
                 } else {
                     // if the control name of form name:id, then we will call get_control_name passing the id as a parameter
                     $method = 'get_control_' . preg_replace('/[^a-zA-Z]/', '', strtolower($component));
                     if (method_exists(self::$called_class, $method)) {
                         $options['ctrlId'] = $matches['ctrlId'];
                         $html .= call_user_func(array(self::$called_class, $method), $auth, $args, $tabalias, $options);
                     } else {
                         $html .= "Unsupported control {$component}<br/>";
                     }
                 }
                 $hasControls = true;
             } elseif ($component === '[*]') {
                 // this outputs any custom attributes that remain for this tab. The custom attributes can be configured in the
                 // settings text using something like @smpAttr:4|label=My label. The next bit of code parses these out into an
                 // array used when building the html.
                 // Alternatively, a setting like @option=value is applied to all the attributes.
                 $attrSpecificOptions = array();
                 foreach ($options as $option => $value) {
                     // split the id of the option into the control name and option name.
                     $optionId = explode('|', $option);
                     if (count($optionId) > 1) {
                         // Found an option like @smpAttr:4|label=My label
                         if (!isset($attrSpecificOptions[$optionId[0]])) {
                             $attrSpecificOptions[$optionId[0]] = array();
                         }
                         $attrSpecificOptions[$optionId[0]][$optionId[1]] = apply_user_replacements($value);
                     } else {
                         // Found an option like @option=value
                         $defAttrOptions = array_merge($defAttrOptions, array($option => $value));
                     }
                 }
                 $attrHtml = get_attribute_html($attributes, $args, $defAttrOptions, $tab, $attrSpecificOptions);
                 if (!empty($attrHtml)) {
                     $hasControls = true;
                 }
                 $html .= $attrHtml;
             } else {
                 $html .= "The form structure includes a control called {$component} which is not recognised.<br/>";
                 //ensure $hasControls is true so that the error message is shown
                 $hasControls = true;
             }
         } elseif ($component === '|') {
             // column splitter. So, store the col html and start on the next column.
             $cols[] = $html;
             $html = '';
         } else {
             // output anything else as is. This allow us to add html to the form structure.
             $html .= $component;
         }
     }
     if (count($cols) > 0) {
         $cols[] = $html;
         // a splitter in the structure so put the stuff so far in a 50% width left float div, and the stuff that follows in a 50% width right float div.
         global $indicia_templates;
         $html = str_replace(array('{col-1}', '{col-2}'), $cols, $indicia_templates['two-col-50']);
         if (count($cols) > 2) {
             unset($cols[1]);
             unset($cols[0]);
             $html .= '<div class="follow_on_block" style="clear:both;">' . implode('', $cols) . '</div>';
         } else {
             $html .= '<div class="follow_on_block" style="clear:both;"></div>';
         }
         // needed so any tab div is stretched around them
     }
     return $html;
 }
 /**
  * Gets a taxon name from a Meaning ID.
  *
  * @param int $meaningId The map layer we are preparing.
  * @param array $readAuth Read authentication.
  * @return The taxon name.
  */
 private static function get_taxon($meaningId, $readAuth)
 {
     global $user;
     $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);
     return $taxonRecords[0]['taxon'];
 }
 /**
  * Return the generated form output.
  * @return Form HTML.
  */
 public static function get_form($args)
 {
     global $user;
     $logged_in = $user->uid > 0;
     $r = "\n<form method=\"post\" id=\"entry_form\">\n";
     // 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'];
     // request automatic JS validation
     data_entry_helper::enable_validation('entry_form');
     $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('about you') . "</span></a></li>\n";
         }
         $r .= '  <li><a href="#species"><span>' . lang::get('what did you see') . "</span></a></li>\n";
         $r .= '  <li><a href="#place"><span>' . lang::get('where was it') . "</span></a></li>\n";
         $r .= '  <li><a href="#other"><span>' . lang::get('other information') . "</span></a></li>\n";
         $r .= "</ul>\n";
         data_entry_helper::enable_tabs(array('divId' => 'controls', 'style' => $args['interface']));
     }
     if ($user->uid == 0) {
         $r .= "<div id=\"about_you\">\n";
         $r .= '<p class="page-notice ui-state-highlight ui-corner-all">' . lang::get('about you tab instructions') . "</p>";
         $r .= data_entry_helper::text_input(array('label' => lang::get('first name'), 'fieldname' => 'smpAttr:' . $args['first_name_attr_id'], 'class' => 'control-width-4'));
         $r .= data_entry_helper::text_input(array('label' => lang::get('surname'), 'fieldname' => 'smpAttr:' . $args['surname_attr_id'], 'class' => 'control-width-4'));
         $r .= data_entry_helper::text_input(array('label' => lang::get('email'), 'fieldname' => 'smpAttr:' . $args['email_attr_id'], 'class' => 'control-width-4'));
         $r .= data_entry_helper::text_input(array('label' => lang::get('phone number'), 'fieldname' => 'smpAttr:' . $args['phone_attr_id'], 'class' => 'control-width-4'));
         if ($args['interface'] == 'wizard') {
             $r .= data_entry_helper::wizard_buttons(array('divId' => 'controls', 'page' => 'first'));
         }
         $r .= "</div>\n";
     }
     $r .= "<div id=\"species\">\n";
     // Output all our hidden data here
     $r .= $auth['write'];
     if ($logged_in) {
         // If logged in, output some hidden data about the user
         $r .= iform_user_get_hidden_inputs($args);
     }
     $r .= "<input type=\"hidden\" id=\"website_id\" name=\"website_id\" value=\"" . $args['website_id'] . "\" />\n";
     $r .= "<input type=\"hidden\" id=\"survey_id\" name=\"survey_id\" value=\"" . $args['survey_id'] . "\" />\n";
     $r .= "<input type=\"hidden\" id=\"record_status\" name=\"record_status\" value=\"C\" />\n";
     $r .= '<p class="page-notice ui-state-highlight ui-corner-all">' . lang::get('species tab instructions') . "</p>";
     $extraParams = $readAuth + array('taxon_list_id' => $args['list_id']);
     if ($args['preferred']) {
         $extraParams += array('preferred' => 't');
     }
     if ($args['restrict_species_to_users_lang']) {
         $extraParams += array('language_iso' => iform_lang_iso_639_2($user->lang));
     }
     $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' => 2, 'view' => 'detail', 'parentField' => 'parent_id', 'extraParams' => $extraParams);
     if ($args['species_ctrl'] == 'tree_browser') {
         // change the node template to include images
         global $indicia_templates;
         $indicia_templates['tree_browser_node'] = '<div>' . '<img src="' . data_entry_helper::$base_url . '/upload/thumb-{image_path}" alt="Image of {caption}" width="80" /></div>' . '<span>{caption}</span>';
     }
     // Dynamically generate the species selection control required.
     $r .= call_user_func(array('data_entry_helper', $args['species_ctrl']), $species_list_args);
     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('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('sample:entered_sref'), 'systems' => $systems));
     $r .= data_entry_helper::georeference_lookup(array('label' => lang::get('search for place on map'), 'georefPreferredArea' => $args['georefPreferredArea'], 'georefCountry' => $args['georefCountry'], 'georefLang' => $args['language']));
     // retrieve options for the IndiciaMapPanel, and optionally options for OpenLayers.
     $options = iform_map_get_map_options($args, $readAuth);
     $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('other tab instructions') . "</p>";
     $r .= data_entry_helper::date_picker(array('label' => lang::get('Date'), 'fieldname' => 'sample:date'));
     $r .= data_entry_helper::file_box(array('caption' => 'Upload your photos', 'resizeWidth' => 1024, 'resizeHeight' => 768, 'table' => 'occurrence_image'));
     // Dynamically create a control for the abundance
     $abundance_args = array('label' => lang::get('abundance'), 'fieldname' => 'occAttr:' + $args['abundance_attr_id'], 'table' => 'termlists_term', 'captionField' => 'term', 'valueField' => 'id', 'extraParams' => $readAuth + array('termlist_id' => $args['abundance_termlist_id']), 'size' => 6, 'sep' => '<br/>');
     $r .= call_user_func(array('data_entry_helper', $args['abundance_ctrl']), $abundance_args);
     $r .= data_entry_helper::textarea(array('label' => lang::get('sample:comment'), 'fieldname' => 'sample:comment', 'class' => 'wide'));
     $r .= '<div class="footer">' . data_entry_helper::checkbox(array('label' => lang::get('happy for contact'), 'labelClass' => 'auto', 'fieldname' => 'smpAttr:' . $args['contact_attr_id'])) . '</div>';
     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=\"Save\" />\n";
     }
     $r .= "</div>\n";
     $r .= "</div>\n";
     $r .= "</form>";
     return $r;
 }