Beispiel #1
0
 /**
  * Return the generated form output.
  * @return Form HTML.
  */
 public static function get_form($args)
 {
     $r = "<form method=\"post\">\n";
     // Get authorisation tokens to update and read from the Warehouse.
     $r .= data_entry_helper::get_auth(1, 'password');
     $readAuth = data_entry_helper::get_read_auth($args['website_id'], $args['password']);
     $r .= '<input type="hidden"  name="website_id" value="' . $args['website_id'] . '" />' . "\n";
     $r .= '<input type="hidden" name="sample:survey_id" value="' . $args['survey_id'] . '" />' . "\n";
     $r .= "<input type=\"hidden\" id=\"record_status\" value=\"C\" />\n";
     $r .= data_entry_helper::autocomplete(array('label' => 'Species', 'fieldname' => 'occurrence:taxa_taxon_list_id', 'table' => 'taxa_taxon_list', 'captionField' => 'taxon', 'valueField' => 'id', 'extraParams' => $readAuth + array('taxon_list_id' => $args['taxon_list_id'])));
     $r .= data_entry_helper::date_picker(array('label' => 'Date', 'fieldname' => 'sample:date'));
     $r .= data_entry_helper::map();
     $r .= "<input type=\"submit\" class=\"ui-state-default ui-corner-all\" value=\"Save\" />\n";
     $r .= "</form>";
     return $r;
 }
 /**
  * Return the generated form output.
  * @return Form HTML.
  */
 public static function get_form($args)
 {
     data_entry_helper::enable_tabs(array('divId' => 'controls'));
     $r = "<form method=\"post\">\n";
     // Get authorisation tokens to update and read from the Warehouse.
     $r .= data_entry_helper::get_auth($args['website_id'], $args['password']);
     $readAuth = data_entry_helper::get_read_auth($args['website_id'], $args['password']);
     $r .= "<input type=\"hidden\" id=\"website_id\" name=\"website_id\" value=\"" . $args['website_id'] . "\" />\n";
     $r .= "<input type=\"hidden\" id=\"record_status\" name=\"record_status\" value=\"C\" />\n";
     $r .= "<div id=\"controls\">\n";
     // Create a list which jQuery can parse to create the tabs.
     $r .= "<ul>\r\n      <li><a href=\"#recorder\"><span>Recorder</span></a></li>\r\n      <li><a href=\"#site\"><span>Site</span></a></li>\r\n      <li><a href=\"#species_tab_1\"><span>" . $args['tab_title_1'] . "</span></a></li>\n";
     if ($args['list_id_2']) {
         $r .= "<li><a href=\"#species_tab_2\"><span>" . $args['tab_title_2'] . "</span></a></li>\n";
     }
     if ($args['list_id_3']) {
         $r .= "<li><a href=\"#species_tab_3\"><span>" . $args['tab_title_3'] . "</span></a></li>\n";
     }
     if ($args['list_id_4']) {
         $r .= "<li><a href=\"#species_tab_4\"><span>" . $args['tab_title_4'] . "</span></a></li>\n";
     }
     $r .= "</ul>\n";
     $r .= "<div id=\"recorder\">\n";
     $r .= data_entry_helper::select(array('label' => 'Title', 'fieldname' => 'smpAttr:5', 'table' => 'termlists_term', 'captionField' => 'term', 'valueField' => 'id', 'extraParams' => $readAuth + array('termlist_external_key' => 'indicia:titles')));
     $r .= data_entry_helper::text_input(array('label' => 'First name', 'fieldname' => 'smpAttr:6'));
     $r .= data_entry_helper::text_input(array('label' => 'Last name', 'fieldname' => 'smpAttr:7'));
     $r .= data_entry_helper::text_input(array('label' => 'Email', 'fieldname' => 'smpAttr:8'));
     // Postcode before address since entering the postcode auto-populates part of the address.
     $r .= data_entry_helper::postcode_textbox(array('label' => 'Postcode', 'fieldname' => 'smpAttr:10', 'linkedAddressBoxId' => 'address', 'hiddenFields' => false));
     $r .= data_entry_helper::textarea(array('label' => 'Address', 'fieldname' => 'smpAttr:9', 'id' => 'address'));
     $r .= "</div>\n";
     $r .= "<div id=\"site\">\n";
     $r .= data_entry_helper::map();
     $r .= data_entry_helper::date_picker(array('label' => 'Date', 'fieldname' => 'sample:date'));
     $r .= "</div>\n";
     $r .= "<div id=\"species_tab_1\">\n";
     $species_list_args = array('label' => 'Species', 'fieldname' => 'occurrence:taxa_taxon_list_id', 'table' => 'taxa_taxon_list', 'captionField' => 'taxon', 'valueField' => 'id', 'columns' => 2, 'extraParams' => $readAuth + array('taxon_list_id' => $args['list_id_1']));
     $r .= data_entry_helper::species_checklist($species_list_args);
     $r .= "</div>\n";
     $r .= "</div>\n";
     $r .= "<input type=\"submit\" class=\"ui-state-default ui-corner-all\" value=\"Save\" />\n";
     $r .= "</form>";
     return $r;
 }
Beispiel #3
0
 /**
  * Return the generated form output.
  * @return Form HTML.
  */
 public static function get_form($args)
 {
     $r = "<form method=\"post\">\n";
     // Get authorisation tokens to update and read from the Warehouse.
     $r .= data_entry_helper::get_auth($args['website_id'], $args['password']);
     $readAuth = data_entry_helper::get_read_auth($args['website_id'], $args['password']);
     $r .= "<input type=\"hidden\" id=\"website_id\" name=\"website_id\" value=\"" . $args['website_id'] . "\" />\n";
     $r .= "<input type=\"hidden\" id=\"record_status\" name=\"record_status\" value=\"C\" />\n";
     $r .= "<div id=\"controls\">\n";
     if ($args['tabs']) {
         $r .= "<ul>\n        <li><a href=\"#species\"><span>Species</span></a></li>\n        <li><a href=\"#place\"><span>Place</span></a></li>\n        <li><a href=\"#other\"><span>Other Information</span></a></li>\n      </ul>\n";
         data_entry_helper::enable_tabs(array('divId' => 'controls'));
     }
     $r .= "<div id=\"species\">\n";
     $extraParams = $readAuth + array('taxon_list_id' => $args['list_id']);
     if ($args['preferred']) {
         $extraParams += array('preferred' => 't');
     }
     $species_list_args = array('label' => 'Species', 'itemTemplate' => 'select_species', 'fieldname' => 'occurrence:taxa_taxon_list_id', 'table' => 'taxa_taxon_list', 'captionField' => 'taxon', 'valueField' => 'id', 'columns' => 2, 'extraParams' => $extraParams);
     // Dynamically generate the species selection control required.
     $r .= call_user_func(array('data_entry_helper', $args['species_ctrl']), $species_list_args);
     $r .= "</div>\n";
     $r .= "<div id=\"place\">\n";
     // for this form, use bing and no geoplanet lookup, since then it requires no API keys so is a good
     // quick demo of how things work.
     $mapOptions = array('presetLayers' => array('bing_aerial'), 'locate' => false);
     if ($args['tabs']) {
         $mapOptions['tabDiv'] = 'place';
     }
     $r .= data_entry_helper::map($mapOptions);
     $r .= "</div>\n";
     $r .= "<div id=\"other\">\n";
     $r .= data_entry_helper::date_picker(array('label' => 'Date', 'fieldname' => 'sample:date'));
     $r .= data_entry_helper::select(array('label' => 'Survey', 'fieldname' => 'sample:survey_id', 'table' => 'survey', 'captionField' => 'title', 'valueField' => 'id', 'extraParams' => $readAuth));
     $r .= data_entry_helper::textarea(array('label' => 'Comment', 'fieldname' => 'sample:comment', 'class' => 'wide'));
     $r .= "</div>\n";
     $r .= "</div>\n";
     $r .= "<input type=\"submit\" class=\"ui-state-default ui-corner-all\" value=\"Save\" />\n";
     $r .= "</form>";
     return $r;
 }
 /**
  * Return the generated form output.
  * @return Form HTML.
  */
 public static function get_form($args, $node)
 {
     global $user;
     $logged_in = $user->uid > 0;
     $r = '';
     // Get authorisation tokens to update and read from the Warehouse.
     $writeAuth = data_entry_helper::get_auth($args['website_id'], $args['password']);
     $readAuth = data_entry_helper::get_read_auth($args['website_id'], $args['password']);
     $svcUrl = data_entry_helper::$base_url . '/index.php/services';
     $mode = 0;
     // default mode : display survey selector
     // mode 1: display new sample
     // mode 2: display existing sample
     $loadID = null;
     $displayThisOcc = true;
     // when populating from the DB rather than POST we have to be
     // careful with selection object, as geom in wrong format.
     if ($_POST) {
         if (!is_null(data_entry_helper::$entity_to_load)) {
             $mode = 2;
             // errors with new sample, entity poulated with post, so display this data.
         }
         // else valid save, so go back to gridview: default mode 0
     } else {
         if (array_key_exists('sample_id', $_GET)) {
             $mode = 2;
             $loadID = $_GET['sample_id'];
         } else {
             if (array_key_exists('newSample', $_GET)) {
                 $mode = 1;
                 data_entry_helper::$entity_to_load = array();
             }
         }
         // else default to mode 0
     }
     ///////////////////////////////////////////////////////////////////
     // default mode 0 : display survey selector
     ///////////////////////////////////////////////////////////////////
     if ($mode == 0) {
         // Create the Sample list datagrid for this user.
         drupal_add_js(drupal_get_path('module', 'iform') . '/media/js/hasharray.js', 'module');
         drupal_add_js(drupal_get_path('module', 'iform') . '/media/js/jquery.datagrid.js', 'module');
         drupal_add_js("jQuery(document).ready(function(){\n  \$('div#smp_grid').indiciaDataGrid('rpt:mnhnl_collab_list_samples', {\n    indiciaSvc: '" . $svcUrl . "',\n    dataColumns: ['location_name', 'entered_sref', 'date', 'num_occurrences', 'completed'],\n    reportColumnTitles: {location_name : '" . lang::get('LANG_Location') . "', entered_sref : '" . lang::get('LANG_Spatial_ref') . "', date : '" . lang::get('LANG_Date') . "', num_occurrences : '" . lang::get('LANG_Num_Occurrences') . "', completed : '" . lang::get('LANG_Completed') . "'},\n    actionColumns: {" . lang::get('LANG_Edit') . " : \"" . url('node/' . $node->nid, array('query' => 'sample_id=�id�')) . "\"},\n    auth : { nonce : '" . $readAuth['nonce'] . "', auth_token : '" . $readAuth['auth_token'] . "'},\n    parameters : {\n    \t\t\tsurvey_id : '" . $args['survey_id'] . "',\n    \t\t\tuserID_attr_id : '" . $args['uid_attr_id'] . "',\n    \t\t\tuserID : '" . $user->uid . "'\n    \t\t\t\t},\n    itemsPerPage : 12 \n  });\n});\n\n", 'inline');
         $r .= '<div id="sampleList" class="mnhnl-btw-datapanel"><div id="smp_grid"></div>';
         $r .= '<form><input type="button" value="' . lang::get('LANG_Add_Sample') . '" onclick="window.location.href=\'' . url('node/' . $node->nid, array('query' => 'newSample')) . '\'"></form></div>';
         $r .= "</div>\n";
         return $r;
     }
     ///////////////////////////////////////////////////////////////////
     data_entry_helper::$javascript .= "\n// Create vector layers: one to display the location onto, and another for the occurrence list\n// the default edit layer is used for the occurrences themselves\nlocStyleMap = new OpenLayers.StyleMap({\n                \"default\": new OpenLayers.Style({\n                    fillColor: \"Green\",\n                    strokeColor: \"Black\",\n                    fillOpacity: 0.3,\n                    strokeWidth: 1\n                  })\n  });\nlocationLayer = new OpenLayers.Layer.Vector(\"" . lang::get("LANG_Location_Layer") . "\",\n                                    {styleMap: locStyleMap});\n";
     if ($loadID) {
         // Can't cache these as data may have just changed
         data_entry_helper::$entity_to_load['occurrence:record_status'] = 'I';
         $url = $svcUrl . '/data/sample/' . $loadID;
         $url .= "?mode=json&view=detail&auth_token=" . $readAuth['auth_token'] . "&nonce=" . $readAuth["nonce"];
         $session = curl_init($url);
         curl_setopt($session, CURLOPT_RETURNTRANSFER, true);
         $entity = json_decode(curl_exec($session), true);
         // Attributes should be loaded by get_attributes.
         data_entry_helper::$entity_to_load = array();
         foreach ($entity[0] as $key => $value) {
             data_entry_helper::$entity_to_load['sample:' . $key] = $value;
         }
         $url = $svcUrl . '/data/occurrence';
         $url .= "?mode=json&view=detail&auth_token=" . $readAuth['auth_token'] . "&nonce=" . $readAuth["nonce"] . "&sample_id=" . $loadID . "&deleted=FALSE";
         $session = curl_init($url);
         curl_setopt($session, CURLOPT_RETURNTRANSFER, true);
         $entities = json_decode(curl_exec($session), true);
         foreach ($entities as $entity) {
             data_entry_helper::$entity_to_load['occurrence:record_status'] = $entity['record_status'];
             data_entry_helper::$entity_to_load['sc:' . $entity['taxa_taxon_list_id'] . ':' . $entity['id'] . ':present'] = true;
         }
         data_entry_helper::$entity_to_load['sample:geom'] = '';
         // value received from db is not WKT, which is assumed by all the code.
         data_entry_helper::$entity_to_load['sample:date'] = data_entry_helper::$entity_to_load['sample:date_start'];
         // bit of a bodge to get around vague dates.
     }
     $defAttrOptions = array('extraParams' => $readAuth);
     //    $r .= "<h1>MODE = ".$mode."</h1>";
     //    $r .= "<h2>readOnly = ".$readOnly."</h2>";
     $r = "<form method=\"post\" id=\"entry_form\">\n";
     // Get authorisation tokens to update and read from the Warehouse.
     $r .= $writeAuth;
     $r .= "<input type=\"hidden\" id=\"website_id\" name=\"website_id\" value=\"" . $args['website_id'] . "\" />\n";
     $r .= "<input type=\"hidden\" id=\"sample:survey_id\" name=\"sample:survey_id\" value=\"" . $args['survey_id'] . "\" />\n";
     if (array_key_exists('sample:id', data_entry_helper::$entity_to_load)) {
         $r .= "<input type=\"hidden\" id=\"sample:id\" name=\"sample:id\" value=\"" . data_entry_helper::$entity_to_load['sample:id'] . "\" />\n";
     }
     // request automatic JS validation
     data_entry_helper::enable_validation('entry_form');
     $attributes = data_entry_helper::getAttributes(array('id' => data_entry_helper::$entity_to_load['sample:id'], 'valuetable' => 'sample_attribute_value', 'attrtable' => 'sample_attribute', 'key' => 'sample_id', 'fieldprefix' => 'smpAttr', 'extraParams' => $readAuth, 'survey_id' => $args['survey_id']));
     if ($logged_in) {
         // If logged in, output some hidden data about the user
         $uid = $user->uid;
         $email = $user->mail;
         $username = $user->name;
         $uid_attr_id = $args['uid_attr_id'];
         $email_attr_id = $args['email_attr_id'];
         $username_attr_id = $args['username_attr_id'];
         // This assumes that we have the following attributes : no built in error checking.
         $r .= "<input type=\"hidden\" name=\"" . $attributes[$uid_attr_id]['fieldname'] . "\" value=\"{$uid}\" />\n";
         $r .= "<input type=\"hidden\" name=\"" . $attributes[$email_attr_id]['fieldname'] . "\" value=\"{$email}\" />\n";
         $r .= "<input type=\"hidden\" name=\"" . $attributes[$username_attr_id]['fieldname'] . "\" value=\"{$username}\" />\n";
     }
     $r .= "<div id=\"controls\">\n";
     if ($args['interface'] != 'one_page') {
         $r .= "<ul>\n";
         if (!$logged_in) {
             $r .= '  <li><a href="#about_you"><span>' . lang::get('LANG_About_You_Tab') . "</span></a></li>\n";
         }
         $r .= '  <li><a href="#species"><span>' . lang::get('LANG_Species_Tab') . "</span></a></li>\n";
         $r .= '  <li><a href="#place"><span>' . lang::get('LANG_Place_Tab') . "</span></a></li>\n";
         $r .= '  <li><a href="#other"><span>' . lang::get('LANG_Other_Information_Tab') . "</span></a></li>\n";
         $r .= "</ul>\n";
         data_entry_helper::enable_tabs(array('divId' => 'controls', 'style' => $args['interface']));
     }
     ////////////////////////////////////////////////////////////////////////////////////////////////////////////
     if (!$logged_in) {
         $r .= "<div id=\"about_you\">\n";
         $r .= '<p class="page-notice ui-state-highlight ui-corner-all">' . lang::get('LANG_About_You_Tab_Instructions') . "</p>";
         $defAttrOptions['class'] = 'control-width-4';
         $r .= data_entry_helper::outputAttribute($attributes[$args['first_name_attr_id']], $defAttrOptions);
         $r .= data_entry_helper::outputAttribute($attributes[$args['surname_attr_id']], $defAttrOptions);
         $r .= data_entry_helper::outputAttribute($attributes[$args['email_attr_id']], $defAttrOptions);
         $r .= data_entry_helper::outputAttribute($attributes[$args['phone_attr_id']], $defAttrOptions);
         if ($args['interface'] == 'wizard') {
             $r .= data_entry_helper::wizard_buttons(array('divId' => 'controls', 'page' => 'first'));
         }
         unset($defAttrOptions['class']);
         $r .= "</div>\n";
     }
     ////////////////////////////////////////////////////////////////////////////////////////////////////////////
     global $indicia_templates;
     $indicia_templates['taxon_label'] = '<div class="biota"><span class="nobreak sci binomial"><em>{taxon}</em></span> {authority}</div>';
     $r .= "<div id=\"species\">\n";
     $r .= '<p class="page-notice ui-state-highlight ui-corner-all">' . lang::get('LANG_Species_Tab_Instructions') . "</p>";
     $extraParams = $readAuth + array('taxon_list_id' => $args['list_id']);
     $species_list_args = array('label' => lang::get('occurrence:taxa_taxon_list_id'), 'fieldname' => 'occurrence:taxa_taxon_list_id', 'table' => 'taxa_taxon_list', 'captionField' => 'taxon', 'valueField' => 'id', 'columns' => 1, 'view' => 'detail', 'parentField' => 'parent_id', 'occAttrs' => explode(',', $args['checklist_attributes']), 'extraParams' => $extraParams, 'survey_id' => $args['survey_id']);
     $r .= data_entry_helper::species_checklist($species_list_args);
     $r .= "<label for=\"sample:comment\">" . lang::get('LANG_Sample_Comment_Label') . "</label><input type=\"text\" id=\"sample:comment\" name=\"sample:comment\" value=\"" . data_entry_helper::$entity_to_load['sample:comment'] . "\" />\n";
     if ($args['interface'] == 'wizard') {
         $r .= data_entry_helper::wizard_buttons(array('divId' => 'controls', 'page' => $user->id == 0 ? 'first' : 'middle'));
     }
     $r .= "</div>\n";
     ////////////////////////////////////////////////////////////////////////////////////////////////////////////
     $r .= "<div id=\"place\">\n";
     $r .= '<p class="page-notice ui-state-highlight ui-corner-all">' . lang::get('LANG_Place_Tab_Instructions') . "</p>";
     // Build the array of spatial reference systems into a format Indicia can use.
     $systems = array();
     $list = explode(',', str_replace(' ', '', $args['spatial_systems']));
     foreach ($list as $system) {
         $systems[$system] = lang::get($system);
     }
     $r .= data_entry_helper::sref_and_system(array('label' => lang::get('LANG_SRef_Label'), 'systems' => $systems));
     $location_list_args = array('label' => lang::get('LANG_Location_Label'), 'view' => 'detail', 'extraParams' => array_merge(array('view' => 'detail', 'orderby' => 'name'), $extraParams));
     $r .= call_user_func(array('data_entry_helper', $args['location_ctrl']), $location_list_args);
     $r .= data_entry_helper::georeference_lookup(array('label' => lang::get('LANG_Georef_Label'), 'georefPreferredArea' => $args['georefPreferredArea'], 'georefCountry' => $args['georefCountry'], 'georefLang' => $args['language']));
     $options = iform_map_get_map_options($args, $readAuth);
     $options['layers'][] = 'locationLayer';
     $olOptions = iform_map_get_ol_options($args);
     $r .= data_entry_helper::map_panel($options, $olOptions);
     if ($args['interface'] == 'wizard') {
         $r .= data_entry_helper::wizard_buttons(array('divId' => 'controls'));
     }
     $r .= "</div>\n";
     ////////////////////////////////////////////////////////////////////////////////////////////////////////////
     $r .= "<div id=\"other\">\n";
     $r .= '<p class="page-notice ui-state-highlight ui-corner-all">' . lang::get('LANG_Other_Information_Tab_Instructions') . "</p>";
     $r .= data_entry_helper::date_picker(array('label' => lang::get('LANG_Date'), 'fieldname' => 'sample:date'));
     $r .= data_entry_helper::outputAttribute($attributes[$args['biotope_attr_id']], $defAttrOptions);
     $r .= data_entry_helper::outputAttribute($attributes[$args['voucher_attr_id']], $defAttrOptions);
     $values = array('I', 'C');
     // not initially doing V=Verified
     $r .= '<label for="occurrence:record_status">' . lang::get('LANG_Record_Status_Label') . '</label><select id="occurrence:record_status" name="occurrence:record_status">';
     foreach ($values as $value) {
         $r .= '<option value="' . $value . '"';
         if (isset(data_entry_helper::$entity_to_load['occurrence:record_status'])) {
             if (data_entry_helper::$entity_to_load['occurrence:record_status'] == $value) {
                 $r .= ' selected="selected"';
             }
         }
         $r .= '>' . lang::get('LANG_Record_Status_' . $value) . '</option>';
     }
     $r .= '</select>';
     //  TODO image upload - not sure how to do this as images are attached to occurrences, and occurrences
     //  are embedded in the species list.
     //    $r .= "<label for='occurrence:image'>".lang::get('LANG_Image_Label')."</label>\n".
     //        data_entry_helper::image_upload('occurrence:image');
     $r .= '<br/><br/>';
     if ($args['interface'] == 'wizard') {
         $r .= data_entry_helper::wizard_buttons(array('divId' => 'controls', 'page' => 'last'));
     } else {
         $r .= "<input type=\"submit\" class=\"ui-state-default ui-corner-all\" value=\"" . lang::get('LANG_Save') . "\" />\n";
     }
     $r .= "</div>\n";
     $r .= "</div>\n";
     if (!empty(data_entry_helper::$validation_errors)) {
         $r .= data_entry_helper::dump_remaining_errors();
     }
     $r .= "</form>";
     // may need to keep following code for location change functionality
     data_entry_helper::$onload_javascript .= "\n    \nlocationChange = function(obj){\n\tlocationLayer.destroyFeatures();\n\tif(obj.value != ''){\n\t\tjQuery.getJSON(\"" . $svcUrl . "\" + \"/data/location/\"+obj.value +\n\t\t\t\"?mode=json&view=detail&auth_token=" . $readAuth['auth_token'] . "&nonce=" . $readAuth["nonce"] . "\" +\n\t\t\t\"&callback=?\", function(data) {\n            if (data.length>0) {\n            \tvar parser = new OpenLayers.Format.WKT();\n            \tfor (var i=0;i<data.length;i++)\n\t\t\t\t{\n\t      \t\t\tif(data[i].centroid_geom){\n\t\t\t\t\t\tfeature = parser.read(data[i].centroid_geom);\n\t\t\t\t\t\tcentre = feature.geometry.getCentroid();\n\t\t\t\t\t\tcentrefeature = new OpenLayers.Feature.Vector(centre, {}, {label: data[i].name});\n\t\t\t\t\t\tlocationLayer.addFeatures([feature, centrefeature]); \n\t\t\t\t\t}\n\t\t\t\t\tif(data[i].boundary_geom){\n\t\t\t\t\t\tfeature = parser.read(data[i].boundary_geom);\n\t\t\t\t\t\tfeature.style = {strokeColor: \"Blue\",\n    \t                \tstrokeWidth: 2,\n  \t\t\t\t\t\t\tlabel: (data[i].centroid_geom ? \"\" : data[i].name)};\n\t\t\t\t\t\tlocationLayer.addFeatures([feature]);\n \t\t\t\t\t}\n    \t\t\t\tlocationLayer.map.zoomToExtent(locationLayer.getDataExtent());\n  \t\t\t\t}\n\t\t\t}\n\t\t});\n  }\n};\njQuery('#imp-location').unbind('change');\njQuery('#imp-location').change(function(){\n\tlocationChange(this);\n});\n// upload location & sref initial values into map.\njQuery('#imp-location').change();\njQuery('#imp-sref').change();\n\n";
     return $r;
 }
 /**
  * Return the generated form output.
  * @param array $args List of parameter values passed through to the form depending on how the form has been configured.
  * This array always contains a value for language.
  * @param object $node The Drupal node object.
  * @param array $response When this form is reloading after saving a submission, contains the response from the service call.
  * Note this does not apply when redirecting (in this case the details of the saved object are in the $_GET data).
  * @return Form HTML.
  * @todo: Implement this method 
  */
 public static function get_form($args, $node, $response = null)
 {
     global $indicia_templates, $user;
     data_entry_helper::enable_validation('entry_form');
     $url = !empty($_SERVER['HTTPS']) ? "https://" . $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI'] : "http://" . $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI'];
     $r = data_entry_helper::loading_block_start();
     $r .= "<form method=\"post\" id=\"entry_form\" action=\"{$url}\">\n";
     $readAuth = data_entry_helper::get_read_auth($args['website_id'], $args['password']);
     $r .= "<div id=\"controls\">\n";
     if ($args['interface'] != 'one_page') {
         $r .= "<ul>\n";
         if ($user->uid == 0) {
             $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 .= "<fieldset id=\"about_you\">\n";
         if ($args['interface'] == 'one_page') {
             $r .= '<legend>' . lang::get('about you') . '</legend>';
         }
         $r .= data_entry_helper::text_input(array('label' => lang::get('first name'), 'fieldname' => 'smpAttr:' . $args['first_name_attr_id'], 'class' => 'control-width-4', 'validation' => array('required')));
         $r .= data_entry_helper::text_input(array('label' => lang::get('surname'), 'fieldname' => 'smpAttr:' . $args['surname_attr_id'], 'class' => 'control-width-4', 'validation' => array('required')));
         $r .= data_entry_helper::text_input(array('label' => lang::get('phone number'), 'fieldname' => 'smpAttr:' . $args['phone_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 optional', 'validation' => array('email')));
         if ($args['interface'] == 'wizard') {
             $r .= data_entry_helper::wizard_buttons(array('divId' => 'controls', 'page' => 'first'));
         }
         $r .= "</fieldset>\n";
     }
     // Species tab
     $r .= "<fieldset id=\"species\">\n";
     if ($args['interface'] == 'one_page') {
         $r .= '<legend>' . lang::get('what did you see') . '</legend>';
     }
     $species_list_args = array('label' => lang::get('Species'), 'fieldname' => 'occurrence:taxa_taxon_list_id', 'table' => 'taxa_taxon_list', 'captionField' => 'taxon', 'valueField' => 'id', 'listId' => $args['species_list_id'], 'columns' => 1, 'parentField' => 'parent_id', 'checkboxCol' => false, 'occAttrs' => array($args['abundance_attr_id']), 'extraParams' => $readAuth + array('view' => 'detail', 'orderby' => 'taxonomic_sort_order'), 'survey_id' => $args['survey_id'], 'header' => false, 'view' => 'detail', 'PHPtaxonLabel' => true);
     // Build a nice template to show a picture of each species, with fancybox.
     data_entry_helper::add_resource('fancybox');
     data_entry_helper::$javascript .= "jQuery('a.fancybox').fancybox();\n";
     $indicia_templates['taxon_label'] = 'return \'<div class="taxon-cell">' . '<a href="' . data_entry_helper::$base_url . 'upload/{image_path}" class="fancybox" >' . '<img alt="{taxon}" src="' . data_entry_helper::$base_url . 'upload/med-{image_path}" width="250"/></a>' . '<div>{taxon}</div></div>' . '<div class="taxon-desc"><ul><li>\'.str_replace("\\n", "</li><li>","{description_in_list}").\'</li></ul>' . '<a href="http://www.marine-life.org.uk/northeastcetaceans/?q=\'.
     strtolower(str_replace(array(" ", "\\\'"), array("-", ""), "{taxon}")).
     \'" target="_blank" class="ui-state-default ui-corner-all indicia-button">' . lang::get('More Info') . '...</a></div>\';';
     // Template the taxon label cell
     $indicia_templates['taxon_label_cell'] = "\n<td class='scTaxonCell'>{content}</td>";
     // Also template the attribute controls to show the label in place.
     $indicia_templates['attribute_cell'] = "\n<td class='scOccAttrCell'><label>{label}:</label><br/>{content}</td>";
     $r .= data_entry_helper::species_checklist($species_list_args);
     if ($args['interface'] == 'wizard') {
         $r .= data_entry_helper::wizard_buttons(array('divId' => 'controls', 'page' => $user->uid == 0 ? 'middle' : 'first'));
     }
     $r .= "</fieldset>";
     // --Place tab--
     $r .= "<fieldset id=\"place\">\n";
     if ($args['interface'] == 'one_page') {
         $r .= '<legend>' . lang::get('where was it') . '</legend>';
     }
     $r .= data_entry_helper::radio_group(array('label' => 'Where were you when you made the sighting?', 'fieldname' => 'smpAttr:' . $args['platform_attr_id'], 'table' => 'termlists_term', 'captionField' => 'term', 'valueField' => 'id', 'extraParams' => $readAuth + array('termlist_id' => $args['platform_termlist_id']), 'sep' => '<br />', 'labelClass' => 'auto', 'class' => 'inline sighting-platform', 'validation' => array('required')));
     $r .= '<div id="place_wrapper" class="hidden">';
     // Some instructions only visible when entering data from a boat
     $r .= '<p class="boat_mode page-notice ui-state-highlight ui-corner-all">' . lang::get('Instructions for when on boat') . '</p>';
     // Some instructions only visible when entering data from the shore
     $r .= '<p class="shore_mode page-notice ui-state-highlight ui-corner-all">' . lang::get('Instructions for clicking on map') . '</p>';
     $r .= '<div class="boat_mode">';
     // Add help examples to the lat and long boxes
     $indicia_templates['sref_textbox_latlong'] = '<label for="{idLat}">{labelLat}:</label>' . '<input type="text" id="{idLat}" name="{fieldnameLat}" {class} {disabled} value="{default}" /> <p class="helpText">e.g. 55:12.345N</p>' . '<label for="{idLong}">{labelLong}:</label>' . '<input type="text" id="{idLong}" name="{fieldnameLong}" {class} {disabled} value="{default}" /> <p class="helpText">e.g. 0:45.678W</p>' . '<input type="hidden" id="imp-geom" name="{table}:geom" value="{defaultGeom}" />' . '<input type="text" id="{id}" name="{fieldname}" style="display:none" value="{default}" />';
     $r .= data_entry_helper::sref_and_system(array('systems' => array(4326 => lang::get('Latitude, Longitude')), 'splitLatLong' => true, 'helpText' => lang::get('Instructions for latlong')));
     $r .= '</div>';
     // Initially, we hide the map. Only show it when the user selects the sighting was from the shore,
     // as a click on the map for boat recordings will not be accurate.
     $r .= '<div class="shore_mode">';
     $options = iform_map_get_map_options($args, $readAuth);
     $olOptions = iform_map_get_ol_options($args);
     $options['maxZoom'] = 9;
     // Switch to degrees and decimal minutes for lat long.
     $options['latLongFormat'] = 'DM';
     $r .= data_entry_helper::map_panel($options, $olOptions);
     // Now, add some JavaScript to show or hide the map. Show it for when the sighting was from the shore.
     // Hide it for boat based sightings as we want a GPS coordinate in this case. The JavaScript looks for the
     // checked radio button to see the value
     data_entry_helper::$javascript .= 'jQuery(".sighting-platform input").click(
   function() {
     var platformId = jQuery("input[name=smpAttr\\\\:' . $args['platform_attr_id'] . ']:checked").val();
     if (platformId == ' . $args['platform_mapped_term_id'] . ') {
       jQuery("#place_wrapper").removeClass("hidden");
       jQuery(".shore_mode").removeClass("hidden");
       jQuery(".boat_mode").addClass("hidden");
     } else {          
       jQuery("#place_wrapper").removeClass("hidden");
       jQuery(".shore_mode").addClass("hidden");
       jQuery(".boat_mode").removeClass("hidden");
     }
   }
 );' . "\n";
     // Force existing setting of the radio buttons to reload when showign page after validation failure
     data_entry_helper::$onload_javascript .= '
 jQuery("input[name=smpAttr\\\\:' . $args['platform_attr_id'] . ']:checked").trigger("click");
 ';
     $r .= '</div></div>';
     if ($args['interface'] == 'wizard') {
         $r .= data_entry_helper::wizard_buttons(array('divId' => 'controls'));
     }
     $r .= '</fieldset>';
     // --Other information tab--
     $r .= "<fieldset id=\"other\">\n";
     // Get authorisation tokens to update and read from the Warehouse.
     $r .= data_entry_helper::get_auth($args['website_id'], $args['password']);
     $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=\"occurrence:record_status\" value=\"C\" />\n";
     if ($args['interface'] == 'one_page') {
         $r .= '<legend>' . lang::get('other information') . '</legend>';
     }
     $r .= data_entry_helper::date_picker(array('label' => lang::get('Sighting Date'), 'fieldname' => 'sample:date'));
     $indicia_templates['timeFormat'] = '<label>hh:mm</label><br/>';
     $r .= data_entry_helper::text_input(array('label' => lang::get('Sighting Time'), 'fieldname' => 'smpAttr:' . $args['sample_time_attr_id'], 'class' => 'control-width-1', 'suffixTemplate' => 'timeFormat'));
     $r .= data_entry_helper::textarea(array('label' => lang::get('Any other information'), 'fieldname' => 'sample:comment', 'class' => 'control-width-6', 'helpText' => lang::get('Instructions for any other info')));
     $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></div>";
     $r .= "</form>";
     $r .= data_entry_helper::loading_block_end();
     return $r;
 }
            curl_setopt($session, CURLOPT_RETURNTRANSFER, true);
            $entity = json_decode(curl_exec($session), true);
            $entity_to_load = $entity[0];
        } else {
            $entity = null;
        }
    }
}
global $reload_post_data;
$reload_post_data = true;
?>
<form method="post" enctype="multipart/form-data" >

<?php 
// Get authentication information
echo data_entry_helper::get_auth($config['website_id'], $config['password']);
?>
<input type='hidden' id='website_id' name='website_id' value='1' />
<input type='hidden' id='record_status' name='record_status' value='C' />
<input type='hidden' id='id' name='id' value='<?php 
echo data_entry_helper::check_default_value('id');
?>
' />
<?php 
echo data_entry_helper::autocomplete(array('label' => 'Taxon', 'fieldname' => 'occurrence:taxa_taxon_list_id', 'table' => 'taxa_taxon_list', 'captionField' => 'taxon', 'valueField' => 'id', 'extraParams' => $readAuth));
echo data_entry_helper::date_picker(array('label' => 'Date', 'fieldname' => 'sample:date'));
echo data_entry_helper::map();
echo data_entry_helper::text_input(array('label' => 'Locality Description', 'fieldname' => 'sample:location_name', 'class' => 'wide'));
echo data_entry_helper::select(array('label' => 'Survey', 'fieldname' => 'sample:survey_id', 'table' => 'survey', 'captionField' => 'title', 'valueField' => 'id', 'extraParams' => $readAuth));
?>
<br />
 /**
  * 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;
 }
   /**
    * 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;
   }