Exemplo n.º 1
0
    /**
     * Return the generated form output.
     * @return Form HTML.
     */
    public static function get_form($args, $node)
    {
        global $user;
        // There is a language entry in the args parameter list: this is derived from the $language DRUPAL global.
        // It holds the 2 letter code, used to pick the language file from the lang subdirectory of prebuilt_forms.
        // There should be no explicitly output text in this file.
        // We must translate any field names and ensure that the termlists and taxonlists use the correct language.
        // For attributes, the caption is automatically translated by data_entry_helper.
        $logged_in = $user->uid > 0;
        $uid = $user->uid;
        $email = $user->mail;
        $username = $user->name;
        if (!user_access('IForm n' . $node->nid . ' access')) {
            return "<p>" . lang::get('LANG_Insufficient_Privileges') . "</p>";
        }
        $r = '';
        // Get authorisation tokens to update and read from the Warehouse.
        $readAuth = data_entry_helper::get_read_auth($args['website_id'], $args['password']);
        $svcUrl = data_entry_helper::$base_url . '/index.php/services';
        drupal_add_js(drupal_get_path('module', 'iform') . '/media/js/jquery.form.js', 'module');
        data_entry_helper::link_default_stylesheet();
        data_entry_helper::add_resource('jquery_ui');
        data_entry_helper::enable_validation('cc-1-collection-details');
        // don't care about ID itself, just want resources
        if ($args['help_module'] != '' && $args['help_inclusion_function'] != '' && module_exists($args['help_module']) && function_exists($args['help_inclusion_function'])) {
            $use_help = true;
            data_entry_helper::$javascript .= call_user_func($args['help_inclusion_function']);
        } else {
            $use_help = false;
        }
        if ($args['ID_tool_module'] != '' && $args['ID_tool_inclusion_function'] != '' && module_exists($args['ID_tool_module']) && function_exists($args['ID_tool_inclusion_function'])) {
            $use_ID_tool = true;
            data_entry_helper::$javascript .= call_user_func($args['ID_tool_inclusion_function']);
        } else {
            $use_ID_tool = false;
        }
        // The only things that will be editable after the collection is saved will be the identifiaction of the flower/insects.
        // no id - just getting the attributes, rest will be filled in using AJAX
        $sample_attributes = data_entry_helper::getAttributes(array('valuetable' => 'sample_attribute_value', 'attrtable' => 'sample_attribute', 'key' => 'sample_id', 'fieldprefix' => 'smpAttr', 'extraParams' => $readAuth, 'survey_id' => $args['survey_id']));
        $occurrence_attributes = data_entry_helper::getAttributes(array('valuetable' => 'occurrence_attribute_value', 'attrtable' => 'occurrence_attribute', 'key' => 'occurrence_id', 'fieldprefix' => 'occAttr', 'extraParams' => $readAuth, 'survey_id' => $args['survey_id']));
        $location_attributes = data_entry_helper::getAttributes(array('valuetable' => 'location_attribute_value', 'attrtable' => 'location_attribute', 'key' => 'location_id', 'fieldprefix' => 'locAttr', 'extraParams' => $readAuth, 'survey_id' => $args['survey_id']));
        $defAttrOptions = array('extraParams' => $readAuth, 'lookUpListCtrl' => 'radio_group', 'validation' => array('required'), 'language' => iform_lang_iso_639_2($args['language']), 'containerClass' => 'group-control-box', 'suffixTemplate' => 'nosuffix');
        $language = iform_lang_iso_639_2($args['language']);
        global $indicia_templates;
        $indicia_templates['sref_textbox_latlong'] = '<label for="{idLat}">{labelLat}:</label>' . '<input type="text" id="{idLat}" name="{fieldnameLat}" {class} {disabled} value="{default}" />' . '<label for="{idLong}">{labelLong}:</label>' . '<input type="text" id="{idLong}" name="{fieldnameLong}" {class} {disabled} value="{default}" />';
        $r .= data_entry_helper::loading_block_start();
        // note we have to proxy the post. Every time a write transaction is carried out, the write nonce is trashed.
        // For security reasons we don't want to give the user the ability to generate their own nonce, so we use
        // the fact that the user is logged in to drupal as the main authentication/authorisation/identification
        // process for the user. The proxy packages the post into the correct format
        //
        // There are 2 types of submission:
        // When a user validates a panel using the validate button, the following panel is opened on success
        // When a user presses a modify button, the open panel gets validated, and the panel to be modified is opened.
        $r .= '
<div id="cc-1" class="poll-section">
  <div id="cc-1-title" class="ui-accordion-header ui-helper-reset ui-state-active ui-corner-top poll-section-title">
  	<span id="cc-1-title-details">' . lang::get('LANG_Collection_Details') . '</span>
    <div class="right">
      <div>
        <span id="cc-1-reinit-button" class="ui-state-default ui-corner-all reinit-button">' . lang::get('LANG_Reinitialise') . '</span>
        <span id="cc-1-mod-button" class="ui-state-default ui-corner-all mod-button">' . lang::get('LANG_Modify') . '</span>
      </div>
    </div>
  </div>
  <div id="cc-1-details" class="ui-accordion-content ui-helper-reset ui-widget-content ui-accordion-content-active">
    <span id="cc-1-protocol-details"></span>
  </div>
  <div id="cc-1-body" class="ui-accordion-content ui-helper-reset ui-widget-content ui-accordion-content-active poll-section-body">
   <form id="cc-1-collection-details" action="' . iform_ajaxproxy_url($node, 'loc-sample') . '" method="POST">
    <input type="hidden" id="website_id"       name="website_id" value="' . $args['website_id'] . '" />
    <input type="hidden" id="imp-sref"         name="location:centroid_sref"  value="" />
    <input type="hidden" id="imp-geom"         name="location:centroid_geom" value="" />
    <input type="hidden" id="imp-sref-system"  name="location:centroid_sref_system" value="4326" />
    <input type="hidden" id="sample:survey_id" name="sample:survey_id" value="' . $args['survey_id'] . '" />
    ' . iform_pollenators::help_button($use_help, "collection-help-button", $args['help_function'], $args['help_collection_arg']) . '
    <label for="location:name">' . lang::get('LANG_Collection_Name_Label') . '</label>
 	<input type="text" id="location:name"      name="location:name" value="" class="required"/>
    <input type="hidden" id="sample:location_name" name="sample:location_name" value=""/>
 	' . data_entry_helper::outputAttribute($sample_attributes[$args['protocol_attr_id']], $defAttrOptions) . '    <input type="hidden"                       name="sample:date" value="2010-01-01"/>
    <input type="hidden" id="smpAttr:' . $args['complete_attr_id'] . '" name="smpAttr:' . $args['complete_attr_id'] . '" value="0" />
    <input type="hidden" id="smpAttr:' . $args['uid_attr_id'] . '" name="smpAttr:' . $args['uid_attr_id'] . '" value="' . $uid . '" />
    <input type="hidden" id="smpAttr:' . $args['email_attr_id'] . '" name="smpAttr:' . $args['email_attr_id'] . '" value="' . $email . '" />
    <input type="hidden" id="smpAttr:' . $args['username_attr_id'] . '" name="smpAttr:' . $args['username_attr_id'] . '" value="' . $username . '" />  
    <input type="hidden" id="locations_website:website_id" name="locations_website:website_id" value="' . $args['website_id'] . '" />
    <input type="hidden" id="location:id"      name="location:id" value="" disabled="disabled" />
    <input type="hidden" id="sample:id"        name="sample:id" value="" disabled="disabled" />
    </form>
    <div id="cc-1-valid-button" class="ui-state-default ui-corner-all save-button">' . lang::get('LANG_Validate') . '</div>
  </div>  
<div style="display:none" />
    <form id="cc-1-delete-collection" action="' . iform_ajaxproxy_url($node, 'sample') . '" method="POST">
       <input type="hidden" name="website_id" value="' . $args['website_id'] . '" />
       <input type="hidden" name="sample:survey_id" value="' . $args['survey_id'] . '" />
       <input type="hidden" name="sample:id" value="" />
       <input type="hidden" name="sample:date" value="2010-01-01"/>
       <input type="hidden" name="sample:location_id" value="" />
       <input type="hidden" name="sample:deleted" value="t" />
    </form>
</div>
  <div id="cc-1-main-body" class="ui-accordion-content ui-helper-reset ui-widget-content ui-corner-bottom ui-accordion-content-active">
';
        data_entry_helper::$javascript .= "\n\$.validator.messages.required = \"" . lang::get('validation_required') . "\";\nvar sessionCounter = 0;\n\n\$.fn.foldPanel = function(){\n\tthis.children('.poll-section-body').addClass('poll-hide');\n\tthis.children('.poll-section-footer').addClass('poll-hide');\n\tthis.children('.poll-section-title').find('.reinit-button').show();\n\tthis.children('.poll-section-title').find('.mod-button').show();\n\tthis.children('.photoReelContainer').addClass('ui-corner-all').removeClass('ui-corner-top')\n};\n\n\$.fn.unFoldPanel = function(){\n\tthis.children('.poll-section-body').removeClass('poll-hide');\n\tthis.children('.poll-section-footer').removeClass('poll-hide');\n\tthis.children('.poll-section-title').find('.mod-button').hide();\n\tthis.children('.photoReelContainer').addClass('ui-corner-top').removeClass('ui-corner-all')\n\twindow.scroll(0,0); // force the window to display the top.\n\t// any reinit button is left in place\n};\n\n// because the map has to be generated in a properly sized div, we can't use the normal hide/show functions.\n// just move the panels off to the side.\n\$.fn.showPanel = function(){\n\tthis.removeClass('poll-hide');\n\tthis.unFoldPanel();\n};\n\n\$.fn.hidePanel = function(){\n\tthis.addClass('poll-hide'); \n};\n\ninseeLayer = null;\n\ndefaultSref = '" . ((int) $args['map_centroid_lat'] > 0 ? $args['map_centroid_lat'] . 'N' : -(int) $args['map_centroid_lat'] . 'S') . ' ' . ((int) $args['map_centroid_long'] > 0 ? $args['map_centroid_long'] . 'E' : -(int) $args['map_centroid_long'] . 'W') . "';\ndefaultGeom = '';\n\$.getJSON('" . $svcUrl . "' + '/spatial/sref_to_wkt'+\n        \t\t\t'?sref=' + defaultSref +\n          \t\t\t'&system=' + jQuery('#imp-sref-system').val() +\n          \t\t\t'&callback=?', function(data) {\n            \tdefaultGeom = data.wkt;\n        \t});\n\n\$.fn.resetPanel = function(){\n\tthis.find('.poll-section-body').removeClass('poll-hide');\n\tthis.find('.poll-section-footer').removeClass('poll-hide');\n\tthis.find('.reinit-button').show();\n\tthis.find('.mod-button').show();\n\tthis.find('.poll-image').empty();\n\tthis.find('.poll-session').empty();\n\n\t// resetForm does not reset the hidden fields. record_status, imp-sref-system, website_id and survey_id are not altered so do not reset.\n\t// hidden Attributes generally hold unchanging data, but the name needs to be reset (does it for non hidden as well).\n\t// hidden location:name are set in code anyway.\n\tthis.find('form').each(function(){\n\t\tjQuery(this).resetForm();\n\t\tjQuery(this).find('[name=sample\\:location_name],[name=location_image\\:path],[name=occurrence_image\\:path]').val('');\n\t\tjQuery(this).filter('#cc-1-collection-details').find('[name=sample\\:id],[name=location\\:id]').val('').attr('disabled', 'disabled');\n\t\tjQuery(this).find('[name=location_image\\:id],[name=occurrence\\:id],[name=occurrence_image\\:id]').val('').attr('disabled', 'disabled');\n\t\tjQuery(this).find('[name=sample\\:date]:hidden').val('2010-01-01');\t\t\n        jQuery(this).find('input[name=locations_website\\:website_id]').removeAttr('disabled');\n\t\tjQuery(this).find('[name^=smpAttr\\:],[name^=locAttr\\:],[name^=occAttr\\:]').each(function(){\n\t\t\tvar name = jQuery(this).attr('name').split(':');\n\t\t\tjQuery(this).attr('name', name[0]+':'+name[1]);\n\t\t});\n\t\tjQuery(this).find('input[name=location\\:centroid_sref]').val('');\n\t\tjQuery(this).find('input[name=location\\:centroid_geom]').val('');\n    });\t\n\tthis.find('.poll-dummy-form > input').val('');\n\tthis.find('.poll-dummy-form > select').val('');\n  };\n\ncheckProtocolStatus = function(){\n\tif (jQuery('#cc-3-body').children().length === 1) {\n\t    jQuery('#cc-3').find('.delete-button').hide();\n  \t} else {\n\t\tjQuery('#cc-3').find('.delete-button').show();\n\t}\n\tif(jQuery('[name=smpAttr\\:" . $args['protocol_attr_id'] . "],[name^=smpAttr\\:" . $args['protocol_attr_id'] . "\\:]').filter(':first').filter('[checked]').length >0){\n\t    jQuery('#cc-3').find('.add-button').hide();\n\t} else {\n\t    jQuery('#cc-3').find('.add-button').show();\n  \t}\n  \tvar checkedProtocol = jQuery('[name=smpAttr\\:" . $args['protocol_attr_id'] . "],[name^=smpAttr\\:" . $args['protocol_attr_id'] . "\\:]').filter('[checked]').parent();\n    if(jQuery('[name=location\\:name]').val() != '' && checkedProtocol.length > 0) {\n        jQuery('#cc-1-title-details').empty().text(jQuery('#cc-1-collection-details input[name=location\\:name]:first').val());\n        jQuery('#cc-1-protocol-details').empty().show().text(\"" . lang::get('LANG_Protocol_Title_Label') . " : \" + checkedProtocol.find('label')[0].innerHTML;\n    } else {\n        jQuery('#cc-1-title-details').empty().text(\"" . lang::get('LANG_Collection_Details') . "\");\n        // TODO autogenerate a name\n        jQuery('#cc-1-protocol-details').empty().hide();\n    }\n};\n\nshowStationPanel = true;\n\n// The validate functionality for each panel is sufficiently different that we can't generalise a function\n// this is the one called when we don't want the panel following to be opened automatically.\nvalidateCollectionPanel = function(){\n\tif(jQuery('#cc-1-body').filter('.poll-hide').length > 0) return true; // body hidden so data already been validated successfully.\n\tif(!jQuery('#cc-1-body').find('form > input').valid()){ return false; }\n\t// no need to check protocol - if we are this far, we've already filled it in.\n  \tshowStationPanel = false;\n\tjQuery('#cc-1-collection-details').submit();\n\treturn true;\n  };\n\nvalidateRadio = function(name, formSel){\n    var controls = jQuery(formSel).find('[name='+name+'],[name^='+name+'\\:]');\n\tcontrols.parent().parent().find('p').remove(); // remove existing errors\n    if(controls.filter('[checked]').length < 1) {\n        var label = \$('<p/>')\n\t\t\t\t.attr({'for': name})\n\t\t\t\t.addClass('radio-error')\n\t\t\t\t.html(\$.validator.messages.required);\n\t\tlabel.insertBefore(controls.filter(':first').parent());\n\t\treturn false;\n    }\n    return true;\n}\n\nvalidateRequiredField = function(name, formSel){\n    var control = jQuery(formSel).find('[name='+name+']');\n\tcontrol.parent().find('.required-error').remove(); // remove existing errors\n    if(control.val() == '') {\n        var label = \$('<p/>')\n\t\t\t\t.attr({'for': name})\n\t\t\t\t.addClass('required-error')\n\t\t\t\t.html(\$.validator.messages.required);\n\t\tlabel.insertBefore(control);\n\t\treturn false;\n    }\n    return true;\n}\n\n\$('#cc-1-collection-details').ajaxForm({ \n        // dataType identifies the expected content type of the server response \n        dataType:  'json', \n        // success identifies the function to invoke when the server response \n        // has been received \n        beforeSubmit:   function(data, obj, options){\n        \tvar valid = true;\n        \tif (!jQuery('form#cc-1-collection-details > input').valid()) { valid = false; }\n        \tif (!validateRadio('smpAttr\\:" . $args['protocol_attr_id'] . "', 'form#cc-1-collection-details')) { valid = false; }\n\t       \tif ( valid == false ) return valid;\n  \t\t\t// Warning this assumes that:\n  \t\t\t// 1) the location:name is the sixth field in the form.\n  \t\t\t// 1) the sample:location_name is the seventh field in the form.\n  \t\t\tdata[6].value = data[5].value;\n  \t\t\tif(data[1].value=='') data[1].value=defaultSref;\n  \t\t\tif(data[2].value=='') data[2].value=defaultGeom;\n  \t\t\tjQuery('#cc-2-floral-station > input[name=location\\:name]').val(data[5].value);\n        \treturn true;\n  \t\t},\n        success:   function(data){\n        \tif(data.success == 'multiple records' && data.outer_table == 'location'){\n        \t    jQuery('#cc-1-collection-details > input[name=location\\:id]').removeAttr('disabled').val(data.outer_id);\n        \t    jQuery('#cc-1-collection-details > input[name=locations_website\\:website_id]').attr('disabled', 'disabled');\n        \t    jQuery('#cc-2-floral-station > input[name=location\\:id]').removeAttr('disabled').val(data.outer_id);\n        \t    \$.getJSON(\"" . $svcUrl . "\" + \"/data/sample\" +\n\t\t\t          \"?mode=json&view=detail&nonce=" . $readAuth['nonce'] . "&auth_token=" . $readAuth['auth_token'] . "\" +\n\t\t\t          \"&location_id=\"+data.outer_id+\"&parent_id=NULL&callback=?\", function(data) {\n\t\t\t\t\tif (data.length>0) {\n\t\t\t       \t\t    jQuery('#cc-6-consult-collection').attr('href', '" . url('node/' . $args['gallery_node']) . "'+'?collection_id='+data[0].id);\n\t\t\t        \t    jQuery('#cc-1-collection-details > input[name=sample\\:id]').removeAttr('disabled').val(data[0].id);\n\t\t\t        \t    jQuery('#cc-2-floral-station > input[name=sample\\:id]').removeAttr('disabled').val(data[0].id);\n\t\t\t        \t    // In this case we use loadAttributes to set the names of the attributes to include the attribute_value id.\n   \t       \t\t\t\t\tloadAttributes('sample_attribute_value', 'sample_attribute_id', 'sample_id', 'sample\\:id', data[0].id, 'smpAttr');\n\t\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t   \tcheckProtocolStatus();\n        \t\t\$('#cc-1').foldPanel();\n    \t\t\tif(showStationPanel){ \$('#cc-2').showPanel(); }\n\t\t    \tshowStationPanel = true;\n        \t}  else {\n\t\t\t\tvar errorString = \"" . lang::get('LANG_Indicia_Warehouse_Error') . "\";\n\t\t\t\tif(data.error){\n\t\t\t\t\terrorString = errorString + ' : ' + data.error;\n\t\t\t\t}\n\t\t\t\tif(data.errors){\n\t\t\t\t\tfor (var i in data.errors)\n\t\t\t\t\t{\n\t\t\t\t\t\terrorString = errorString + ' : ' + data.errors[i];\n\t\t\t\t\t}\t\t\t\t\n\t\t\t\t}\n\t\t\t\talert(errorString);\n\t\t\t}\n        } \n});\n\n\$('#cc-1-delete-collection').ajaxForm({ \n        dataType:  'json', \n        beforeSubmit:   function(data, obj, options){\n  \t\t\t// Warning this assumes that the data is fixed position:\n       \t\tdata[2].value = jQuery('#cc-1-collection-details input[name=sample\\:id]').val();\n       \t\tdata[3].value = jQuery('#cc-1-collection-details input[name=sample\\:date]').val();\n       \t\tdata[4].value = jQuery('#cc-1-collection-details input[name=location\\:id]').val();\n        \tif(data[2].value == '') return false;\n        \treturn true;\n  \t\t},\n        success:   function(data){\n\t\t\tjQuery('#cc-3-body').empty();\n        \tjQuery('.poll-section').resetPanel();\n\t\t\tsessionCounter = 0;\n\t\t\taddSession();\n\t\t\tcheckProtocolStatus();\n\t\t\tjQuery('.poll-section').hidePanel();\n\t\t\tjQuery('.poll-image').empty();\n\t\t\tjQuery('#cc-1').showPanel();\n\t\t\tjQuery('.reinit-button').hide();\n\t\t\tjQuery('#map')[0].map.editLayer.destroyFeatures();\n  \t\t} \n});\n\n\$('#cc-1-valid-button').click(function() {\n\tjQuery('#cc-1-collection-details').submit();\n});\n\n\$('#cc-1-reinit-button').click(function() {\n\tif(jQuery('form#cc-1-collection-details > input[name=sample\\:id]').filter('[disabled]').length > 0) { return } // sample id is disabled, so no data has been saved - do nothing.\n    if (!jQuery('form#cc-1-collection-details > input').valid()) {\n    \talert(\"" . lang::get('LANG_Unable_To_Reinit') . "\");\n        return ;\n  \t}\n\tif(confirm(\"" . lang::get('LANG_Confirm_Reinit') . "\")){\n\t\tjQuery('#cc-1-delete-collection').submit();\n\t}\n});\n\n";
        // Flower Station section.
        $options = iform_map_get_map_options($args, $readAuth);
        $olOptions = iform_map_get_ol_options($args);
        // The maps internal projection will be left at its default of 900913.
        $options['searchLayer'] = 'true';
        $options['initialFeatureWkt'] = null;
        $options['proxy'] = '';
        // Switch to degrees, minutes, seconds for lat long.
        $options['latLongFormat'] = 'DMS';
        $options['suffixTemplate'] = 'nosuffix';
        $extraParams = $readAuth + array('taxon_list_id' => $args['flower_list_id'], 'orderby' => 'taxon');
        $species_ctrl_args = array('label' => lang::get('LANG_Flower_Species'), 'fieldname' => 'flower:taxa_taxon_list_id', 'table' => 'taxa_taxon_list', 'captionField' => 'taxon', 'valueField' => 'id', 'columns' => 2, 'validation' => array('required'), 'blankText' => lang::get('LANG_Choose_Taxon'), 'extraParams' => $extraParams, 'suffixTemplate' => 'nosuffix');
        $r .= '
<div id="cc-2" class="poll-section">
  <div id="cc-2-title" class="ui-accordion-header ui-helper-reset ui-state-active ui-corner-all poll-section-title"><span>' . lang::get('LANG_Flower_Station') . '</span>
    <div class="right">
      <span id="cc-2-mod-button" class="ui-state-default ui-corner-all mod-button">' . lang::get('LANG_Modify') . '</span>
    </div>
  </div>
  <div id="cc-2-body" class="ui-accordion-content ui-helper-reset ui-widget-content ui-corner-top ui-accordion-content-active poll-section-body">
    <div id="cc-2-flower" >
	  <form id="cc-2-flower-upload" enctype="multipart/form-data" action="' . iform_ajaxproxy_url($node, 'media') . '" method="POST">
    		<input type="hidden" id="website_id" name="website_id" value="' . $args['website_id'] . '" />
    		<input name="upload_file" type="file" class="required" />
     		<input type="submit" value="' . lang::get('LANG_Upload_Flower') . '" class="btn-submit" />
      </form>
 	  <div id="cc-2-flower-image" class="poll-image"></div>
 	  <div id="cc-2-flower-identify" class="poll-dummy-form">
        ' . iform_pollenators::help_button($use_help, "flower-help-button", $args['help_function'], $args['help_flower_arg']) . '
 	    <p><strong>' . lang::get('LANG_Identify_Flower') . '</strong></p>
        <label for="id-flower-later" class="follow-on">' . lang::get('LANG_ID_Flower_Later') . ' </label><input type="checkbox" id="id-flower-later" name="id-flower-later" /> 
		' . ($args['ID_tool_flower_url'] != '' && $args['ID_tool_flower_poll_dir'] ? '<label for="flower-id-button">' . lang::get('LANG_Flower_ID_Key_label') . ' :</label><span id="flower-id-button" class="ui-state-default ui-corner-all poll-id-button" >' . lang::get('LANG_Launch_ID_Key') . '</span>' : '') . '<span id="flower-id-cancel" class="ui-state-default ui-corner-all poll-id-cancel" >' . lang::get('LANG_Cancel_ID') . '</span>
    	' . data_entry_helper::select($species_ctrl_args) . '
		<input type="text" name="flower:taxon_text_description" readonly="readonly">
      </div>
 	</div>
    <div class="poll-break"></div>
 	<div id="cc-2-environment">
	  <form id="cc-2-environment-upload" enctype="multipart/form-data" action="' . iform_ajaxproxy_url($node, 'media') . '" method="POST">
    		<input type="hidden" id="website_id" name="website_id" value="' . $args['website_id'] . '" />
    		<input name="upload_file" type="file" class="required" />
    		<input type="submit" value="' . lang::get('LANG_Upload_Environment') . '" class="btn-submit" />
      </form>
 	  <div id="cc-2-environment-image" class="poll-image"></div>
 	</div>
 	<form id="cc-2-floral-station" action="' . iform_ajaxproxy_url($node, 'loc-smp-occ') . '" method="POST">
      <input type="hidden" id="website_id" name="website_id" value="' . $args['website_id'] . '" />
      <input type="hidden" id="location:id" name="location:id" value="" />
      <input type="hidden" id="location:name" name="location:name" value=""/>
      <input type="hidden" name="location:centroid_sref" />
      <input type="hidden" name="location:centroid_geom" />
      <input type="hidden" name="location:centroid_sref_system" value="4326" />
      <input type="hidden" id="location_image:path" name="location_image:path" value="" />
      <input type="hidden" id="sample:survey_id" name="sample:survey_id" value="' . $args['survey_id'] . '" />
      <input type="hidden" id="sample:id" name="sample:id" value=""/>
      <input type="hidden" name="sample:date" value="2010-01-01"/>
      <input type="hidden" name="determination:taxa_taxon_list_id" value=""/>  
      <input type="hidden" name="determination:taxon_text_description" value=""/>  
      <input type="hidden" name="determination:cms_ref" value="' . $uid . '" />
      <input type="hidden" name="determination:email_address" value="' . $email . '" />
      <input type="hidden" name="determination:person_name" value="' . $username . '" />  
      <input type="hidden" name="occurrence:use_determination" value="Y"/>    
      <input type="hidden" name="occurrence:record_status" value="C" />
      <input type="hidden" id="location_image:id" name="location_image:id" value="" disabled="disabled" />
      <input type="hidden" id="occurrence:id" name="occurrence:id" value="" disabled="disabled" />
      <input type="hidden" id="determination:id" name="determination:id" value="" disabled="disabled" />
      <input type="hidden" id="occurrence_image:id" name="occurrence_image:id" value="" disabled="disabled" />
      <input type="hidden" id="occurrence_image:path" name="occurrence_image:path" value="" />
      ' . data_entry_helper::outputAttribute($occurrence_attributes[$args['flower_type_attr_id']], array('extraParams' => $readAuth, 'lookUpListCtrl' => 'radio_group', 'sep' => ' &nbsp; ', 'language' => iform_lang_iso_639_2($args['language']), 'containerClass' => 'group-control-box', 'suffixTemplate' => 'nosuffix')) . data_entry_helper::outputAttribute($location_attributes[$args['distance_attr_id']], array('extraParams' => $readAuth, 'lookUpListCtrl' => 'radio_group', 'sep' => ' &nbsp; ', 'language' => iform_lang_iso_639_2($args['language']), 'containerClass' => 'group-control-box', 'suffixTemplate' => 'nosuffix')) . data_entry_helper::outputAttribute($location_attributes[$args['habitat_attr_id']], array('extraParams' => $readAuth, 'lookUpListCtrl' => 'checkbox_group', 'sep' => ' &nbsp; ', 'language' => iform_lang_iso_639_2($args['language']), 'containerClass' => 'group-control-box', 'suffixTemplate' => 'nosuffix')) . '
    </form>
    <div class="poll-break"></div>
    <div>
      ' . iform_pollenators::help_button($use_help, "location-help-button", $args['help_function'], $args['help_location_arg']) . '
      <div>' . lang::get('LANG_Location_Notes') . '</div>
 	  <div class="poll-map-container">
    ';
        $r .= data_entry_helper::map_panel($options, $olOptions);
        $r .= '
      </div>
      <div><div id="cc-2-location-entry">
        ' . data_entry_helper::georeference_lookup(array('label' => lang::get('LANG_Georef_Label'), 'georefPreferredArea' => $args['georefPreferredArea'], 'georefCountry' => $args['georefCountry'], 'georefLang' => $args['language'], 'suffixTemplate' => 'nosuffix')) . '
    	<span >' . lang::get('LANG_Georef_Notes') . '</span>
 	    <label for="place:INSEE">' . lang::get('LANG_Or') . '</label>
 		<input type="text" id="place:INSEE" name="place:INSEE" value="' . lang::get('LANG_INSEE') . '"
	 		onclick="if(this.value==\'' . lang::get('LANG_INSEE') . '\'){this.value=\'\'; this.style.color=\'#000\'}"  
            onblur="if(this.value==\'\'){this.value=\'' . lang::get('LANG_INSEE') . '\'; this.style.color=\'#555\'}" />
    	<input type="button" id="search-insee-button" class="ui-corner-all ui-widget-content ui-state-default search-button" value="Search" />
        ' . data_entry_helper::sref_textbox(array('srefField' => 'place:entered_sref', 'systemfield' => 'place:entered_sref_system', 'id' => 'place-sref', 'fieldname' => 'place:name', 'splitLatLong' => true, 'labelLat' => lang::get('Latitude'), 'fieldnameLat' => 'place:lat', 'labelLong' => lang::get('Longitude'), 'fieldnameLong' => 'place:long', 'idLat' => 'imp-sref-lat', 'idLong' => 'imp-sref-long', 'suffixTemplate' => 'nosuffix')) . '
 	  </div></div>
      <div id="cc-2-loc-description"></div>
    </div>
  </div>
  <div id="cc-2-footer" class="ui-accordion-content ui-helper-reset ui-widget-content ui-corner-bottom ui-accordion-content-active poll-section-footer">
    <div id="cc-2-valid-button" class="ui-state-default ui-corner-all save-button">' . lang::get('LANG_Validate_Flower') . '</div>
  </div>
</div>';
        // NB the distance attribute is left blank at the moment if unknown: TODO put in a checkbox : checked if blank for nsp
        data_entry_helper::$javascript .= "\n\nshowSessionsPanel = true;\n\nvar flowerTimer1;\nvar flowerTimer2;\nvar IDcounter = 0;\n\nflowerPoller = function(){\n\tflowerTimer1 = setTimeout('flowerPoller();', " . $args['ID_tool_poll_interval'] . ");\n\t\$.get('" . str_replace("{HOST}", $_SERVER['HTTP_HOST'], $args['ID_tool_flower_poll_dir']) . session_id() . "_'+IDcounter.toString(), function(data){\n      var da = data.split('\\n');\n      // first count number of returned items.\n      // if > 1 put all into taxon_description.\n      // if = 1 rip out the description, remove the formatting, scan the flower select for it, and set the value. Set the taxon description.\n\t  da[1] = da[1].replace(/\\\\\\\\i\\{\\}/g, '').replace(/\\\\\\\\i0\\{\\}/g, '');\n      var items = da[1].split(':');\n\t  var count = items.length;\n\t  if(items[count-1] == '') count--;\n\t  if(count <= 0){\n\t  \t// no valid stuff so blank it all out.\n\t  \tjQuery('#cc-2-flower-identify > select[name=flower\\:taxa_taxon_list_id]').val('');\n\t  \tjQuery('#cc-2-flower-identify > select[name=flower\\:taxon_text_description]').val('');\n\t  } else if(count == 1){\n\t  \tjQuery('#cc-2-flower-identify > select[name=flower\\:taxa_taxon_list_id]').val('');\n\t  \tjQuery('#cc-2-flower-identify > select[name=flower\\:taxon_text_description]').val(items[0]);\n  \t\tvar x = jQuery('#cc-2-flower-identify').find('option').filter('[text='+items[0]+']');\n\t  \tif(x.length > 0){\n\t\t\tjQuery('#cc-2-flower-identify > select[name=flower\\:taxon_text_description]').val('');\n\t  \t\tjQuery('#cc-2-flower-identify > select[name=flower\\:taxa_taxon_list_id]').val(x[0].value);\n  \t\t}\n\t  } else {\n\t  \tjQuery('#cc-2-flower-identify > select[name=flower\\:taxa_taxon_list_id]').val('');\n\t  \tjQuery('#cc-2-flower-identify > select[name=flower\\:taxon_text_description]').val(da[1]);\n\t  }\n\t  flowerReset();\n    });\n};\nflowerReset = function(){\n\tclearTimeout(flowerTimer1);\n\tclearTimeout(flowerTimer2);\n\tjQuery('#flower-id-cancel').hide();\n};\n\njQuery('#flower-id-button').click(function(){\n\tIDcounter++;\n\tclearTimeout(flowerTimer1);\n\tclearTimeout(flowerTimer2);\n\twindow.open('" . $args['ID_tool_flower_url'] . session_id() . "_'+IDcounter.toString(),'','') \n\tflowerTimer1 = setTimeout('flowerPoller();', " . $args['ID_tool_poll_interval'] . ");\n\tflowerTimer2 = setTimeout('flowerReset();', " . $args['ID_tool_poll_timeout'] . ");\n\tjQuery('#flower-id-cancel').show();\n});\njQuery('#flower-id-cancel').click(function(){\n\tflowerReset();\n});\njQuery('#flower-id-cancel').hide();\n\njQuery('#search-insee-button').click(function(){\n\tif(inseeLayer != null)\n\t\tinseeLayer.destroy();\n\tvar filters = [];\n  \tvar place = jQuery('input[name=place\\:INSEE]').val();\n  \tif(place == '" . lang::get('LANG_INSEE') . "') return;\n  \tfilters.push(new OpenLayers.Filter.Comparison({\n  \t\t\ttype: OpenLayers.Filter.Comparison.EQUAL_TO ,\n    \t\tproperty: 'INSEE_NEW',\n    \t\tvalue: place\n  \t\t}));\n  \tfilters.push(new OpenLayers.Filter.Comparison({\n  \t\t\ttype: OpenLayers.Filter.Comparison.EQUAL_TO ,\n    \t\tproperty: 'INSEE_OLD',\n    \t\tvalue: place\n  \t\t}));\n\n\tvar strategy = new OpenLayers.Strategy.Fixed({preload: false, autoActivate: false});\n\tvar styleMap = new OpenLayers.StyleMap({\n                \"default\": new OpenLayers.Style({\n                    fillColor: \"Red\",\n                    strokeColor: \"Red\",\n                    fillOpacity: 0,\n                    strokeWidth: 1\n                  })\n\t});\n\tinseeLayer = new OpenLayers.Layer.Vector('INSEE Layer', {\n\t\t  styleMap: styleMap,\n          strategies: [strategy],\n          displayInLayerSwitcher: false,\n\t      protocol: new OpenLayers.Protocol.WFS({\n              url:  '" . str_replace("{HOST}", $_SERVER['HTTP_HOST'], $args['INSEE_url']) . "',\n              featurePrefix: '" . $args['INSEE_prefix'] . "',\n              featureType: '" . $args['INSEE_type'] . "',\n              geometryName:'the_geom',\n              featureNS: '" . $args['INSEE_ns'] . "',\n              srsName: 'EPSG:900913',\n              version: '1.1.0'                  \n      \t\t  ,propertyNames: ['the_geom']\n  \t\t\t})\n    });\n\tinseeLayer.events.register('featuresadded', {}, function(a1){\n\t\tvar div = jQuery('#map')[0];\n\t\tdiv.map.searchLayer.destroyFeatures();\n\t\tvar bounds=inseeLayer.getDataExtent();\n    \tvar dy = (bounds.top-bounds.bottom)/10;\n    \tvar dx = (bounds.right-bounds.left)/10;\n    \tbounds.top = bounds.top + dy;\n    \tbounds.bottom = bounds.bottom - dy;\n    \tbounds.right = bounds.right + dx;\n    \tbounds.left = bounds.left - dx;\n    \t// if showing a point, don't zoom in too far\n    \tif (dy===0 && dx===0) {\n    \t\tdiv.map.setCenter(bounds.getCenterLonLat(), div.settings.maxZoom);\n    \t} else {\n    \t\tdiv.map.zoomToExtent(bounds);\n    \t}\n    });\n\tinseeLayer.events.register('loadend', {}, function(){\n\t\tif(inseeLayer.features.length == 0){\n\t\t\talert(\"" . lang::get('LANG_NO_INSEE') . "\");\n\t\t}\n    });\n    jQuery('#map')[0].map.addLayer(inseeLayer);\n\tstrategy.load({filter: new OpenLayers.Filter.Logical({\n\t\t\t      type: OpenLayers.Filter.Logical.OR,\n\t\t\t      filters: filters\n\t\t  \t  })});\n});\n\nvalidateStationPanel = function(){\n\tvar myPanel = jQuery('#cc-2');\n\tvar valid = true;\n\tif(myPanel.filter('.poll-hide').length > 0) return true; // panel is not visible so no data to fail validation.\n\tif(myPanel.find('.poll-section-body').filter('.poll-hide').length > 0) return true; // body hidden so data already been validated successfully.\n\t// If no data entered also return true: this can only be the case when pressing the modify button on the collections panel\n\tif(jQuery('form#cc-2-floral-station > input[name=location_image\\:path]').val() == '' &&\n\t\t\tjQuery('form#cc-2-floral-station > input[name=occurrence\\:id]').val() == '' &&\n\t\t\tjQuery('form#cc-2-floral-station > input[name=occurrence_image\\:path]').val() == '' &&\n\t\t\tjQuery('#cc-2-flower-identify > select[name=flower\\:taxa_taxon_list_id]').val() == '' &&\n    \t\tjQuery('[name=occAttr\\:" . $args['flower_type_attr_id'] . "],[name^=occAttr\\:" . $args['flower_type_attr_id'] . "\\:]').filter('[checked]').length == 0 &&\n    \t\tjQuery('[name=locAttr\\:" . $args['habitat_attr_id'] . "],[name^=locAttr\\:" . $args['habitat_attr_id'] . "\\:]').filter('[checked]').length == 0 &&\n    \t\tjQuery('[name=locAttr\\:" . $args['distance_attr_id'] . "],[name^=locAttr\\:" . $args['distance_attr_id'] . "\\:]').val() == '') {\n\t\tjQuery('#cc-2').foldPanel();\n\t\treturn true;\n\t}\n    if(jQuery('form#cc-2-floral-station > input[name=location_image\\:path]').val() == '' ||\n\t\t\t\t\tjQuery('form#cc-2-floral-station > input[name=occurrence_image\\:path]').val() == ''){\n\t\talert(\"" . lang::get('LANG_Must_Provide_Pictures') . "\");\n\t\tvalid = false;\n\t}\n    if(jQuery('#imp-geom').val() == '') {\n\t\talert(\"" . lang::get('LANG_Must_Provide_Location') . "\");\n\t\tvalid = false;\n\t}\n\tif (jQuery('#id-flower-later').attr('checked') == ''){\n\t\tif(!validateRequiredField('flower\\:taxa_taxon_list_id', '#cc-2-flower-identify')) { valid = false; }\n\t}\n\tif (!jQuery('form#cc-2-floral-station > input').valid()) { valid = false; }\n   \tif (!validateRadio('occAttr\\:" . $args['flower_type_attr_id'] . "', 'form#cc-2-floral-station')) { valid = false; }\n   \tif ( valid == false ) return valid;\n\tshowSessionsPanel = false;\n\tjQuery('form#cc-2-floral-station').submit();\n\treturn true;\n};\n\n// Flower upload picture form.\n\$('#cc-2-flower-upload').ajaxForm({ \n        dataType:  'json', \n        beforeSubmit:   function(data, obj, options){\n         \tif (!jQuery('form#cc-2-flower-upload').valid()) { return false; }\n        \t\$('#cc-2-flower-image').empty();\n        \t\$('#cc-2-flower-image').addClass('loading')\n        },\n        success:   function(data){\n        \tif(data.success == true){\n\t        \t// There is only one file\n\t        \tjQuery('form#cc-2-floral-station input[name=occurrence_image\\:path]').val(data.files[0]);\n\t        \tvar img = new Image();\n\t        \t\$(img).load(function () {\n        \t\t\t\t\$(this).hide();\n        \t\t\t\t\$('#cc-2-flower-image').removeClass('loading').append(this);\n        \t\t\t\t\$(this).fadeIn();\n\t\t\t    \t})\n\t\t\t\t    .attr('src', '" . data_entry_helper::$base_url . data_entry_helper::$indicia_upload_path . "med-'+data.files[0])\n\t\t\t\t    .css('max-width', \$('#cc-2-flower-image').width()).css('max-height', \$('#cc-2-flower-image').height())\n\t\t\t\t    .css('vertical-align', 'middle').css('margin-left', 'auto').css('margin-right', 'auto').css('display', 'block');\n\t\t\t\tjQuery('#cc-2-flower-upload input[name=upload_file]').val('');\n\t\t\t} else {\n\t\t\t\tvar errorString = \"" . lang::get('LANG_Indicia_Warehouse_Error') . "\";\n\t        \tjQuery('form#cc-2-floral-station input[name=occurrence_image\\:path]').val('');\n\t\t\t\t\$('#cc-2-flower-image').removeClass('loading');\n\t\t\t\tif(data.error){\n\t\t\t\t\terrorString = errorString + ' : ' + data.error;\n\t\t\t\t}\n\t\t\t\tif(data.errors){\n\t\t\t\t\tfor (var i in data.errors)\n\t\t\t\t\t{\n\t\t\t\t\t\terrorString = errorString + ' : ' + data.errors[i];\n\t\t\t\t\t}\t\t\t\t\n\t\t\t\t}\n\t\t\t\talert(errorString);\n\t\t\t}\n  \t\t} \n});\n\n// Flower upload picture form.\n\$('#cc-2-environment-upload').ajaxForm({ \n        dataType:  'json', \n        beforeSubmit:   function(data, obj, options){\n         \tif (!jQuery('form#cc-2-environment-upload').valid()) { return false; }\n        \t\$('#cc-2-environment-image').empty();\n        \t\$('#cc-2-environment-image').addClass('loading')\n        },\n        success:   function(data){\n        \tif(data.success == true){\n\t        \t// There is only one file\n\t        \tjQuery('form#cc-2-floral-station input[name=location_image\\:path]').val(data.files[0]);\n\t        \tvar img = new Image();\n\t        \t\$(img).load(function () {\n        \t\t\t\t\$(this).hide();\n        \t\t\t\t\$('#cc-2-environment-image').removeClass('loading').append(this);\n        \t\t\t\t\$(this).fadeIn();\n\t\t\t    \t})\n\t\t\t\t    .attr('src', '" . data_entry_helper::$base_url . data_entry_helper::$indicia_upload_path . "med-'+data.files[0])\n\t\t\t\t    .css('max-width', \$('#cc-2-environment-image').width()).css('max-height', \$('#cc-2-environment-image').height())\n\t\t\t\t    .css('vertical-align', 'middle').css('margin-left', 'auto').css('margin-right', 'auto').css('display', 'block');\n\t\t\t\tjQuery('#cc-2-environment-upload input[name=upload_file]').val('');\n\t\t\t} else {\n\t\t\t\tvar errorString = \"" . lang::get('LANG_Indicia_Warehouse_Error') . "\";\n\t        \tjQuery('form#cc-2-floral-station input[name=location_image\\:path]').val('');\n\t\t\t\t\$('#cc-2-environment-image').removeClass('loading');\n\t\t\t\tif(data.error){\n\t\t\t\t\terrorString = errorString + ' : ' + data.error;\n\t\t\t\t}\n\t\t\t\tif(data.errors){\n\t\t\t\t\tfor (var i in data.errors)\n\t\t\t\t\t{\n\t\t\t\t\t\terrorString = errorString + ' : ' + data.errors[i];\n\t\t\t\t\t}\t\t\t\t\n\t\t\t\t}\n\t\t\t\talert(errorString);\n\t\t\t}\n        } \n});\n\n\$('#cc-2-floral-station').ajaxForm({ \n    dataType:  'json', \n    beforeSubmit:   function(data, obj, options){\n\t\tvar valid = true;\n    \tif(jQuery('form#cc-2-floral-station > input[name=location_image\\:path]').val() == '' ||\n\t\t\t\t\tjQuery('form#cc-2-floral-station > input[name=occurrence_image\\:path]').val() == '' ){\n\t\t\talert(\"" . lang::get('LANG_Must_Provide_Pictures') . "\");\n\t\t\tvalid = false;\n\t\t}\n\t\tif(jQuery('#imp-geom').val() == '') {\n\t\t\talert(\"" . lang::get('LANG_Must_Provide_Location') . "\");\n\t\t\tvalid = false;\n\t\t}\n\t\tif (!jQuery('form#cc-2-floral-station > input').valid()) { valid = false; }\n   \t\tif (!validateRadio('occAttr\\:" . $args['flower_type_attr_id'] . "', 'form#cc-2-floral-station')) { valid = false; }\n\t\t// DANGER this assumes certain positioning of the centroid sref and geom within the data array\n\t\tif(data[3].name != 'location:centroid_sref' || data[4].name != 'location:centroid_geom') {\n\t\t\talert('Internal error: imp-sref or imp-geom post location mismatch');\n\t\t\treturn false;\n\t\t}\n\t\tdata[3].value = jQuery('#imp-sref').val();\n\t\tdata[4].value = jQuery('#imp-geom').val();\n\t\tdata[10].value = jQuery('#cc-2-flower-identify > select[name=flower\\:taxa_taxon_list_id]').val();\n\t\tdata[11].value = jQuery('#cc-2-flower-identify > select[name=flower\\:taxon_text_description]').val();\n\t\tif (jQuery('#id-flower-later').attr('checked') == ''){\n\t\t\tif (!validateRequiredField('flower\\:taxa_taxon_list_id', '#cc-2-flower-identify')) { valid = false; }\n\t\t} else {\n\t\t\tdata.splice(10,5); // remove determination entries.\n\t\t}\n   \t\tif ( valid == false ) return valid;\n\t\treturn true;\n\t},\n    success:   function(data){\n       \tif(data.success == 'multiple records' && data.outer_table == 'sample'){\n       \t\t// the sample and location ids are already fixed, so just need to populate the occurrence and image IDs, and rename the location and occurrence attribute.\n       \t    \$.getJSON(\"" . $svcUrl . "\" + \"/data/occurrence\" +\n\t\t          \"?mode=json&view=detail&nonce=" . $readAuth['nonce'] . "&auth_token=" . $readAuth['auth_token'] . "\" +\n\t\t          \"&sample_id=\"+data.outer_id+\"&callback=?\", function(occdata) {\n\t\t\t\tif (occdata.length>0) {\n\t\t        \tjQuery('#cc-2-floral-station > input[name=occurrence\\:id]').removeAttr('disabled').val(occdata[0].id);\n       \t\t\t\tloadAttributes('occurrence_attribute_value', 'occurrence_attribute_id', 'occurrence_id', 'occurrence\\:id', occdata[0].id, 'occAttr');\n\t\t\t\t\t\$.getJSON(\"" . $svcUrl . "/data/occurrence_image/\" +\n       \t\t\t\t\t\t\"?mode=json&view=list&nonce=" . $readAuth['nonce'] . "&auth_token=" . $readAuth['auth_token'] . "\" +\n       \t\t\t\t\t\t\"&occurrence_id=\"+occdata[0].id+\"&callback=?\", function(imgdata) {\n\t\t\t\t\t    if (imgdata.length>0) {\n\t\t        \t\t\tjQuery('#cc-2-floral-station > input[name=occurrence_image\\:id]').removeAttr('disabled').val(imgdata[0].id);\n\t\t        \t\t}});\n\t\t        }});\n\t\t    var location_id = jQuery('#cc-2-floral-station > input[name=location\\:id]').val();\n       \t\tloadAttributes('location_attribute_value', 'location_attribute_id', 'location_id', 'location\\:id', location_id, 'locAttr');\n\t\t\t\$.getJSON(\"" . $svcUrl . "/data/location_image/\" +\n       \t\t\t\t\"?mode=json&view=list&nonce=" . $readAuth['nonce'] . "&auth_token=" . $readAuth['auth_token'] . "\" +\n       \t\t\t\t\"&location_id=\"+location_id+\"&callback=?\", function(data) {\n\t\t\t\tif (data.length>0) {\n\t\t        \tjQuery('#cc-2-floral-station > input[name=location_image\\:id]').removeAttr('disabled').val(data[0].id);\n\t\t        }});\n\t\t\tjQuery('#cc-2').foldPanel();\n\t\t\tif(showSessionsPanel) { jQuery('#cc-3').showPanel(); }\n\t\t\tshowSessionsPanel = true;\n        } \n\t}\n});\n\n\$('#cc-2-valid-button').click(function() {\n\tjQuery('#cc-2-floral-station').submit();\n});\n\n";
        // Sessions.
        $r .= '
<div id="cc-3" class="poll-section">
  <div id="cc-3-title" class="ui-accordion-header ui-helper-reset ui-state-active ui-corner-all poll-section-title"><span>' . lang::get('LANG_Sessions_Title') . '</span>
    <div id="cc-3-mod-button" class="right ui-state-default ui-corner-all mod-button">' . lang::get('LANG_Modify') . '</div>
  </div>
  <div id="cc-3-body" class="ui-accordion-content ui-helper-reset ui-widget-content ui-corner-top ui-accordion-content-active poll-section-body">
  </div>
  <div id="cc-3-footer" class="ui-accordion-content ui-helper-reset ui-widget-content ui-corner-bottom ui-accordion-content-active poll-section-footer">
	<div id="cc-3-add-button" class="ui-state-default ui-corner-all add-button">' . lang::get('LANG_Add_Session') . '</div>
    <div id="cc-3-valid-button" class="ui-state-default ui-corner-all save-button">' . lang::get('LANG_Validate_Session') . '</div>
  </div>
</div>
<div style="display:none" />
    <form id="cc-3-delete-session" action="' . iform_ajaxproxy_url($node, 'sample') . '" method="POST">
       <input type="hidden" name="website_id" value="' . $args['website_id'] . '" />
       <input type="hidden" name="sample:survey_id" value="' . $args['survey_id'] . '" />
       <input type="hidden" name="sample:id" value="" />
       <input type="hidden" name="sample:date" value="2010-01-01"/>
       <input type="hidden" name="sample:location_id" value="" />
       <input type="hidden" name="sample:deleted" value="t" />
    </form>
</div>';
        data_entry_helper::$javascript .= "\n\$('#cc-3-delete-session').ajaxForm({ \n        dataType:  'json', \n        beforeSubmit:   function(data, obj, options){\n  \t\t\t// Warning this assumes that the data is fixed position:\n       \t\tdata[4].value = jQuery('#cc-1-collection-details input[name=location\\:id]').val();\n        \tif(data[2].value == '') return false;\n        \treturn true;\n  \t\t},\n        success:   function(data){\n  \t\t} \n});\npopulateSessionSelect = function(){\n\tvar insectSessionSelect = jQuery('form#cc-4-main-form > select[name=occurrence\\:sample_id]');\n\tvar value = insectSessionSelect.val();\n\tinsectSessionSelect.empty();\n\t// NB at this point the attributes have been loaded so have full name.\n\t\$('.poll-session-form').each(function(i){\n\t\tjQuery('<option value=\"'+\n\t\t\t\tjQuery(this).children('input[name=sample\\:id]').val()+\n\t\t\t\t'\">'+\n\t\t\t\tjQuery(this).children('input[name=sample\\:date]').val()+\n\t\t\t\t' : '+\n\t\t\t\tjQuery(this).children('[name=smpAttr\\:" . $args['start_time_attr_id'] . "],[name^=smpAttr\\:" . $args['start_time_attr_id'] . "\\:]').val()+\n\t\t\t\t' > '+\n\t\t\t\tjQuery(this).children('[name=smpAttr\\:" . $args['end_time_attr_id'] . "],[name^=smpAttr\\:" . $args['end_time_attr_id'] . "\\:]').val()+\n\t\t\t\t'</option>')\n\t\t\t.appendTo(insectSessionSelect);\n\t});\n\tif(value)\n\t\tinsectSessionSelect.val(value);\n}\n\nvalidateAndSubmitOpenSessions = function(){\n\tvar valid = true;\n\t// only check the visible forms as rest have already been validated successfully.\n\t\$('.poll-session-form:visible').each(function(i){\n\t    if (!jQuery(this).children('input').valid()) {\n\t    \tvalid = false; }\n\t    if (!jQuery('form#cc-2-floral-station > input').valid()) { valid = false; }\n   \t\tif (!validateRadio('smpAttr\\:" . $args['sky_state_attr_id'] . "', this)) { valid = false; }\n   \t\tif (!validateRadio('smpAttr\\:" . $args['temperature_attr_id'] . "', this)) { valid = false; }\n   \t\tif (!validateRadio('smpAttr\\:" . $args['wind_attr_id'] . "', this)) { valid = false; }\n    });\n\tif(valid == false) return false;\n\t\$('.poll-session-form:visible').submit();\n\treturn true;\n}\n\naddSession = function(){\n\tsessionCounter = sessionCounter + 1;\n\t// dynamically build the contents of the session block.\n\tvar newSession = jQuery('<div id=\"cc-3-session-'+sessionCounter+'\" class=\"poll-session\"/>')\n\t\t.appendTo('#cc-3-body');\n\tvar newTitle = jQuery('<div class=\"poll-session-title\">" . lang::get('LANG_Session') . " '+sessionCounter+'</div>')\n\t\t.appendTo(newSession);\n\tvar newModButton = jQuery('<div class=\"right ui-state-default ui-corner-all mod-button\">" . lang::get('LANG_Modify') . "</div>')\n\t\t.appendTo(newTitle).hide();\n\tvar newDeleteButton = jQuery('<div class=\"right ui-state-default ui-corner-all delete-button\">" . lang::get('LANG_Delete_Session') . "</div>')\n\t\t.appendTo(newTitle);\t\n\tnewModButton.click(function() {\n\t\tif(!validateAndSubmitOpenSessions()) return false;\n\t\tvar session=\$(this).parents('.poll-session');;\n\t\tsession.show();\n\t\tsession.children().show();\n\t\tsession.children(':first').children(':first').hide(); // this is the mod button itself\n    });\n    var formContainer = jQuery('<div />').appendTo(newSession);\n    var newForm = jQuery('<form action=\"" . iform_ajaxproxy_url($node, 'sample') . "\" method=\"POST\" class=\"poll-session-form\" />').appendTo(formContainer);\n\tjQuery('<input type=\"hidden\" name=\"website_id\" value=\"" . $args['website_id'] . "\" />').appendTo(newForm);\n\tjQuery('<input type=\"hidden\" name=\"sample:survey_id\" value=\"" . $args['survey_id'] . "\" />').appendTo(newForm);\n\tjQuery('<input type=\"hidden\" name=\"sample:parent_id\" />').appendTo(newForm).val(jQuery('#cc-1-collection-details > input[name=sample\\:id]').val());\n\tjQuery('<input type=\"hidden\" name=\"sample:location_id\" />').appendTo(newForm).val(jQuery('#cc-1-collection-details > input[name=location\\:id]').val());\n\tjQuery('<input type=\"hidden\" name=\"sample:id\" value=\"\" disabled=\"disabled\" />').appendTo(newForm);\n";
        if ($use_help) {
            data_entry_helper::$javascript .= "\n\tvar helpDiv = jQuery('<div class=\"right ui-state-default ui-corner-all help-button\">" . lang::get('LANG_Help_Button') . "</div>');\n\thelpDiv.click(function(){\n\t\t" . $args['help_function'] . "(" . $args['help_session_arg'] . ");\n\t});\n\thelpDiv.appendTo(newForm);";
        }
        data_entry_helper::$javascript .= "\n\tvar dateAttr = '" . str_replace("\n", "", data_entry_helper::date_picker(array('label' => lang::get('LANG_Date'), 'id' => '<id>', 'fieldname' => 'sample:date', 'class' => 'vague-date-picker required', 'suffixTemplate' => 'nosuffix'))) . "';\n\tvar dateID = 'cc-3-session-date-'+sessionCounter;\n\tjQuery(dateAttr.replace(/<id>/g, dateID)).appendTo(newForm);\n    jQuery('#'+dateID).datepicker({\n\t\tdateFormat : 'yy-mm-dd',\n\t\tconstrainInput: false,\n\t\tmaxDate: '0'\n\t});\n    jQuery('" . data_entry_helper::outputAttribute($sample_attributes[$args['start_time_attr_id']], $defAttrOptions) . "').appendTo(newForm);\n\tjQuery('" . data_entry_helper::outputAttribute($sample_attributes[$args['end_time_attr_id']], $defAttrOptions) . "').appendTo(newForm);\n\tjQuery('" . data_entry_helper::outputAttribute($sample_attributes[$args['sky_state_attr_id']], $defAttrOptions) . "').appendTo(newForm);\n\tjQuery('" . data_entry_helper::outputAttribute($sample_attributes[$args['temperature_attr_id']], $defAttrOptions) . "').appendTo(newForm);\n\tjQuery('" . data_entry_helper::outputAttribute($sample_attributes[$args['wind_attr_id']], $defAttrOptions) . "').appendTo(newForm);\n\tjQuery('" . data_entry_helper::outputAttribute($sample_attributes[$args['shade_attr_id']], $defAttrOptions) . "').appendTo(newForm);\n\tnewDeleteButton.click(function() {\n\t\tvar container = \$(this).parent().parent();\n\t\tjQuery('#cc-3-delete-session').find('[name=sample\\:id]').val(container.find('[name=sample\\:id]').val());\n\t\tjQuery('#cc-3-delete-session').find('[name=sample\\:date]').val(container.find('[name=sample\\:date]').val());\n\t\tjQuery('#cc-3-delete-session').find('[name=sample\\:location_id]').val(container.find('[name=sample\\:location_id]').val());\n\t\tif(container.find('[name=sample\\:id]').filter('[disabled]').length == 0){\n\t\t\t\$.getJSON(\"" . $svcUrl . "/data/occurrence/\" +\n\t\t\t\t\t\"?mode=json&view=detail&nonce=" . $readAuth['nonce'] . "&auth_token=" . $readAuth['auth_token'] . "\" +\n\t\t\t\t\t\"&sample_id=\"+container.find('[name=sample\\:id]').val()+\"&callback=?\", function(insectData) {\n\t\t\t\tif (insectData.length>0) {\n\t\t\t\t\talert(\"" . lang::get('LANG_Cant_Delete_Session') . "\");\n\t\t\t\t} else if(confirm(\"" . lang::get('LANG_Confirm_Session_Delete') . "\")){\n\t\t\t\t\tjQuery('#cc-3-delete-session').submit();\n\t\t\t\t\tcontainer.remove();\n\t\t\t\t\tcheckProtocolStatus();\n\t\t\t\t}\n\t\t\t});\n\t\t} else if(confirm(\"" . lang::get('LANG_Confirm_Session_Delete') . "\")){\n\t\t\tcontainer.remove();\n\t\t\tcheckProtocolStatus();\n\t\t}\n    });\n    newForm.ajaxForm({ \n    \tdataType:  'json',\n    \tbeforeSubmit:   function(data, obj, options){\n    \t\tvar valid = true;\n    \t\tif (!obj.find('input').valid()) {\n    \t\t\tvalid = false; }\n    \t\tif (!validateRadio('smpAttr\\:" . $args['sky_state_attr_id'] . "', obj)) { valid = false; }\n   \t\t\tif (!validateRadio('smpAttr\\:" . $args['temperature_attr_id'] . "', obj)) { valid = false; }\n   \t\t\tif (!validateRadio('smpAttr\\:" . $args['wind_attr_id'] . "', obj)) { valid = false; }\n    \t\tdata[2].value = jQuery('#cc-1-collection-details > input[name=sample\\:id]').val();\n\t\t\tdata[3].value = jQuery('#cc-1-collection-details > input[name=location\\:id]').val();\n\t\t\treturn valid;\n\t\t},\n   \t    success:   function(data, status, form){\n   \t    // TODO: error condition handling, eg no date.\n   \t    \tvar thisSession = form.parents('.poll-session');\n    \t\tif(data.success == 'multiple records' && data.outer_table == 'sample'){\n   \t    \t    form.children('input[name=sample\\:id]').removeAttr('disabled').val(data.outer_id);\n   \t    \t    loadAttributes('sample_attribute_value', 'sample_attribute_id', 'sample_id', 'sample\\:id', data.outer_id, 'smpAttr');\n        \t}\n\t\t\tthisSession.show();\n\t\t\tthisSession.children(':first').show().find('*').show();\n\t\t\tthisSession.children().not(':first').hide();\n  \t\t}\n\t});\n\tcheckProtocolStatus();\n    return(newSession);\n};\n\nvalidateSessionsPanel = function(){\n\tif(jQuery('#cc-3').filter('.poll-hide').length > 0) return true; // panel is not visible so no data to fail validation.\n\tif(jQuery('#cc-3').find('.poll-section-body').filter('.poll-hide').length > 0) return true; // body hidden so data already been validated successfully.\n\tvar openSession = jQuery('.poll-session-form:visible');\n\tif(openSession.length > 0){\n\t\tif(jQuery('input[name=sample\\:id]', openSession).val() == '' &&\n\t\t\t\tjQuery('input[name=sample\\:date]', openSession).val() == '" . lang::get('click here') . "' &&\n\t\t\t\tjQuery('[name=smpAttr\\:" . $args['start_time_attr_id'] . "],[name^=smpAttr\\:" . $args['start_time_attr_id'] . "\\:]', openSession).val() == '' &&\n\t\t\t\tjQuery('[name=smpAttr\\:" . $args['end_time_attr_id'] . "],[name^=smpAttr\\:" . $args['end_time_attr_id'] . "\\:]', openSession).val() == '' &&\n\t\t\t\tjQuery('[name=smpAttr\\:" . $args['sky_state_attr_id'] . "],[name^=smpAttr\\:" . $args['sky_state_attr_id'] . "\\:]', openSession).filter('[checked]').length == 0 &&\n    \t\t\tjQuery('[name=smpAttr\\:" . $args['temperature_attr_id'] . "],[name^=smpAttr\\:" . $args['temperature_attr_id'] . "\\:]', openSession).filter('[checked]').length == 0 &&\n    \t\t\tjQuery('[name=smpAttr\\:" . $args['wind_attr_id'] . "],[name^=smpAttr\\:" . $args['wind_attr_id'] . "\\:]', openSession).filter('[checked]').length == 0) {\n\t\t\t// NB shade is a boolean, and always has one set (default no)\n    \t\tjQuery('#cc-3').foldPanel();\n\t\t\treturn true;\n\t\t}\n\t}\n\t// not putting in an empty data set check here - user can delete the session if needed, and there must be at least one.\n\tif(!validateAndSubmitOpenSessions()) return false;\n\tjQuery('#cc-3').foldPanel();\n\tpopulateSessionSelect();\n\treturn true;\n};\njQuery('#cc-3-valid-button').click(function(){\n\tif(!validateAndSubmitOpenSessions()) return;\n\tjQuery('#cc-3').foldPanel();\n\tjQuery('#cc-4').showPanel();\n\tpopulateSessionSelect();\n});\njQuery('#cc-3-add-button').click(function(){\n\tif(!validateAndSubmitOpenSessions()) return;\n\taddSession();\n});\n\njQuery('.mod-button').click(function() {\n\t// first close all the other panels, ensuring any data is saved.\n\tif(!validateCollectionPanel() || !validateStationPanel() || !validateSessionsPanel() || !validateInsectPanel())\n\t\treturn;\n\tjQuery('#cc-5').hidePanel();\n\tjQuery(this).parents('.poll-section-title').parent().unFoldPanel(); //slightly complicated because cc-1 contains the rest.\n});\n\n";
        $extraParams = $readAuth + array('taxon_list_id' => $args['insect_list_id'], 'orderby' => 'taxon');
        $species_ctrl_args = array('label' => lang::get('LANG_Insect_Species'), 'fieldname' => 'insect:taxa_taxon_list_id', 'table' => 'taxa_taxon_list', 'captionField' => 'taxon', 'valueField' => 'id', 'columns' => 2, 'validation' => array('required'), 'blankText' => lang::get('LANG_Choose_Taxon'), 'extraParams' => $extraParams, 'suffixTemplate' => 'nosuffix');
        $r .= '
<div id="cc-4" class="poll-section">
  <div id="cc-4-title" class="ui-accordion-header ui-helper-reset ui-state-active ui-corner-all poll-section-title">' . lang::get('LANG_Photos') . '
    <div id="cc-4-mod-button" class="right ui-state-default ui-corner-all mod-button">' . lang::get('LANG_Modify') . '</div>
  </div>
  <div id="cc-4-photo-reel" class="ui-accordion-content ui-helper-reset ui-widget-content ui-corner-top ui-accordion-content-active photoReelContainer" >
  </div>
  <div id="cc-4-body" class="ui-accordion-content ui-helper-reset ui-widget-content ui-accordion-content-active poll-section-body">  
    <div id="cc-4-insect">
	  <form id="cc-4-insect-upload" enctype="multipart/form-data" action="' . iform_ajaxproxy_url($node, 'media') . '" method="POST">
    		<input type="hidden" id="website_id" name="website_id" value="' . $args['website_id'] . '" />
    		<input name="upload_file" type="file" class="required" />
    		<input type="submit" value="' . lang::get('LANG_Upload_Insect') . '" class="btn-submit" />
      </form>
 	  <div id="cc-4-insect-image" class="poll-image"></div>
 	  <div id="cc-4-insect-identify" class="poll-dummy-form">
 	    ' . iform_pollenators::help_button($use_help, "insect-help-button", $args['help_function'], $args['help_insect_arg']) . '
        <p><strong>' . lang::get('LANG_Identify_Insect') . '</strong></p>
        <label for="id-insect-later" class="follow-on">' . lang::get('LANG_ID_Insect_Later') . ' </label><input type="checkbox" id="id-insect-later" name="id-insect-later" /> 
		' . ($args['ID_tool_insect_url'] != '' && $args['ID_tool_insect_poll_dir'] ? '<label for="insect-id-button">' . lang::get('LANG_Insect_ID_Key_label') . ' :</label><span id="insect-id-button" class="ui-state-default ui-corner-all poll-id-button" >' . lang::get('LANG_Launch_ID_Key') . '</span>' : '') . '<span id="insect-id-cancel" class="ui-state-default ui-corner-all poll-id-cancel" >' . lang::get('LANG_Cancel_ID') . '</span>' . data_entry_helper::select($species_ctrl_args) . '
		<input type="text" name="insect:taxon_text_description" readonly="readonly">
      </div>
    </div>
    <div class="poll-break"></div> 
 	<form id="cc-4-main-form" action="' . iform_ajaxproxy_url($node, 'occurrence') . '" method="POST" >
    	<input type="hidden" id="website_id" name="website_id" value="' . $args['website_id'] . '" />
    	<input type="hidden" id="occurrence_image:path" name="occurrence_image:path" value="" />
    	<input type="hidden" id="occurrence:record_status" name="occurrence:record_status" value="C" />
        <input type="hidden" name="occurrence:use_determination" value="Y"/>    
    	<input type="hidden" name="determination:taxa_taxon_list_id" value=""/> 
        <input type="hidden" name="determination:taxon_text_description" value=""/>  	
		<input type="hidden" name="determination:cms_ref" value="' . $uid . '" />
    	<input type="hidden" name="determination:email_address" value="' . $email . '" />
    	<input type="hidden" name="determination:person_name" value="' . $username . '" /> 
        <input type="hidden" id="occurrence:id" name="occurrence:id" value="" disabled="disabled" />
	    <input type="hidden" id="determination:id" name="determination:id" value="" disabled="disabled" />
	    <input type="hidden" id="occurrence_image:id" name="occurrence_image:id" value="" disabled="disabled" />
	    <label for="occurrence:sample_id">' . lang::get('LANG_Session') . '</label>
	    <select id="occurrence:sample_id" name="occurrence:sample_id" value="" class="required" /></select>
	    ' . data_entry_helper::textarea(array('label' => lang::get('LANG_Comment'), 'fieldname' => 'occurrence:comment', 'suffixTemplate' => 'nosuffix')) . data_entry_helper::outputAttribute($occurrence_attributes[$args['number_attr_id']], $defAttrOptions) . data_entry_helper::outputAttribute($occurrence_attributes[$args['foraging_attr_id']], $defAttrOptions) . '
    </form>
    <span id="cc-4-valid-insect-button" class="ui-state-default ui-corner-all save-button">' . lang::get('LANG_Validate_Insect') . '</span>
    <span id="cc-4-delete-insect-button" class="ui-state-default ui-corner-all delete-button">' . lang::get('LANG_Delete_Insect') . '</span>
  </div>
  <div id="cc-4-footer" class="ui-accordion-content ui-helper-reset ui-widget-content ui-corner-bottom ui-accordion-content-active poll-section-footer">
    <div id="cc-4-valid-photo-button" class="ui-state-default ui-corner-all save-button">' . lang::get('LANG_Validate_Photos') . '</div>
  </div>
</div>
<div style="display:none" />
    <form id="cc-4-delete-insect" action="' . iform_ajaxproxy_url($node, 'occurrence') . '" method="POST">
       <input type="hidden" name="website_id" value="' . $args['website_id'] . '" />
       <input type="hidden" name="occurrence:use_determination" value="Y"/>    
       <input type="hidden" name="occurrence:id" value="" />
       <input type="hidden" name="occurrence:sample_id" value="" />
       <input type="hidden" name="occurrence:deleted" value="t" />
    </form>
</div>';
        data_entry_helper::$javascript .= "\nloadInsectPanel = null;\n\nvar insectTimer1;\nvar insectTimer2;\n\ninsectPoller = function(){\n\tinsectTimer1 = setTimeout('insectPoller();', " . $args['ID_tool_poll_interval'] . ");\n\t\$.get('" . str_replace("{HOST}", $_SERVER['HTTP_HOST'], $args['ID_tool_insect_poll_dir']) . session_id() . "_'+IDcounter.toString(), function(data){\n\tvar da = data.split('\\n');\n      // first count number of returned items.\n      // if > 1 put all into taxon_description.\n      // if = 1 rip out the description, remove the formatting, scan the flower select for it, and set the value. Set the taxon description.\n\t  da[1] = da[1].replace(/\\\\\\\\i\\{\\}/g, '').replace(/\\\\\\\\i0\\{\\}/g, '');\n      var items = da[1].split(':');\n\t  var count = items.length;\n\t  if(items[count-1] == '') count--;\n\t  if(count <= 0){\n\t  \t// no valid stuff so blank it all out.\n\t  \tjQuery('#cc-4-insect-identify > select[name=insect\\:taxa_taxon_list_id]').val('');\n\t  \tjQuery('#cc-4-flower-identify > select[name=insect\\:taxon_text_description]').val('');\n\t  } else if(count == 1){\n\t  \tjQuery('#cc-4-insect-identify > select[name=insect\\:taxa_taxon_list_id]').val('');\n\t  \tjQuery('#cc-4-insect-identify > select[name=insect\\:taxon_text_description]').val(items[0]);\n\t  \tvar x = jQuery('#cc-4-insect-identify').find('option').filter('[text='+items[0]+']');\n\t  \tif(x.length > 0){\n\t\t  \tjQuery('#cc-4-insect-identify > select[name=insect\\:taxon_text_description]').val('');\n\t  \t\tjQuery('#cc-4-insect-identify > select[name=insect\\:taxa_taxon_list_id]').val(x[0].value);\n  \t\t}\n\t  } else {\n\t  \tjQuery('#cc-4-insect-identify > select[name=insect\\:taxa_taxon_list_id]').val('');\n\t  \tjQuery('#cc-4-insect-identify > select[name=insect\\:taxon_text_description]').val(da[1]);\n\t  }\n\t  insectReset();\n    });\n};\ninsectReset = function(){\n\tclearTimeout(insectTimer1);\n\tclearTimeout(insectTimer2);\n\tjQuery('#insect-id-cancel').hide();\n};\n\njQuery('#insect-id-button').click(function(){\n\tIDcounter++;\n\tclearTimeout(insectTimer1);\n\tclearTimeout(insectTimer2);\n\twindow.open('" . $args['ID_tool_insect_url'] . session_id() . "_'+IDcounter.toString(),'','') \n\tinsectTimer1 = setTimeout('insectPoller();', " . $args['ID_tool_poll_interval'] . ");\n\tinsectTimer2 = setTimeout('insectReset();', " . $args['ID_tool_poll_timeout'] . ");\n\tjQuery('#insect-id-cancel').show();\n});\njQuery('#insect-id-cancel').click(function(){\n\tinsectReset();\n});\njQuery('#insect-id-cancel').hide();\n\n    \n// Insect upload picture form.\n\$('#cc-4-insect-upload').ajaxForm({ \n        dataType:  'json', \n        beforeSubmit:   function(data, obj, options){\n        \tif(jQuery('#cc-4-insect-upload input[name=upload_file]').val() == '')\n        \t\treturn false;\n        \t\$('#cc-4-insect-image').empty();\n        \t\$('#cc-4-insect-image').addClass('loading')\n        },\n        success:   function(data){\n        \tif(data.success == true){\n\t        \t// There is only one file\n\t        \tjQuery('form#cc-4-main-form input[name=occurrence_image\\:path]').val(data.files[0]);\n\t        \tvar img = new Image();\n\t        \t\$(img).load(function () {\n        \t\t\t\t\$(this).hide();\n        \t\t\t\t\$('#cc-4-insect-image').removeClass('loading').append(this);\n        \t\t\t\t\$(this).fadeIn();\n\t\t\t    \t})\n\t\t\t\t    .attr('src', '" . data_entry_helper::$base_url . data_entry_helper::$indicia_upload_path . "med-'+data.files[0])\n\t\t\t\t    .css('max-width', \$('#cc-4-insect-image').width()).css('max-height', \$('#cc-4-insect-image').height())\n\t\t\t\t    .css('vertical-align', 'middle').css('margin-left', 'auto').css('margin-right', 'auto').css('display', 'block');\n\t\t\t\tjQuery('#cc-4-insect-upload input[name=upload_file]').val('');\n\t\t\t} else {\n\t\t\t\tvar errorString = \"" . lang::get('LANG_Indicia_Warehouse_Error') . "\";\n\t        \tjQuery('form#cc-4-main-form input[name=occurrence_image\\:path]').val('');\n\t\t\t\t\$('#cc-4-insect-image').removeClass('loading');\n\t\t\t\tif(data.error){\n\t\t\t\t\terrorString = errorString + ' : ' + data.error;\n\t\t\t\t}\n\t\t\t\tif(data.errors){\n\t\t\t\t\tfor (var i in data.errors)\n\t\t\t\t\t{\n\t\t\t\t\t\terrorString = errorString + ' : ' + data.errors[i];\n\t\t\t\t\t}\t\t\t\t\n\t\t\t\t}\n\t\t\t\talert(errorString);\n\t\t\t}\n        } \n});\n\n\$('#cc-4-main-form').ajaxForm({ \n    dataType:  'json', \n    beforeSubmit:   function(data, obj, options){\n    \tvar valid = true;\n\t\tif (!jQuery('form#cc-4-main-form > input').valid()) { valid = false; }\n\t\tif (!validateRequiredField('occurrence\\:sample_id', 'form#cc-4-main-form')) { valid = false; }\n\t\tif (!validateRadio('occAttr\\:" . $args['number_attr_id'] . "', obj)) { valid = false; }\n    \tif(data[1].value == '' ){\n\t\t\talert(\"" . lang::get('LANG_Must_Provide_Insect_Picture') . "\");\n\t\t\tvalid = false;\n\t\t}\n\t\tdata[4].value = jQuery('select[name=insect\\:taxa_taxon_list_id]').val();\n\t\tdata[5].value = jQuery('select[name=insect\\:taxon_text_description]').val();\n\t\tif (jQuery('#id-insect-later').attr('checked') == ''){\n\t\t\tif (!validateRequiredField('insect\\:taxa_taxon_list_id', '#cc-4-insect-identify')) { valid = false; }\n\t\t} else {\n\t\t\tdata.splice(4,5); // remove determination entries.\n\t\t}\n\t\treturn valid;\n\t},\n    success:   function(data){\n       \tif(data.success == 'multiple records' && data.outer_table == 'occurrence'){\n       \t\t// if the currently highlighted thumbnail is blank, add the new insect.\n       \t\tvar thumbnail = jQuery('[occId='+data.outer_id+']');\n       \t\tif(thumbnail.length == 0){\n       \t\t\taddToPhotoReel(data.outer_id);\n       \t\t} else {\n       \t\t\tupdatePhotoReel(thumbnail, data.outer_id);\n  \t\t\t}\n\t\t\tif(loadInsectPanel == null){\n\t\t\t\tclearInsect();\n\t\t\t} else {\n\t\t\t\tloadInsect(loadInsectPanel);\n\t\t\t}\n\t\t\tloadInsectPanel=null;\n\t\t\twindow.scroll(0,0);\n        }\n\t}\n});\n\nvalidateInsectPanel = function(){\n\tif(jQuery('#cc-4').filter('.poll-hide').length > 0) return true; // panel is not visible so no data to fail validation.\n\tif(jQuery('#cc-4-body').filter('.poll-hide').length > 0) return true; // body hidden so data already been validated successfully.\n\tif(!validateInsect()){ return false; }\n  \tjQuery('#cc-4').foldPanel();\n\treturn true;\n};\n\nclearInsect = function(){\n\tjQuery('#cc-4-main-form').resetForm();\n\tjQuery('[name=insect\\:taxa_taxon_list_id]').val('');\n\tjQuery('[name=insect\\:taxon_text_description]').val('');\n    jQuery('#id-insect-later').removeAttr('checked').removeAttr('disabled');\n    jQuery('#cc-4-main-form').find('[name=determination:cms_ref]').val('" . $uid . "');\n    jQuery('#cc-4-main-form').find('[name=determination:email_address]').val('" . $email . "');\n    jQuery('#cc-4-main-form').find('[name=determination:person_name]').val('" . $username . "'); \n    jQuery('#cc-4-main-form').find('[name=occurrence_image\\:path]').val('');\n\tjQuery('#cc-4-main-form').find('[name=occurrence\\:id],[name=occurrence_image\\:id],[name=determination\\:id]').val('').attr('disabled', 'disabled');\n    jQuery('#cc-4-main-form').find('[name=occurrence_image\\:path]').val('');\n\tjQuery('#cc-4-main-form').find('[name^=occAttr\\:]').each(function(){\n\t\tvar name = jQuery(this).attr('name').split(':');\n\t\tjQuery(this).attr('name', name[0]+':'+name[1]);\n\t});\n    jQuery('#cc-4-insect-image').empty();\n};\n\nloadInsect = function(id){\n\tclearInsect();\n\t\$.getJSON(\"" . $svcUrl . "/data/occurrence/\" + id +\n          \"?mode=json&view=detail&nonce=" . $readAuth['nonce'] . "&auth_token=" . $readAuth['auth_token'] . "&callback=?\", function(data) {\n\t    if (data.length>0) {\n\t        jQuery('form#cc-4-main-form > input[name=occurrence\\:id]').removeAttr('disabled').val(data[0].id);\n\t        jQuery('form#cc-4-main-form > [name=occurrence\\:sample_id]').val(data[0].sample_id);\n\t\t\tjQuery('form#cc-4-main-form > textarea[name=occurrence\\:comment]').val(data[0].comment);\n\t\t\tloadAttributes('occurrence_attribute_value', 'occurrence_attribute_id', 'occurrence_id', 'occurrence\\:id', data[0].id, 'occAttr');\n    \t\tloadImage('occurrence_image', 'occurrence_id', 'occurrence\\:id', data[0].id, '#cc-4-insect-image');\n  \t\t}\n\t});\n\t\$.getJSON(\"" . $svcUrl . "/data/determination?occurrence_id=\" + id +\n          \"&mode=json&view=list&nonce=" . $readAuth['nonce'] . "&auth_token=" . $readAuth['auth_token'] . "&callback=?\", function(data) {\n\t    if (data.length>0) {\n\t    \tjQuery('#id-insect-later').removeAttr('checked').attr('disabled', 'disabled');\n\t        jQuery('form#cc-4-main-form > input[name=determination\\:id]').removeAttr('disabled').val(data[0].id);\n\t        jQuery('form#cc-4-main-form > input[name=determination\\:cms_ref]').val(data[0].cms_ref);\n\t        jQuery('form#cc-4-main-form > input[name=determination\\:email_address]').val(data[0].email_address);\n\t        jQuery('form#cc-4-main-form > input[name=determination\\:person_name]').val(data[0].person_name);\n       \t\tjQuery('[name=insect\\:taxa_taxon_list_id]').val(data[0].taxa_taxon_list_id);\n       \t\tjQuery('[name=insect\\:taxon_text_description]').val(data[0].taxon_text_description);\n  \t\t} else\n  \t\t\tjQuery('#id-insect-later').attr('checked', 'checked').removeAttr('disabled');\n\t});\t\n}\n\nupdatePhotoReel = function(container, occId){\n\tcontainer.empty();\n\t\$.getJSON(\"" . $svcUrl . "/data/occurrence_image\" +\n   \t\t\t\"?mode=json&view=list&nonce=" . $readAuth['nonce'] . "&auth_token=" . $readAuth['auth_token'] . "\" +\n   \t\t\t\"&occurrence_id=\" + occId + \"&callback=?\", function(imageData) {\n\t\tif (imageData.length>0) {\n\t\t\tvar img = new Image();\n\t\t\tjQuery(img).attr('src', '" . data_entry_helper::$base_url . data_entry_helper::$indicia_upload_path . "thumb-'+imageData[0].path)\n\t\t\t    .attr('width', container.width()).attr('height', container.height()).addClass('thumb-image').appendTo(container);\n\t\t}\n\t});\n\t\$.getJSON(\"" . $svcUrl . "/data/determination\" + \n    \t\t\"?mode=json&view=list&nonce=" . $readAuth['nonce'] . "&auth_token=" . $readAuth['auth_token'] . "\" + \n    \t\t\"&occurrence_id=\" + occId + \"&deleted=f&callback=?\", function(detData) {\n\t    if (detData.length==0) {\n\t    \t// no determination records, so no attempt made at identification. Put up a question mark.\n\t\t\tjQuery('<span>?</span>').addClass('thumb-text').appendTo(container);\n\t\t}\n\t});\n}\n\naddToPhotoReel = function(occId){\n\t// last photo in list is the blank empty one. Add to just before this.\n\tvar container = jQuery('<div/>').addClass('thumb').insertBefore('.blankPhoto').attr('occId', occId.toString()).click(function () {setInsect(this, occId)});\n\tupdatePhotoReel(container, occId);\n}\n\nsetInsect = function(context, id){\n\t// first close all the other panels, ensuring any data is saved.\n\tif(!validateCollectionPanel() || !validateStationPanel() || !validateSessionsPanel())\n\t\treturn;\n\t\t\n\tif(jQuery('#cc-4-body').filter('.poll-hide').length > 0) {\n\t\tjQuery('div#cc-4').unFoldPanel();\n\t\tloadInsect(id);\n\t} else {\n\t\tloadInsectPanel=id;\n\t\tif(!validateInsect()){\n\t\t\tloadInsectPanel=null;\n\t\t\treturn;\n\t\t} \n\t}\n\tjQuery('.currentPhoto').removeClass('currentPhoto');\n\tjQuery('[occId='+id+']').addClass('currentPhoto');\n};\n\nsetNoInsect = function(){\n\t// first close all the other panels, ensuring any data is saved.\n\tif(!validateCollectionPanel() || !validateStationPanel() || !validateSessionsPanel())\n\t\treturn;\n\t\t\n\tif(jQuery('#cc-4-body').filter('.poll-hide').length > 0)\n\t\tjQuery('div#cc-4').unFoldPanel();\n\telse\n\t\tif(!validateInsect()){ return ; }\n\t// At this point the empty panel is displayed, as it is reset after a successful validate.\t\n\tjQuery('.currentPhoto').removeClass('currentPhoto');\n\tjQuery('.blankPhoto').addClass('currentPhoto');\n};\n\ncreatePhotoReel = function(div){\n\tjQuery(div).empty();\n\tjQuery('<div/>').addClass('blankPhoto thumb currentPhoto').appendTo(div).click(setNoInsect);\n}\n\ncreatePhotoReel('#cc-4-photo-reel');\n\n// TODO separate photoreel out into own js\n\nvalidateInsect = function(){\n\t// TODO will have to expand when use key.\n\tif(jQuery('form#cc-4-main-form > input[name=occurrence\\:id]').val() == '' &&\n\t\t\tjQuery('form#cc-4-main-form > input[name=occurrence_image\\:path]').val() == '' &&\n\t\t\tjQuery('[name=insect\\:taxa_taxon_list_id]').val() == '' &&\n\t\t\tjQuery('form#cc-4-main-form > textarea[name=occurrence\\:comment]').val() == '' &&\n\t\t\tjQuery('[name=occAttr\\:" . $args['number_attr_id'] . "],[name^=occAttr\\:" . $args['number_attr_id'] . "\\:]').filter('[checked]').length == 0){\n\t\tif(loadInsectPanel != null){\n\t\t\tloadInsect(loadInsectPanel);\n\t\t}\n\t\tloadInsectPanel=null;\n\t\treturn true;\n\t}\n\tvar valid = true;\n    if (!jQuery('form#cc-4-main-form > input').valid()) { return false; }\n  \tif (!validateRadio('occAttr\\:" . $args['number_attr_id'] . "', 'form#cc-4-main-form')) { valid = false; }\n\t\tif (jQuery('#id-insect-later').attr('checked') == ''){\n\t\t\tif (!validateRequiredField('insect\\:taxa_taxon_list_id', '#cc-4-insect-identify')) { valid = false; }\n\t\t}\n \tif (!validateRequiredField('occurrence\\:sample_id', 'form#cc-4-main-form')) { valid = false; }\n\tif(jQuery('form#cc-4-main-form input[name=occurrence_image\\:path]').val() == ''){\n\t\talert(\"" . lang::get('LANG_Must_Provide_Insect_Picture') . "\");\n\t\tvalid = false;;\n\t}\n\tif(valid == false) return false;\n\tjQuery('form#cc-4-main-form').submit();\n\treturn true;\n  }\n\n\$('#cc-4-valid-insect-button').click(validateInsect);\n\n\$('#cc-4-delete-insect-button').click(function() {\n\tvar container = \$(this).parent().parent();\n\tjQuery('#cc-4-delete-insect').find('[name=occurrence\\:id]').val(jQuery('#cc-4-main-form').find('[name=occurrence\\:id]').val());\n\tjQuery('#cc-4-delete-insect').find('[name=occurrence\\:sample_id]').val(jQuery('#cc-4-main-form').find('[name=occurrence\\:sample_id]').val());\n\tif(confirm(\"" . lang::get('LANG_Confirm_Insect_Delete') . "\")){\n\t\tif(jQuery('#cc-4-main-form').find('[name=occurrence\\:id]').filter('[disabled]').length == 0){\n\t\t\tjQuery('#cc-4-delete-insect').submit();\n\t\t\tjQuery('.currentPhoto').remove();\n\t\t\tjQuery('.blankPhoto').addClass('currentPhoto');\n\t\t}\n\t\tclearInsect();\n\t}\n});\n\n\$('#cc-4-delete-insect').ajaxForm({ \n        dataType:  'json', \n        beforeSubmit:   function(data, obj, options){\n  \t\t\t// Warning this assumes that the data is fixed position:\n        \tif(data[2].value == '') return false;\n        \treturn true;\n  \t\t},\n        success:   function(data){\n  \t\t} \n});\n\n\$('#cc-4-valid-photo-button').click(function(){\n\tif(!validateInsect()) return;\n\tjQuery('#cc-4').foldPanel();\n\tjQuery('#cc-5').showPanel();\n\tvar numInsects = jQuery('#cc-4-photo-reel').find('.thumb').length - 1; // ignore blank\n\tvar numUnidentified = jQuery('#cc-4-photo-reel').find('.thumb-text').length;\n\tif(jQuery('#id-flower-later').attr('checked') != '' || numInsects==0 || (numUnidentified/numInsects > (1-(" . $args['percent_insects'] . "/100.0)))){\n\t\tjQuery('#cc-5-good').hide();\n\t\tjQuery('#cc-5-bad').show();\n\t\tjQuery('#cc-5-complete-collection').hide();\n\t\tjQuery('#cc-5-trailer').hide();\n    } else {\n    \tjQuery('#cc-5-good').show();\n\t\tjQuery('#cc-5-bad').hide();\n\t\tjQuery('#cc-5-complete-collection').show();\n\t\tjQuery('#cc-5-trailer').show();\n\t}\n});\n";
        $r .= '
<div id="cc-5" class="poll-section">
  <div id="cc-5-body" class="ui-accordion-header ui-helper-reset ui-state-active ui-corner-all poll-section-body"> 
   <p id="cc-5-good">' . lang::get('LANG_Can_Complete_Msg') . '</p> 
   <p id="cc-5-bad">' . lang::get('LANG_Cant_Complete_Msg') . '</p> 
   <div style="display:none" />
    <form id="cc-5-collection" action="' . iform_ajaxproxy_url($node, 'sample') . '" method="POST">
       <input type="hidden" name="website_id" value="' . $args['website_id'] . '" />
       <input type="hidden" name="sample:survey_id" value="' . $args['survey_id'] . '" />
       <input type="hidden" name="sample:id" value="" />
       <input type="hidden" name="sample:date" value="2010-01-01"/>
       <input type="hidden" name="sample:location_id" value="" />
       <input type="hidden" id="smpAttr:' . $args['complete_attr_id'] . '" name="smpAttr:' . $args['complete_attr_id'] . '" value="1" />
    </form>
   </div>
   <div id="cc-5-complete-collection" class="ui-state-default ui-corner-all complete-button">' . lang::get('LANG_Complete_Collection') . '</div>
  </div>
  <div id="cc-5-trailer" class="poll-section-trailer">
    <p>' . lang::get('LANG_Trailer_Head') . '</p>
    <ul>
      <li>' . lang::get('LANG_Trailer_Point_1') . '</li>
      <li>' . lang::get('LANG_Trailer_Point_2') . '</li>
      <li>' . lang::get('LANG_Trailer_Point_3') . '</li>
      <li>' . lang::get('LANG_Trailer_Point_4') . '</li>
    </ul>
  </div>
</div>';
        data_entry_helper::$javascript .= "\n\$('#cc-5-collection').ajaxForm({ \n        dataType:  'json', \n        beforeSubmit:   function(data, obj, options){\n       \t\tdata[2].value = jQuery('#cc-1-collection-details input[name=sample\\:id]').val();\n       \t\tvar date_start = '';\n       \t\tvar date_end = '';\n       \t\tjQuery('.poll-session').find('[name=sample\\:date]').each(function(index, el){\n       \t\t\tvar value = \$(this).val();\n       \t\t\tif(date_start == '' || date_start > value) {\n       \t\t\t\tdate_start = value;\n       \t\t\t}\n       \t\t\tif(date_end == '' || date_end < value) {\n       \t\t\t\tdate_end = value;\n       \t\t\t}\n  \t\t\t});\n  \t\t\tif(date_start == date_end){\n\t       \t\tdata[3].value = date_start;\n\t       \t} else {\n\t       \t\tdata[3].value = date_start+' to '+date_end;\n  \t\t\t}\n\t       \tjQuery('[name=sample\\:date]:hidden').val(data[3].value);\n  \t\t\tdata[4].value = jQuery('#cc-1-collection-details input[name=location\\:id]').val();\n       \t\tdata[5].name = jQuery('#cc-1-collection-details input[name^=smpAttr\\:" . $args['complete_attr_id'] . "\\:]').attr('name');\n        \treturn true;\n  \t\t},\n        success:   function(data){\n\t\t\t\$('#cc-6').showPanel();\n  \t\t} \n});\n\$('#cc-5-complete-collection').click(function(){\n\tjQuery('#cc-2,#cc-3,#cc-4,#cc-5').hidePanel();\n\tjQuery('.reinit-button').hide();\n\tjQuery('.mod-button').hide();\n\tjQuery('#cc-5-collection').submit();\n});\n";
        $r .= '
<div id="cc-6" class="poll-section">
  <div id="cc-6-body" class="ui-accordion-header ui-helper-reset ui-state-active ui-corner-top poll-section-body"> 
   <p>' . lang::get('LANG_Final_1') . '</p> 
   <p>' . lang::get('LANG_Final_2') . '</p> 
   </div>
  <div id="cc-6-footer" class="ui-accordion-content ui-helper-reset ui-widget-content ui-corner-bottom ui-accordion-content-active poll-section-footer">
    <a id="cc-6-consult-collection" href="" class="ui-state-default ui-corner-all link-button">' . lang::get('LANG_Consult_Collection') . '</a>
    <a href="' . url('node/' . $node->nid) . '" class="ui-state-default ui-corner-all link-button">' . lang::get('LANG_Create_New_Collection') . '</a>
  </div>
</div>
</div></div>';
        data_entry_helper::$javascript .= "\n \t\t\t\nloadAttributes = function(attributeTable, attributeKey, key, keyName, keyValue, prefix){\n\tvar form = jQuery('input[name='+keyName+'][value='+keyValue+']').parent();\n\tvar checkboxes = jQuery('[name^='+prefix+'\\:]', form).filter(':checkbox').removeAttr('checked');\n\tcheckboxes.each(function(){\n\t\tvar name = jQuery(this).attr('name').split(':');\n\t\tif(name.length > 2)\n\t\t\tjQuery(this).attr('name', name[0]+':'+name[1]+'[]');\n\t});\n\t\n\t\$.getJSON(\"" . $svcUrl . "/data/\" + attributeTable +\n   \t\t\t\"?mode=json&view=list&nonce=" . $readAuth['nonce'] . "&auth_token=" . $readAuth['auth_token'] . "\" +\n   \t\t\t\"&\" + key + \"=\" + keyValue + \"&callback=?\", function(attrdata) {\n\t\tif (attrdata.length>0) {\n\t\t\tvar form = jQuery('input[name='+keyName+'][value='+keyValue+']').parent();\n\t\t\tfor (var i=0;i<attrdata.length;i++){\n\t\t\t\tif (attrdata[i].id && (attrdata[i].iso == null || attrdata[i].iso == '' || attrdata[i].iso == '" . $language . "')){\n\t\t\t\t\tvar checkboxes = jQuery('[name='+prefix+'\\:'+attrdata[i][attributeKey]+'\\[\\]],[name^='+prefix+'\\:'+attrdata[i][attributeKey]+':]', form).filter(':checkbox');\n\t\t\t\t\tvar radiobuttons = jQuery('[name='+prefix+'\\:'+attrdata[i][attributeKey]+'],[name^='+prefix+'\\:'+attrdata[i][attributeKey]+':]', form).filter(':radio');\n\t\t\t\t\tif(radiobuttons.length > 0){\n\t\t\t\t\t\tradiobuttons\n\t\t\t\t\t\t\t.attr('name', prefix+':'+attrdata[i][attributeKey]+':'+attrdata[i].id)\n\t\t\t\t\t\t\t.filter('[value='+attrdata[i].raw_value+']')\n\t\t\t\t\t\t\t.attr('checked', 'checked');\n\t\t\t\t\t} else \tif(checkboxes.length > 0){\n\t\t\t\t\t\tvar checkbox = checkboxes.filter('[value='+attrdata[i].raw_value+']')\n\t\t\t\t\t\t\t.attr('name', prefix+':'+attrdata[i][attributeKey]+':'+attrdata[i].id)\n\t\t\t\t\t\t\t.attr('checked', 'checked');\n\t\t\t\t\t} else {\n\t\t\t\t\t\tjQuery('[name='+prefix+'\\:'+attrdata[i][attributeKey]+']', form)\n\t\t\t\t\t\t\t.attr('name', prefix+':'+attrdata[i][attributeKey]+':'+attrdata[i].id)\n\t\t\t\t\t\t\t.val(attrdata[i].raw_value);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tcheckProtocolStatus();\n\t\tpopulateSessionSelect();\n\t});\n}\n\nloadImage = function(imageTable, key, keyName, keyValue, target){\n\t\t\t\t\t// location_image, location_id, location:id, 1, #cc-4-insect-image\n\t\$.getJSON(\"" . $svcUrl . "/data/\" + imageTable +\n   \t\t\t\"?mode=json&view=list&nonce=" . $readAuth['nonce'] . "&auth_token=" . $readAuth['auth_token'] . "\" +\n   \t\t\t\"&\" + key + \"=\" + keyValue + \"&callback=?\", function(imageData) {\n\t\tif (imageData.length>0) {\n\t\t\tvar form = jQuery('input[name='+keyName+'][value='+keyValue+']').parent();\n\t\t\tjQuery('[name='+imageTable+'\\:id]', form).val(imageData[0].id).removeAttr('disabled');\n\t\t\tjQuery('[name='+imageTable+'\\:path]', form).val(imageData[0].path);\n\t\t\tvar img = new Image();\n\t\t\t\$(img).load(function () {\n        \t\t\t\$(target).empty().append(this);\n\t\t\t    })\n\t\t\t    .attr('src', '" . data_entry_helper::$base_url . data_entry_helper::$indicia_upload_path . "med-'+imageData[0].path)\n\t\t\t\t.css('max-width', \$(target).width()).css('max-height', \$(target).height()).css('display', 'block')\n\t\t\t\t.css('vertical-align', 'middle').css('margin-left', 'auto').css('margin-right', 'auto');\n\t\t}\n\t});\n}\n\n// load in any existing incomplete collection.\n// general philosophy is that you are taken back to the stage last verified.\n// Load in the first if there are more than one. Use the internal report which provides my collections.\n// Requires that there is an attribute for completeness, and one for the CMS\n// load the data in the order it is entered, so can stop when get to the point where the user finished.\n// have to reset the entire form first...\njQuery('.poll-section').resetPanel();\n// Default state: hide everything except the collection details block.\njQuery('.poll-section').hidePanel();\njQuery('#cc-1').showPanel();\njQuery('.reinit-button').hide();\naddSession();\n\njQuery.getJSON(\"" . $svcUrl . "\" + \"/report/requestReport?report=poll_my_collections.xml&reportSource=local&mode=json\" +\n\t\t\t\"&auth_token=" . $readAuth['auth_token'] . "&nonce=" . $readAuth["nonce"] . "\" + \n\t\t\t\"&survey_id=" . $args['survey_id'] . "&userID_attr_id=" . $args['uid_attr_id'] . "&userID=" . $uid . "&complete_attr_id=" . $args['complete_attr_id'] . "&callback=?\", function(data) {\n\tif (data.length>0) {\n\t\tvar i;\n       \tfor ( i=0;i<data.length;i++) {\n       \t\tif(data[i].completed == '0'){\n       \t\t    jQuery('#cc-6-consult-collection').attr('href', '" . url('node/' . $args['gallery_node']) . "'+'?collection_id='+data[i].id);\n       \t\t\t// load up collection details: existing ID, location name and protocol\n       \t\t\tjQuery('#cc-1-collection-details,#cc-2').find('input[name=sample\\:id]').val(data[i].id).removeAttr('disabled');\n       \t\t\t// main sample date is only set when collection is completed, so leave default.\n       \t\t\tloadAttributes('sample_attribute_value', 'sample_attribute_id', 'sample_id', 'sample\\:id', data[i].id, 'smpAttr');\n  \t\t\t\t\$.getJSON(\"" . $svcUrl . "/data/location/\" + data[i].location_id +\n          \t\t\t\t\t\"?mode=json&view=detail&nonce=" . $readAuth['nonce'] . "&auth_token=" . $readAuth['auth_token'] . "\" +\n          \t\t\t\t\t\"&callback=?\", function(locationdata) {\n\t\t    \t\tif (locationdata.length>0) {\n\t\t    \t\t\tjQuery('input[name=location\\:id]').val(locationdata[0].id).removeAttr('disabled');\n\t    \t\t\t\tjQuery('input[name=location\\:name]').val(locationdata[0].name);\n       \t\t\t\t\tjQuery('input[name=sample\\:location_name]').val(locationdata[0].name); // make sure the 2 coincide\n\t    \t\t\t\t// NB the location geometry is stored in centroid, due to restrictions in location model.\n\t    \t\t\t\tjQuery('input[name=location\\:centroid_sref]').val(locationdata[0].centroid_sref);\n\t    \t\t\t\tjQuery('input[name=location\\:centroid_sref_system]').val(locationdata[0].centroid_sref_system);\n\t    \t\t\t\tjQuery('input[name=location\\:centroid_geom]').val(locationdata[0].centroid_geom);\n\t    \t\t\t\tjQuery('input[name=locations_website\\:website_id]').attr('disabled', 'disabled');\n\t    \t\t\t\tloadAttributes('location_attribute_value', 'location_attribute_id', 'location_id', 'location\\:id', locationdata[0].id, 'locAttr');\n    \t   \t\t\t\tloadImage('location_image', 'location_id', 'location\\:id', locationdata[0].id, '#cc-2-environment-image');\n\t\t\t\t\t\tjQuery('#imp-sref').change();\n\t\t\t\t        var parts=locationdata[0].centroid_sref.split(' ');\n \t\t\t\t\t\tjQuery('input[name=place\\:lat]').val(parts[0]);\n\t\t\t\t\t\tjQuery('input[name=place\\:long]').val(parts[1]);\n  \t\t\t\t\t}\n  \t\t\t\t});\n  \t\t\t\t\$.getJSON(\"" . $svcUrl . "/data/occurrence/\" +\n          \t\t\t\t\t\"?mode=json&view=detail&nonce=" . $readAuth['nonce'] . "&auth_token=" . $readAuth['auth_token'] . "\" +\n          \t\t\t\t\t\"&sample_id=\"+data[i].id+\"&callback=?\", function(flowerData) {\n          \t\t\t// there will only be an occurrence if the floral station panel has previously been displayed & validated. \n\t\t    \t\tif (flowerData.length>0) {\n  \t\t\t\t\t\t\$('#cc-1').foldPanel();\n  \t\t\t\t\t\t\$('#cc-2').showPanel();\n\t\t    \t\t\tjQuery('form#cc-2-floral-station > input[name=occurrence\\:sample_id]').val(data[i].id);\n\t\t    \t\t\tjQuery('form#cc-2-floral-station > input[name=occurrence\\:id]').val(flowerData[0].id).removeAttr('disabled');\n\t\t    \t\t\tloadAttributes('occurrence_attribute_value', 'occurrence_attribute_id', 'occurrence_id', 'occurrence\\:id', flowerData[0].id, 'occAttr');\n    \t   \t\t\t\tloadImage('occurrence_image', 'occurrence_id', 'occurrence\\:id', flowerData[0].id, '#cc-2-flower-image');\n\n    \t   \t\t\t\t\$.getJSON(\"" . $svcUrl . "/data/determination\" + \n    \t      \t\t\t\t\t\t\"?mode=json&view=list&nonce=" . $readAuth['nonce'] . "&auth_token=" . $readAuth['auth_token'] . "&occurrence_id=\"+flowerData[0].id+\"&deleted=f&callback=?\",\n    \t      \t\t\t\t\tfunction(detData) {\n\t    \t\t\t  \t\tif (detData.length>0) {\n\t\t\t\t\t\t\t\tjQuery('#id-flower-later').removeAttr('checked').attr('disabled', 'disabled');\n\t    \t\t\t  \t\t\tjQuery('form#cc-2-floral-station > input[name=determination\\:id]').val(detData[0].id).removeAttr('disabled');\n\t\t    \t\t\t\t\tjQuery('form#cc-2-floral-station > input[name=determination\\:cms_ref]').val(detData[0].cms_ref);\n\t\t\t\t\t\t\t\tjQuery('form#cc-2-floral-station > input[name=determination\\:email_address]').val(detData[0].email_address);\n\t\t\t\t\t\t\t\tjQuery('form#cc-2-floral-station > input[name=determination\\:person_name]').val(detData[0].person_name);\n\t\t\t\t\t\t\t\tjQuery('select[name=flower\\:taxa_taxon_list_id]').val(detData[0].taxa_taxon_list_id);\n\t\t\t\t\t\t\t\tjQuery('select[name=flower\\:taxon_text_description]').val(detData[0].taxon_text_description);\n  \t\t\t\t\t\t\t} else {\n\t    \t\t\t  \t\t\tjQuery('form#cc-2-floral-station > input[name=determination\\:id]').val('').attr('disabled', 'disabled');\n\t\t\t\t\t\t\t\tjQuery('#id-flower-later').attr('checked', 'checked').removeAttr('disabled');\n\t\t\t\t\t\t\t}\n  \t\t\t\t\t\t});\n\n    \t   \t\t\t\t\$.getJSON(\"" . $svcUrl . "/data/sample\" + \n    \t      \t\t\t\t\t\"?mode=json&view=detail&nonce=" . $readAuth['nonce'] . "&auth_token=" . $readAuth['auth_token'] . "&parent_id=\"+data[i].id+\"&callback=?\", function(sessiondata) {\n\t    \t\t\t  \t\tif (sessiondata.length>0) {\n\t\t\t\t\t\t\t\tjQuery('#cc-2').foldPanel();\n\t\t\t\t\t\t\t\tsessionCounter = 0;\n\t\t\t\t\t\t\t\tjQuery('#cc-3-body').empty();\n \t\t\t\t\t\t\t\t\$('#cc-3').showPanel();\n\t\t\t\t\t\t\t\tfor (var i=0;i<sessiondata.length;i++){\n\t\t\t\t\t\t\t\t\tvar thisSession = addSession();\n\t\t\t\t\t\t\t\t\tjQuery('input[name=sample\\:id]', thisSession).val(sessiondata[i].id).removeAttr('disabled');\n\t\t\t\t\t\t\t\t\tjQuery('input[name=sample\\:date]', thisSession).val(sessiondata[i].date_start);\n       \t\t\t\t\t\t\t\tloadAttributes('sample_attribute_value', 'sample_attribute_id', 'sample_id', 'sample\\:id', sessiondata[i].id, 'smpAttr');\n  \t\t\t\t\t\t\t\t\t// fold this session.\n  \t\t\t\t\t\t\t\t\tthisSession.show();\n\t\t\t\t\t\t\t\t\tthisSession.children(':first').show().children().show();\n\t\t\t\t\t\t\t\t\tthisSession.children().not(':first').hide();\n\t\t\t\t\t\t\t\t\t\$.getJSON(\"" . $svcUrl . "/data/occurrence/\" +\n          \t\t\t\t\t\t\t\t\t\"?mode=json&view=detail&nonce=" . $readAuth['nonce'] . "&auth_token=" . $readAuth['auth_token'] . "&orderby=id\" +\n          \t\t\t\t\t\t\t\t\t\"&sample_id=\"+sessiondata[i].id+\"&callback=?\", function(insectData) {\n\t\t    \t\t\t\t\t\t\tif (insectData.length>0) {\n \t\t\t\t\t\t\t\t\t\t\tfor (var j=0;j<insectData.length;j++){\n\t\t\t\t\t\t\t\t\t\t\t\taddToPhotoReel(insectData[j].id);\n\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t}\n\t\t    \t\t\t\t\t\t});\n\t\t\t\t\t\t\t\t}\n \t\t\t\t\t\t\t\t\$('#cc-3').foldPanel();\n \t\t\t\t\t\t\t\t\$('#cc-4').showPanel();\n\t\t\t\t\t\t\t\tpopulateSessionSelect();\n \t\t\t\t\t  \t\t}\n \t\t\t\t\t  \t\t\$('.loading-panel').remove();\n\t\t\t\t\t\t\t\$('.loading-hide').removeClass('loading-hide');\n\t\t\t\t\t\t});\n    \t   \t\t\t} else {\n    \t   \t\t\t\t\$('.loading-panel').remove();\n\t\t\t\t\t\t\$('.loading-hide').removeClass('loading-hide');\n    \t   \t\t\t}\n  \t\t\t\t});\n\t\t\t\t// only use the first one which is not complete..\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\tif (i >= data.length) {\n\t\t\t\$('.loading-panel').remove();\n\t\t\t\$('.loading-hide').removeClass('loading-hide');\n  \t\t}\n\t} else {\n\t\t\$('.loading-panel').remove();\n\t\t\$('.loading-hide').removeClass('loading-hide');\n\t}\n});\n  \n  ";
        // because of the use of getJson to retrieve the data - which is asynchronous, the use of the normal loading_block_end
        // is not practical - it will do its stuff before the data is loaded, defeating the purpose. Also it uses hide (display:none)
        // which is a no-no in relation to the map. This means we have to dispense with the slow fade in.
        // it is also complicated by the attibutes and images being loaded asynchronously - and non-linearly.
        // Do the best we can!
        data_entry_helper::$onload_javascript .= "jQuery('#map')[0].map.searchLayer.events.register('featuresadded', {}, function(a1){\n\tif(inseeLayer != null)\n\t\tinseeLayer.destroyFeatures();\n});\njQuery('#map')[0].map.editLayer.events.register('featuresadded', {}, function(a1){\n\tif(inseeLayer != null)\n\t\tinseeLayer.destroy();\n\t\t\n  \tvar filter = new OpenLayers.Filter.Spatial({\n  \t\t\ttype: OpenLayers.Filter.Spatial.CONTAINS ,\n    \t\tproperty: 'the_geom',\n    \t\tvalue: jQuery('#map')[0].map.editLayer.features[0].geometry\n  \t\t});\n\n\tvar strategy = new OpenLayers.Strategy.Fixed({preload: false, autoActivate: false});\n\tvar styleMap = new OpenLayers.StyleMap({\n                \"default\": new OpenLayers.Style({\n                    fillColor: \"Red\",\n                    strokeColor: \"Red\",\n                    fillOpacity: 0,\n                    strokeWidth: 1\n                  })\n\t});\n\tinseeLayer = new OpenLayers.Layer.Vector('INSEE Layer', {\n\t\t  styleMap: styleMap,\n          strategies: [strategy],\n          displayInLayerSwitcher: false,\n\t      protocol: new OpenLayers.Protocol.WFS({\n              url:  '" . str_replace("{HOST}", $_SERVER['HTTP_HOST'], $args['INSEE_url']) . "',\n\t          featurePrefix: '" . $args['INSEE_prefix'] . "',\n              featureType: '" . $args['INSEE_type'] . "',\n              geometryName:'the_geom',\n              featureNS: '" . $args['INSEE_ns'] . "',\n              srsName: 'EPSG:900913',\n              version: '1.1.0'                  \n      \t\t  ,propertyNames: ['the_geom', 'NOM', 'INSEE_NEW', 'DEPT_NUM', 'DEPT_NOM', 'REG_NUM', 'REG_NOM']\n  \t\t\t})\n    });\n    inseeLayer.events.register('featuresadded', {}, function(a1){\n    \tjQuery('#cc-2-loc-description').empty();\n    \tjQuery('<span>'+a1.features[0].attributes.NOM+' ('+a1.features[0].attributes.INSEE_NEW+'), '+a1.features[0].attributes.DEPT_NOM+' ('+a1.features[0].attributes.DEPT_NUM+'), '+a1.features[0].attributes.REG_NOM+' ('+a1.features[0].attributes.REG_NUM+')</span>').appendTo('#cc-2-loc-description');\n    });\n\tjQuery('#map')[0].map.addLayer(inseeLayer);\n\tstrategy.load({filter: filter});\n});\n\n";
        global $indicia_templates;
        $r .= $indicia_templates['loading_block_end'];
        return $r;
    }
Exemplo n.º 2
0
    /**
     * Return the generated form output.
     * @return Form HTML.
     */
    public static function get_form($args, $node)
    {
        global $user;
        // There is a language entry in the args parameter list: this is derived from the $language DRUPAL global.
        // It holds the 2 letter code, used to pick the language file from the lang subdirectory of prebuilt_forms.
        // There should be no explicitly output text in this file.
        // We must translate any field names and ensure that the termlists and taxonlists use the correct language.
        // For attributes, the caption is automatically translated by data_entry_helper.
        $logged_in = $user->uid > 0;
        $uid = $user->uid;
        $email = $user->mail;
        $username = $user->name;
        if (!user_access('IForm n' . $node->nid . ' access')) {
            return "<p>" . lang::get('LANG_Insufficient_Privileges') . "</p>";
        }
        $r = '';
        // Get authorisation tokens to update and read from the Warehouse.
        $readAuth = data_entry_helper::get_read_auth($args['website_id'], $args['password']);
        $svcUrl = data_entry_helper::$base_url . '/index.php/services';
        drupal_add_js(drupal_get_path('module', 'iform') . '/media/js/jquery.form.js', 'module');
        data_entry_helper::link_default_stylesheet();
        data_entry_helper::add_resource('jquery_ui');
        data_entry_helper::add_resource('autocomplete');
        if ($args['language'] != 'en') {
            data_entry_helper::add_resource('jquery_ui_' . $args['language']);
        }
        data_entry_helper::enable_validation('cc-1-collection-details');
        // don't care about ID itself, just want resources
        if ($args['help_module'] != '' && $args['help_inclusion_function'] != '' && module_exists($args['help_module']) && function_exists($args['help_inclusion_function'])) {
            $use_help = true;
            data_entry_helper::$javascript .= call_user_func($args['help_inclusion_function']);
        } else {
            $use_help = false;
        }
        // The only things that will be editable after the collection is saved will be the identifiaction of the flower/insects.
        // no id - just getting the attributes, rest will be filled in using AJAX
        $sample_attributes = data_entry_helper::getAttributes(array('valuetable' => 'sample_attribute_value', 'attrtable' => 'sample_attribute', 'key' => 'sample_id', 'fieldprefix' => 'smpAttr', 'extraParams' => $readAuth, 'survey_id' => $args['survey_id']));
        $occurrence_attributes = data_entry_helper::getAttributes(array('valuetable' => 'occurrence_attribute_value', 'attrtable' => 'occurrence_attribute', 'key' => 'occurrence_id', 'fieldprefix' => 'occAttr', 'extraParams' => $readAuth, 'survey_id' => $args['survey_id']));
        $location_attributes = data_entry_helper::getAttributes(array('valuetable' => 'location_attribute_value', 'attrtable' => 'location_attribute', 'key' => 'location_id', 'fieldprefix' => 'locAttr', 'extraParams' => $readAuth, 'survey_id' => $args['survey_id']));
        $taxon_attributes = data_entry_helper::getAttributes(array('valuetable' => 'taxa_taxon_list_attribute_value', 'attrtable' => 'taxa_taxon_list_attribute', 'key' => 'taxa_taxon_list_id', 'fieldprefix' => 'taxAttr', 'extraParams' => $readAuth), false);
        if (count($taxon_attributes) != 1 || $taxon_attributes[0][caption] != "XPER ID") {
            return "<p>Internal error: Expected 1 taxon attribute (XPER ID), got " . count($taxon_attributes) . "</p>Dump:<br/>" . print_r($taxon_attributes, true);
        }
        $defNRAttrOptions = array('extraParams' => $readAuth + array('orderby' => 'id'), 'lookUpListCtrl' => 'radio_group', 'lookUpKey' => 'meaning_id', 'language' => iform_lang_iso_639_2($args['language']), 'booleanCtrl' => 'radio', 'containerClass' => 'group-control-box', 'sep' => ' &nbsp; ');
        $defAttrOptions = $defNRAttrOptions;
        $defAttrOptions['validation'] = array('required');
        $checkOptions = $defNRAttrOptions;
        $checkOptions['lookUpListCtrl'] = 'checkbox_group';
        $language = iform_lang_iso_639_2($args['language']);
        global $indicia_templates;
        $indicia_templates['sref_textbox_latlong'] = '<div class="latLongDiv"><label for="{idLat}">{labelLat}:</label>' . '<input type="text" id="{idLat}" name="{fieldnameLat}" {class} {disabled} value="{default}" /></div>' . '<div class="latLongDiv"><label for="{idLong}">{labelLong}:</label>' . '<input type="text" id="{idLong}" name="{fieldnameLong}" {class} {disabled} value="{default}" /></div>';
        $base = base_path();
        if (substr($base, -1) != '/') {
            $base .= '/';
        }
        $r .= '<script type="text/javascript">
/* <![CDATA[ */
document.write("<div class=\\"ui-widget ui-widget-content ui-corner-all loading-panel\\" ><img src=\\"' . $base . drupal_get_path('module', 'iform') . '/media/images/ajax-loader2.gif\\" />' . lang::get('loading') . '...<span class=\\"poll-loading-extras\\">0</span></div>");
document.write("<div class=\\"poll-loading-hide\\" style=\\"display:none;\\">");
/* ]]> */</script>
';
        data_entry_helper::$javascript .= "var flowerTaxa = [";
        $extraParams = $readAuth + array('taxon_list_id' => $args['flower_list_id'], 'view' => 'list');
        $species_data_def = array('table' => 'taxa_taxon_list', 'extraParams' => $extraParams);
        $taxa = data_entry_helper::get_population_data($species_data_def);
        $first = true;
        // Flowers do not have XPER ID. Flowers list still required to do multiple selection list conversion.
        foreach ($taxa as $taxon) {
            data_entry_helper::$javascript .= ($first ? '' : ',') . "{id: " . $taxon['id'] . ", taxon: \"" . str_replace('"', '\\"', $taxon['taxon']) . "\"}\n";
            $first = false;
        }
        data_entry_helper::$javascript .= "];\nvar insectTaxa = [";
        $extraParams = $readAuth + array('taxon_list_id' => $args['insect_list_id'], 'view' => 'list');
        $taxa_attribute_values_data_def = array('table' => 'taxa_taxon_list_attribute_value', 'extraParams' => $extraParams);
        $taxa_attribute_values = data_entry_helper::get_population_data($taxa_attribute_values_data_def);
        // full list : no allow_data_entry filter.
        $extraParams['taxon_list_id'] = $args['insect_list_id'];
        $species_data_def['extraParams'] = $extraParams;
        $taxa = data_entry_helper::get_population_data($species_data_def);
        $first = true;
        foreach ($taxa as $taxon) {
            // TODO this is not the most performance orientated, but it works.
            $xperID = "NoXPERID";
            foreach ($taxa_attribute_values as $xperRecord) {
                if ($xperRecord["id"] != NULL && $xperRecord['taxa_taxon_list_id'] == $taxon['id']) {
                    $xperID = $xperRecord['value'];
                    break;
                }
            }
            data_entry_helper::$javascript .= ($first ? '' : ',') . '{id: ' . $taxon['id'] . ', taxon: "' . str_replace('"', '\\"', $taxon['taxon']) . '", xperID: "' . $xperID . '"}' . "\n";
            $first = false;
        }
        data_entry_helper::$javascript .= "];";
        // note we have to proxy the post. Every time a write transaction is carried out, the write nonce is trashed.
        // For security reasons we don't want to give the user the ability to generate their own nonce, so we use
        // the fact that the user is logged in to drupal as the main authentication/authorisation/identification
        // process for the user. The proxy packages the post into the correct format
        //
        // There are 2 types of submission:
        // When a user validates a panel using the validate button, the following panel is opened on success
        // When a user presses a modify button, the open panel gets validated, and the panel to be modified is opened.
        // loadAttribute
        // <form id="cc-1-collection-details"
        // has the main sample (+attributes), location (no attributes).
        // form id="cc-1-delete-collection" just has the main sample.
        // form id="cc-2-flower-upload" just uploads the flower picture: no DB
        // form id="cc-2-environment-upload" just uploads the location picture: no DB
        // form id="cc-2-floral-station"
        // has the location (+attributes), location_image, main sample (no attributes), flower occurrence (+attributes), determination, flower_image
        // form id="cc-3-delete-session" just has the session sample.
        // form class=\"poll-session-form\" has the session (+attributes)
        // form id="cc-4-insect-upload" just uploads the insect picture: no DB
        // form id="cc-4-main-form"
        // has the insect occurrence (+attributes), determination, insect image
        // form id="cc-4-delete-insect" just has the insect occurrence.
        // form id="cc-5-collection" has the main sample and closed attribute (forced to 1).
        $r .= '
<div id="refresh-message" style="display:none" ><p>' . lang::get('LANG_Please_Refresh_Page') . '</p></div>
<div id="cc-1" class="poll-section">
  <div id="cc-1-title" class="ui-accordion-header ui-helper-reset ui-state-active ui-corner-top poll-section-title">
  	<span id="cc-1-title-details">' . lang::get('LANG_Collection_Details') . '</span>
    <div class="right">
      <div>
        <span id="cc-1-reinit-button" class="ui-state-default ui-corner-all reinit-button">' . lang::get('LANG_Reinitialise') . '</span>
        <span id="cc-1-mod-button" class="ui-state-default ui-corner-all mod-button">' . lang::get('LANG_Modify') . '</span>
      </div>
    </div>
  </div>
  <div id="cc-1-details" class="ui-accordion-content ui-helper-reset ui-widget-content">
    <span id="cc-1-protocol-details"></span>
  </div>
  <div id="cc-1-body" class="ui-accordion-content ui-helper-reset ui-widget-content ui-accordion-content-active poll-section-body">
   <form id="cc-1-collection-details" action="' . iform_ajaxproxy_url($node, 'loc-sample') . '" method="POST">
    <input type="hidden" id="website_id"       name="website_id" value="' . $args['website_id'] . '" />
    <input type="hidden" id="imp-sref"         name="location:centroid_sref"  value="" />
    <input type="hidden" id="imp-geom"         name="location:centroid_geom" value="" />
    <input type="hidden" id="X-sref-system"  name="location:centroid_sref_system" value="900913" />
    <input type="hidden" id="sample:survey_id" name="sample:survey_id" value="' . $args['survey_id'] . '" />
    ' . iform_pollenators::help_button($use_help, "collection-help-button", $args['help_function'], $args['help_collection_arg']) . '
    <label for="location:name">' . lang::get('LANG_Collection_Name_Label') . ':</label>
 	<input type="text" id="location:name"      name="location:name" value="" class="required"/>
    <input type="hidden" id="sample:location_name" name="sample:location_name" value=""/>
 	' . str_replace("\n", "", data_entry_helper::outputAttribute($sample_attributes[$args['protocol_attr_id']], $defNRAttrOptions)) . '    <input type="hidden"                       name="sample:date" value="2010-01-01"/>
    <input type="hidden" id="smpAttr:' . $args['complete_attr_id'] . '" name="smpAttr:' . $args['complete_attr_id'] . '" value="0" />
    <input type="hidden" id="smpAttr:' . $args['uid_attr_id'] . '" name="smpAttr:' . $args['uid_attr_id'] . '" value="' . $uid . '" />
    <input type="hidden" id="smpAttr:' . $args['email_attr_id'] . '" name="smpAttr:' . $args['email_attr_id'] . '" value="' . $email . '" />
    <input type="hidden" id="smpAttr:' . $args['username_attr_id'] . '" name="smpAttr:' . $args['username_attr_id'] . '" value="' . $username . '" />  
    <input type="hidden" id="locations_website:website_id" name="locations_website:website_id" value="' . $args['website_id'] . '" />
    <input type="hidden" id="location:id"      name="location:id" value="" disabled="disabled" />
    <input type="hidden" id="sample:id"        name="sample:id" value="" disabled="disabled" />
    </form>
    <div class="button-container">
      <div id="cc-1-valid-button" class="ui-state-default ui-corner-all save-button">' . lang::get('LANG_Validate') . '</div>
    </div>
  </div>
  <div id="cc-1-trailer" class="poll-section-trailer">
    <div id="cc-1-trailer-image" ><img src="' . $base . drupal_get_path('module', 'iform') . '/media/images/exclamation.jpg" /></div>
    <p>' . lang::get('LANG_Collection_Trailer_Point_1') . '</p>
    <p>' . lang::get('LANG_Collection_Trailer_Point_2') . '</p>
  </div>
<div style="display:none" />
    <form id="cc-1-delete-collection" action="' . iform_ajaxproxy_url($node, 'sample') . '" method="POST">
       <input type="hidden" name="website_id" value="' . $args['website_id'] . '" />
       <input type="hidden" name="sample:survey_id" value="' . $args['survey_id'] . '" />
       <input type="hidden" name="sample:id" value="" />
       <input type="hidden" name="sample:date" value="2010-01-01"/>
       <input type="hidden" name="sample:location_id" value="" />
       <input type="hidden" name="sample:deleted" value="t" />
    </form>
</div>
  <div id="cc-1-main-body" class="ui-accordion-content ui-helper-reset ui-widget-content ui-corner-bottom ui-accordion-content-active">
';
        data_entry_helper::$javascript .= "\n\$.validator.messages.required = \"" . lang::get('validation_required') . "\";\nvar sessionCounter = 0;\njQuery('#imp-georef-search-btn').removeClass('indicia-button').addClass('search-button');\n// can't use shuffle to side as dynamic generated code does like it in IE7\n\nhtmlspecialchars = function(value){\n\treturn value.replace(/[<>\"'&]/g, function(m){return replacechar(m)})\n};\n\nreplacechar = function(match){\n\tif (match==\"<\") return \"&lt;\"\n\telse if (match==\">\") return \"&gt;\"\n\telse if (match=='\"') return \"&quot;\"\n\telse if (match==\"'\") return \"&#039;\"\n\telse if (match==\"&\") return \"&amp;\"\n};\n\n\$.fn.foldPanel = function(){\n\tthis.children('.poll-section-body,.poll-section-footer,.poll-section-trailer').hide();\n\tthis.children('.poll-section-title').find('.reinit-button,.mod-button').show();\n\tthis.children('.photoReelContainer').addClass('ui-corner-all').removeClass('ui-corner-top'); /* visibility depends on specific circumstances */\n};\n\n\$.fn.unFoldPanel = function(){\n\tthis.children('.poll-section-body,.poll-section-footer,.poll-section-trailer,.photoReelContainer').show();\n\tthis.children('.poll-section-title').find('.mod-button').hide();\n\tthis.children('.photoReelContainer').addClass('ui-corner-top').removeClass('ui-corner-all');\n\twindow.scroll(0,0); // force the window to display the top.\n\tbuildMap();\n\tcheckSessionButtons();\n\t// any reinit button is left in place\n};\n\n\$.fn.showPanel = function(){\n\tthis.show();\n\tthis.unFoldPanel();\n};\n\n\$.fn.hidePanel = function(){\n\tthis.hide(); \n};\n\ninseeLayer = null;\n\nnewDefaultSref = '0, 0';\noldDefaultSref = '" . ((int) $args['map_centroid_lat'] > 0 ? $args['map_centroid_lat'] . 'N' : -(int) $args['map_centroid_lat'] . 'S') . ' ' . ((int) $args['map_centroid_long'] > 0 ? $args['map_centroid_long'] . 'E' : -(int) $args['map_centroid_long'] . 'W') . "';\ndefaultGeom = '';\n\$.getJSON('" . $svcUrl . "' + '/spatial/sref_to_wkt'+\n        \t\t\t'?sref=' + newDefaultSref +\n          \t\t\t'&system=' + jQuery('#imp-sref-system').val() +\n          \t\t\t'&callback=?', function(data) {\n            \tdefaultGeom = data.wkt;\n                   \t});\n\n\$.fn.resetPanel = function(){\n\tthis.find('.poll-section-body').show();\n\tthis.find('.poll-section-footer,.poll-section-trailer').show();\n\tthis.find('.reinit-button').show();\n\tthis.find('.mod-button').show();\n\tthis.find('.poll-image').empty();\n\tthis.find('.poll-session').remove();\n\tthis.find('.inline-error').remove();\n\tthis.find('#imp-georef-search').val('');\n\tthis.find('#imp-georef-div').hide();\n\tthis.find('#imp-georef-output-div').empty();\n\tthis.find('[name=place\\:INSEE]').val('" . lang::get('LANG_INSEE') . "');\n\tthis.find('#imp-sref-lat').val('');\n\tthis.find('#imp-sref-long').val('');\n\tthis.find('#X-sref-system').val('900913'); //note only one of these in cc-1, distinct from location:centroid_sref_system. This indicates no geolocation loaded.\n\t// TODO Map\n\tthis.find('.thumb').not('.blankPhoto').remove();\n\tthis.find('.blankPhoto').addClass('currentPhoto');\n\t\n\t// resetForm does not reset the hidden fields. record_status, website_id and survey_id are not altered so do not reset.\n\t// hidden Attributes generally hold unchanging data, but the name needs to be reset (does it for non hidden as well).\n\t// hidden location:name are set in code anyway.\n\tthis.find('.poll-dummy-form input').val('');\n\tthis.find('.poll-dummy-form input').removeAttr('checked');\n\tthis.find('.poll-dummy-form select').val('');\n\tthis.find('.poll-dummy-form textarea').val('');\n\tthis.find('.poll-dummy-form').find('[name\$=\\:determination_type]').val('A');\n\tthis.find('form').each(function(){\n\t\tjQuery(this).resetForm();\n\t\tjQuery(this).find('[name=sample\\:location_name],[name=location_image\\:path],[name=occurrence_image\\:path]').val('');\n\t\tjQuery(this).filter('#cc-1-collection-details').find('[name=sample\\:id],[name=location\\:id]').val('').attr('disabled', 'disabled');\n\t\tjQuery(this).find('[name=location_image\\:id],[name=occurrence\\:id],[name=determination\\:id],[name=occurrence_image\\:id]').val('').attr('disabled', 'disabled');\n\t\tjQuery(this).find('[name=sample\\:date]:hidden').val('2010-01-01');\n\t\tjQuery(this).find('input[name=locations_website\\:website_id]').removeAttr('disabled');\n\t\tjQuery(this).find('[name=locAttr\\:" . $args['location_picture_camera_attr_id'] . "],[name^=locAttr\\:" . $args['location_picture_camera_attr_id'] . "\\:],[name=locAttr\\:" . $args['location_picture_datetime_attr_id'] . "],[name^=locAttr\\:" . $args['location_picture_datetime_attr_id'] . "\\:],[name=occAttr\\:" . $args['occurrence_picture_camera_attr_id'] . "],[name^=occAttr\\:" . $args['occurrence_picture_camera_attr_id'] . "\\:],[name=occAttr\\:" . $args['occurrence_picture_datetime_attr_id'] . "],[name^=occAttr\\:" . $args['occurrence_picture_datetime_attr_id'] . "\\:]').val('');\n\t\tjQuery(this).find('[name^=smpAttr\\:],[name^=locAttr\\:],[name^=occAttr\\:]').filter('.multiselect').remove();\n\t\tjQuery(this).find('[name^=smpAttr\\:],[name^=locAttr\\:],[name^=occAttr\\:]').each(function(){\n\t\t\tvar name = jQuery(this).attr('name').split(':');\n\t\t\tif(name[1].indexOf('[]') > 0) name[1] = name[1].substr(0, name[1].indexOf('[]'));\n\t\t\tjQuery(this).attr('name', name[0]+':'+name[1]);\n\t\t});\n\t\tjQuery(this).find('[name^=smpAttr\\:],[name^=locAttr\\:],[name^=occAttr\\:]').filter(':checkbox').removeAttr('checked').each(function(){\n\t\t\tvar name = jQuery(this).attr('name').split(':');\n\t\t\tvar similar = jQuery('[name='+name[0]+'\\:'+name[1]+'],[name='+name[0]+'\\:'+name[1]+'\\[\\]]').filter(':checkbox');\n\t\t\tif(similar.length > 1)\n\t\t\t\tjQuery(this).attr('name', name[0]+':'+name[1]+'[]');\n\t\t});\n\t\tjQuery(this).find('input[name=location\\:centroid_sref]').val('');\n\t\tjQuery(this).find('input[name=location\\:centroid_geom]').val('');\n    });\t\n  };\n\nalertIndiciaError = function(data){\n\tvar errorString = \"" . lang::get('LANG_Indicia_Warehouse_Error') . "\";\n\tif(data.error){\terrorString = errorString + ' : ' + data.error;\t}\n\tif(data.errors){\n\t\tfor (var i in data.errors){\n\t\t\terrorString = errorString + ' : ' + data.errors[i];\n\t\t}\t\t\t\t\n\t}\n\talert(errorString);\n\t// the most likely cause is authentication failure - eg the read authentication has timed out.\n\t// prevent further use of the form:\n\t\$('.loading-panel').remove();\n\t\$('.poll-loading-hide').show();\n\tjQuery('#cc-1').hide();\n\tjQuery('#refresh-message').show();\n\tthrow('WAREHOUSE ERROR');\n};\n\t\t\t\ncheckProtocolStatus = function(display){\n  \tvar checkedProtocol = jQuery('[name=smpAttr\\:" . $args['protocol_attr_id'] . "],[name^=smpAttr\\:" . $args['protocol_attr_id'] . "\\:]').filter('[checked]').parent();\n    if(jQuery('[name=location\\:name]').val() != '' && checkedProtocol.length > 0) {\n        jQuery('#cc-1-title-details').empty().text(jQuery('#cc-1-collection-details input[name=location\\:name]:first').val());\n        firstBracket = checkedProtocol.find('label')[0].innerHTML.indexOf('(');\n        secondBracket = checkedProtocol.find('label')[0].innerHTML.lastIndexOf(')');\n        jQuery('#cc-1-protocol-details').empty().show().html('<strong>" . lang::get('LANG_Protocol_Title_Label') . "</strong> : <span class=\"protocol-head\">' +\n                  checkedProtocol.find('label')[0].innerHTML.slice(0, firstBracket-1) +\n                  '</span><span class=\"protocol-description\"> | ' +\n                  checkedProtocol.find('label')[0].innerHTML.slice(firstBracket+1, secondBracket) + '</span>');\n    } else {\n        jQuery('#cc-1-title-details').empty().text(\"" . lang::get('LANG_Collection_Details') . "\");\n        // TODO autogenerate a name\n        jQuery('#cc-1-protocol-details').empty().hide();\n    }\n    if(display == true){\n      jQuery('#cc-1-details').addClass('ui-accordian-content-active');\n    } else if(display == false){\n      jQuery('#cc-1-details').removeClass('ui-accordian-content-active');\n    } // anything else just leave\n};\ncheckForagingStatus = function(setForagingConfirm){\n\tjQuery('[name=occAttr\\:" . $args['foraging_attr_id'] . "],[name^=occAttr\\:" . $args['foraging_attr_id'] . ":]').filter('[checked]').each(function(index, elem){\n\t\tif(elem.value==1){ // need to allow string 1 comparison so no ===\n\t\t\tjQuery('#Foraging_Confirm').show();\n\t\t\tif(setForagingConfirm)\n\t\t\t\tjQuery('[name=dummy_foraging_confirm]').filter('[value=1]').attr('checked',true);\n\t\t} else\n\t\t\tjQuery('#Foraging_Confirm').hide();\n\t});\n};\ncheckSessionButtons = function(){\n\tif (jQuery('#cc-3-body').children().length === 1) {\n\t    jQuery('#cc-3').find('.delete-button').hide();\n\t    jQuery('#cc-3-valid-button').empty().text(\"" . lang::get('LANG_Validate_Session') . "\")\n  \t} else {\n\t\tjQuery('#cc-3').find('.delete-button').show();\n\t    jQuery('#cc-3-valid-button').empty().text(\"" . lang::get('LANG_Validate_Session_Plural') . "\")\n  \t}\n\tif(jQuery('[name=smpAttr\\:" . $args['protocol_attr_id'] . "],[name^=smpAttr\\:" . $args['protocol_attr_id'] . "\\:]').filter(':first').filter('[checked]').length >0){\n\t    jQuery('#cc-3-title-title').empty().text(\"" . lang::get('LANG_Sessions_Title') . "\");\n\t\tjQuery('#cc-3').find('.add-button').hide();\n\t} else {\n\t    jQuery('#cc-3-title-title').empty().text(\"" . lang::get('LANG_Sessions_Title_Plural') . "\");\n\t\tjQuery('#cc-3').find('.add-button').show();\n  \t}\n};\n\nshowStationPanel = true;\n\n// The validate functionality for each panel is sufficiently different that we can't generalise a function\n// this is the one called when we don't want the panel following to be opened automatically.\nvalidateCollectionPanel = function(){\n\tclearErrors('form#cc-1-collection-details');\n\tif(jQuery('#cc-1-body:visible').length == 0) return true; // body hidden so data already been validated successfully.\n\tif(!jQuery('#cc-1-body').find('form > input').valid()){\n\t\tmyScrollToError();\n\t\treturn false;\n  \t}\n\t// no need to check protocol - if we are this far, we've already filled it in.\n  \tshowStationPanel = false;\n\tjQuery('#cc-1-collection-details').submit();\n\treturn true;\n  };\n\nerrorPos = null;\nclearErrors = function(formSel) {\n\tjQuery(formSel).find('.inline-error').remove();\n\terrorPos = null;\n};\nmyScrollTo = function(selector){\n\tjQuery(selector).filter(':visible').each(function(){\n\t\tif(errorPos == null || jQuery(this).offset().top < errorPos){\n\t\t\terrorPos = jQuery(this).offset().top;\n\t\t\twindow.scroll(0,errorPos);\n\t\t}\n\t});\n};\nmyScrollToError = function(){\n\tjQuery('.inline-error,.error').filter(':visible').prev().each(function(){\n\t\tif(errorPos == null || jQuery(this).offset().top < errorPos){\n\t\t\terrorPos = jQuery(this).offset().top;\n\t\t\twindow.scroll(0,errorPos);\n\t\t}\n\t});\n};\n\nvalidateRadio = function(name, formSel){\n    var controls = jQuery(formSel).find('[name='+name+'],[name^='+name+'\\:]');\n    if(controls.filter('[checked]').length < 1) {\n        var label = \$('<p/>')\n\t\t\t\t.attr({'for': name})\n\t\t\t\t.addClass('inline-error')\n\t\t\t\t.html(\$.validator.messages.required);\n\t\tlabel.insertBefore(controls.filter(':first').parent());\n\t\treturn false;\n    }\n    return true;\n}\n\nvalidateRequiredField = function(name, formSel){\n    var control = jQuery(formSel).find('[name='+name+']');\n    if(control.val() == '') {\n        var label = \$('<p/>')\n\t\t\t\t.attr({'for': name})\n\t\t\t\t.addClass('inline-error')\n\t\t\t\t.html(\$.validator.messages.required);\n\t\tlabel.insertBefore(control);\n\t\treturn false;\n    }\n    return true;\n}\n\nvalidateOptInt = function(name, formSel){\n\tvar control = jQuery(formSel).find('[name='+name+'],[name^='+name+'\\:]');\n\tvar ctrvalue = control.val();\n\tvar OK = true;\n\tif(ctrvalue == '') return true;\n\tfor (i = 0 ; i < ctrvalue.length ; i++) {\n\t\tif ((ctrvalue.charAt(i) < '0') || (ctrvalue.charAt(i) > '9')) OK = false\n\t}\n\tif(OK) return OK;\n\tvar label = \$('<p/>')\n\t\t\t\t.attr({'for': name})\n\t\t\t\t.addClass('inline-error')\n\t\t\t\t.html(\"" . lang::get('validation_integer') . "\");\n\tlabel.insertBefore(control);\n\treturn false;\n}\n\ninsertImage = function(path, target, ratio){\n\tvar img = new Image();\n\tjQuery(img).load(function () {\n        target.removeClass('loading').append(this);\n        if(this.width/this.height > ratio){\n\t    \tjQuery(this).css('width', '100%').css('height', 'auto').css('vertical-align', 'middle').css('margin-left', 'auto').css('margin-right', 'auto').css('display', 'block');\n  \t\t} else {\n\t        jQuery(this).css('width', (100*this.width/(this.height*ratio))+'%').css('height', 'auto').css('vertical-align', 'middle').css('margin-left', 'auto').css('margin-right', 'auto').css('display', 'block');\n  \t\t}\n\t}).attr('src', '" . data_entry_helper::$base_url . data_entry_helper::$indicia_upload_path . "'+path);\n}\n\t\t\t\t    \n\$('#cc-1').ajaxError(function(event, request, settings){\n\tvar insectURL = insectIDstruc.pollURL+insectIDstruc.sessionID;\n\tif(settings.url != insectURL){ // this url may not be present.\n\t\talert(\"" . lang::get('ajax_error') . "\" + '\\n' + settings.url + '\\n' + request.status + ' ' + request.statusText + '\\n' + \"" . lang::get('ajax_error_bumpf') . "\");\n\t\t// unknown data state so prevent further use of the form:\n\t\t\$('.loading-panel').remove();\n\t\t\$('.poll-loading-hide').show();\n\t\tjQuery('#cc-1').hide();\n\t\tjQuery('#refresh-message').show();\n\t\tthrow('AJAX ERROR');\n\t}\n});\n \nvalidateTime = function(name, formSel){\n    var control = jQuery(formSel).find('[name='+name+'],[name^='+name+'\\:]');\n    if(control.val().match(/^(2[0-3]|[0,1][0-9]):[0-5][0-9]\$/) == null) {\n        var label = \$('<p/>')\n\t\t\t\t.attr({'for': name})\n\t\t\t\t.addClass('inline-error')\n\t\t\t\t.html('" . lang::get('validation_time') . "');\n\t\tlabel.insertBefore(control);\n\t\treturn false;\n    }\n    return true;\n}\n\n\$('#cc-1-collection-details').ajaxForm({\n\t\tasync: false,\n        dataType:  'json', \n        beforeSubmit:   function(data, obj, options){\n        \t// if location id filled in but sample id is not -> error\n        \tif(data.length == 15 && data[14].value == ''){\n        \t\talertIndiciaError({error : \"" . lang::get('Internal Error 1: sample id not filled in, so not safe to save collection') . "\"});\n\t\t\t\treturn false;\n\t\t\t}\n        \tclearErrors('form#cc-1-collection-details');\n        \tvar valid = true;\n        \tif (!jQuery('form#cc-1-collection-details > input').valid()) { valid = false; }\n        \tif (!validateRadio('smpAttr\\:" . $args['protocol_attr_id'] . "', 'form#cc-1-collection-details')) { valid = false; }\n\t       \tif ( valid == false ) {\n\t\t\t\tmyScrollToError();\n\t\t\t\treturn false;\n  \t\t\t};\n  \t\t\t// Warning this assumes that:\n  \t\t\t// 1) the location:name is the sixth field in the form.\n  \t\t\t// 1) the sample:location_name is the seventh field in the form.\n  \t\t\tdata[6].value = data[5].value;\n  \t\t\tif(data[3].value=='900913'){\n  \t\t\t\tdata[1].value=newDefaultSref;\n  \t\t\t\tdata[2].value=defaultGeom;\n  \t\t\t}\n  \t\t\tjQuery('#cc-2-floral-station > input[name=location\\:name]').val(data[5].value);\n  \t\t\tjQuery('#cc-1-valid-button').addClass('loading-button');\n        \treturn true;\n  \t\t},\n        success:   function(data){\n        \tif(data.success == 'multiple records' && data.outer_table == 'location'){\n        \t    jQuery('[name=location\\:id],[name=sample\\:location_id]').removeAttr('disabled').val(data.outer_id);\n        \t    jQuery('[name=locations_website\\:website_id]').attr('disabled', 'disabled');\n        \t    // data.struct.children[0] holds the details of the sample record.\n\t\t\t\tjQuery('#cc-6-consult-collection').attr('href', '" . url('node/' . $args['gallery_node']) . "'+'?collection_id='+data.struct.children[0].id);\n\t\t\t\tjQuery('#cc-1-collection-details,#cc-2-floral-station,#cc-1-delete-collection').find('[name=sample\\:id]').removeAttr('disabled').val(data.struct.children[0].id);\n\t\t\t\t// In this case we use loadAttributes to set the names of the attributes to include the attribute_value id.\n\t\t\t\t// cant use the struct as it can't tell which attribute is which. \n\t\t\t\tloadAttributes('#cc-1-collection-details,#cc-5-collection', 'sample_attribute_value', 'sample_attribute_id', 'sample_id', data.struct.children[0].id, 'smpAttr', true, true);\n\t\t\t   \tcheckProtocolStatus(true);\n        \t\t\$('#cc-1').foldPanel();\n    \t\t\tif(showStationPanel){ \$('#cc-2').showPanel(); }\n\t\t    \tshowStationPanel = true;\n        \t}  else \n\t\t\t\talertIndiciaError(data);\n        },\n        complete: function (){\n  \t\t\tjQuery('.loading-button').removeClass('loading-button');\n  \t\t}\n});\n\n\$('#cc-1-delete-collection').ajaxForm({ \n\t\tasync: false,\n\t\tdataType:  'json', \n        beforeSubmit:   function(data, obj, options){\n  \t\t\t// Warning this assumes that the data is fixed position:\n       \t\tdata[3].value = jQuery('#cc-1-collection-details input[name=sample\\:date]').val();\n        \tif(data[2].value == '') return false;\n\t\t\tif(data[4].value == ''){ // double check that location id is filled in\n\t\t\t\talertIndiciaError({error : \"" . lang::get('Internal Error 3: location id not set, so unsafe to delete collection.') . "\"});\n\t\t\t\treturn false;\n\t\t\t}\n  \t\t\tjQuery('#cc-1-reinit-button').addClass('loading-button');\n        \treturn true;\n  \t\t},\n        success:   function(data){\n        \tif(data.success == 'multiple records' && data.outer_table == 'sample'){\n        \t\tjQuery('#cc-3-body').empty();\n        \t\tpollReset(insectIDstruc);\n\t        \tjQuery('.poll-section').resetPanel();\n\t\t\t\tsessionCounter = 0;\n\t\t\t\taddSession();\n\t\t\t\tcheckProtocolStatus(false);\n\t\t\t\tjQuery('.poll-section').hidePanel();\n\t\t\t\tjQuery('.poll-image').empty();\n\t\t\t\tjQuery('#cc-1').showPanel();\n\t\t\t\tjQuery('.reinit-button').hide();\n\t\t\t\tif(jQuery('#map').children().length > 0) {\n\t\t\t\t\tvar div = jQuery('#map')[0];\n\t\t\t\t\tdiv.map.editLayer.destroyFeatures();\n\t\t\t\t\tdiv.map.searchLayer.destroyFeatures();\n\t\t\t\t\tif(inseeLayer != null) inseeLayer.destroyFeatures();\n\t\t\t\t\tjQuery('#cc-2-loc-description').empty();\n\t\t\t\t\tvar center = new OpenLayers.LonLat(" . $args['map_centroid_long'] . ", " . $args['map_centroid_lat'] . ");\n\t\t\t\t\tcenter.transform(div.map.displayProjection, div.map.projection);\n\t\t\t\t\tdiv.map.setCenter(center, " . (int) $args['map_zoom'] . ");\n\t\t\t\t}\n        \t}  else \n\t\t\t\talertIndiciaError(data);\n  \t\t},\n        complete: function (){\n  \t\t\tjQuery('.loading-button').removeClass('loading-button');\n  \t\t}\n});\n\n\$('#cc-1-valid-button').click(function() {\n\tjQuery('#cc-1-collection-details').submit();\n});\n\n\$('#cc-1-reinit-button').click(function() {\n    clearErrors('form#cc-1-collection-details');\n\tif(jQuery('form#cc-1-collection-details > input[name=sample\\:id]').filter('[disabled]').length > 0) { return } // sample id is disabled, so no data has been saved - do nothing.\n    if (!jQuery('form#cc-1-collection-details > input').valid()) {\n    \tmyScrollToError();\n    \talert(\"" . lang::get('LANG_Unable_To_Reinit') . "\");\n        return ;\n  \t}\n\tif(confirm(\"" . lang::get('LANG_Confirm_Reinit') . "\")){\n\t\tjQuery('#cc-1-delete-collection').submit();\n\t}\n});\n\n";
        // Flower Station section.
        $options = iform_map_get_map_options($args, $readAuth);
        $olOptions = iform_map_get_ol_options($args);
        // The maps internal projection will be left at its default of 900913.
        $options['searchLayer'] = 'true';
        $options['initialFeatureWkt'] = null;
        $options['proxy'] = '';
        // Switch to degrees, minutes, seconds for lat long.
        $options['latLongFormat'] = 'DMS';
        if (lang::get('msgGeorefSelectPlace') != 'msgGeorefSelectPlace') {
            $options['msgGeorefSelectPlace'] = lang::get('msgGeorefSelectPlace');
        }
        if (lang::get('msgGeorefNothingFound') != 'msgGeorefNothingFound') {
            $options['msgGeorefNothingFound'] = lang::get('msgGeorefNothingFound');
        }
        $extraParams = $readAuth + array('taxon_list_id' => $args['flower_list_id'], 'view' => 'detail', 'orderby' => 'taxonomic_sort_order', 'allow_data_entry' => 't');
        $species_ctrl_args = array('fieldname' => 'flowerSelect', 'table' => 'taxa_taxon_list', 'captionField' => 'taxon', 'listCaptionSpecialChars' => true, 'valueField' => 'id', 'columns' => 2, 'blankText' => lang::get('LANG_Choose_Taxon'), 'extraParams' => $extraParams, 'suffixTemplate' => 'nosuffix');
        $r .= '
<div id="cc-2" class="poll-section">
  <div id="cc-2-title" class="ui-accordion-header ui-helper-reset ui-state-active ui-corner-all poll-section-title"><span>' . lang::get('LANG_Flower_Station') . '</span>
    <div class="right">
      <span id="cc-2-mod-button" class="ui-state-default ui-corner-all mod-button">' . lang::get('LANG_Modify') . '</span>
    </div>
  </div>
  <div id="cc-2-body" class="ui-accordion-content ui-helper-reset ui-widget-content ui-corner-top ui-accordion-content-active poll-section-body">
    <div id="cc-2-flower" >
	  <div id="cc-2-flower-title">' . lang::get('LANG_Upload_Flower') . '</div>
	  <form id="cc-2-flower-upload" enctype="multipart/form-data" action="' . iform_ajaxproxy_url($node, 'media') . '" method="POST">
    		<input type="hidden" id="website_id" name="website_id" value="' . $args['website_id'] . '" />
    		<input name="upload_file" type="file" class="required" />
     		<input type="submit" value="' . lang::get('LANG_Upload') . '" class="btn-submit" />
 	  		<div id="cc-2-flower-image" class="poll-image"></div>
      </form>
      <div id="cc-2-flower-identify" class="poll-dummy-form">
        <div class="id-tool-group">
          ' . iform_pollenators::help_button($use_help, "flower-help-button", $args['help_function'], $args['help_flower_arg']) . '
		  <p><strong>' . lang::get('LANG_Identify_Flower') . ' :</strong></p>
          <div class="id-later-group">
            <label for="id-flower-later" class="follow-on">' . lang::get('LANG_ID_Flower_Later') . ' </label><input type="checkbox" id="id-flower-later" name="id-flower-later" /> 
          </div>
		  <input type="hidden" id="flower:taxon_details" name="flower:taxon_details" value=""/>
          <input type="hidden" name="flower:determination_type" value="A" />
          <input type="hidden" name="flower:taxa_taxon_list_id" value="" />
          <label for="id-flower-unknown" class="follow-on">' . lang::get('LANG_ID_Flower_Unknown') . ' </label><input type="checkbox" id="id-flower-unknown" name="id-flower-unknown" /><br/>
          ' . lang::get('LANG_Known_Species') . ' : <input name="flowerAutocomplete" id="flowerAutocomplete" />' . data_entry_helper::select($species_ctrl_args) . '
          <table id="flower-species-list"><tbody id="flower-species-list-body"></tbody></table>
        </div>
 	    <div class="id-specified-group">
          <label for="flower:taxon_extra_info" class="follow-on">' . lang::get('LANG_ID_More_Precise') . ' </label> 
          <input type="text" id="flower:taxon_extra_info" name="flower:taxon_extra_info" class="taxon-info" />
        </div>
      </div>
      <div class="id-comment">
        <label for="flower:comment" >' . lang::get('LANG_ID_Comment') . ' </label>
        <textarea id="flower:comment" name="flower:comment" class="taxon-comment" rows="3" ></textarea>
      </div>
    </div>
    <div class="poll-break"></div>
 	<div id="cc-2-environment">
	  ' . iform_pollenators::help_button($use_help, "environment-help-button", $args['help_function'], $args['help_environment_arg']) . '
	  <div id="cc-2-environment-title">' . lang::get('LANG_Upload_Environment') . '</div>
 	  <form id="cc-2-environment-upload" enctype="multipart/form-data" action="' . iform_ajaxproxy_url($node, 'media') . '" method="POST">
    	<input type="hidden" id="website_id" name="website_id" value="' . $args['website_id'] . '" />
    	<input name="upload_file" type="file" class="required" />
    	<input type="submit" value="' . lang::get('LANG_Upload') . '" class="btn-submit" />
 	  	<div id="cc-2-environment-image" class="poll-image"></div>
      </form>
 	</div>
 	<form id="cc-2-floral-station" action="' . iform_ajaxproxy_url($node, 'loc-smp-occ') . '" method="POST">
      <input type="hidden" id="website_id" name="website_id" value="' . $args['website_id'] . '" />
      <input type="hidden" id="location:id" name="location:id" value="" />
      <input type="hidden" id="location:name" name="location:name" value=""/>
      <input type="hidden" name="location:centroid_sref" />
      <input type="hidden" name="location:centroid_geom" />
      <input type="hidden" id="imp-sref-system" name="location:centroid_sref_system" value="4326" />
      <input type="hidden" id="location_image:path" name="location_image:path" value="" />
      <input type="hidden" id="location_picture_camera_attr" name="locAttr:' . $args['location_picture_camera_attr_id'] . '" value="" />
      <input type="hidden" id="location_picture_datetime_attr" name="locAttr:' . $args['location_picture_datetime_attr_id'] . '" value="" />
      <input type="hidden" id="sample:survey_id" name="sample:survey_id" value="' . $args['survey_id'] . '" />
      <input type="hidden" id="sample:id" name="sample:id" value=""/>
      <input type="hidden" name="sample:date" value="2010-01-01"/>
      <input type="hidden" name="determination:taxa_taxon_list_id" value=""/>  
      <input type="hidden" name="determination:taxon_details" value=""/>  
      <input type="hidden" name="determination:taxon_extra_info" value=""/>  
      <input type="hidden" name="determination:comment" value=""/>  
      <input type="hidden" name="determination:determination_type" value="A" />  
      <input type="hidden" name="determination:cms_ref" value="' . $uid . '" />
      <input type="hidden" name="determination:email_address" value="' . $email . '" />
      <input type="hidden" name="determination:person_name" value="' . $username . '" />  
      <input type="hidden" name="occurrence:use_determination" value="Y"/>    
      <input type="hidden" name="occurrence:record_status" value="C" />
      <input type="hidden" id="location_image:id" name="location_image:id" value="" disabled="disabled" />
      <input type="hidden" id="occurrence:id" name="occurrence:id" value="" disabled="disabled" />
      <input type="hidden" id="determination:id" name="determination:id" value="" disabled="disabled" />
      <input type="hidden" id="occurrence_image:id" name="occurrence_image:id" value="" disabled="disabled" />
      <input type="hidden" id="occurrence_image:path" name="occurrence_image:path" value="" />
      <input type="hidden" id="flower_picture_camera_attr" name="occAttr:' . $args['occurrence_picture_camera_attr_id'] . '" value="" />
      <input type="hidden" id="flower_picture_datetime_attr" name="occAttr:' . $args['occurrence_picture_datetime_attr_id'] . '" value="" />
      ' . str_replace("\n", "", data_entry_helper::outputAttribute($occurrence_attributes[$args['flower_type_attr_id']], $defNRAttrOptions)) . str_replace("\n", "", data_entry_helper::outputAttribute($location_attributes[$args['distance_attr_id']], $defNRAttrOptions)) . str_replace("\n", "", data_entry_helper::outputAttribute($location_attributes[$args['within50m_attr_id']], $defNRAttrOptions)) . str_replace("\n", "", data_entry_helper::outputAttribute($location_attributes[$args['habitat_attr_id']], $checkOptions)) . '
    </form>
    <div class="poll-break"></div>
    <div id="cc-2-location-container">
      ' . iform_pollenators::help_button($use_help, "location-help-button", $args['help_function'], $args['help_location_arg']) . '
      <div id="cc-2-location-notes" >' . lang::get('LANG_Location_Notes') . '</div>
      <div id="cc-2-location-entry">
        ' . data_entry_helper::georeference_lookup(iform_map_get_georef_options($args, $readAuth)) . '
  	    <label for="place:INSEE">' . lang::get('LANG_Or') . '</label><input type="text" id="place:INSEE" name="place:INSEE" value="' . lang::get('LANG_INSEE') . '"
	 		onclick="if(this.value==\'' . lang::get('LANG_INSEE') . '\'){this.value=\'\'; this.style.color=\'#000\'}"  
            onblur="if(this.value==\'\'){this.value=\'' . lang::get('LANG_INSEE') . '\'; this.style.color=\'#555\'}" /><input type="button" id="search-insee-button" class="ui-corner-all ui-widget-content ui-state-default search-button" value="' . lang::get('search') . '" />
 	    <label >' . lang::get('LANG_Or') . '</label>
    	' . data_entry_helper::sref_textbox(array('srefField' => 'place:entered_sref', 'systemfield' => 'place:entered_sref_system', 'id' => 'place-sref', 'fieldname' => 'place:name', 'splitLatLong' => true, 'labelLat' => lang::get('Latitude'), 'fieldnameLat' => 'place:lat', 'labelLong' => lang::get('Longitude'), 'fieldnameLong' => 'place:long', 'idLat' => 'imp-sref-lat', 'idLong' => 'imp-sref-long')) . '
 	  </div>
 	  <div class="poll-map-container">';
        $tempScript = data_entry_helper::$onload_javascript;
        data_entry_helper::$onload_javascript = '';
        $r .= data_entry_helper::map_panel($options, $olOptions);
        $map1JS = data_entry_helper::$onload_javascript;
        data_entry_helper::$onload_javascript = $tempScript;
        $r .= '</div>
 	  <div id="cc-2-loc-description"></div>
    </div>
  </div>
  <div id="cc-2-footer" class="ui-accordion-content ui-helper-reset ui-widget-content ui-corner-bottom ui-accordion-content-active poll-section-footer">
    <div id="cc-2-valid-button" class="ui-state-default ui-corner-all save-button">' . lang::get('LANG_Validate_Flower') . '</div>
  </div>
</div>';
        // NB the distance attribute is left blank at the moment if unknown: TODO put in a checkbox : checked if blank for nsp
        data_entry_helper::$javascript .= "\njQuery('input#flowerAutocomplete').autocomplete(flowerTaxa,\n      { matchContains: true,\n        parse: function(data)\n        {\n          var results = [];\n          jQuery.each(data, function(i, item) {\n            results[results.length] =\n            {\n              'data' : item,\n              'result' : item.id,\n              'value' : item.taxon\n            };\n          });\n          return results;\n        },\n      formatItem: function(item)\n      {\n        return item.taxon;\n      }\n      // {max}\n});\njQuery('input#flowerAutocomplete').result(function(event, data) {\n  if(jQuery('#flower-species-list input[value='+data.id+']').length > 0) return;\n  jQuery('input#flowerAutocomplete').val('');\n  jQuery('<tr class=\"flower-species-list-entry\"><td><input type=\"hidden\" name=\"flower:taxa_taxon_list_id_list[]\" value=\"'+data.id+'\"\\>'+htmlspecialchars(data.taxon)+'</td><td><img class=\"removeRow\" src=\"/misc/watchdog-error.png\" alt=\"" . lang::get('Remove this entry') . "\" title=\"" . lang::get('Remove this entry') . "\"/></td></tr>').appendTo('#flower-species-list-body');\n  jQuery('#cc-2-flower-identify [name=flower\\:determination_type]').val('A');\n  jQuery('#id-flower-unknown').removeAttr('checked');\n  jQuery('#id-flower-later').removeAttr('checked').attr('disabled','disabled');\n});\njQuery('select#flowerSelect').change(function() {\n  if(jQuery('#flower-species-list input[value='+jQuery(this).val()+']').length > 0) return;\n  jQuery('<tr class=\"flower-species-list-entry\"><td><input type=\"hidden\" name=\"flower:taxa_taxon_list_id_list[]\" value=\"'+jQuery(this).val()+'\"\\>'+htmlspecialchars(jQuery(this).find('option[value='+jQuery(this).val()+']').text())+'</td><td><img class=\"removeRow\" src=\"/misc/watchdog-error.png\" alt=\"" . lang::get('Remove this entry') . "\" title=\"" . lang::get('Remove this entry') . "\"/></td></tr>').appendTo('#flower-species-list-body');\n  jQuery('#cc-2-flower-identify [name=flower\\:determination_type]').val('A');\n  jQuery('select#flowerSelect').val('');\n  jQuery('#id-flower-unknown').removeAttr('checked');\n  jQuery('#id-flower-later').removeAttr('checked').attr('disabled','disabled');\n});\nshowSessionsPanel = true;\n\nbuildMap = function (){\n\tif(jQuery('.poll-map-container:visible').length == 0) return; \n\tif(jQuery('#map').children().length == 0) {\n\t\t" . $map1JS . "\n  \t\tjQuery('#map')[0].map.searchLayer.events.register('featuresadded', {}, function(a1){\n\t\t\tif(inseeLayer != null) inseeLayer.destroyFeatures();\n\t\t});\n\t\tjQuery('#map')[0].map.editLayer.events.register('featuresadded', {}, function(a1){\n\t\t\tif(inseeLayer != null) inseeLayer.destroy();\n\t\t\tjQuery('#cc-2-loc-description').empty();\n\t\t  \tvar filter = new OpenLayers.Filter.Spatial({type: OpenLayers.Filter.Spatial.CONTAINS, property: 'the_geom', value: jQuery('#map')[0].map.editLayer.features[0].geometry});\n\t\t\tvar strategy = new OpenLayers.Strategy.Fixed({preload: false, autoActivate: false});\n\t\t\tvar styleMap = new OpenLayers.StyleMap({\"default\": new OpenLayers.Style({fillColor: \"Red\", strokeColor: \"Red\", fillOpacity: 0, strokeWidth: 1})});\n\t\t\tinseeLayer = new OpenLayers.Layer.Vector('INSEE Layer', {\n\t\t\t\tstyleMap: styleMap,\n\t\t\t\tstrategies: [strategy],\n\t\t\t\tdisplayInLayerSwitcher: false,\n\t\t\t\tprotocol: new OpenLayers.Protocol.WFS({\n\t\t\t\t\turl:  '" . str_replace("{HOST}", $_SERVER['HTTP_HOST'], $args['INSEE_url']) . "',\n\t\t\t\t\tfeaturePrefix: '" . $args['INSEE_prefix'] . "',\n\t\t\t\t\tfeatureType: '" . $args['INSEE_type'] . "',\n\t\t\t\t\tgeometryName:'the_geom',\n\t\t\t\t\tfeatureNS: '" . $args['INSEE_ns'] . "',\n\t\t\t\t\tsrsName: 'EPSG:900913',\n\t\t\t\t\tversion: '1.1.0'                  \n\t\t\t\t\t,propertyNames: ['the_geom', 'NOM', 'INSEE_NEW', 'DEPT_NUM', 'DEPT_NOM', 'REG_NUM', 'REG_NOM']\n\t\t\t\t}),\n\t\t\t\tfilter: filter\n\t\t\t});\n\t\t    inseeLayer.events.register('featuresadded', {}, function(a1){\n    \t\t\tif(a1.features.length > 0)\n\t\t\t    \tjQuery('<span>'+a1.features[0].attributes.NOM+' ('+a1.features[0].attributes.INSEE_NEW+'), '+a1.features[0].attributes.DEPT_NOM+' ('+a1.features[0].attributes.DEPT_NUM+'), '+a1.features[0].attributes.REG_NOM+' ('+a1.features[0].attributes.REG_NUM+')</span>').appendTo('#cc-2-loc-description');\n\t\t    });\n\t\t\tjQuery('#map')[0].map.addLayer(inseeLayer);\n\t\t\tstrategy.load({});\n\t\t});\n\t}\n}\n\nflowerIDstruc = {\n\ttype: 'flower',\n\tselector: '#cc-2-flower-identify',\n\tmainForm: 'form#cc-2-floral-station',\n\tuseKey: false,\n\tstoredTaxaList: [],\n\tname: 'flowerIDstruc',\n\ttaxaList: flowerTaxa\n};\n\ntoolPoller = function(toolStruct){\n\tif(toolStruct.sessionID == '') return;\n\ttoolStruct.pollTimer = setTimeout('toolPoller('+toolStruct.name+');', " . $args['ID_tool_poll_interval'] . ");\n\tjQuery.ajax({\n\t url: toolStruct.pollURL+toolStruct.sessionID,\n\t dataType: 'jsonp',\n     toolStruct: toolStruct,\n\t success: function(da){ // now jsonp form, so comes in already parsed.\n\t  pollReset(this.toolStruct);\n\t  var status = da.data.sddversion + ' : ' + JSON.stringify(da.data.history);\n      jQuery(this.toolStruct.selector+' [name='+this.toolStruct.type+'\\:taxon_details]').val(status); // Stores details how the identification was arrived at within the tool.\n      if(typeof da.urlimage != 'undefined' && da.urlimage != 'none'){\n        // Upload image file into server.\n        // TODO ids should be data driven from ID Struct items.\n        jQuery('#cc-4-insect-upload input[name=upload_file]').val('');\n        \$('#cc-4-insect-image').empty();\n        \$('#cc-4-insect-image').addClass('loading');\n        jQuery('form#cc-4-main-form input[name=occurrence_image\\:path]').val('');\n        \$.post('" . iform_ajaxproxy_url($node, 'remoteMedia') . "',\n\t\t\t{ website_id : '" . $args['website_id'] . "',\n\t\t\t  file_url : da.urlimage },\n\t\t\tfunction(data) {\n\t\t\t\t\$('#cc-4-insect-image').removeClass('loading');\n        \t\tif(data.success == true){\n\t        \t\t// There is only one file\n\t        \t\tjQuery('form#cc-4-main-form input[name=occurrence_image\\:path]').val(data.files[0].filename);\n\t        \t\tjQuery('#insect_picture_camera_attr').val(data.files[0].EXIF_Camera_Make);\n\t        \t\tjQuery('#insect_picture_datetime_attr').val(data.files[0].EXIF_DateTime);\n\t        \t\tinsertImage('med-'+data.files[0].filename, jQuery('#cc-4-insect-image'), " . $args['Insect_Image_Ratio'] . ");\n\t\t\t\t}  else\n\t\t\t\t\talertIndiciaError(data);\n\t\t\t},\n\t\t\t'json');\n      }\n      var items = da.data.itemsselected;\n\t  var count = items.length;\n\t  if(count <= 0){\n\t  \t// no valid stuff so blank it all out.\n\t  \tjQuery('#'+this.toolStruct.type+'_taxa_list').append(\"" . lang::get('LANG_Taxa_Unknown_In_Tool') . "\");\n\t  \tjQuery(this.toolStruct.selector+' [name='+this.toolStruct.type+'\\:determination_type]').val('X'); // Unidentified.\n      } else {\n      \tvar resultsIDs = [];\n      \tvar resultsText = \"" . lang::get('LANG_Taxa_Returned') . "<br />{ \";\n      \tvar notFound = '';\n\t\tfor(var j=0; j < count; j++){\n\t\t\tvar found = false;\n\t\t\tfor(i = 0; i< this.toolStruct.taxaList.length; i++){\n  \t\t\t\tif(this.toolStruct.taxaList[i].xperID == items[j].itemId){\n\t  \t\t\t\tresultsIDs.push(this.toolStruct.taxaList[i].id);\n\t  \t\t\t\tresultsText = resultsText + (j == 0 ? '' : '<br />&nbsp;&nbsp;') + htmlspecialchars(this.toolStruct.taxaList[i].taxon);\n\t  \t\t\t\tfound = true;\n\t  \t\t\t\tbreak;\n  \t\t\t\t}\n  \t\t\t};\n  \t\t\tif(!found){\n  \t\t\t\tnotFound = (notFound == '' ? '' : notFound + ', ') + items[j].itemId; // don't need special chars as going into an input field\n  \t\t\t}\n  \t\t}\n\t\tjQuery('#'+this.toolStruct.type+'_taxa_list').append(resultsText+ ' }');\n\t\tthis.toolStruct.storedTaxaList = resultsIDs;\n\t  \tif(notFound != ''){\n\t\t\tvar comment = jQuery('[name='+this.toolStruct.type+'\\:comment]');\n\t\t\tcomment.val('" . lang::get('LANG_ID_Unrecognised') . " '+notFound+'. '+comment.val());\n\t\t}\n  \t  }\n    }});\n};\n\npollReset = function(toolStruct){\n\tclearTimeout(toolStruct.timeOutTimer);\n\tclearTimeout(toolStruct.pollTimer);\n\tjQuery('#'+toolStruct.type+'-id-cancel').hide();\n\tjQuery('#'+toolStruct.type+'-id-button').show();\n\ttoolStruct.storedTaxaList = [];\n\tjQuery(toolStruct.selector+' [name='+toolStruct.type+'\\:taxon_details]').val('');\n\tjQuery('#'+toolStruct.type+'_taxa_list').empty();\n\ttoolStruct.sessionID='';\n\ttoolStruct.timeOutTimer = null;\n\ttoolStruct.pollTimer = null;\n};\n\nidButtonPressed = function(toolStruct){\n    if(!toolStruct.useKey) return;\n\tjQuery(toolStruct.selector+' [name='+toolStruct.type+'\\:determination_type]').val('A');\n\tjQuery('#id-'+toolStruct.type+'-later').removeAttr('checked');\n\ttoolStruct.storedTaxaList = [];\n\tjQuery(toolStruct.selector+' [name='+toolStruct.type+'\\:taxon_details]').val('');\n\tjQuery('#'+toolStruct.type+'_taxa_list').empty();\n\tjQuery(toolStruct.selector+' [name='+toolStruct.type+'\\:taxa_taxon_list_id]').val('');\n\tjQuery('#'+toolStruct.type+'-id-cancel').show();\n\tjQuery('#'+toolStruct.type+'-id-button').hide();\n\tvar d = new Date;\n\tvar s = d.getTime();\n\ttoolStruct.sessionID = '" . session_id() . "_'+s.toString()\n\tclearTimeout(toolStruct.timeOutTimer);\n\tclearTimeout(toolStruct.pollTimer);\n\tvar toolURL = toolStruct.invokeURL+'" . $args['ID_tool_session_param'] . "'+toolStruct.sessionID;\n\tvar path = jQuery('form#cc-4-main-form input[name=occurrence_image\\:path]').val();\n\tif(path != '') {\n    \tvar file = '" . data_entry_helper::$base_url . data_entry_helper::$indicia_upload_path . "'+path;\n    \ttoolURL += '&urlimageuser='******'','');\n\ttoolStruct.pollTimer = setTimeout('toolPoller('+toolStruct.name+');', " . $args['ID_tool_poll_interval'] . ");\n\ttoolStruct.timeOutTimer = setTimeout('toolReset('+toolStruct.name+');', " . $args['ID_tool_poll_timeout'] . ");\n};\n\ntaxonChosen = function(toolStruct){\n  \tjQuery('#id-'+toolStruct.type+'-later').removeAttr('checked');\n\ttoolStruct.storedTaxaList = [];\n\tjQuery(toolStruct.selector+' [name='+toolStruct.type+'\\:taxon_details]').val('');\n\tjQuery('#'+toolStruct.type+'_taxa_list').empty();\n\tjQuery('[name='+toolStruct.type+'\\:comment]').val('');\n\tjQuery(toolStruct.selector+' [name='+toolStruct.type+'\\:taxon_extra_info]').val('');\n\tjQuery(toolStruct.selector+' [name='+toolStruct.type+'\\:determination_type]').val('A');\n};\n\nidLater = function (toolStruct){\n  if (jQuery('#id-'+toolStruct.type+'later').attr('checked') != '') {\n    jQuery(toolStruct.selector+' [name='+toolStruct.type+'\\:determination_type]').val('A');\n    jQuery('.'+toolStruct.type+'-species-list-entry').remove();\n    jQuery('#id-'+toolStruct.type+'-unknown').removeAttr('checked');\n    toolStruct.storedTaxaList = [];\n    jQuery(toolStruct.selector+' [name='+toolStruct.type+'\\:taxon_details]').val('');\n    jQuery('#'+toolStruct.type+'_taxa_list').empty();\n    jQuery(toolStruct.selector+' [name='+toolStruct.type+'\\:taxa_taxon_list_id]').val('');\n    jQuery(toolStruct.selector+' [name='+toolStruct.type+'\\:taxon_extra_info]').val(''); // more precise info\n    jQuery('[name='+toolStruct.type+'\\:comment]').val('');\n  }\n};\njQuery('#id-flower-later').change(function (){\n\tidLater(flowerIDstruc);\n});\njQuery('#id-flower-unknown').change(function (){\n  if (jQuery('#id-flower-unknown').attr('checked') != '') {\n    jQuery('#id-flower-later').removeAttr('checked').attr('disabled','disabled');\n    jQuery('#cc-2-flower-identify [name=flower\\:determination_type]').val('X');\n    jQuery('.flower-species-list-entry').remove();\n    jQuery('#cc-2-flower-identify [name=flower\\:taxon_details]').val('');\n    jQuery('#cc-2-flower-identify [name=flower\\:taxa_taxon_list_id]').val('');\n    jQuery('#cc-2-flower-identify [name=flower\\:taxon_extra_info]').val(''); // more precise info\n    jQuery('[name=flower\\:comment]').val('');\n  } else\n    jQuery('#id-flower-later').removeAttr('disabled');\n});\njQuery('.removeRow').live('click', function (){\n  if(jQuery('.removeRow').length <= 1)\n    jQuery('#id-flower-later').removeAttr('disabled');\n  jQuery(this).closest('tr.flower-species-list-entry').remove();\n});\n\njQuery('#search-insee-button').click(function(){\n\tif(inseeLayer != null)\n\t\tinseeLayer.destroy();\n\tvar filters = [];\n  \tvar place = jQuery('input[name=place\\:INSEE]').val();\n  \tif(place == '" . lang::get('LANG_INSEE') . "') return;\n  \tfilters.push(new OpenLayers.Filter.Comparison({\n  \t\t\ttype: OpenLayers.Filter.Comparison.EQUAL_TO ,\n    \t\tproperty: 'INSEE_NEW',\n    \t\tvalue: place\n  \t\t}));\n  \tfilters.push(new OpenLayers.Filter.Comparison({\n  \t\t\ttype: OpenLayers.Filter.Comparison.EQUAL_TO ,\n    \t\tproperty: 'INSEE_OLD',\n    \t\tvalue: place\n  \t\t}));\n\n\tvar strategy = new OpenLayers.Strategy.Fixed({preload: false, autoActivate: false});\n\tvar styleMap = new OpenLayers.StyleMap({\n                \"default\": new OpenLayers.Style({\n                    fillColor: \"Red\",\n                    strokeColor: \"Red\",\n                    fillOpacity: 0,\n                    strokeWidth: 1\n                  })\n\t});\n\tinseeLayer = new OpenLayers.Layer.Vector('INSEE Layer', {\n\t\t  styleMap: styleMap,\n          strategies: [strategy],\n          displayInLayerSwitcher: false,\n\t      protocol: new OpenLayers.Protocol.WFS({\n              url:  '" . str_replace("{HOST}", $_SERVER['HTTP_HOST'], $args['INSEE_url']) . "',\n              featurePrefix: '" . $args['INSEE_prefix'] . "',\n              featureType: '" . $args['INSEE_type'] . "',\n              geometryName:'the_geom',\n              featureNS: '" . $args['INSEE_ns'] . "',\n              srsName: 'EPSG:900913',\n              version: '1.1.0'                  \n      \t\t  ,propertyNames: ['the_geom']\n  \t\t\t}),\n  \t\t  filter: new OpenLayers.Filter.Logical({\n\t\t\t      type: OpenLayers.Filter.Logical.OR,\n\t\t\t      filters: filters\n\t\t  })\n    });\n\tinseeLayer.events.register('featuresadded', {}, function(a1){\n\t\tvar div = jQuery('#map')[0];\n\t\tdiv.map.searchLayer.destroyFeatures();\n\t\tvar bounds=inseeLayer.getDataExtent();\n    \tvar dy = (bounds.top-bounds.bottom)/10;\n    \tvar dx = (bounds.right-bounds.left)/10;\n    \tbounds.top = bounds.top + dy;\n    \tbounds.bottom = bounds.bottom - dy;\n    \tbounds.right = bounds.right + dx;\n    \tbounds.left = bounds.left - dx;\n    \t// if showing a point, don't zoom in too far\n    \tif (dy===0 && dx===0) {\n    \t\tdiv.map.setCenter(bounds.getCenterLonLat(), div.settings.maxZoom);\n    \t} else {\n    \t\tdiv.map.zoomToExtent(bounds);\n    \t}\n    });\n\tinseeLayer.events.register('loadend', {}, function(){\n\t\tif(inseeLayer.features.length == 0){\n\t\t\talert(\"" . lang::get('LANG_NO_INSEE') . "\");\n\t\t}\n    });\n    jQuery('#map')[0].map.addLayer(inseeLayer);\n\tstrategy.load({});\n});\n\nvalidateStationPanel = function(){\n\tvar myPanel = jQuery('#cc-2');\n\tvar valid = true;\n\tclearErrors('form#cc-2-floral-station');\n\tclearErrors('#cc-2-flower-identify');\n\tif(myPanel.filter(':visible').length == 0) return true; // panel is not visible so no data to fail validation.\n\tif(myPanel.find('.poll-section-body:visible').length == 0) return true; // body hidden so data already been validated successfully.\n\t// If no data entered also return true: this can only be the case when pressing the modify button on the collections panel\n\tif(jQuery('form#cc-2-floral-station > input[name=location_image\\:path]').val() == '' &&\n\t\t\tjQuery('form#cc-2-floral-station > input[name=occurrence\\:id]').val() == '' &&\n\t\t\tjQuery('form#cc-2-floral-station > input[name=occurrence_image\\:path]').val() == '' &&\n\t\t\tjQuery('.flower-species-list-entry').length == 0 &&\n\t\t\tjQuery('#cc-2-flower-identify [name=flower\\:taxon_extra_info]').val() == '' &&\n\t\t\tjQuery('[name=flower\\:comment]').val() == '' &&\n\t\t\tjQuery('[name=occAttr\\:" . $args['flower_type_attr_id'] . "],[name^=occAttr\\:" . $args['flower_type_attr_id'] . "\\:]').filter('[checked]').length == 0 &&\n\t\t\tjQuery('[name=locAttr\\:" . $args['within50m_attr_id'] . "],[name^=locAttr\\:" . $args['within50m_attr_id'] . "\\:]').filter('[checked]').length == 0 &&\n\t\t\tjQuery('[name=locAttr\\:" . $args['habitat_attr_id'] . "],[name^=locAttr\\:" . $args['habitat_attr_id'] . "\\:]').filter('[checked]').length == 0 &&\n    \t\tjQuery('[name=locAttr\\:" . $args['distance_attr_id'] . "],[name^=locAttr\\:" . $args['distance_attr_id'] . "\\:]').val() == '') {\n\t\tjQuery('#cc-2').foldPanel();\n\t\treturn true;\n\t}\n    if(jQuery('form#cc-2-floral-station > input[name=location_image\\:path]').val() == '' ||\n\t\t\t\t\tjQuery('form#cc-2-floral-station > input[name=occurrence_image\\:path]').val() == ''){\n\t\tif(jQuery('form#cc-2-floral-station > input[name=occurrence_image\\:path]').val() == '')\n\t\t\tmyScrollTo('#cc-2-flower-upload');\n\t\telse\n\t\t\tmyScrollTo('#cc-2-environment-upload');\n\t\talert(\"" . lang::get('LANG_Must_Provide_Pictures') . "\");\n\t\tvalid = false;\n\t}\n    if(jQuery('#imp-geom').val() == '') {\n\t\talert(\"" . lang::get('LANG_Must_Provide_Location') . "\");\n\t\tmyScrollTo('.poll-map-container');\n\t\tvalid = false;\n\t}\n\tif (jQuery('#id-flower-later').attr('checked') == '' && jQuery('#id-flower-unknown').attr('checked') == '' && jQuery('.flower-species-list-entry').length == 0){\n\t\talert(\"" . lang::get('LANG_Must_Provide_Identification') . "\");\n\t\tmyScrollTo('#id-flower-later');\n\t\tvalid = false;\n    }\n\tif (!jQuery('form#cc-2-floral-station > input').valid()) { valid = false; }\n\tif (!validateRadio('occAttr\\:" . $args['flower_type_attr_id'] . "', 'form#cc-2-floral-station')) { valid = false; }\n\tif (!validateRadio('locAttr\\:" . $args['within50m_attr_id'] . "', 'form#cc-2-floral-station')) { valid = false; }\n\tif (!validateOptInt('locAttr\\:" . $args['distance_attr_id'] . "', 'form#cc-2-floral-station')) { valid = false; }\n   \tif ( valid == false ) {\n   \t\tmyScrollToError();\n   \t\treturn valid;\n   \t}\n\tshowSessionsPanel = false;\n\tjQuery('form#cc-2-floral-station').submit();\n\treturn true;\n};\n\n// Flower upload picture form.\n\$('#cc-2-flower-upload').ajaxForm({ \n\t\tasync: false,\n\t\tdataType:  'json', \n        beforeSubmit:   function(data, obj, options){\n         \tif (!jQuery('form#cc-2-flower-upload').valid() ||\n                    jQuery('#cc-2-flower-image').hasClass('loading')) {\n   \t\t\t\treturn false;\n   \t\t\t}\n   \t\t\t\$('#cc-2-flower-image').empty();\n        \t\$('#cc-2-flower-image').addClass('loading');\n\t\t   \tjQuery('form#cc-2-floral-station input[name=occurrence_image\\:path]').val('');\n  \t\t},\n        success:   function(data){\n        \tif(data.success == true){\n\t        \t// There is only one file\n\t        \tjQuery('form#cc-2-floral-station input[name=occurrence_image\\:path]').val(data.files[0].filename);\n\t        \tjQuery('#flower_picture_camera_attr').val(data.files[0].EXIF_Camera_Make);\n\t        \tjQuery('#flower_picture_datetime_attr').val(data.files[0].EXIF_DateTime);\n\t        \tinsertImage('med-'+data.files[0].filename, jQuery('#cc-2-flower-image'), " . $args['Flower_Image_Ratio'] . ");\n\t        \tjQuery('#cc-2-flower-upload input[name=upload_file]').val('');\n  \t\t\t} else\n\t\t\t\talertIndiciaError(data);\n  \t\t},\n  \t\tcomplete: function(){\n\t\t\t\$('#cc-2-flower-image').removeClass('loading');\n  \t\t}\n});\n\n// Flower upload picture form.\n\$('#cc-2-environment-upload').ajaxForm({ \n\t\tasync: false,\n\t\tdataType:  'json', \n        beforeSubmit:   function(data, obj, options){\n         \tif (!jQuery('form#cc-2-environment-upload').valid()) {\n   \t\t\t\treturn false;\n   \t\t\t}\n        \t\$('#cc-2-environment-image').empty();\n        \t\$('#cc-2-environment-image').addClass('loading')\n\t       \tjQuery('form#cc-2-floral-station input[name=location_image\\:path]').val('');\n  \t\t},\n        success:   function(data){\n        \tif(data.success == true){\n\t        \t// There is only one file\n\t        \tjQuery('form#cc-2-floral-station input[name=location_image\\:path]').val(data.files[0].filename);\n\t        \tjQuery('#location_picture_camera_attr').val(data.files[0].EXIF_Camera_Make);\n\t        \tjQuery('#location_picture_datetime_attr').val(data.files[0].EXIF_DateTime);\n\t        \tinsertImage('med-'+data.files[0].filename, jQuery('#cc-2-environment-image'), " . $args['Environment_Image_Ratio'] . ");\n\t\t\t\tjQuery('#cc-2-environment-upload input[name=upload_file]').val('');\n\t\t\t} else\n\t\t\t\talertIndiciaError(data);\n        },\n  \t\tcomplete: function(){\n\t\t\t\$('#cc-2-environment-image').removeClass('loading');\n  \t\t}\n});\n\nfindID = function(name, data){\n\tfor(var i=0; i< data.length;i++){\n\t\tif(data[i].name == name) return i;\n\t}\n};\n\n\$('#cc-2-floral-station').ajaxForm({ \n\tasync: false,\n\tdataType:  'json', \n    beforeSubmit:   function(data, obj, options){\n\t\tvar valid = true;\n\t\tclearErrors('form#cc-2-floral-station');\n\t\tclearErrors('#cc-2-flower-identify');\n    \tif(jQuery('form#cc-2-floral-station > input[name=location_image\\:path]').val() == '' ||\n\t\t\t\t\tjQuery('form#cc-2-floral-station > input[name=occurrence_image\\:path]').val() == '' ){\n\t\t\tif(jQuery('form#cc-2-floral-station > input[name=occurrence_image\\:path]').val() == '')\n\t\t\t\tmyScrollTo('#cc-2-flower-upload');\n\t\t\telse\n\t\t\t\tmyScrollTo('#cc-2-environment-upload');\n\t\t\talert(\"" . lang::get('LANG_Must_Provide_Pictures') . "\");\n\t\t\tvalid = false;\n\t\t}\n\t\tif(jQuery('#imp-geom').val() == '') {\n\t\t\tmyScrollTo('.poll-map-container');\n\t\t\talert(\"" . lang::get('LANG_Must_Provide_Location') . "\");\n\t\t\tvalid = false;\n\t\t}\n\t\tif (!jQuery('form#cc-2-floral-station > input').valid()) { valid = false; }\n\t\tif (!validateRadio('occAttr\\:" . $args['flower_type_attr_id'] . "', 'form#cc-2-floral-station')) { valid = false; }\n\t\tif (!validateRadio('locAttr\\:" . $args['within50m_attr_id'] . "', 'form#cc-2-floral-station')) { valid = false; }\n\t\tif (!validateOptInt('locAttr\\:" . $args['distance_attr_id'] . "', 'form#cc-2-floral-station')) { valid = false; }\n\t\tdata[findID('location:centroid_sref', data)].value = jQuery('#imp-sref').val();\n\t\tdata[findID('location:centroid_geom', data)].value = jQuery('#imp-geom').val();\n\t\tif (jQuery('#id-flower-later').attr('checked') == ''){\n\t\t    var entries = jQuery('.flower-species-list-entry');\n\t\t    if (jQuery('#id-flower-unknown').attr('checked') == '' && entries.length == 0){\n\t\t      alert(\"" . lang::get('LANG_Must_Provide_Identification') . "\");\n\t\t      myScrollTo('#id-flower-later');\n\t\t      valid = false;\n            }\n\t\t    data[findID('determination:taxa_taxon_list_id', data)].value = '';\n\t\t\tdata[findID('determination:taxon_details', data)].value = jQuery('#cc-2-flower-identify [name=flower\\:taxon_details]').val();\n\t\t\tdata[findID('determination:taxon_extra_info', data)].value = jQuery('#cc-2-flower-identify [name=flower\\:taxon_extra_info]').val();\n\t\t\tdata[findID('determination:comment', data)].value = jQuery('[name=flower\\:comment]').val();\n\t\t\tdata[findID('determination:determination_type', data)].value = jQuery('#cc-2-flower-identify [name=flower\\:determination_type]').val();\n\t\t\tif (data[findID('determination:determination_type', data)].value == 'A'){\n\t\t\t  if(entries.length == 1)\n\t\t\t    data[findID('determination:taxa_taxon_list_id', data)].value = jQuery(entries[0]).find('input').val();\n\t\t\t  else\n\t\t\t    for(var i = 0; i< entries.length; i++){\n\t\t\t\t  data.push({name: 'determination\\:taxa_taxon_list_id_list[]', value: jQuery(entries[i]).find('input').val()});\n                }\n\t\t\t}\n\t\t} else { // ID later - remove determination entries from form.\n\t\t    data.splice(findID('determination:taxa_taxon_list_id', data),1);\n\t\t\tdata.splice(findID('determination:taxon_details', data),1);\n\t\t\tdata.splice(findID('determination:taxon_extra_info', data),1);\n\t\t\tdata.splice(findID('determination:comment', data),1);\n\t\t\tdata.splice(findID('determination:determination_type', data),1);\n\t\t\tdata.splice(findID('determination:cms_ref', data),1);\n\t\t\tdata.splice(findID('determination:email_address', data),1);\n\t\t\tdata.splice(findID('determination:person_name', data),1);\n\t\t\t// data.splice(12,8); \n\t\t}\n   \t\tif ( valid == false ) {\n\t\t\tmyScrollToError();\n\t\t\treturn false;\n\t\t};\n  \t\tjQuery('#cc-2-valid-button').addClass('loading-button');\n   \t\treturn true;\n\t},\n    success:   function(data){\n       \tif(data.success == 'multiple records' && data.outer_table == 'sample'){\n       \t\t// the sample and location ids are already fixed, so just need to populate the occurrence and image IDs, and rename the location and occurrence attribute.\n\t\t\t// ONLY 1 CHILD, THE OCCURRENCE: TBD ADD CHECK THAT IF ALREADY EXISTS THAT VALUES ARE THE SAME.\n\t\t\tjQuery('#cc-2-floral-station > input[name=occurrence\\:id]').removeAttr('disabled').val(data.struct.children[0].id);\n\t\t\t// the occurrence has whole range of children: attributes, image and determination.\n\t\t\tloadAttributes('#cc-2-floral-station', 'occurrence_attribute_value', 'occurrence_attribute_id', 'occurrence_id', data.struct.children[0].id, 'occAttr', false, true);\n\t\t\tfor(i=0; i<data.struct.children[0].children.length; i++){\n\t\t\t\tif(data.struct.children[0].children[i].model == 'occurrence_image'){\n\t\t\t\t\tjQuery('#cc-2-floral-station > input[name=occurrence_image\\:id]').removeAttr('disabled').val(data.struct.children[0].children[i].id);}\n\t\t\t\tif(data.struct.children[0].children[i].model == 'determination'){\n\t\t\t\t\tjQuery('#cc-2-floral-station > input[name=determination\\:id]').removeAttr('disabled').val(data.struct.children[0].children[i].id);}\n\t\t\t}\n\t\t\t// ONLY 1 PARENT, THE LOCATION: TBD ADD CHECK THAT IF ALREADY EXISTS THAT VALUES ARE THE SAME.\n\t\t    var location_id = jQuery('#cc-2-floral-station > input[name=location\\:id]').val();\n       \t\tloadAttributes('#cc-2-floral-station', 'location_attribute_value', 'location_attribute_id', 'location_id', location_id, 'locAttr', true, true);\n\t\t\tfor(i=0; i<data.struct.parents[0].children.length; i++){\n\t\t\t\tif(data.struct.parents[0].children[i].model == 'location_image'){\n\t\t\t\t\tjQuery('#cc-2-floral-station > input[name=location_image\\:id]').removeAttr('disabled').val(data.struct.parents[0].children[i].id);}}\n\t\t\tjQuery('#cc-2').foldPanel();\n\t\t\tif(showSessionsPanel) { jQuery('#cc-3').showPanel(); }\n\t\t\tshowSessionsPanel = true;\n        }  else {\n\t\t\tif(data.error){\n\t\t\t\tvar lastIndex = data.error.lastIndexOf('Validation error'); \n    \t\t\tif (lastIndex != -1 && lastIndex  == (data.error.length - 16)){ \n\t\t\t\t\tif(data.errors){\n\t\t\t\t\t\tif(data.errors['location:centroid_sref']){\n\t\t\t\t\t\t\tvar label = \$('<p/>')\n\t\t\t\t\t\t\t\t.addClass('inline-error')\n\t\t\t\t\t\t\t\t.html(\"" . lang::get('LANG_Invalid_Location') . "\");\n\t\t\t\t\t\t\tlabel.insertBefore('.latLongDiv:first');\n\t\t\t\t\t\t\tmyScrollToError();\n\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\talertIndiciaError(data);\n\t\t}\n\t},\n    complete: function (){\n  \t\tjQuery('.loading-button').removeClass('loading-button');\n  \t}\n});\n\n\$('#cc-2-valid-button').click(function() {\n\tjQuery('#cc-2-floral-station').submit();\n});\n\n";
        // Sessions.
        $r .= '
<div id="cc-3" class="poll-section">
  <div id="cc-3-title" class="ui-accordion-header ui-helper-reset ui-state-active ui-corner-all poll-section-title"><span id="cc-3-title-title" >' . lang::get('LANG_Sessions_Title') . '</span>
    <div id="cc-3-mod-button" class="right ui-state-default ui-corner-all mod-button">' . lang::get('LANG_Modify') . '</div>
  </div>
  <div id="cc-3-body" class="ui-accordion-content ui-helper-reset ui-widget-content ui-corner-top ui-accordion-content-active poll-section-body">
  </div>
  <div id="cc-3-footer" class="ui-accordion-content ui-helper-reset ui-widget-content ui-corner-bottom ui-accordion-content-active poll-section-footer">
	<div id="cc-3-add-button" class="ui-state-default ui-corner-all add-button">' . lang::get('LANG_Add_Session') . '</div>
    <div id="cc-3-valid-button" class="ui-state-default ui-corner-all save-button">' . lang::get('LANG_Validate_Session') . '</div>
  </div>
</div>
<div style="display:none" />
    <form id="cc-3-delete-session" action="' . iform_ajaxproxy_url($node, 'sample') . '" method="POST">
       <input type="hidden" name="website_id" value="' . $args['website_id'] . '" />
       <input type="hidden" name="sample:survey_id" value="' . $args['survey_id'] . '" />
       <input type="hidden" name="sample:id" value="" />
       <input type="hidden" name="sample:date" value="2010-01-01"/>
       <input type="hidden" name="sample:location_id" value="" />
       <input type="hidden" name="sample:deleted" value="t" />
    </form>
</div>';
        data_entry_helper::$javascript .= "\n\$('#cc-3-delete-session').ajaxForm({ \n\t\tasync: false,\n\t\tdataType:  'json', \n\t\tbeforeSubmit:   function(data, obj, options){\n\t\t\t// Warning this assumes that the data is fixed position:\n\t\t\tdata[4].value = jQuery('#cc-1-collection-details input[name=location\\:id]').val();\n\t\t\tif(data[2].value == '') return false;\n\t\t\t// double check that location id is filled in\n\t\t\tif(data[4].value == ''){\n\t\t\t\talertIndiciaError({error : \"" . lang::get('Internal Error 7: location id not set, so unsafe to delete session.') . "\"});\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\t// don't have to worry about parent_id\n\t\t\treturn true;\n  \t\t},\n        success:   function(data){\n        \tif(data.success != 'multiple records' || data.outer_table != 'sample')\n\t\t\t\talertIndiciaError(data);\n  \t\t}\n        ,complete: function (){\n  \t\t\tjQuery('.loading-button').removeClass('loading-button');\n  \t\t}\n});\npopulateSessionSelect = function(){\n\tvar insectSessionSelect = jQuery('form#cc-4-main-form > select[name=occurrence\\:sample_id]');\n\tvar value = insectSessionSelect.val();\n\tinsectSessionSelect.empty();\n\t// NB at this point the attributes have been loaded so have full name.\n\t\$('.poll-session-form').each(function(i){\n\t\tjQuery('<option value=\"'+\n\t\t\t\tjQuery(this).children('input[name=sample\\:id]').val()+\n\t\t\t\t'\">'+\n\t\t\t\tjQuery(this).children('input[name=dummy_date]').val()+\n\t\t\t\t' : '+\n\t\t\t\tjQuery(this).children('[name=smpAttr\\:" . $args['start_time_attr_id'] . "],[name^=smpAttr\\:" . $args['start_time_attr_id'] . "\\:]').val()+\n\t\t\t\t' > '+\n\t\t\t\tjQuery(this).children('[name=smpAttr\\:" . $args['end_time_attr_id'] . "],[name^=smpAttr\\:" . $args['end_time_attr_id'] . "\\:]').val()+\n\t\t\t\t'</option>')\n\t\t\t.appendTo(insectSessionSelect);\n\t});\n\tinsectSessionSelect.find('option').each(function(i,obj){\n  \t\tif(i == 0 || jQuery(obj).val() == value)\n\t\t\tinsectSessionSelect.val(insectSessionSelect.find('option').filter(':first').val());\n  \t});\n}\ncompareTimes = function(nameStart, nameEnd, formSel){\n    var controlStart = jQuery(formSel).find('[name='+nameStart+'],[name^='+nameStart+'\\:]');\n    var controlEnd = jQuery(formSel).find('[name='+nameEnd+'],[name^='+nameEnd+'\\:]');\n    var valueStart = controlStart.val().split(':');\n    var valueEnd = controlEnd.val().split(':');\n    var minsDiff = (valueEnd[0]-valueStart[0])*60+(valueEnd[1]-valueStart[1]);\n    if(minsDiff < 0){\n        \$('<p/>').attr({'for': nameEnd}).addClass('inline-error').html(\"" . lang::get('validation_endtime_before_start') . "\").insertBefore(controlEnd);\n\t\treturn false;\n    }\n    // The Flash selection is first, Long second for the protocol: So\n    var isFlashProtocol = jQuery('[name=smpAttr\\:" . $args['protocol_attr_id'] . "],[name^=smpAttr\\:" . $args['protocol_attr_id'] . "\\:]').filter(':first').filter('[checked]').length >0;\n    if(!isFlashProtocol && minsDiff < 20){ // Long Protocol, session must not be less than 20mins\n        \$('<p/>').attr({'for': nameStart}).addClass('inline-error').html(\"" . lang::get('validation_time_less_than_20') . "\").insertBefore(controlStart);\n        \$('<p/>').attr({'for': nameEnd}).addClass('inline-error').html(\"" . lang::get('validation_please_check') . "\").insertBefore(controlEnd);\n\t\treturn false;\n    }\n    if(isFlashProtocol && minsDiff != 20){ // Flash Protocol, session must be exactly 20mins\n        \$('<p/>').attr({'for': nameStart}).addClass('inline-error').html(\"" . lang::get('validation_time_not_20') . "\").insertBefore(controlStart);\n        \$('<p/>').attr({'for': nameEnd}).addClass('inline-error').html(\"" . lang::get('validation_please_check') . "\").insertBefore(controlEnd);\n\t\treturn false;\n    }\n    return true;\n}\nconvertDate = function(dateStr){\n\t// Converts a YYYY-MM-DD date to YYYY/MM/DD so IE can handle it.\n\treturn dateStr.slice(0,4)+'/'+dateStr.slice(5,7)+'/'+dateStr.slice(8,10);\n} \n\ncheckDate = function(name, formSel){\n  var control = jQuery(formSel).find('[name='+name+']');\n  var session = this;\n  var dateError = false;\n  var d2 = new Date(convertDate(control.val()));\n  var two_days=1000*60*61*(24+25); // allows a bit of leaway, plus extra hour for Day light saving transition. (milliSeconds)\n  jQuery('.required').filter('[name=sample:date]').each(function(){\n    var d1 = new Date(convertDate(jQuery(this).val()));\n    if(Math.abs(d1.getTime()-d2.getTime()) > two_days){\n      dateError=true;\n    }\n  });\n  if(dateError){\n    \$('<p/>').attr({'for': name}).addClass('inline-error').html(\"" . lang::get('validation_session_date_error') . "\").insertBefore(control);\n    return false;\n  };\n  return true;\n}\n\nvalidateAndSubmitOpenSessions = function(){\n\tvar valid = true;\n\t// only check the visible forms as rest have already been validated successfully.\n\t\$('.poll-session-form:visible').each(function(i){\n\t\tclearErrors(this);\n   \t\tif (valid && !checkDate('sample\\:date', this)) { valid = false; }\n\t\tif (!jQuery(this).children('input').valid()) { valid = false; }\n\t    if (!validateTime('smpAttr\\:" . $args['start_time_attr_id'] . "', this)) { valid = false; }\n   \t\tif (!validateTime('smpAttr\\:" . $args['end_time_attr_id'] . "', this)) { valid = false; }\n   \t\tif (valid && !compareTimes('smpAttr\\:" . $args['start_time_attr_id'] . "', 'smpAttr\\:" . $args['end_time_attr_id'] . "', this)) { valid = false; }\n   \t\tif (!validateRadio('smpAttr\\:" . $args['sky_state_attr_id'] . "', this)) { valid = false; }\n   \t\tif (!validateRadio('smpAttr\\:" . $args['temperature_attr_id'] . "', this)) { valid = false; }\n   \t\tif (!validateRadio('smpAttr\\:" . $args['wind_attr_id'] . "', this)) { valid = false; }\n   \t\tif (!validateRadio('smpAttr\\:" . $args['shade_attr_id'] . "', this)) { valid = false; }\n   });\n\tif(valid == false) {\n\t\tmyScrollToError();\n\t\treturn false;\n\t};\n\t\$('.poll-session-form:visible').submit();\n\treturn true;\n}\n\naddSession = function(){\n\tsessionCounter = sessionCounter + 1;\n\t// dynamically build the contents of the session block.\n\tvar newSession = jQuery('<div id=\"cc-3-session-'+sessionCounter+'\" class=\"poll-session\"/>')\n\t\t.appendTo('#cc-3-body');\n\tvar newTitle = jQuery('<div class=\"poll-session-title\">" . lang::get('LANG_Session') . " '+sessionCounter+'</div>')\n\t\t.appendTo(newSession);\n\tvar newModButton = jQuery('<div class=\"right ui-state-default ui-corner-all mod-button\">" . lang::get('LANG_Modify') . "</div>')\n\t\t.appendTo(newTitle).hide();\n\tvar newDeleteButton = jQuery('<div class=\"right ui-state-default ui-corner-all delete-button\">" . lang::get('LANG_Delete_Session') . "</div>')\n\t\t.appendTo(newTitle);\t\n\tnewModButton.click(function() {\n\t\tif(!validateAndSubmitOpenSessions()) return false;\n\t\tvar session=\$(this).parents('.poll-session');\n\t\tsession.show();\n\t\tsession.children().show();\n\t\tsession.children(':first').children(':first').hide(); // this is the mod button itself\n    });\n    var formContainer = jQuery('<div />').appendTo(newSession);\n    var newForm = jQuery('<form action=\"" . iform_ajaxproxy_url($node, 'sample') . "\" method=\"POST\" class=\"poll-session-form\" />').appendTo(formContainer);\n\tjQuery('<input type=\"hidden\" name=\"website_id\" value=\"" . $args['website_id'] . "\" />').appendTo(newForm);\n\tjQuery('<input type=\"hidden\" name=\"sample:survey_id\" value=\"" . $args['survey_id'] . "\" />').appendTo(newForm);\n\tjQuery('<input type=\"hidden\" name=\"sample:parent_id\" />').appendTo(newForm).val(jQuery('#cc-1-collection-details > input[name=sample\\:id]').val());\n\tjQuery('<input type=\"hidden\" name=\"sample:location_id\" />').appendTo(newForm).val(jQuery('#cc-1-collection-details > input[name=location\\:id]').val());\n\tjQuery('<input type=\"hidden\" name=\"sample:id\" value=\"\" disabled=\"disabled\" />').appendTo(newForm);\n";
        if ($use_help) {
            data_entry_helper::$javascript .= "\n\tvar helpDiv = jQuery('<div class=\"right ui-state-default ui-corner-all help-button\">" . lang::get('LANG_Help_Button') . "</div>');\n\thelpDiv.click(function(){\n\t\t" . $args['help_function'] . "(" . $args['help_session_arg'] . ");\n\t});\n\thelpDiv.appendTo(newForm);";
        }
        // we have to be careful with the dates: Indicia supplies dates as YYYY-MM-DD, but this is not ready understood by the IE JS Date, which is OK with YYYY/MM/DD.
        // We keep the YYYY-MM-DD internally for consistency.
        data_entry_helper::$javascript .= "\n\tvar dateID = 'cc-3-session-date-'+sessionCounter;\n\tvar dateAttr = '<label for=\"'+dateID+'\">" . lang::get('LANG_Date') . " :</label><input type=\"text\" size=\"10\" class=\"vague-date-picker required\" id=\"'+dateID+'\" name=\"dummy_date\" value=\"" . lang::get('click here') . "\" /> ';\n\tdateAttr = dateAttr + '<input type=\"hidden\" id=\"real-'+dateID+'\" name=\"sample:date\" value=\"\" class=\"required\"/> ';\n    jQuery(dateAttr).appendTo(newForm);\n\tjQuery('#'+dateID).datepicker({\n\t\tdateFormat : 'dd/mm/yy',\n\t\tconstrainInput: false,\n\t\tmaxDate: '0',\n\t\taltField : '#real-'+dateID,\n\t\taltFormat : 'yy-mm-dd'\n\t});\n    jQuery('" . str_replace("\n", "", data_entry_helper::outputAttribute($sample_attributes[$args['start_time_attr_id']], $defAttrOptions)) . "').appendTo(newForm);\n\tjQuery('" . str_replace("\n", "", data_entry_helper::outputAttribute($sample_attributes[$args['end_time_attr_id']], $defAttrOptions)) . "').appendTo(newForm);\n\tjQuery('" . str_replace("\n", "", data_entry_helper::outputAttribute($sample_attributes[$args['sky_state_attr_id']], $defNRAttrOptions)) . "').appendTo(newForm);\n\tjQuery('" . str_replace("\n", "", data_entry_helper::outputAttribute($sample_attributes[$args['temperature_attr_id']], $defNRAttrOptions)) . "').appendTo(newForm);\n\tjQuery('" . str_replace("\n", "", data_entry_helper::outputAttribute($sample_attributes[$args['wind_attr_id']], $defNRAttrOptions)) . "').appendTo(newForm);\n\tjQuery('" . str_replace("\n", "", data_entry_helper::outputAttribute($sample_attributes[$args['shade_attr_id']], array_merge($defNRAttrOptions, array('default' => '-1')))) . "').appendTo(newForm);\n\tnewDeleteButton.click(function() {\n\t\tvar container = \$(this).parent().parent();\n\t\tjQuery('#cc-3-delete-session').find('[name=sample\\:id]').val(container.find('[name=sample\\:id]').val());\n\t\tjQuery('#cc-3-delete-session').find('[name=sample\\:date]').val(container.find('[name=sample\\:date]').val());\n\t\tjQuery('#cc-3-delete-session').find('[name=sample\\:location_id]').val(container.find('[name=sample\\:location_id]').val());\n\t\tif(container.find('[name=sample\\:id]').filter('[disabled]').length == 0){\n\t\t\tjQuery(this).addClass('loading-button');\n\t\t\t\$.getJSON(\"" . $svcUrl . "/data/occurrence/\" +\n\t\t\t\t\t\"?mode=json&view=detail&reset_timeout=true&nonce=" . $readAuth['nonce'] . "&auth_token=" . $readAuth['auth_token'] . "\" +\n\t\t\t\t\t\"&sample_id=\"+container.find('[name=sample\\:id]').val()+\"&deleted=f&callback=?\", function(insectData) {\n\t\t\t\tif(!(insectData instanceof Array)){\n   \t\t\t\t\talertIndiciaError(insectData);\n   \t\t\t\t} else if (insectData.length>0) {\n\t\t\t\t\tjQuery('.loading-button').removeClass('loading-button');\n\t\t\t\t\talert(\"" . lang::get('LANG_Cant_Delete_Session') . "\");\n\t\t\t\t} else if(confirm(\"" . lang::get('LANG_Confirm_Session_Delete') . "\")){\n\t\t\t\t\tjQuery('#cc-3-delete-session').submit();\n\t\t\t\t\tcontainer.remove();\n\t\t\t\t\tcheckSessionButtons();\n\t\t\t\t}\n\t\t\t});\n\t\t} else if(confirm(\"" . lang::get('LANG_Confirm_Session_Delete') . "\")){\n\t\t\tcontainer.remove();\n\t\t\tcheckSessionButtons();\n\t\t}\n    });\n    newForm.ajaxForm({\n   \t\tasync: false,\n    \tdataType:  'json',\n    \tbeforeSubmit:   function(data, obj, options){\n\t\t\t// double check that location id and sample id are filled in\n\t\t\tif(jQuery('#cc-1-collection-details input[name=location\\:id]').val() == ''){\n\t\t\t\talertIndiciaError({error : \"" . lang::get('Internal Error 8: location id not set, so unsafe to save session.') . "\"});\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\tif(jQuery('#cc-1-collection-details input[name=sample\\:id]').val() == ''){\n\t\t\t\talertIndiciaError({error : \"" . lang::get('Internal Error 9: sample id not set, so unsafe to save session.') . "\"});\n\t\t\t\treturn false;\n\t\t\t}\n\t    \tvar valid = true;\n    \t\tclearErrors(obj);\n    \t\tif (!obj.find('input').valid()) {\n    \t\t\tvalid = false; }\n    \t\tif (!validateRadio('smpAttr\\:" . $args['sky_state_attr_id'] . "', obj)) { valid = false; }\n   \t\t\tif (!validateRadio('smpAttr\\:" . $args['temperature_attr_id'] . "', obj)) { valid = false; }\n   \t\t\tif (!validateRadio('smpAttr\\:" . $args['wind_attr_id'] . "', obj)) { valid = false; }\n   \t\t\tif (!validateRadio('smpAttr\\:" . $args['shade_attr_id'] . "', obj)) { valid = false; }\n   \t\t\tdata[2].value = jQuery('#cc-1-collection-details > input[name=sample\\:id]').val();\n\t\t\tdata[3].value = jQuery('#cc-1-collection-details > input[name=location\\:id]').val();\n\t\t\tjQuery('#cc-3-valid-button').addClass('loading-button');\n\t\t\tif(!valid) myScrollToError();\n\t\t\treturn valid;\n\t\t},\n   \t    success:   function(data, status, form){\n   \t    \tvar thisSession = form.parents('.poll-session');\n    \t\tif(data.success == 'multiple records' && data.outer_table == 'sample'){\n   \t    \t    form.children('input[name=sample\\:id]').removeAttr('disabled').val(data.outer_id);\n   \t    \t    loadAttributes(form, 'sample_attribute_value', 'sample_attribute_id', 'sample_id', data.outer_id, 'smpAttr', true, true);\n\t\t\t\tthisSession.show();\n\t\t\t\tthisSession.children(':first').show().find('*').show();\n\t\t\t\tthisSession.children().not(':first').hide();\n  \t\t\t} else \n\t        \talertIndiciaError(data);\n  \t\t},\n        complete: function (){\n  \t\t\tjQuery('.loading-button').removeClass('loading-button');\n  \t\t}\n\t});\n\tnewSession.find('.deh-required').remove();\n    return(newSession);\n};\n\nvalidateSessionsPanel = function(){\n\tif(jQuery('#cc-3:visible').length == 0) return true; // panel is not visible so no data to fail validation.\n\tif(jQuery('#cc-3').find('.poll-section-body:visible').length == 0) return true; // body hidden so data already been validated successfully.\n\tvar openSession = jQuery('.poll-session-form:visible');\n\tif(openSession.length > 0){\n\t\tif(jQuery('input[name=sample\\:id]', openSession).val() == '' &&\n\t\t\t\tjQuery('input[name=sample\\:date]', openSession).val() == '' &&\n\t\t\t\tjQuery('[name=smpAttr\\:" . $args['start_time_attr_id'] . "],[name^=smpAttr\\:" . $args['start_time_attr_id'] . "\\:]', openSession).val() == '' &&\n\t\t\t\tjQuery('[name=smpAttr\\:" . $args['end_time_attr_id'] . "],[name^=smpAttr\\:" . $args['end_time_attr_id'] . "\\:]', openSession).val() == '' &&\n\t\t\t\tjQuery('[name=smpAttr\\:" . $args['sky_state_attr_id'] . "],[name^=smpAttr\\:" . $args['sky_state_attr_id'] . "\\:]', openSession).filter('[checked]').length == 0 &&\n    \t\t\tjQuery('[name=smpAttr\\:" . $args['temperature_attr_id'] . "],[name^=smpAttr\\:" . $args['temperature_attr_id'] . "\\:]', openSession).filter('[checked]').length == 0 &&\n    \t\t\tjQuery('[name=smpAttr\\:" . $args['wind_attr_id'] . "],[name^=smpAttr\\:" . $args['wind_attr_id'] . "\\:]', openSession).filter('[checked]').length == 0 &&\n    \t\t\tjQuery('[name=smpAttr\\:" . $args['shade_attr_id'] . "],[name^=smpAttr\\:" . $args['shade_attr_id'] . "\\:]', openSession).filter('[checked]').length == 0) {\n    \t\tjQuery('#cc-3').foldPanel();\n\t\t\treturn true;\n\t\t}\n\t}\n\t// not putting in an empty data set check here - user can delete the session if needed, and there must be at least one.\n\tif(!validateAndSubmitOpenSessions()) return false;\n\tjQuery('#cc-3').foldPanel();\n\tpopulateSessionSelect();\n\treturn true;\n};\njQuery('#cc-3-valid-button').click(function(){\n\tif(!validateAndSubmitOpenSessions()) return;\n\tjQuery('#cc-3').foldPanel();\n\tjQuery('#cc-4').showPanel();\n\tpopulateSessionSelect();\n});\njQuery('#cc-3-add-button').click(function(){\n\tif(!validateAndSubmitOpenSessions()) return;\n\taddSession();\n\tcheckSessionButtons();\n});\n\njQuery('.mod-button').click(function() {\n\t// first close all the other panels, ensuring any data is saved.\n\tif(!validateCollectionPanel() || !validateStationPanel() || !validateSessionsPanel() || !validateInsectPanel())\n\t\treturn;\n\tjQuery('#cc-5').hidePanel();\n\tjQuery(this).parents('.poll-section-title').parent().unFoldPanel(); //slightly complicated because cc-1 contains the rest.\n});\n\n";
        $extraParams = $readAuth + array('taxon_list_id' => $args['insect_list_id'], 'view' => 'detail', 'orderby' => 'taxonomic_sort_order', 'allow_data_entry' => 't');
        $species_ctrl_args = array('label' => lang::get('LANG_Insect_Species'), 'fieldname' => 'insect:taxa_taxon_list_id', 'table' => 'taxa_taxon_list', 'captionField' => 'taxon', 'listCaptionSpecialChars' => true, 'valueField' => 'id', 'columns' => 2, 'blankText' => lang::get('LANG_Choose_Taxon'), 'extraParams' => $extraParams);
        $checkOptions['labelClass'] = 'checkbox-label';
        $r .= '
<div id="cc-4" class="poll-section">
  <div id="cc-4-title" class="ui-accordion-header ui-helper-reset ui-state-active ui-corner-all poll-section-title">' . lang::get('LANG_Photos') . '
    <div id="cc-4-mod-button" class="right ui-state-default ui-corner-all mod-button">' . lang::get('LANG_Modify') . '</div>
  </div>
  <div id="cc-4-photo-reel" class="ui-accordion-content ui-helper-reset ui-widget-content ui-corner-top ui-accordion-content-active photoReelContainer" >
    <div class="photo-blurb">' . lang::get('LANG_Photo_Blurb') . '</div>
    <div class="blankPhoto thumb currentPhoto"></div>
  </div>
  <div id="cc-4-body" class="ui-accordion-content ui-helper-reset ui-widget-content ui-accordion-content-active poll-section-body">  
    <div id="cc-4-insect">
      <div id="cc-4-insect-title">' . lang::get('LANG_Upload_Insect') . '</div>
      <form id="cc-4-insect-upload" enctype="multipart/form-data" action="' . iform_ajaxproxy_url($node, 'media') . '" method="POST">
    	<input type="hidden" id="website_id" name="website_id" value="' . $args['website_id'] . '" />
    	<input name="upload_file" type="file" class="required" />
        <input type="submit" value="' . lang::get('LANG_Upload') . '" class="btn-submit" />
 	    <div id="cc-4-insect-image" class="poll-image"></div>
      </form>
      <div id="cc-4-insect-identify" class="poll-dummy-form">
 	    <div class="id-tool-group">
          ' . iform_pollenators::help_button($use_help, "insect-help-button", $args['help_function'], $args['help_insect_arg']) . '
          <p><strong>' . lang::get('LANG_Identify_Insect') . '</strong></p>
          <input type="hidden" id="insect:taxon_details" name="insect:taxon_details" />
          <input type="hidden" name="insect:determination_type" value="A" />  
		  <label for="insect-id-button">' . lang::get('LANG_Insect_ID_Key_label') . ' :</label><span id="insect-id-button" class="ui-state-default ui-corner-all poll-id-button" >' . lang::get('LANG_Launch_ID_Key') . '</span>
		  <span id="insect-id-cancel" class="ui-state-default ui-corner-all poll-id-cancel" >' . lang::get('LANG_Cancel_ID') . '</span>
		  <p id="insect_taxa_list"></p> 
 	    </div>
 	    <div class="id-later-group">
 	      <label for="id-insect-later" class="follow-on">' . lang::get('LANG_ID_Insect_Later') . ' </label><input type="checkbox" id="id-insect-later" name="id-insect-later" />
 	    </div>
 	    <div class="id-specified-group">
 	      ' . data_entry_helper::select($species_ctrl_args) . '
          <label for="insect:taxon_extra_info" class="follow-on">' . lang::get('LANG_ID_More_Precise') . ' </label> 
    	  <input type="text" id="insect:taxon_extra_info" name="insect:taxon_extra_info" class="taxon-info" />
        </div>
      </div>
 	  <div class="id-comment">
        <label for="insect:comment" >' . lang::get('LANG_ID_Comment') . ' </label>
        <textarea id="insect:comment" name="insect:comment" class="taxon-comment" rows="3" ></textarea>
      </div>
    </div>
    <div class="poll-break"></div> 
 	<form id="cc-4-main-form" action="' . iform_ajaxproxy_url($node, 'occurrence') . '" method="POST" >
    	<input type="hidden" id="website_id" name="website_id" value="' . $args['website_id'] . '" />
    	<input type="hidden" id="occurrence_image:path" name="occurrence_image:path" value="" />
    	<input type="hidden" id="occurrence:record_status" name="occurrence:record_status" value="C" />
        <input type="hidden" name="occurrence:use_determination" value="Y"/>    
        <input type="hidden" name="determination:taxa_taxon_list_id" value=""/> 
        <input type="hidden" name="determination:taxon_details" value=""/>  	
        <input type="hidden" name="determination:taxon_extra_info" value=""/>  	
        <input type="hidden" name="determination:comment" value=""/>  	
    	<input type="hidden" name="determination:determination_type" value="A" /> 
        <input type="hidden" name="determination:cms_ref" value="' . $uid . '" />
    	<input type="hidden" name="determination:email_address" value="' . $email . '" />
    	<input type="hidden" name="determination:person_name" value="' . $username . '" /> 
    	<input type="hidden" id="occurrence:id" name="occurrence:id" value="" disabled="disabled" />
	    <input type="hidden" id="determination:id" name="determination:id" value="" disabled="disabled" />
	    <input type="hidden" id="occurrence_image:id" name="occurrence_image:id" value="" disabled="disabled" />
        <input type="hidden" id="insect_picture_camera_attr" name="occAttr:' . $args['occurrence_picture_camera_attr_id'] . '" value="" />
        <input type="hidden" id="insect_picture_datetime_attr" name="occAttr:' . $args['occurrence_picture_datetime_attr_id'] . '" value="" />
	    <label for="occurrence:sample_id">' . lang::get('LANG_Session') . ' :</label>
	    <select id="occurrence:sample_id" name="occurrence:sample_id" value="" class="required" /></select>
	    ' . data_entry_helper::textarea(array('label' => lang::get('LANG_Comment'), 'fieldname' => 'occurrence:comment')) . str_replace("\n", "", data_entry_helper::outputAttribute($occurrence_attributes[$args['number_attr_id']], $defNRAttrOptions)) . str_replace("\n", "", data_entry_helper::outputAttribute($occurrence_attributes[$args['foraging_attr_id']], $checkOptions)) . '
	<div id="Foraging_Confirm"><label>' . lang::get('Foraging_Confirm') . '</label><div class="control-box "><nobr><span><input type="radio" name="dummy_foraging_confirm" value="0" checked="checked"  /><label>' . lang::get('No') . '</label></span></nobr> &nbsp; <nobr><span><input type="radio" name="dummy_foraging_confirm" value="1" /><label>' . lang::get('Yes') . '</label></span></nobr></div></div></form><br />
    <div class="button-container">
      <span id="cc-4-valid-insect-button" class="ui-state-default ui-corner-all save-button">' . lang::get('LANG_Validate_Insect') . '</span>
      <span id="cc-4-delete-insect-button" class="ui-state-default ui-corner-all delete-button">' . lang::get('LANG_Delete_Insect') . '</span>
    </div>
  </div>
  <div id="cc-4-footer" class="ui-accordion-content ui-helper-reset ui-widget-content ui-corner-bottom ui-accordion-content-active poll-section-footer">
    <div id="cc-4-valid-photo-button" class="ui-state-default ui-corner-all save-button">' . lang::get('LANG_Validate_Photos') . '</div>
  </div>
</div>
<div style="display:none" />
    <form id="cc-4-delete-insect" action="' . iform_ajaxproxy_url($node, 'occurrence') . '" method="POST">
       <input type="hidden" name="website_id" value="' . $args['website_id'] . '" />
       <input type="hidden" name="occurrence:use_determination" value="Y"/>    
       <input type="hidden" name="occurrence:id" value="" />
       <input type="hidden" name="occurrence:sample_id" value="" />
       <input type="hidden" name="occurrence:deleted" value="t" />
    </form>
</div>';
        data_entry_helper::$javascript .= "\njQuery('#Foraging_Confirm').hide();\njQuery('[name=occAttr\\:" . $args['foraging_attr_id'] . "],[name^=occAttr\\:" . $args['foraging_attr_id'] . ":]').change(function(){\n\tjQuery('[name=dummy_foraging_confirm]').filter('[value=0]').attr('checked',true);\n\tcheckForagingStatus(false);\n});\n\ninsectIDstruc = {\n\ttype: 'insect',\n\tselector: '#cc-4-insect-identify',\n\tmainForm: '#cc-4-main-form',\n\tuseKey: true,\n\tstoredTaxaList: [],\n\ttimeOutTimer: null,\n\tpollTimer: null,\n\tsessionID: '',\n\tinvokeURL: '" . $args['ID_tool_insect_url'] . "',\n\tpollURL: '" . str_replace("{HOST}", $_SERVER['HTTP_HOST'], $args['ID_tool_insect_poll_dir']) . "',\n\tname: 'insectIDstruc',\n\ttaxaList: insectTaxa\n};\n\njQuery('#insect-id-button').click(function(){\n\tidButtonPressed(insectIDstruc);\n});\n\njQuery('#insect-id-cancel').click(function(){\n\tpollReset(insectIDstruc);\n});\njQuery('#insect-id-cancel').hide();\n\njQuery('#cc-4-insect-identify select[name=insect\\:taxa_taxon_list_id]').change(function(){\n\tpollReset(insectIDstruc);\n\ttaxonChosen(insectIDstruc);\n});\njQuery('#id-insect-later').change(function (){\n\tpollReset(insectIDstruc);\n\tidLater(insectIDstruc);\n});\n\n// Insect upload picture form.\n\$('#cc-4-insect-upload').ajaxForm({ \n\t\tasync: false,\n\t\tdataType:  'json', \n        beforeSubmit:   function(data, obj, options){\n        \tif(jQuery('#cc-4-insect-upload input[name=upload_file]').val() == '')\n        \t\treturn false;\n        \t\$('#cc-4-insect-image').empty();\n        \t\$('#cc-4-insect-image').addClass('loading');\n        \tjQuery('form#cc-4-main-form input[name=occurrence_image\\:path]').val('');\n        },\n        success:   function(data){\n        \tif(data.success == true){\n\t        \t// There is only one file\n\t        \tjQuery('form#cc-4-main-form input[name=occurrence_image\\:path]').val(data.files[0].filename);\n\t        \tjQuery('#insect_picture_camera_attr').val(data.files[0].EXIF_Camera_Make);\n\t        \tjQuery('#insect_picture_datetime_attr').val(data.files[0].EXIF_DateTime);\n\t        \tinsertImage('med-'+data.files[0].filename, jQuery('#cc-4-insect-image'), " . $args['Insect_Image_Ratio'] . ");\n\t\t\t\tjQuery('#cc-4-insect-upload input[name=upload_file]').val('');\n\t\t\t}  else\n\t\t\t\talertIndiciaError(data);\n  \t\t},\n  \t\tcomplete: function(){\n\t\t\t\$('#cc-4-insect-image').removeClass('loading');\n  \t\t}\n});\n\n\$('#cc-4-main-form').ajaxForm({ \n\tasync: false,\n\tdataType:  'json', \n    beforeSubmit:   function(data, obj, options){\n    \tvar valid = true;\n    \tclearErrors('form#cc-4-main-form');\n    \tclearErrors('#cc-4-insect-identify');\n    \tif (!jQuery('form#cc-4-main-form > input').valid()) { valid = false; }\n\t\tif (!validateRequiredField('occurrence\\:sample_id', 'form#cc-4-main-form')) { valid = false; }\n\t\tif (!validateRadio('occAttr\\:" . $args['number_attr_id'] . "', obj)) { valid = false; }\n    \tif(data[1].value == '' ){\n    \t\tmyScrollTo('#cc-4-insect-upload');\n\t\t\talert(\"" . lang::get('LANG_Must_Provide_Insect_Picture') . "\");\n\t\t\tvalid = false;\n\t\t}\n\t\tif (jQuery('#id-insect-later').attr('checked') == ''){\n\t\t\tprepPhotoReelForNew(false, jQuery('#cc-4-main-form').find('[name=occurrence\\:id]').val());\n\t\t\tdata[findID('determination:taxa_taxon_list_id', data)].value = jQuery('#cc-4-insect-identify select[name=insect\\:taxa_taxon_list_id]').val();\n\t\t\tdata[findID('determination:taxon_details', data)].value = jQuery('#cc-4-insect-identify [name=insect\\:taxon_details]').val();\n\t\t\tdata[findID('determination:taxon_extra_info', data)].value = jQuery('#cc-4-insect-identify [name=insect\\:taxon_extra_info]').val();\n\t\t\tdata[findID('determination:comment', data)].value = jQuery('[name=insect\\:comment]').val();\n\t\t\tdata[findID('determination:determination_type', data)].value = jQuery('#cc-4-insect-identify [name=insect\\:determination_type]').val();\n\t\t\tif (jQuery('#cc-4-insect-identify [name=insect\\:taxon_details]').val() == ''){\n\t\t\t\tif (!validateRequiredField('insect\\:taxa_taxon_list_id', '#cc-4-insect-identify')) {\n\t\t\t\t\tvalid = false;\n  \t\t\t\t} else {\n\t\t\t\t\tdata.push({name: 'determination:taxa_taxon_list_id_list[]', value: ''});\n  \t\t\t\t}\n\t\t\t} else {\n\t\t\t\tvar toolValues = insectIDstruc.storedTaxaList;\n\t\t\t\tfor(var i = 0; i<toolValues.length; i++){\n\t\t\t\t\tdata.push({name: 'determination:taxa_taxon_list_id_list[]', value: toolValues[i]});\n\t\t\t\t}\t\t\t\n\t\t\t}\n\t\t} else {\n\t\t\tprepPhotoReelForNew(true, jQuery('#cc-4-main-form').find('[name=occurrence\\:id]').val());\n\t\t\tdata.splice(4,8); // remove determination entries: TODO expand to be explicit - see flowers\n\t\t}\n   \t\tif ( valid == false ) {\n\t\t\tmyScrollToError();\n\t\t\treturn false;\n\t\t};\n\t\tjQuery('#cc-4-valid-insect-button').addClass('loading-button');\n\t\treturn true;\n\t},\n    success:   function(data){\n       \tif(data.success == 'multiple records' && data.outer_table == 'occurrence'){\n       \t\taddNewToPhotoReel(data.outer_id);\n\t\t\twindow.scroll(0,0);\n        } else\n\t\t\talertIndiciaError(data);\n\t},\n    complete: function (){\n  \t\tjQuery('.loading-button').removeClass('loading-button');\n  \t}\n});\n\nvalidateInsectPanel = function(){\n\tif(jQuery('#cc-4:visible').length == 0) return true; // panel is not visible so no data to fail validation.\n\tif(jQuery('#cc-4-body:visible').length == 0) return true; // body hidden so data already been validated successfully.\n\tif(!validateInsect()){ return false; }\n\tclearInsect();\n  \tjQuery('#cc-4').foldPanel();\n\treturn true;\n};\n\nclearInsect = function(){\n\tjQuery('#cc-4-main-form').resetForm();\n\tinsectIDstruc.storedTaxaList = [];\n\tjQuery('#insect_taxa_list').empty();\n\tjQuery('[name=insect\\:taxa_taxon_list_id],[name=insect\\:taxon_extra_info],[name=insect\\:comment],[name=insect\\:taxon_details]').val('');\n    jQuery('[name=insect\\:determination_type]').val('A'); \n\tjQuery('#id-insect-later').removeAttr('checked').removeAttr('disabled');\n    jQuery('#cc-4-main-form').find('[name=determination\\:cms_ref]').val('" . $uid . "');\n    jQuery('#cc-4-main-form').find('[name=determination\\:email_address]').val('" . $email . "');\n    jQuery('#cc-4-main-form').find('[name=determination\\:person_name]').val('" . $username . "'); \n    jQuery('#cc-4-main-form').find('[name=determination\\:determination_type]').val('A'); \n    jQuery('#cc-4-main-form').find('[name=occurrence_image\\:path]').val('');\n\tjQuery('#cc-4-main-form').find('[name=occurrence\\:id],[name=occurrence_image\\:id],[name=determination\\:id]').val('').attr('disabled', 'disabled');\n\t// First rename, to be safe. Then add [] to multiple choice checkboxes.\n\tjQuery('#cc-4-main-form').find('[name^=occAttr\\:]').each(function(){\n\t\tvar name = jQuery(this).attr('name').split(':');\n\t\tif(name[1].indexOf('[]') > 0) name[1] = name[1].substr(0, name[1].indexOf('[]'));\n\t\tjQuery(this).attr('name', 'occAttr:'+name[1]);\n\t});\n\tjQuery('#cc-4-main-form').find('[name^=occAttr\\:]').filter(':checkbox').removeAttr('checked').each(function(){\n\t\tvar myName = jQuery(this).attr('name').split(':');\n\t\tvar similar = jQuery('[name=occAttr\\:'+name[1]+'],[name=occAttr\\:'+name[1]+'\\[\\]]').filter(':checkbox');\n\t\tif(similar.length > 1) jQuery(this).attr('name', 'occAttr:'+name[1]+'[]');\n\t});\n    jQuery('#cc-4-insect-image').empty();\n    populateSessionSelect();\n    jQuery('#Foraging_Confirm').hide();\n    jQuery('[name=dummy_foraging_confirm]').filter('[value=0]').attr('checked',true);\n    jQuery('#cc-4').find('.inline-error').remove();\n\tjQuery('.currentPhoto').removeClass('currentPhoto');\n\tjQuery('.blankPhoto').addClass('currentPhoto');\n};\n\nloadInsect = function(id){\n\tclearInsect();\n\tjQuery('form#cc-4-main-form > input[name=occurrence\\:id]').removeAttr('disabled').val(id);\n\tloadAttributes('form#cc-4-main-form', 'occurrence_attribute_value', 'occurrence_attribute_id', 'occurrence_id', id, 'occAttr', true, true);\n\tloadImage('occurrence_image', 'occurrence_id', 'occurrence\\:id', id, '#cc-4-insect-image', " . $args['Insect_Image_Ratio'] . ", true);\n\t\$.getJSON(\"" . $svcUrl . "/data/occurrence/\" + id +\n          \"?mode=json&view=detail&nonce=" . $readAuth['nonce'] . "&auth_token=" . $readAuth['auth_token'] . "&callback=?\", function(data) {\n\t    if(!(data instanceof Array)){\n   \t\t\talertIndiciaError(data);\n   \t\t} else if (data.length>0) {\n\t        jQuery('form#cc-4-main-form > [name=occurrence\\:sample_id]').val(data[0].sample_id);\n\t\t\tjQuery('form#cc-4-main-form > textarea[name=occurrence\\:comment]').val(data[0].comment);\n  \t\t} else {\n   \t\t\talertIndiciaError({error : \"" . lang::get('Internal Error 10: no insect data available for id ') . "\"+id});\n  \t\t}\n\t});\n\t\$.getJSON(\"" . $svcUrl . "/data/determination?occurrence_id=\" + id +\n          \"&mode=json&view=list&nonce=" . $readAuth['nonce'] . "&auth_token=" . $readAuth['auth_token'] . "&orderby=id&deleted=f&callback=?\", function(data) {\n        if(!(data instanceof Array)){\n   \t\t\talertIndiciaError(data);\n   \t\t} else loadDetermination(data, insectIDstruc);\n\t});\t\n\tjQuery('.currentPhoto').removeClass('currentPhoto');\n\tjQuery('[occId='+id+']').addClass('currentPhoto');\n}\n\nprepPhotoReelForNew = function(notID, id){\n\tvar container;\n\tif(id == '')\n\t\tcontainer = jQuery('<div/>').addClass('thumb').insertBefore('.blankPhoto').attr('occId', 'new');\n\telse\n\t\tcontainer = jQuery('[occId='+id+']').empty();\n\tif(notID){\n\t\tvar img = new Image();\n\t\tvar src = '" . $base . drupal_get_path('module', 'iform') . "/client_helpers/prebuilt_forms/images/boundary-unknown.png';\n\t\timg = jQuery(img).attr('src', src).attr('width', container.width()).attr('height', container.height()).addClass('thumb-image').addClass('unidentified').appendTo(container);\n\t}\n}\n\naddNewToPhotoReel = function(occId){\n\tvar container = jQuery('[occId='+occId+']');\n\tif(container.length == 0) {\n\t\tcontainer = jQuery('[occId=new]');\n\t\tcontainer.attr('occId', occId.toString()).click(function () {\n\t\t    setInsect(occId)});\n\t}\n\t\$.getJSON(\"" . $svcUrl . "/data/occurrence_image\" +\n\t\t\t\"?mode=json&view=list&nonce=" . $readAuth['nonce'] . "&auth_token=" . $readAuth['auth_token'] . "\" +\n\t\t\t\"&occurrence_id=\" + occId + \"&callback=?\", function(imageData) {\n\t\tif(!(imageData instanceof Array)){\n\t\t\talertIndiciaError(imageData);\n\t\t} else if (imageData.length>0) {\n\t\t\tvar img = new Image();\n\t\t\tvar container = jQuery('[occId='+imageData[0].occurrence_id+']');\n\t\t\tif(container.children().length>0){\n\t\t\t\tvar background = '" . data_entry_helper::$base_url . data_entry_helper::$indicia_upload_path . "thumb-'+imageData[0].path;\n\t\t\t\tcontainer.children().css('background', 'url('+background+')').css('background-size','100% 100%');\n\t\t\t} else {\n\t\t\t\tjQuery(img).attr('src', '" . data_entry_helper::$base_url . data_entry_helper::$indicia_upload_path . "thumb-'+imageData[0].path)\n\t\t\t\t    .attr('width', container.width()).attr('height', container.height()).addClass('thumb-image').appendTo(container);\n\t\t\t}\n\t\t} else {\n\t\t\talertIndiciaError({error : \"" . lang::get('Internal Error 11: image could not be loaded into photoreel for insect ') . "\"+occId});\n\t\t}});\n}\n\naddExistingToPhotoReel = function(occId){\n\tvar container = jQuery('[occId='+occId+']');\n\tif(container.length == 0)\n\t\tcontainer = jQuery('<div/>').addClass('thumb').insertBefore('.blankPhoto').attr('occId', occId.toString()).click(function () {\n\t\t    setInsect(occId)});\n\telse\n\t\tcontainer.empty();\n\t// we use the presence of the text to determine whether the \n\t// insect has been identified or not. NB an insect tagged as unidentified (type = 'X') has actually been through the ID\n\t// process, so is not unidentified!!!\n\tjQuery.ajax({ \n        type: \"GET\", \n        url: \"" . $svcUrl . "/data/determination\" + \n    \t\t\"?mode=json&view=list&nonce=" . $readAuth['nonce'] . "&auth_token=" . $readAuth['auth_token'] . "\" + \n    \t\t\"&reset_timeout=true&occurrence_id=\" + occId + \"&orderby=id&deleted=f&callback=?\", \n        success: function(detData) {\n\t    \tif(!(detData instanceof Array)){\n   \t\t\t\talertIndiciaError(detData);\n   \t\t\t} else if (detData.length>0) {\n\t\t\t\t\$.getJSON(\"" . $svcUrl . "/data/occurrence_image\" +\n\t\t\t\t\t\t\"?mode=json&view=list&nonce=" . $readAuth['nonce'] . "&auth_token=" . $readAuth['auth_token'] . "\" +\n\t\t\t\t\t\t\"&occurrence_id=\" + occId + \"&callback=?\", function(imageData) {\n\t\t\t\t\tif(!(imageData instanceof Array)){\n\t\t\t\t\t\talertIndiciaError(imageData);\n\t\t\t\t\t} else if (imageData.length>0) {\n\t\t\t\t\t\tvar img = new Image();\n\t\t\t\t\t\tvar container = jQuery('[occId='+imageData[0].occurrence_id+']');\n\t\t\t\t\t\tjQuery(img).attr('src', '" . data_entry_helper::$base_url . data_entry_helper::$indicia_upload_path . "thumb-'+imageData[0].path)\n\t\t\t    \t\t\t.attr('width', container.width()).attr('height', container.height()).addClass('thumb-image').appendTo(container);\n\t\t\t\t\t} else {\n\t\t\t\t\t\talertIndiciaError({error : \"" . lang::get('Internal Error 12: image could not be loaded into photoreel for existing insect ') . "\"+occId});\n\t\t\t\t\t}\n\t\t\t\t});\n\t    \t} else { // is conceivable that insect is not identified yet -> does not have determinations\n\t\t\t\t\$.getJSON(\"" . $svcUrl . "/data/occurrence_image\" +\n\t\t\t\t\t\t\"?mode=json&view=list&nonce=" . $readAuth['nonce'] . "&auth_token=" . $readAuth['auth_token'] . "\" +\n\t\t\t\t\t\t\"&occurrence_id=\" + occId + \"&callback=?\", function(imageData) {\n\t\t\t\t\tif(!(imageData instanceof Array)){\n\t\t\t\t\t\talertIndiciaError(imageData);\n\t\t\t\t\t} else if (imageData.length>0) {\n\t\t\t\t\t\tvar img = new Image();\n\t\t\t\t\t\tvar container = jQuery('[occId='+imageData[0].occurrence_id+']');\n\t\t\t\t\t\tvar src = '" . $base . drupal_get_path('module', 'iform') . "/client_helpers/prebuilt_forms/images/boundary-unknown.png';\n\t\t\t\t\t\tvar background = '" . data_entry_helper::$base_url . data_entry_helper::$indicia_upload_path . "thumb-'+imageData[0].path;\n\t\t\t\t\t\timg = jQuery(img).attr('src', src).attr('width', container.width()).attr('height', container.height()).addClass('thumb-image').addClass('unidentified').appendTo(container);\n\t\t\t\t\t\timg.css('background', 'url('+background+')').css('background-size','100% 100%');\n\t\t\t\t\t} else {\n\t\t\t\t\t\talertIndiciaError({error : \"" . lang::get('Internal Error 12: image could not be loaded into photoreel for existing insect ') . "\"+occId});\n\t\t\t\t\t}\n\t\t\t\t});\n\t    \t}\n  \t\t}, \n    \tdataType: 'json' \n    });\n}\n\nsetInsect = function(id){\n\t// first close all the other panels, ensuring any data is saved.\n\tif(!validateCollectionPanel() || !validateStationPanel() || !validateSessionsPanel())\n\t\treturn;\n\tjQuery('#cc-5').hidePanel();\n\n\tif(jQuery('#cc-4-body:visible').length == 0)\n\t\tjQuery('div#cc-4').unFoldPanel();\n\telse\n\t\tif(!validateInsect()){ return ; }\n\tloadInsect(id);\n};\n\nsetNoInsect = function(){\n\t// first close all the other panels, ensuring any data is saved.\n\tif(!validateCollectionPanel() || !validateStationPanel() || !validateSessionsPanel())\n\t\treturn;\n\t\t\n\tif(jQuery('#cc-4-body:visible').length == 0)\n\t\tjQuery('div#cc-4').unFoldPanel();\n\telse\n\t\tif(!validateInsect()){ return ; }\n\tclearInsect();\n};\n\njQuery('.blankPhoto').click(setNoInsect);\n\n// TODO separate photoreel out into own js\nvalidateInsect = function(){\n    clearErrors('form#cc-4-main-form');\n    clearErrors('#cc-4-insect-identify');\n    if(jQuery('form#cc-4-main-form > input[name=occurrence\\:id]').val() == '' &&\n\t\t\tjQuery('form#cc-4-main-form > input[name=occurrence_image\\:path]').val() == '' &&\n\t\t\tjQuery('[name=insect\\:taxa_taxon_list_id]').val() == '' &&\n\t\t\tjQuery('[name=insect\\:taxon_details]').val() == '' &&\n\t\t\tjQuery('[name=insect\\:comment]').val() == '' &&\n\t\t\tjQuery('[name=insect\\:taxon_extra_info]').val() == '' &&\n\t\t\tjQuery('form#cc-4-main-form > textarea[name=occurrence\\:comment]').val() == '' &&\n\t\t\tjQuery('[name=occAttr\\:" . $args['number_attr_id'] . "],[name^=occAttr\\:" . $args['number_attr_id'] . "\\:]').filter('[checked]').length == 0){\n\t\treturn true;\n\t}\n\tvar valid = true;\n    if (!jQuery('form#cc-4-main-form > input').valid()) { valid = false; }\n  \tif (!validateRadio('occAttr\\:" . $args['number_attr_id'] . "', 'form#cc-4-main-form')) { valid = false; }\n\tif (jQuery('#id-insect-later').attr('checked') == '' && jQuery('[name=insect\\:taxon_details]').val() == ''){\n\t\tif (!validateRequiredField('insect\\:taxa_taxon_list_id', '#cc-4-insect-identify')) { valid = false; }\n\t}\n \tif (!validateRequiredField('occurrence\\:sample_id', 'form#cc-4-main-form')) { valid = false; }\n\tif(jQuery('form#cc-4-main-form input[name=occurrence_image\\:path]').val() == ''){\n    \tmyScrollTo('#cc-4-insect-upload');\n\t\talert(\"" . lang::get('LANG_Must_Provide_Insect_Picture') . "\");\n\t\tvalid = false;\n\t}\n\tif(jQuery('[name=occAttr\\:" . $args['foraging_attr_id'] . "],[name^=occAttr\\:" . $args['foraging_attr_id'] . ":]').filter('[checked]').val()==1){\n\t\tif(jQuery('[name=dummy_foraging_confirm]').filter('[checked]').val()==0){\n\t\t\tvalid = false;\n\t        var label = \$('<p/>')\n\t\t\t\t.attr({'for': 'dummy_foraging_confirm'})\n\t\t\t\t.addClass('inline-error')\n\t\t\t\t.html(\"" . lang::get('Foraging_Validation') . "\");\n\t\t\tlabel.appendTo(jQuery('#Foraging_Confirm'));\n\t\t}\n\t}\n\tif(valid == false) {\n\t\tmyScrollToError();\n\t\treturn false;\n\t}\n\tjQuery('form#cc-4-main-form').submit();\n\tclearInsect();\n\tmyScrollTo('.blankPhoto')\n\treturn true;\n}\n\n\$('#cc-4-valid-insect-button').click(validateInsect);\n\n\$('#cc-4-delete-insect-button').click(function() {\n\tvar container = \$(this).parent().parent();\n\tjQuery('#cc-4-delete-insect').find('[name=occurrence\\:id]').val(jQuery('#cc-4-main-form').find('[name=occurrence\\:id]').val()).removeAttr('disabled');\n\tjQuery('#cc-4-delete-insect').find('[name=occurrence\\:sample_id]').val(jQuery('#cc-4-main-form').find('[name=occurrence\\:sample_id]').val()).removeAttr('disabled');\n\tif(confirm(\"" . lang::get('LANG_Confirm_Insect_Delete') . "\")){\n\t\tif(jQuery('#cc-4-main-form').find('[name=occurrence\\:id]').filter('[disabled]').length == 0){\n\t\t\tjQuery('#cc-4-delete-insect').submit();\n\t\t\tjQuery('.currentPhoto').remove();\n\t\t\tjQuery('.blankPhoto').addClass('currentPhoto');\n\t\t}\n\t\tclearInsect();\n\t\tmyScrollTo('.blankPhoto')\n\t}\n});\n\n\$('#cc-4-delete-insect').ajaxForm({ \n\t\tasync: false,\n\t\tdataType:  'json', \n        beforeSubmit:   function(data, obj, options){\n  \t\t\t// Warning this assumes that the data is fixed position:\n        \tif(data[2].value == '') return false;\n\t\t\tif(data[3].value == ''){\n\t\t\t\talertIndiciaError({error : \"" . lang::get('Internal Error 13: sample id not set, so unsafe to save insect.') . "\"});\n\t\t\t\treturn false;\n\t\t\t}\n        \tjQuery('#cc-4-delete-insect').addClass('loading-button');\n        \treturn true;\n  \t\t},\n        success:   function(data){\n       \t\tif(data.success != 'multiple records' || data.outer_table != 'occurrence')\n        \t\talertIndiciaError(data);\n  \t\t},\n        complete: function (){\n  \t\t\tjQuery('.loading-button').removeClass('loading-button');\n  \t\t}\n});\n\n\$('#cc-4-valid-photo-button').click(function(){\n\tif(!validateInsect()) return;\n\tjQuery('#cc-4').foldPanel();\n\tjQuery('#cc-5').showPanel();\n\tvar numInsects = jQuery('#cc-4-photo-reel').find('.thumb').length - 1; // ignore blank\n\tvar numUnidentified = jQuery('#cc-4-photo-reel').find('.unidentified').length;\n\tif(jQuery('#id-flower-later').attr('checked') != '' || (numInsects>0 && (numUnidentified/numInsects > (1-(" . $args['percent_insects'] . "/100.0))))){\n\t\tjQuery('#cc-5-bad').show();\n\t\tjQuery('#cc-5-good,#cc-5-body2,#cc-5-complete-collection').hide();\n    } else {\n    \tjQuery('#cc-5-bad').hide(); // photoreel is left showing\n    \tjQuery('#cc-5-good,#cc-5-body2,#cc-5-complete-collection').show();\n\t}\n});\n";
        $r .= '
<div id="cc-5" class="poll-section">
  <div id="cc-5-body" class="ui-accordion-header ui-helper-reset ui-state-active ui-corner-top poll-section-body"> 
   <p id="cc-5-good">' . lang::get('LANG_Can_Complete_Msg') . '</p> 
   <p id="cc-5-bad">' . lang::get('LANG_Cant_Complete_Msg') . '</p> 
   <div style="display:none" />
    <form id="cc-5-collection" action="' . iform_ajaxproxy_url($node, 'sample') . '" method="POST">
       <input type="hidden" name="website_id" value="' . $args['website_id'] . '" />
       <input type="hidden" name="sample:survey_id" value="' . $args['survey_id'] . '" />
       <input type="hidden" name="sample:id" value="" />
       <input type="hidden" name="sample:date_start" value="2010-01-01"/>
       <input type="hidden" name="sample:date_end" value="2010-01-01"/>
       <input type="hidden" name="sample:date_type" value="D"/>
       <input type="hidden" name="sample:location_id" value="" />
       <input type="hidden" id="smpAttr:' . $args['complete_attr_id'] . '" name="smpAttr:' . $args['complete_attr_id'] . '" value="1" />
    </form>
   </div>
  </div>
  <div id="cc-5-body2" class="ui-accordion-content ui-helper-reset ui-widget-content ui-accordion-content-active poll-section-body">
    <p><img src="' . $base . drupal_get_path('module', 'iform') . '/media/images/exclamation.jpg" /> ' . lang::get('LANG_Trailer_Head') . ' :</p>
    <ul>
      <li>' . lang::get('LANG_Trailer_Point_1') . '</li>
      <li>' . lang::get('LANG_Trailer_Point_2') . '</li>
      <li>' . lang::get('LANG_Trailer_Point_3') . '</li>
      <li>' . lang::get('LANG_Trailer_Point_4') . '</li>
    </ul>
  </div>
  <div id="cc-5-trailer" class="ui-accordion-content ui-helper-reset ui-widget-content ui-corner-bottom ui-accordion-content-active poll-section-footer">
    <div id="cc-5-complete-collection" class="ui-state-default ui-corner-all complete-button">' . lang::get('LANG_Complete_Collection') . '</div>
  </div>
</div>';
        data_entry_helper::$javascript .= "\n\$('#cc-5-collection').ajaxForm({ \n\t\tasync: false,\n\t\tdataType:  'json', \n        beforeSubmit:   function(data, obj, options){\n            // double check that location id and sample id are filled in\n\t\t\tif(jQuery('#cc-1-collection-details input[name=location\\:id]').val() == ''){\n\t\t\t\talertIndiciaError({error : \"" . lang::get('Internal Error 14: location id not set, so unsafe to save collection.') . "\"});\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\tif(jQuery('#cc-1-collection-details input[name=sample\\:id]').val() == ''){\n\t\t\t\talertIndiciaError({error : \"" . lang::get('Internal Error 15: sample id not set, so unsafe to save collection.') . "\"});\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\tjQuery('#cc-5-complete-collection').addClass('loading-button');\n        \tdata[findID('sample:id', data)].value = jQuery('#cc-1-collection-details input[name=sample\\:id]').val();\n\t\t\tdata[findID('sample:date_start', data)].value = '';\n\t\t\tdata[findID('sample:date_end', data)].value = '';\n\t\t\tdate_start = '';\n\t\t\tdate_end = '';\n\t\t\tjQuery('.poll-session-form').each(function(i){\n\t\t\t\tif(jQuery(this).find('input[name=sample\\:id]').val() != '') {\n\t\t\t\t\tvar sessDate = jQuery(this).find('input[name=sample\\:date]').val();\n\t\t\t\t\tvar sessDateDate = new Date(convertDate(sessDate)); // sessions are only on one date.\n\t\t\t\t\tif(date_start == '' || date_start > sessDateDate) {\n\t\t\t\t\t\tdate_start = sessDateDate;\n\t\t\t\t\t\tdata[findID('sample:date_start', data)].value = sessDate;\n\t\t\t\t\t}\n\t\t\t\t\tif(date_end == '' || date_end < sessDateDate) {\n\t\t\t\t\t\tdate_end = sessDateDate;\n\t\t\t\t\t\tdata[findID('sample:date_end', data)].value = sessDate;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t});\n\t\t\tif(data[findID('sample:date_start', data)].value == '') {\n\t\t\t\talert(\"" . lang::get('LANG_Session_Error') . "\");\n\t\t\t\tjQuery('#cc-5-complete-collection').removeClass('loading-button');\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\tdata[findID('sample:date_type', data)].value = (data[3].value == data[4].value ? 'D' : 'DD');\n\t       \tjQuery('#cc-1-collection-details,#cc-2').find('[name=sample\\:date]:hidden').val(data[3].value);\n  \t\t\tdata[findID('sample:location_id', data)].value = jQuery('#cc-1-collection-details input[name=location\\:id]').val();\n       \t\tdata[7].name = jQuery('#cc-1-collection-details input[name^=smpAttr\\:" . $args['complete_attr_id'] . "\\:]').attr('name');\n       \t\treturn true;\n  \t\t},\n        success:   function(data){\n       \t\tif(data.success == 'multiple records' && data.outer_table == 'sample'){\n\t\t\t\t\$('#cc-6').showPanel();\n  \t\t\t}  else\n\t\t\t\talertIndiciaError(data);\n  \t\t},\n        complete: function (){\n  \t\t\tjQuery('.loading-button').removeClass('loading-button');\n  \t\t}\n});\n\$('#cc-5-complete-collection').click(function(){\n\tjQuery('#cc-5-complete-collection').addClass('loading-button');\n\tjQuery('#cc-2,#cc-3,#cc-4,#cc-5').hidePanel();\n\tjQuery('.reinit-button').hide();\n\tjQuery('.mod-button').hide();\n\tjQuery('#cc-5-collection').submit();\n});\n";
        $r .= '
<div id="cc-6" class="poll-section">
  <div id="cc-6-body" class="ui-accordion-header ui-helper-reset ui-state-active ui-corner-top poll-section-body"> 
   <p>' . lang::get('LANG_Final_1') . '</p> 
   <p>' . lang::get('LANG_Final_2') . '</p> 
   </div>
  <div id="cc-6-footer" class="ui-accordion-content ui-helper-reset ui-widget-content ui-corner-bottom ui-accordion-content-active poll-section-footer">
    <a id="cc-6-consult-collection" href="" class="ui-state-default ui-corner-all link-button">' . lang::get('LANG_Consult_Collection') . '</a>
    <a href="' . url('node/' . $node->nid) . '" class="ui-state-default ui-corner-all link-button">' . lang::get('LANG_Create_New_Collection') . '</a>
  </div>
</div>
</div></div>
<script type="text/javascript">
/* <![CDATA[ */
document.write("</div>");
/* ]]> */</script>
';
        data_entry_helper::$javascript .= "\nloadAttributes = function(formsel, attributeTable, attributeKey, key, keyValue, prefix, reset_timeout, required){\n\t// first need to remove any hidden multiselect checkbox unclick fields\n\tjQuery(formsel).find('[name^='+prefix+'\\:]').filter('.multiselect').remove();\n\t// rename, to be safe. Then add [] to multiple choice checkboxes.\n\tjQuery(formsel).find('[name^='+prefix+'\\:]').each(function(){\n\t\tvar name = jQuery(this).attr('name').split(':');\n\t\tif(name[1].indexOf('[]') > 0) name[1] = name[1].substr(0, name[1].indexOf('[]'));\n\t\tjQuery(this).attr('name', name[0]+':'+name[1]);\n\t});\n\tjQuery(formsel).find('[name^='+prefix+'\\:]').filter(':checkbox').removeAttr('checked').each(function(){\n\t\tvar myName = jQuery(this).attr('name').split(':');\n\t\tvar similar = jQuery('[name='+myName[0]+'\\:'+myName[1]+'],[name='+myName[0]+'\\:'+myName[1]+'\\[\\]]').filter(':checkbox');\n\t\tif(similar.length > 1)\n\t\t\tjQuery(this).attr('name', myName[0]+':'+myName[1]+'[]');\n\t});\n    jQuery.ajax({ \n        type: \"GET\", \n        url: \"" . $svcUrl . "/data/\" + attributeTable + \"?mode=json&view=list\" +\n        \t(reset_timeout ? \"&reset_timeout=true\" : \"\") + \"&nonce=" . $readAuth['nonce'] . "&auth_token=" . $readAuth['auth_token'] . "\" +\n   \t\t\t\"&\" + key + \"=\" + keyValue + \"&callback=?\", \n        data: {},\n        myFormsel: formsel,\n        myAttributeKey: attributeKey,\n        success: function(attrdata) {\n\t\t  if(!(attrdata instanceof Array)){\n   \t\t\talertIndiciaError(attrdata);\n   \t\t  } else if (attrdata.length>0) {\n\t\t\tfor (var i=0;i<attrdata.length;i++){\n\t\t\t\t// attribute list views now use id rather than meaning_id for the term.\n\t\t\t\t// This means (1) that the term will be either not present or wrong, as we are storing the meaning_id.\n\t\t\t\t// and (2) only one row will be returned per attribute.\n\t\t\t\t// As we already use raw_value below, the only change is no need to check the iso field.\n\t\t\t\tif (attrdata[i].id){\n\t\t\t\t\tvar radiobuttons = jQuery(this.myFormsel).find('[name='+prefix+'\\:'+attrdata[i][this.myAttributeKey]+'],[name^='+prefix+'\\:'+attrdata[i][this.myAttributeKey]+'\\:]').filter(':radio');\n\t\t\t\t\tvar multicheckboxes = jQuery(this.myFormsel).find('[name='+prefix+'\\:'+attrdata[i][this.myAttributeKey]+'\\[\\]],[name^='+prefix+'\\:'+attrdata[i][this.myAttributeKey]+':]').filter(':checkbox');\n\t\t\t\t\tvar boolcheckbox = jQuery(this.myFormsel).find('[name='+prefix+'\\:'+attrdata[i][this.myAttributeKey]+'],[name^='+prefix+'\\:'+attrdata[i][this.myAttributeKey]+':]').filter(':checkbox');\n\t\t\t\t\tif(radiobuttons.length > 0){ // radio buttons all share the same name, only one checked.\n\t\t\t\t\t\tradiobuttons\n\t\t\t\t\t\t\t.attr('name', prefix+':'+attrdata[i][this.myAttributeKey]+':'+attrdata[i].id)\n\t\t\t\t\t\t\t.filter('[value='+attrdata[i].raw_value+']')\n\t\t\t\t\t\t\t.attr('checked', 'checked');\n\t\t\t\t\t} else if(multicheckboxes.length > 0){ // individually named\n\t\t\t\t\t\tmulticheckboxes = multicheckboxes.filter('[value='+attrdata[i].raw_value+']')\n\t\t\t\t\t\t\t.attr('name', prefix+':'+attrdata[i][this.myAttributeKey]+':'+attrdata[i].id)\n\t\t\t\t\t\t\t.attr('checked', 'checked');\n\t\t\t\t\t\tmulticheckboxes.each(function(){\n\t\t\t\t\t\t\tjQuery('<input type=\"hidden\" value=\"0\" class=\"multiselect\">').attr('name', jQuery(this).attr('name')).insertBefore(this);\n\t\t\t\t\t\t});\n\t\t\t\t\t} else if(boolcheckbox.length > 0){ // has extra hidden field to force zero if unchecked.\n\t\t\t\t\t\tjQuery(this.myFormsel).find('[name='+prefix+'\\:'+attrdata[i][this.myAttributeKey]+'],[name^='+prefix+'\\:'+attrdata[i][this.myAttributeKey]+':]')\n\t\t\t\t\t\t\t.attr('name', prefix+':'+attrdata[i][this.myAttributeKey]+':'+attrdata[i].id);\n\t\t\t\t\t\tif (attrdata[i].raw_value == '1')\n\t\t\t\t\t\t\tboolcheckbox.attr('checked', 'checked');\n\t\t\t\t\t} else if (prefix == 'smpAttr' && attrdata[i][this.myAttributeKey] == " . $args['complete_attr_id'] . ") {\n\t\t\t\t\t\t// The hidden closed attributes are special: these have forced values, and are used to control the state. Do not update their values.\n\t\t\t\t\t\tjQuery(this.myFormsel).find('[name='+prefix+'\\:'+attrdata[i][this.myAttributeKey]+']')\n\t\t\t\t\t\t\t.attr('name', prefix+':'+attrdata[i][this.myAttributeKey]+':'+attrdata[i].id);\n\t\t\t\t\t} else {\n\t\t\t\t\t\tjQuery(this.myFormsel).find('[name='+prefix+'\\:'+attrdata[i][this.myAttributeKey]+']')\n\t\t\t\t\t\t\t.attr('name', prefix+':'+attrdata[i][this.myAttributeKey]+':'+attrdata[i].id)\n\t\t\t\t\t\t\t.val(attrdata[i].raw_value);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t  } else if (required){\n\t\t\talertIndiciaError({error : \"" . lang::get('Internal Error 16: could not load attributes ') . "\"+attributeTable+' '+keyName+' '+keyValue});\n\t\t  }\n\t\t  checkProtocolStatus('leave');\n\t\t  populateSessionSelect();\n\t\t  checkForagingStatus(true);\n\t\t},\n\t\tdataType: 'json'\n\t});\n}\n\nloadImage = function(imageTable, key, keyName, keyValue, target, ratio, required){\n\t\t\t\t\t// location_image, location_id, location:id, 1, #cc-4-insect-image\n\t\$.getJSON(\"" . $svcUrl . "/data/\" + imageTable +\n   \t\t\t\"?mode=json&view=list&nonce=" . $readAuth['nonce'] . "&auth_token=" . $readAuth['auth_token'] . "\" +\n   \t\t\t\"&\" + key + \"=\" + keyValue + \"&callback=?\", function(imageData) {\n\t\tif(!(imageData instanceof Array)){\n   \t\t\talertIndiciaError(imageData);\n   \t\t} else if (imageData.length>0) {\n\t\t\tvar form = jQuery('input[name='+keyName+'][value='+keyValue+']').parent();\n\t\t\tjQuery('[name='+imageTable+'\\:id]', form).val(imageData[0].id).removeAttr('disabled');\n\t\t\tjQuery('[name='+imageTable+'\\:path]', form).val(imageData[0].path);\n\t        insertImage('med-'+imageData[0].path, jQuery(target), ratio);\n\t\t} else if(required){\n\t\t\talertIndiciaError({error : \"" . lang::get('Internal Error 17: could not load ') . "\"+imageTable+' '+keyName+' '+keyValue});\n\t\t}\n\t});\n}\n\nloadDetermination = function(detData, toolStruc){\n\tjQuery('#'+toolStruc.type+'_taxa_list').empty();\n\ttoolStruc.storedTaxaList = [];\n\tjQuery(toolStruc.mainForm+' input[name=determination\\:id]').val('').attr('disabled', 'disabled');\n\tjQuery('#id-'+toolStruc.type+'-later').removeAttr('checked').removeAttr('disabled');\n\tjQuery('[name='+toolStruc.type+'\\:determination_type]').val('A');\n\tjQuery(toolStruc.mainForm+' input[name=determination\\:determination_type]').val('A');\n\tjQuery('[name='+toolStruc.type+'\\:taxon_details],[name='+toolStruc.type+'\\:taxa_taxon_list_id],[name='+toolStruc.type+'\\:comment],[name='+toolStruc.type+'\\:taxon_extra_info]').val('');\n\n\tif (detData.length>0) {\n\t\tjQuery('#id-'+toolStruc.type+'-later').attr('disabled', 'disabled');\n\t\tjQuery(toolStruc.mainForm+' input[name=determination\\:id]').val(detData[0].id).removeAttr('disabled');\n\t\tjQuery('[name='+toolStruc.type+'\\:taxon_details]').val(detData[0].taxon_details);\n\t\tjQuery('[name='+toolStruc.type+'\\:determination_type]').val(detData[0].determination_type);\n\t\tjQuery('[name='+toolStruc.type+'\\:taxa_taxon_list_id]').val(detData[0].taxa_taxon_list_id == null ? '' : detData[0].taxa_taxon_list_id);\n\t\tjQuery('[name='+toolStruc.type+'\\:comment]').val(detData[0].comment);\n\t\tjQuery('[name='+toolStruc.type+'\\:taxon_extra_info]').val(detData[0].taxon_extra_info == null ? '' : detData[0].taxon_extra_info);\n\t\tif(detData[0].determination_type == 'X'){\n\t\t\tjQuery('#'+toolStruc.type+'_taxa_list').append(\"" . lang::get('LANG_Taxa_Unknown_In_Tool') . "\");\n\t\t} else {\n\t\t\tvar resultsIDs = [];\n\t\t\tif(detData[0].taxa_taxon_list_id_list != null && detData[0].taxa_taxon_list_id_list != ''){\n\t\t\t  \tvar resultsText = \"" . lang::get('LANG_Taxa_Returned') . "<br />{ \";\n\t\t\t  \tresultsIDs = detData[0].taxa_taxon_list_id_list.substring(1, detData[0].taxa_taxon_list_id_list.length - 1).split(',');\n\t\t\t  \tfor(var j=0; j < resultsIDs.length; j++){\n\t\t\t\t\tfor(i = 0; i< toolStruc.taxaList.length; i++)\n\t\t\t\t\t\tif(toolStruc.taxaList[i].id == resultsIDs[j])\n\t\t\t\t\t\t\tresultsText = resultsText + (j == 0 ? '' : '<br />&nbsp;&nbsp;') + htmlspecialchars(toolStruc.taxaList[i].taxon);\n\t\t  \t\t}\n\t  \t\t\tif(resultsIDs.length>1 || resultsIDs[0] != '')\n\t\t\t\t\tjQuery('#'+toolStruc.type+'_taxa_list').append(resultsText+ ' }');\n\t\t\t}\n\t\t\ttoolStruc.storedTaxaList = resultsIDs;\n  \t\t}\n\t} else {\n\t\tjQuery('#id-'+toolStruc.type+'-later').attr('checked', 'checked');\n\t}\n};\n// Flowers no longer uses the taxa_taxon_list_id, but instead uses its list equivalent for known species.\n// the flower identification is not held with the cc-2-floral-station form.\nloadFlowerDetermination = function(detData){\n  jQuery('form#cc-2-floral-station input[name=determination\\:id]').val('').attr('disabled', 'disabled');\n  jQuery('#id-flower-later').removeAttr('checked').removeAttr('disabled');\n  jQuery('#id-flower-unknown').removeAttr('checked').removeAttr('disabled');\n  jQuery('[name=flower\\:determination_type]').val('A'); // hidden\n  jQuery('form#cc-2-floral-station input[name=determination\\:determination_type]').val('A');// hidden\n  jQuery('.flower-species-list-entry').remove();\n  jQuery('[name=flower\\:taxon_details],[name=flower\\:taxa_taxon_list_id],[name=flower\\:comment],[name=flower\\:taxon_extra_info]').val('');\n\n  if (detData.length>0) {\n    jQuery('#id-flower-later').attr('disabled', 'disabled');\n    jQuery('form#cc-2-floral-station input[name=determination\\:id]').val(detData[0].id).removeAttr('disabled');\n    jQuery('[name=flower\\:taxon_details]').val(detData[0].taxon_details == null ? '' : detData[0].taxon_details); // stores details from tool.\n    jQuery('[name=flower\\:determination_type]').val(detData[0].determination_type);\n    jQuery('[name=flower\\:comment]').val(detData[0].comment == null ? '' : detData[0].comment);\n    jQuery('[name=flower\\:taxon_extra_info]').val(detData[0].taxon_extra_info == null ? '' : detData[0].taxon_extra_info);\n    if(detData[0].determination_type == 'X') {\n      jQuery('#id-flower-unknown').attr('checked', 'checked');\n    } else if(detData[0].taxa_taxon_list_id != null) { // already set blank up above for null\n      // copy existing data forward to array.\n      for(i = 0; i< flowerTaxa.length; i++)\n        if(flowerTaxa [i].id == detData[0].taxa_taxon_list_id) {\n          jQuery('<tr class=\"flower-species-list-entry\"><td><input type=\"hidden\" name=\"flower:taxa_taxon_list_id_list[]\" value=\"'+flowerTaxa [i].id+'\"\\>'+htmlspecialchars(flowerTaxa[i].taxon)+'<td><img  class=\"removeRow\" src=\"/misc/watchdog-error.png\" alt=\"" . lang::get('Remove this entry') . "\" title=\"" . lang::get('Remove this entry') . "\"/></td></tr>').insertBefore('#flowerAutocompleteRow');\n          break;\n        }\n    } else {\n      if(detData[0].taxa_taxon_list_id_list != null && detData[0].taxa_taxon_list_id_list != ''){\n        var resultsIDs = detData[0].taxa_taxon_list_id_list.substring(1, detData[0].taxa_taxon_list_id_list.length - 1).split(','); // stringified array\n        for(var j=0; j < resultsIDs.length; j++)\n          for(i = 0; i< flowerTaxa.length; i++)\n            if(flowerTaxa[i].id == resultsIDs[j])\n              jQuery('<tr class=\"flower-species-list-entry\"><td><input type=\"hidden\" name=\"flower:taxa_taxon_list_id_list[]\" value=\"'+flowerTaxa [i].id+'\"\\>'+htmlspecialchars(flowerTaxa[i].taxon)+'<td><img class=\"removeRow\" src=\"/misc/watchdog-error.png\" alt=\"" . lang::get('Remove this entry') . "\" title=\"" . lang::get('Remove this entry') . "\"/></td></tr>').insertBefore('#flowerAutocompleteRow');\n      }\n    }\n  } else {\n    jQuery('#id-flower-later').attr('checked', 'checked');\n  }\n};\n\n// load in any existing incomplete collection.\n// general philosophy is that you are taken back to the stage last verified.\n// Load in the first if there are more than one. Use the internal report which provides my collections.\n// Requires that there is an attribute for completeness, and one for the CMS\n// load the data in the order it is entered, so can stop when get to the point where the user finished.\n// have to reset the entire form first...\njQuery('.poll-section').resetPanel();\n// Default state: hide everything except the collection details block.\njQuery('.poll-section').hidePanel();\njQuery('#cc-1').showPanel();\njQuery('.reinit-button').hide();\naddSession();\njQuery('.flower-species-list-entry').remove();\njQuery('#insect_taxa_list').empty();\npreloading=true;\npreloadIDs={location_loaded : false,\n\t\t\tsessions: []};\nsetPreloadStage = function(stage){\n\tpreloadStage=stage;\n\t\$('.poll-loading-extras').empty().text(stage);\n};\nsetPreloadStage(1);\n\njQuery('#cc-1').ajaxStop(function(){\n\tif(!preloading) return;\n\tswitch(preloadStage){\n\t\tcase 1: // just finished the report request\n\t\t\tif(typeof preloadIDs.sample_id == 'undefined' || typeof preloadIDs.location_id == 'undefined'){\n\t\t\t\t\$('.loading-panel').remove();\n\t\t\t\t\$('.poll-loading-hide').show();\n\t\t\t\tpreloading=false;\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tsetPreloadStage(2);\n\t\t\t// main sample date is only set when collection is completed, so don't need to load collection sample itself, and keep date as default \n\t\t\tloadAttributes('#cc-1-collection-details,#cc-5-collection', 'sample_attribute_value', 'sample_attribute_id', 'sample_id', preloadIDs.sample_id, 'smpAttr', false, true);\n  \t\t\tjQuery.getJSON('" . $svcUrl . "/data/location/' + preloadIDs.location_id +\n          \t\t\t\t\t\"?mode=json&view=detail&nonce=" . $readAuth['nonce'] . "&auth_token=" . $readAuth['auth_token'] . "\" +\n          \t\t\t\t\t\"&callback=?\", \n\t\t\t\t\tfunction(locationdata) {\n\t\t    \t\t  if(!(locationdata instanceof Array)){\n   \t\t\t\t\t\talertIndiciaError(locationdata);\n   \t\t\t\t\t  } else if (locationdata.length>0) {\n\t    \t\t\t\tjQuery('input[name=location\\:name]').val(locationdata[0].name);\n       \t\t\t\t\tjQuery('input[name=sample\\:location_name]').val(locationdata[0].name); // make sure the 2 coincide\n\t    \t\t\t\tjQuery('input[name=locations_website\\:website_id]').attr('disabled', 'disabled');\n\t\t\t\t\t\t// The location only holds a valid place if the floral station has been saved: otherwise it holds a default value.\n\t\t\t\t\t\t// we use the centroid_sref_system to indicate this: when the initial save is done the system is 900913,\n\t\t\t\t\t\t// but when a user has loaded one it is in 4326\n\t\t\t\t\t\t// NB the location geometry is stored in centroid, due to restrictions in location model.\n\t\t\t\t\t\tif(locationdata[0].centroid_sref_system == 4326 && locationdata[0].centroid_sref != oldDefaultSref){\n\t\t\t\t\t\t\tjQuery('input[name=location\\:centroid_sref]').val(locationdata[0].centroid_sref);\n\t\t\t\t\t\t\tjQuery('input[name=location\\:centroid_sref_system]').val(locationdata[0].centroid_sref_system); // note this will change the 900913 in cc-1 to 4326\n\t\t\t\t\t\t\tjQuery('input[name=location\\:centroid_geom]').val(locationdata[0].centroid_geom);\n\t\t\t\t\t\t\tvar parts=locationdata[0].centroid_sref.split(' ');\n\t\t\t\t\t\t\tvar refx = parts[0].split(',');\n\t\t\t\t\t\t\tjQuery('input[name=place\\:lat]').val(refx[0]);\n\t\t\t\t\t\t\tjQuery('input[name=place\\:long]').val(parts[1]);\n  \t\t\t\t\t\t}\n  \t\t\t\t\t\tpreloadIDs.location_loaded=true;\n\t\t\t\t\t  } else {\n\t\t\t\t\t\talertIndiciaError({error : \"" . lang::get('Internal Error 18: could not load data for location ') . "\"+data[i].location_id});\n\t\t\t\t\t  }});\n\t\t\tbreak;\n\t\tcase 2: // just finished the collection attributes and the location.\n\t\t\tif(preloadIDs.location_loaded==false)\n\t\t\t\treturn alertIndiciaError({error : \"" . lang::get('Internal Error 19: could not load data for location ') . "\"+preloadIDs.location_id});\n\t\t\tif(jQuery('[name=smpAttr\\:" . $args['protocol_attr_id'] . "]').length > 0)\n\t\t\t\treturn alertIndiciaError({error : \"" . lang::get('Internal Error 20: could not load attributes for sample ') . "\"+preloadIDs.sample_id});\n\t\t\t\$('#cc-1').foldPanel();\n\t\t\tcheckProtocolStatus(true);\n\t\t\t\$('#cc-2').showPanel();\n\t\t\tsetPreloadStage(3);\n\t\t\t// now load floral station stuff.\n\t\t\tloadAttributes('#cc-2-floral-station', 'location_attribute_value', 'location_attribute_id', 'location_id', preloadIDs.location_id, 'locAttr', false, false);\n\t\t\tloadImage('location_image', 'location_id', 'location\\:id', preloadIDs.location_id, '#cc-2-environment-image', " . $args['Environment_Image_Ratio'] . ", false);\n\t\t\tjQuery.getJSON(\"" . $svcUrl . "/data/occurrence/\" +\n          \t\t\t\t\t\"?mode=json&view=detail&nonce=" . $readAuth['nonce'] . "&auth_token=" . $readAuth['auth_token'] . "\" +\n          \t\t\t\t\t\"&sample_id=\"+preloadIDs.sample_id+\"&deleted=f&callback=?\", \n\t\t\t\t\tfunction(flowerData) {\n          \t\t\t  // there will only be an occurrence if the floral station panel has previously been displayed & validated. \n\t\t    \t\t  if(!(flowerData instanceof Array)){\n\t\t\t\t\t\talertIndiciaError(flowerData);\n\t\t\t\t\t  } else if (flowerData.length>0) { // do we need another >1 check as well?\n\t\t\t\t\t\tpreloadIDs.flower_id = flowerData[0].id;\n\t\t\t\t\t\tjQuery('form#cc-2-floral-station > input[name=occurrence\\:sample_id]').val(preloadIDs.sample_id);\n\t\t\t\t\t\tjQuery('form#cc-2-floral-station > input[name=occurrence\\:id]').val(flowerData[0].id).removeAttr('disabled');\n    \t   \t\t\t  }});\n\t\t\tbreak;\n\t\tcase 3: // just finished the location attributes, location image and flower.\n\t\t\t// all must be present or none at all: but location_attributes are all optional.\n\t\t\tif(typeof preloadIDs.flower_id == 'undefined' &&\n\t\t\t\t\tjQuery('[name=location_image\\:id]').val() == '') {\n\t\t\t\t\$('.loading-panel').remove();\n\t\t\t\t\$('.poll-loading-hide').show();\n\t\t\t\tbuildMap();\n\t\t\t\tpreloading=false;\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif(typeof preloadIDs.flower_id == 'undefined')\n\t\t\t\treturn alertIndiciaError({error : \"" . lang::get('Internal Error 21: could not load flower data for collection ') . "\"+preloadIDs.sample_id});\n\t\t\tif(jQuery('[name=location_image\\:id]').val() == '')\n\t\t\t\treturn alertIndiciaError({error : \"" . lang::get('Internal Error 23: could not load environment image for location ') . "\"+preloadIDs.location_id});\n\t\t\tsetPreloadStage(4);\n\t\t\tloadAttributes('#cc-2-floral-station', 'occurrence_attribute_value', 'occurrence_attribute_id', 'occurrence_id', preloadIDs.flower_id, 'occAttr', false, true);\n\t\t\tloadImage('occurrence_image', 'occurrence_id', 'occurrence\\:id', preloadIDs.flower_id, '#cc-2-flower-image', " . $args['Flower_Image_Ratio'] . ", true);\n\t\t\tjQuery.getJSON(\"" . $svcUrl . "/data/determination\" + \n\t\t\t\t\t\"?mode=json&view=list&nonce=" . $readAuth['nonce'] . "&auth_token=" . $readAuth['auth_token'] . "&occurrence_id=\"+preloadIDs.flower_id+\"&orderby=id&deleted=f&callback=?\", \n\t\t\t\tfunction(detData) {\n\t\t\t\t\tif(!(detData instanceof Array)){\n   \t\t\t\t\t\talertIndiciaError(detData);\n   \t\t\t\t\t } else loadFlowerDetermination(detData, flowerIDstruc);\n  \t\t\t\t});\n\t\t\tbreak;\n\t\tcase 4: // just finished the flower attributes, flower image and optional flower determination. Attrs and image mandatory at this point.\n\t\t\tif(jQuery('#cc-2-floral-station > input[name=occurrence_image\\:id]').val() == '')\n\t\t\t\treturn alertIndiciaError({error : \"" . lang::get('Internal Error 24: could not load image for flower ') . "\"+preloadIDs.flower_id});\n\t\t\tif(jQuery('[name=occAttr\\:" . $args['flower_type_attr_id'] . "]').length>0)\n\t\t\t\treturn alertIndiciaError({error : \"" . lang::get('Internal Error 25: could not load attributes for flower ') . "\"+preloadIDs.flower_id});\n\t\t\tsetPreloadStage(5);\n\t\t\tjQuery('#cc-2').foldPanel();\n\t\t\tjQuery('#cc-3').showPanel();\n\t\t\tjQuery.getJSON(\"" . $svcUrl . "/data/sample\" + \n\t\t\t\t\t\"?mode=json&view=detail&nonce=" . $readAuth['nonce'] . "&auth_token=" . $readAuth['auth_token'] . "&parent_id=\"+preloadIDs.sample_id+\"&callback=?\", \n\t\t\t\tfunction(sessiondata) {\n\t\t\t\t\tif(!(sessiondata instanceof Array)){\n\t\t\t\t\t\talertIndiciaError(sessiondata);\n\t\t\t\t\t} else if (sessiondata.length>0) { // may have zero sessions\n\t\t\t\t\t\tsessionCounter = 0;\n\t\t\t\t\t\tjQuery('#cc-3-body').empty();\n\t\t\t\t\t\tfor (var i=0;i<sessiondata.length;i++){\n\t\t\t\t\t\t\tvar thisSession = addSession();\n\t\t\t\t\t\t\tpreloadIDs.sessions.push({id : sessiondata[i].id, div : thisSession});\n\t\t\t\t\t\t\tjQuery('input[name=sample\\:id]', thisSession).val(sessiondata[i].id).removeAttr('disabled');\n\t\t\t\t\t\t\tjQuery('input[name=sample\\:date]', thisSession).val(sessiondata[i].date_start);\n\t\t\t\t\t\t\tjQuery('input[name=dummy_date]', thisSession).datepicker('disable').datepicker('setDate', new Date(convertDate(sessiondata[i].date_start))).datepicker('enable');\n\t\t\t\t\t\t\t// fold this session.\n\t\t\t\t\t\t\tthisSession.show();\n\t\t\t\t\t\t\tthisSession.children(':first').show().children().show();\n\t\t\t\t\t\t\tthisSession.children().not(':first').hide();\n\t\t\t\t\t\t}\n\t\t\t\t\t\tpopulateSessionSelect();\n\t\t\t\t\t}});\n\t\t\tbreak;\n\t\tcase 5: // just finished the sessions. no error situations\n\t\t\tif(preloadIDs.sessions.length == 0){\n\t\t\t\t\$('.loading-panel').remove();\n\t\t\t\t\$('.poll-loading-hide').show();\n\t\t\t\tpreloading=false;\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tsetPreloadStage(6);\n\t\t\t\$('#cc-3').foldPanel();\n\t\t\t\$('#cc-4').showPanel();\n\t\t\tpopulateSessionSelect();\n\t\t\tvar sessionIDs = [];\n\t\t\tfor (var i=0;i<preloadIDs.sessions.length;i++){\n\t\t\t\tloadAttributes(preloadIDs.sessions[i].div, 'sample_attribute_value', 'sample_attribute_id', 'sample_id', preloadIDs.sessions[i].id, 'smpAttr', false, true);\n\t\t\t\tsessionIDs.push(preloadIDs.sessions[i].id);\n\t\t\t}\n\t\t\t\$.getJSON(\"" . $svcUrl . "/data/occurrence/\" +\n\t\t\t\t\t\t\"?mode=json&view=detail&nonce=" . $readAuth['nonce'] . "&auth_token=" . $readAuth['auth_token'] . "&orderby=id\" +\n\t\t\t\t\t\t\"&deleted=f&callback=?&query=\"+escape(escape(JSON.stringify({'in': {'sample_id': sessionIDs}}))),\n\t\t\t\tfunction(insectData) {\n\t\t\t\t\tif(!(insectData instanceof Array)) return alertIndiciaError(insectData);\n\t\t\t\t\tif (insectData.length>0)\n\t\t\t\t\t\tfor (var j=0;j<insectData.length;j++)\n\t\t\t\t\t\t\taddExistingToPhotoReel(insectData[j].id);\n\t\t\t});\n\t\t\tbreak;\n\t\tcase 6: // just finished the session attributes and insects.\n\t\t\t// at this point the insects are optional, as are their determinations, so can't check for their presence.\n\t\t\tfor (var i=0;i<preloadIDs.sessions.length;i++){ // check attributes loaded for each session\n\t\t\t\tif(jQuery('[name=smpAttr\\:" . $args['start_time_attr_id'] . "]', preloadIDs.sessions[i].div).length>0)\n\t\t\t\t\treturn alertIndiciaError({error : \"" . lang::get('Internal Error 26: could not load attributes for session ') . "\"+preloadIDs.sessions[i].id});\n\t\t\t}\n\t\t\t\$('.loading-panel').remove();\n\t\t\t\$('.poll-loading-hide').show();\n\t\t\tpreloading=false;\n\t\t\tbreak;\n  }\n});\njQuery.getJSON(\"" . $svcUrl . "\" + \"/report/requestReport?report=reports_for_prebuilt_forms/poll_my_collections.xml&reportSource=local&mode=json\" +\n\t\t\t\"&auth_token=" . $readAuth['auth_token'] . "&reset_timeout=true&nonce=" . $readAuth["nonce"] . "\" + \n\t\t\t\"&survey_id=" . $args['survey_id'] . "&userID_attr_id=" . $args['uid_attr_id'] . "&userID=" . $uid . "&complete_attr_id=" . $args['complete_attr_id'] . "&callback=?\", \n\tfunction(data) {\n\tif(!(data instanceof Array)){\n   \t\talertIndiciaError(data);\n   \t  } else if (data.length>0) { // could have zero length\n\t\tvar i;\n       \tfor ( i=0;i<data.length;i++) {\n       \t\tif(data[i].completed == '0'){\n       \t\t\tjQuery('#cc-1-collection-details,#cc-1-delete-collection,#cc-2').find('[name=sample\\:id]').val(data[i].id).removeAttr('disabled');\n\t\t    \tjQuery('[name=location\\:id],[name=sample\\:location_id]').val(data[i].location_id).removeAttr('disabled');\n       \t\t\tjQuery('#cc-6-consult-collection').attr('href', '" . url('node/' . $args['gallery_node']) . "'+'?collection_id='+data[i].id);\n       \t\t\tpreloadIDs.sample_id = data[i].id;\n       \t\t\tpreloadIDs.location_id = data[i].location_id;\n\t\t\t\t// only use the first one which is not complete..\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n      }\n    });\n  ";
        // because of the use of getJson to retrieve the data - which is asynchronous, the use of the normal loading_block_end
        // is not practical - it will do its stuff before the data is loaded, defeating the purpose. Also it uses hide (display:none)
        // which is a no-no in relation to the map. This means we have to dispense with the slow fade in.
        // it is also complicated by the attibutes and images being loaded asynchronously - and non-linearly.
        // Do the best we can!
        //    data_entry_helper::$onload_javascript = "jQuery('.my-loading-hide').addClass('loading-hide').removeClass('my-loading-hide');\n".data_entry_helper::$onload_javascript."\nbuildMap();";
        data_entry_helper::$onload_javascript .= "\nbuildMap();";
        return $r;
    }
Exemplo n.º 3
0
    /**
     * Return the generated form output.
     * @return Form HTML.
     */
    public static function get_form($args, $node)
    {
        global $user;
        // There is a language entry in the args parameter list: this is derived from the $language DRUPAL global.
        // It holds the 2 letter code, used to pick the language file from the lang subdirectory of prebuilt_forms.
        // There should be no explicitly output text in this file.
        // We must translate any field names and ensure that the termlists and taxonlists use the correct language.
        // For attributes, the caption is automatically translated by data_entry_helper.
        $logged_in = $user->uid > 0;
        $uid = $user->uid;
        $email = $user->mail;
        $username = $user->name;
        if (!user_access('IForm n' . $node->nid . ' access')) {
            return "<p>" . lang::get('LANG_Insufficient_Privileges') . "</p>";
        }
        $r = '';
        // Get authorisation tokens to update and read from the Warehouse.
        $readAuth = data_entry_helper::get_read_auth($args['website_id'], $args['password']);
        $svcUrl = data_entry_helper::$base_url . '/index.php/services';
        drupal_add_js(drupal_get_path('module', 'iform') . '/media/js/jquery.form.js', 'module');
        data_entry_helper::link_default_stylesheet();
        data_entry_helper::add_resource('jquery_ui');
        if ($args['language'] != 'en') {
            data_entry_helper::add_resource('jquery_ui_' . $args['language']);
        }
        data_entry_helper::enable_validation('cc-1-collection-details');
        // don't care about ID itself, just want resources
        if ($args['help_module'] != '' && $args['help_inclusion_function'] != '' && module_exists($args['help_module']) && function_exists($args['help_inclusion_function'])) {
            $use_help = true;
            data_entry_helper::$javascript .= call_user_func($args['help_inclusion_function']);
        } else {
            $use_help = false;
        }
        // The only things that will be editable after the collection is saved will be the identifiaction of the flower/insects.
        // no id - just getting the attributes, rest will be filled in using AJAX
        $sample_attributes = data_entry_helper::getAttributes(array('valuetable' => 'sample_attribute_value', 'attrtable' => 'sample_attribute', 'key' => 'sample_id', 'fieldprefix' => 'smpAttr', 'extraParams' => $readAuth, 'survey_id' => $args['survey_id']));
        $occurrence_attributes = data_entry_helper::getAttributes(array('valuetable' => 'occurrence_attribute_value', 'attrtable' => 'occurrence_attribute', 'key' => 'occurrence_id', 'fieldprefix' => 'occAttr', 'extraParams' => $readAuth, 'survey_id' => $args['survey_id']));
        $location_attributes = data_entry_helper::getAttributes(array('valuetable' => 'location_attribute_value', 'attrtable' => 'location_attribute', 'key' => 'location_id', 'fieldprefix' => 'locAttr', 'extraParams' => $readAuth, 'survey_id' => $args['survey_id']));
        $defNRAttrOptions = array('extraParams' => $readAuth + array('orderby' => 'id'), 'lookUpListCtrl' => 'radio_group', 'lookUpKey' => 'meaning_id', 'language' => iform_lang_iso_639_2($args['language']), 'containerClass' => 'group-control-box', 'sep' => ' &nbsp; ', 'suffixTemplate' => 'nosuffix');
        $defAttrOptions = $defNRAttrOptions;
        $defAttrOptions['validation'] = array('required');
        $checkOptions = $defNRAttrOptions;
        $checkOptions['lookUpListCtrl'] = 'checkbox_group';
        $language = iform_lang_iso_639_2($args['language']);
        global $indicia_templates;
        $indicia_templates['sref_textbox_latlong'] = '<div class="latLongDiv"><label for="{idLat}">{labelLat}:</label>' . '<input type="text" id="{idLat}" name="{fieldnameLat}" {class} {disabled} value="{default}" /></div>' . '<div class="latLongDiv"><label for="{idLong}">{labelLong}:</label>' . '<input type="text" id="{idLong}" name="{fieldnameLong}" {class} {disabled} value="{default}" /></div>';
        $r .= data_entry_helper::loading_block_start();
        data_entry_helper::$javascript .= "var flowerTaxa = [";
        $extraParams = $readAuth + array('taxon_list_id' => $args['flower_list_id'], 'view' => 'list');
        $species_data_def = array('table' => 'taxa_taxon_list', 'extraParams' => $extraParams);
        $taxa = data_entry_helper::get_population_data($species_data_def);
        $first = true;
        foreach ($taxa as $taxon) {
            data_entry_helper::$javascript .= ($first ? '' : ',') . "{id: " . $taxon['id'] . ", taxon: \"" . htmlSpecialChars($taxon['taxon']) . "\"}\n";
            $first = false;
        }
        data_entry_helper::$javascript .= "];\nvar insectTaxa = [";
        $extraParams['taxon_list_id'] = $args['insect_list_id'];
        $species_data_def['extraParams'] = $extraParams;
        $taxa = data_entry_helper::get_population_data($species_data_def);
        $first = true;
        foreach ($taxa as $taxon) {
            data_entry_helper::$javascript .= ($first ? '' : ',') . "{id: " . $taxon['id'] . ", taxon: \"" . htmlSpecialChars($taxon['taxon']) . "\"}\n";
            $first = false;
        }
        data_entry_helper::$javascript .= "];";
        // note we have to proxy the post. Every time a write transaction is carried out, the write nonce is trashed.
        // For security reasons we don't want to give the user the ability to generate their own nonce, so we use
        // the fact that the user is logged in to drupal as the main authentication/authorisation/identification
        // process for the user. The proxy packages the post into the correct format
        //
        // There are 2 types of submission:
        // When a user validates a panel using the validate button, the following panel is opened on success
        // When a user presses a modify button, the open panel gets validated, and the panel to be modified is opened.
        $r .= '
<div id="refresh-message" style="display:none" ><p>' . lang::get('LANG_Please_Refresh_Page') . '</p></div>
<div id="cc-1" class="poll-section">
  <div id="cc-1-title" class="ui-accordion-header ui-helper-reset ui-state-active ui-corner-top poll-section-title">
  	<span id="cc-1-title-details">' . lang::get('LANG_Collection_Details') . '</span>
    <div class="right">
      <div>
        <span id="cc-1-reinit-button" class="ui-state-default ui-corner-all reinit-button">' . lang::get('LANG_Reinitialise') . '</span>
        <span id="cc-1-mod-button" class="ui-state-default ui-corner-all mod-button">' . lang::get('LANG_Modify') . '</span>
      </div>
    </div>
  </div>
  <div id="cc-1-details" class="ui-accordion-content ui-helper-reset ui-widget-content">
    <span id="cc-1-protocol-details"></span>
  </div>
  <div id="cc-1-body" class="ui-accordion-content ui-helper-reset ui-widget-content ui-accordion-content-active poll-section-body">
   <form id="cc-1-collection-details" action="' . iform_ajaxproxy_url($node, 'loc-sample') . '" method="POST">
    <input type="hidden" id="website_id"       name="website_id" value="' . $args['website_id'] . '" />
    <input type="hidden" id="imp-sref"         name="location:centroid_sref"  value="" />
    <input type="hidden" id="imp-geom"         name="location:centroid_geom" value="" />
    <input type="hidden" id="imp-sref-system"  name="location:centroid_sref_system" value="4326" />
    <input type="hidden" id="sample:survey_id" name="sample:survey_id" value="' . $args['survey_id'] . '" />
    ' . iform_pollenators::help_button($use_help, "collection-help-button", $args['help_function'], $args['help_collection_arg']) . '
    <label for="location:name">' . lang::get('LANG_Collection_Name_Label') . '</label>
 	<input type="text" id="location:name"      name="location:name" value="" class="required"/>
    <input type="hidden" id="sample:location_name" name="sample:location_name" value=""/>
 	' . str_replace("\n", "", data_entry_helper::outputAttribute($sample_attributes[$args['protocol_attr_id']], $defNRAttrOptions)) . '    <input type="hidden"                       name="sample:date" value="2010-01-01"/>
    <input type="hidden" id="smpAttr:' . $args['complete_attr_id'] . '" name="smpAttr:' . $args['complete_attr_id'] . '" value="0" />
    <input type="hidden" id="smpAttr:' . $args['uid_attr_id'] . '" name="smpAttr:' . $args['uid_attr_id'] . '" value="' . $uid . '" />
    <input type="hidden" id="smpAttr:' . $args['email_attr_id'] . '" name="smpAttr:' . $args['email_attr_id'] . '" value="' . $email . '" />
    <input type="hidden" id="smpAttr:' . $args['username_attr_id'] . '" name="smpAttr:' . $args['username_attr_id'] . '" value="' . $username . '" />  
    <input type="hidden" id="locations_website:website_id" name="locations_website:website_id" value="' . $args['website_id'] . '" />
    <input type="hidden" id="location:id"      name="location:id" value="" disabled="disabled" />
    <input type="hidden" id="sample:id"        name="sample:id" value="" disabled="disabled" />
    </form>
    <div id="cc-1-valid-button" class="ui-state-default ui-corner-all save-button">' . lang::get('LANG_Validate') . '</div>
  </div>
  <div id="cc-1-trailer" class="poll-section-trailer">
    <div id="cc-1-trailer-image" ><img src="' . helper_config::$base_url . 'media/images/exclamation.jpg" /></div>
    <p>' . lang::get('LANG_Collection_Trailer_Point_1') . '</p>
    <p>' . lang::get('LANG_Collection_Trailer_Point_2') . '</p>
  </div>
<div style="display:none" />
    <form id="cc-1-delete-collection" action="' . iform_ajaxproxy_url($node, 'sample') . '" method="POST">
       <input type="hidden" name="website_id" value="' . $args['website_id'] . '" />
       <input type="hidden" name="sample:survey_id" value="' . $args['survey_id'] . '" />
       <input type="hidden" name="sample:id" value="" />
       <input type="hidden" name="sample:date" value="2010-01-01"/>
       <input type="hidden" name="sample:location_id" value="" />
       <input type="hidden" name="sample:deleted" value="t" />
    </form>
</div>
  <div id="cc-1-main-body" class="ui-accordion-content ui-helper-reset ui-widget-content ui-corner-bottom ui-accordion-content-active">
';
        data_entry_helper::$javascript .= "\n\$.validator.messages.required = \"" . lang::get('validation_required') . "\";\nvar sessionCounter = 0;\njQuery('#imp-georef-search-btn').removeClass('indicia-button').addClass('search-button');\njQuery('.loading-hide').hide().addClass('my-loading-hide').removeClass('loading-hide');\n// can't use shuffle to side as dynamic generated code does like it in IE7\n\n\$.fn.foldPanel = function(){\n\tthis.children('.poll-section-body').hide();\n\tthis.children('.poll-section-footer,.poll-section-trailer').hide();\n\tthis.children('.poll-section-title').find('.reinit-button').show();\n\tthis.children('.poll-section-title').find('.mod-button').show();\n\tthis.children('.photoReelContainer').addClass('ui-corner-all').removeClass('ui-corner-top')\n};\n\n\$.fn.unFoldPanel = function(){\n\tthis.children('.poll-section-body').show();\n\tthis.children('.poll-section-footer,.poll-section-trailer').show();\n\tthis.children('.poll-section-title').find('.mod-button').hide();\n\tthis.children('.photoReelContainer').addClass('ui-corner-top').removeClass('ui-corner-all')\n\twindow.scroll(0,0); // force the window to display the top.\n\tbuildMap();\n\tcheckSessionButtons();\n\t// any reinit button is left in place\n};\n\n\$.fn.showPanel = function(){\n\tthis.show();\n\tthis.unFoldPanel();\n};\n\n\$.fn.hidePanel = function(){\n\tthis.hide(); \n};\n\ninseeLayer = null;\n\ndefaultSref = '" . ((int) $args['map_centroid_lat'] > 0 ? $args['map_centroid_lat'] . 'N' : -(int) $args['map_centroid_lat'] . 'S') . ' ' . ((int) $args['map_centroid_long'] > 0 ? $args['map_centroid_long'] . 'E' : -(int) $args['map_centroid_long'] . 'W') . "';\ndefaultGeom = '';\n\$.getJSON('" . $svcUrl . "' + '/spatial/sref_to_wkt'+\n        \t\t\t'?sref=' + defaultSref +\n          \t\t\t'&system=' + jQuery('#imp-sref-system').val() +\n          \t\t\t'&callback=?', function(data) {\n            \tdefaultGeom = data.wkt;\n        \t});\n\n\$.fn.resetPanel = function(){\n\tthis.find('.poll-section-body').show();\n\tthis.find('.poll-section-footer,.poll-section-trailer').show();\n\tthis.find('.reinit-button').show();\n\tthis.find('.mod-button').show();\n\tthis.find('.poll-image').empty();\n\tthis.find('.poll-session').remove();\n\tthis.find('.inline-error').remove();\n\tthis.find('#imp-georef-search').val('');\n\tthis.find('#imp-georef-div').hide();\n\tthis.find('#imp-georef-output-div').empty();\n\tthis.find('[name=place\\:INSEE]').val('" . lang::get('LANG_INSEE') . "');\n\tthis.find('#imp-sref-lat').val('');\n\tthis.find('#imp-sref-long').val('');\n\t// TODO Map\n\tthis.find('.thumb').filter('not(.blankPhoto)').remove();\n\n\t// resetForm does not reset the hidden fields. record_status, imp-sref-system, website_id and survey_id are not altered so do not reset.\n\t// hidden Attributes generally hold unchanging data, but the name needs to be reset (does it for non hidden as well).\n\t// hidden location:name are set in code anyway.\n\tthis.find('.poll-dummy-form input').val('');\n\tthis.find('.poll-dummy-form input').removeAttr('checked');\n\tthis.find('.poll-dummy-form select').val('');\n\tthis.find('.poll-dummy-form textarea').val('');\n\tthis.find('.poll-dummy-form').find('[name\$=\\:determination_type]').val('A');\n\tthis.find('form').each(function(){\n\t\tjQuery(this).resetForm();\n\t\tjQuery(this).find('[name=sample\\:location_name],[name=location_image\\:path],[name=occurrence_image\\:path]').val('');\n\t\tjQuery(this).filter('#cc-1-collection-details').find('[name=sample\\:id],[name=location\\:id]').val('').attr('disabled', 'disabled');\n\t\tjQuery(this).find('[name=location_image\\:id],[name=occurrence\\:id],[name=determination\\:id],[name=occurrence_image\\:id]').val('').attr('disabled', 'disabled');\n\t\tjQuery(this).find('[name=sample\\:date]:hidden').val('2010-01-01');\t\t\n        jQuery(this).find('input[name=locations_website\\:website_id]').removeAttr('disabled');\n\t\tjQuery(this).find('[name^=smpAttr\\:],[name^=locAttr\\:],[name^=occAttr\\:]').each(function(){\n\t\t\tvar name = jQuery(this).attr('name').split(':');\n\t\t\tjQuery(this).attr('name', name[0]+':'+name[1]);\n\t\t});\n\t\tjQuery(this).find('input[name=location\\:centroid_sref]').val('');\n\t\tjQuery(this).find('input[name=location\\:centroid_geom]').val('');\n    });\t\n  };\n\nalertIndiciaError = function(data){\n\tvar errorString = \"" . lang::get('LANG_Indicia_Warehouse_Error') . "\";\n\tif(data.error){\terrorString = errorString + ' : ' + data.error;\t}\n\tif(data.errors){\n\t\tfor (var i in data.errors){\n\t\t\terrorString = errorString + ' : ' + data.errors[i];\n\t\t}\t\t\t\t\n\t}\n\talert(errorString);\n\t// the most likely cause is authentication failure - eg the read authentication has timed out.\n\t// prevent further use of the form:\n\t\$('.loading-panel').remove();\n\t\$('.loading-hide').removeClass('loading-hide');\n\tjQuery('#cc-1').hide();\n\tjQuery('#refresh-message').show();\n};\n\t\t\t\ncheckProtocolStatus = function(display){\n  \tvar checkedProtocol = jQuery('[name=smpAttr\\:" . $args['protocol_attr_id'] . "],[name^=smpAttr\\:" . $args['protocol_attr_id'] . "\\:]').filter('[checked]').parent();\n    if(jQuery('[name=location\\:name]').val() != '' && checkedProtocol.length > 0) {\n        jQuery('#cc-1-title-details').empty().text(jQuery('#cc-1-collection-details input[name=location\\:name]:first').val());\n        firstBracket = checkedProtocol.find('label')[0].innerHTML.indexOf('(');\n        secondBracket = checkedProtocol.find('label')[0].innerHTML.lastIndexOf(')');\n        jQuery('#cc-1-protocol-details').empty().show().html('<strong>" . lang::get('LANG_Protocol_Title_Label') . "</strong> : <span class=\"protocol-head\">' +\n                  checkedProtocol.find('label')[0].innerHTML.slice(0, firstBracket-1) +\n                  '</span><span class=\"protocol-description\"> | ' +\n                  checkedProtocol.find('label')[0].innerHTML.slice(firstBracket+1, secondBracket) + '</span>');\n    } else {\n        jQuery('#cc-1-title-details').empty().text(\"" . lang::get('LANG_Collection_Details') . "\");\n        // TODO autogenerate a name\n        jQuery('#cc-1-protocol-details').empty().hide();\n    }\n    if(display == true){\n      jQuery('#cc-1-details').addClass('ui-accordian-content-active');\n    } else if(display == false){\n      jQuery('#cc-1-details').removeClass('ui-accordian-content-active');\n    } // anything else just leave\n};\ncheckSessionButtons = function(){\n\tif (jQuery('#cc-3-body').children().length === 1) {\n\t    jQuery('#cc-3').find('.delete-button').hide();\n\t    jQuery('#cc-3-valid-button').empty().text(\"" . lang::get('LANG_Validate_Session') . "\")\n  \t} else {\n\t\tjQuery('#cc-3').find('.delete-button').show();\n\t    jQuery('#cc-3-valid-button').empty().text(\"" . lang::get('LANG_Validate_Session_Plural') . "\")\n  \t}\n\tif(jQuery('[name=smpAttr\\:" . $args['protocol_attr_id'] . "],[name^=smpAttr\\:" . $args['protocol_attr_id'] . "\\:]').filter(':first').filter('[checked]').length >0){\n\t    jQuery('#cc-3-title-title').empty().text(\"" . lang::get('LANG_Sessions_Title') . "\");\n\t\tjQuery('#cc-3').find('.add-button').hide();\n\t} else {\n\t    jQuery('#cc-3-title-title').empty().text(\"" . lang::get('LANG_Sessions_Title_Plural') . "\");\n\t\tjQuery('#cc-3').find('.add-button').show();\n  \t}\n};\n\nshowStationPanel = true;\n\n// The validate functionality for each panel is sufficiently different that we can't generalise a function\n// this is the one called when we don't want the panel following to be opened automatically.\nvalidateCollectionPanel = function(){\n\tclearErrors('form#cc-1-collection-details');\n\tif(jQuery('#cc-1-body:visible').length == 0) return true; // body hidden so data already been validated successfully.\n\tif(!jQuery('#cc-1-body').find('form > input').valid()){\n\t\tmyScrollToError();\n\t\treturn false;\n  \t}\n\t// no need to check protocol - if we are this far, we've already filled it in.\n  \tshowStationPanel = false;\n\tjQuery('#cc-1-collection-details').submit();\n\treturn true;\n  };\n\nerrorPos = null;\nclearErrors = function(formSel) {\n\tjQuery(formSel).find('.inline-error').remove();\n\terrorPos = null;\n};\nmyScrollTo = function(selector){\n\tjQuery(selector).filter(':visible').each(function(){\n\t\tif(errorPos == null || jQuery(this).offset().top < errorPos){\n\t\t\terrorPos = jQuery(this).offset().top;\n\t\t\twindow.scroll(0,errorPos);\n\t\t}\n\t});\n};\nmyScrollToError = function(){\n\tjQuery('.inline-error,.error').filter(':visible').prev().each(function(){\n\t\tif(errorPos == null || jQuery(this).offset().top < errorPos){\n\t\t\terrorPos = jQuery(this).offset().top;\n\t\t\twindow.scroll(0,errorPos);\n\t\t}\n\t});\n};\n\nvalidateRadio = function(name, formSel){\n    var controls = jQuery(formSel).find('[name='+name+'],[name^='+name+'\\:]');\n    if(controls.filter('[checked]').length < 1) {\n        var label = \$('<p/>')\n\t\t\t\t.attr({'for': name})\n\t\t\t\t.addClass('inline-error')\n\t\t\t\t.html(\$.validator.messages.required);\n\t\tlabel.insertBefore(controls.filter(':first').parent());\n\t\treturn false;\n    }\n    return true;\n}\n\nvalidateRequiredField = function(name, formSel){\n    var control = jQuery(formSel).find('[name='+name+']');\n    if(control.val() == '') {\n        var label = \$('<p/>')\n\t\t\t\t.attr({'for': name})\n\t\t\t\t.addClass('inline-error')\n\t\t\t\t.html(\$.validator.messages.required);\n\t\tlabel.insertBefore(control);\n\t\treturn false;\n    }\n    return true;\n}\n\nvalidateOptInt = function(name, formSel){\n\tvar control = jQuery(formSel).find('[name='+name+'],[name^='+name+'\\:]');\n\tvar ctrvalue = control.val();\n\tvar OK = true;\n\tif(ctrvalue == '') return true;\n\tfor (i = 0 ; i < ctrvalue.length ; i++) {\n\t\tif ((ctrvalue.charAt(i) < '0') || (ctrvalue.charAt(i) > '9')) OK = false\n\t}\n\tif(OK) return OK;\n\tvar label = \$('<p/>')\n\t\t\t\t.attr({'for': name})\n\t\t\t\t.addClass('inline-error')\n\t\t\t\t.html(\"" . lang::get('validation_integer') . "\");\n\tlabel.insertBefore(control);\n\treturn false;\n}\n\ninsertImage = function(path, target, ratio){\n\tvar img = new Image();\n\tjQuery(img).load(function () {\n        target.removeClass('loading').append(this);\n        if(this.width/this.height > ratio){\n\t    \tjQuery(this).css('width', '100%').css('height', 'auto').css('vertical-align', 'middle').css('margin-left', 'auto').css('margin-right', 'auto').css('display', 'block');\n  \t\t} else {\n\t        jQuery(this).css('width', (100*this.width/(this.height*ratio))+'%').css('height', 'auto').css('vertical-align', 'middle').css('margin-left', 'auto').css('margin-right', 'auto').css('display', 'block');\n  \t\t}\n\t}).attr('src', '" . data_entry_helper::$base_url . data_entry_helper::$indicia_upload_path . "'+path);\n}\n\t\t\t\t    \n\$('#cc-1').ajaxError(function(event, request, settings){\n\tvar insectURL = '" . str_replace("{HOST}", $_SERVER['HTTP_HOST'], $args['ID_tool_insect_poll_dir']) . "'+insectSess;\n\tvar flowerURL = '" . str_replace("{HOST}", $_SERVER['HTTP_HOST'], $args['ID_tool_flower_poll_dir']) . "'+flowerSess;\n\tif(settings.url != flowerURL && settings.url != insectURL){\n\t   alert(\"" . lang::get('ajax_error') . "\");\n\t}\n});\n \nvalidateTime = function(name, formSel){\n    var control = jQuery(formSel).find('[name='+name+'],[name^='+name+'\\:]');\n    if(control.val().match(/^(2[0-3]|[0,1][0-9]):[0-5][0-9]\$/) == null) {\n        var label = \$('<p/>')\n\t\t\t\t.attr({'for': name})\n\t\t\t\t.addClass('inline-error')\n\t\t\t\t.html('" . lang::get('validation_date') . "');\n\t\tlabel.insertBefore(control);\n\t\treturn false;\n    }\n    return true;\n}\n\n\$('#cc-1-collection-details').ajaxForm({\n\t\tasync: false,\n        dataType:  'json', \n        beforeSubmit:   function(data, obj, options){\n        \tclearErrors('form#cc-1-collection-details');\n        \tvar valid = true;\n        \tif (!jQuery('form#cc-1-collection-details > input').valid()) { valid = false; }\n        \tif (!validateRadio('smpAttr\\:" . $args['protocol_attr_id'] . "', 'form#cc-1-collection-details')) { valid = false; }\n\t       \tif ( valid == false ) {\n\t\t\t\tmyScrollToError();\n\t\t\t\treturn false;\n  \t\t\t};\n  \t\t\t// Warning this assumes that:\n  \t\t\t// 1) the location:name is the sixth field in the form.\n  \t\t\t// 1) the sample:location_name is the seventh field in the form.\n  \t\t\tdata[6].value = data[5].value;\n  \t\t\tif(data[1].value=='') data[1].value=defaultSref;\n  \t\t\tif(data[2].value=='') data[2].value=defaultGeom;\n  \t\t\tjQuery('#cc-2-floral-station > input[name=location\\:name]').val(data[5].value);\n  \t\t\tjQuery('#cc-1-valid-button').addClass('loading-button');\n        \treturn true;\n  \t\t},\n        success:   function(data){\n        \tif(data.success == 'multiple records' && data.outer_table == 'location'){\n        \t    jQuery('#cc-1-collection-details > input[name=location\\:id]').removeAttr('disabled').val(data.outer_id);\n        \t    jQuery('#cc-1-collection-details > input[name=locations_website\\:website_id]').attr('disabled', 'disabled');\n        \t    jQuery('#cc-2-floral-station > input[name=location\\:id]').removeAttr('disabled').val(data.outer_id);\n        \t    \$.getJSON(\"" . $svcUrl . "\" + \"/data/sample\" +\n\t\t\t          \"?mode=json&view=detail&nonce=" . $readAuth['nonce'] . "&auth_token=" . $readAuth['auth_token'] . "\" +\n\t\t\t          \"&location_id=\"+data.outer_id+\"&parent_id=NULL&callback=?\", function(data) {\n\t\t\t\t\tif(!(data instanceof Array)){\n   \t\t\t\t\t\talertIndiciaError(data);\n   \t\t\t\t\t} else if (data.length>0) {\n\t\t\t       \t\t    jQuery('#cc-6-consult-collection').attr('href', '" . url('node/' . $args['gallery_node']) . "'+'?collection_id='+data[0].id);\n\t\t\t        \t    jQuery('#cc-1-collection-details > input[name=sample\\:id]').removeAttr('disabled').val(data[0].id);\n\t\t\t        \t    jQuery('#cc-2-floral-station > input[name=sample\\:id]').removeAttr('disabled').val(data[0].id);\n\t\t\t        \t    // In this case we use loadAttributes to set the names of the attributes to include the attribute_value id.\n   \t       \t\t\t\t\tloadAttributes('sample_attribute_value', 'sample_attribute_id', 'sample_id', 'sample\\:id', data[0].id, 'smpAttr', true);\n\t\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t   \tcheckProtocolStatus(true);\n        \t\t\$('#cc-1').foldPanel();\n    \t\t\tif(showStationPanel){ \$('#cc-2').showPanel(); }\n\t\t    \tshowStationPanel = true;\n        \t}  else \n\t\t\t\talertIndiciaError(data);\n        },\n        complete: function (){\n  \t\t\tjQuery('.loading-button').removeClass('loading-button');\n  \t\t}\n});\n\n\$('#cc-1-delete-collection').ajaxForm({ \n\t\tasync: false,\n\t\tdataType:  'json', \n        beforeSubmit:   function(data, obj, options){\n  \t\t\t// Warning this assumes that the data is fixed position:\n       \t\tdata[2].value = jQuery('#cc-1-collection-details input[name=sample\\:id]').val();\n       \t\tdata[3].value = jQuery('#cc-1-collection-details input[name=sample\\:date]').val();\n       \t\tdata[4].value = jQuery('#cc-1-collection-details input[name=location\\:id]').val();\n        \tif(data[2].value == '') return false;\n  \t\t\tjQuery('#cc-1-reinit-button').addClass('loading-button');\n        \treturn true;\n  \t\t},\n        success:   function(data){\n        \tif(data.success == 'multiple records' && data.outer_table == 'sample'){\n        \t\tjQuery('#cc-3-body').empty();\n        \t\tpollReset(flowerIDstruc);\n        \t\tpollReset(insectIDstruc);\n\t        \tjQuery('.poll-section').resetPanel();\n\t\t\t\tsessionCounter = 0;\n\t\t\t\taddSession();\n\t\t\t\tcheckProtocolStatus(false);\n\t\t\t\tjQuery('.poll-section').hidePanel();\n\t\t\t\tjQuery('.poll-image').empty();\n\t\t\t\tjQuery('#cc-1').showPanel();\n\t\t\t\tjQuery('.reinit-button').hide();\n\t\t\t\tif(jQuery('#map').children().length > 0) {\n\t\t\t\t\tvar div = jQuery('#map')[0];\n\t\t\t\t\tdiv.map.editLayer.destroyFeatures();\n\t\t\t\t\tvar center = new OpenLayers.LonLat(" . $args['map_centroid_long'] . ", " . $args['map_centroid_lat'] . ");\n\t\t\t\t\tcenter.transform(div.map.displayProjection, div.map.projection);\n\t\t\t\t\tdiv.map.setCenter(center, " . (int) $args['map_zoom'] . ");\n\t\t\t\t}\n        \t}  else \n\t\t\t\talertIndiciaError(data);\n  \t\t},\n        complete: function (){\n  \t\t\tjQuery('.loading-button').removeClass('loading-button');\n  \t\t}\n});\n\n\$('#cc-1-valid-button').click(function() {\n\tjQuery('#cc-1-collection-details').submit();\n});\n\n\$('#cc-1-reinit-button').click(function() {\n    clearErrors('form#cc-1-collection-details');\n\tif(jQuery('form#cc-1-collection-details > input[name=sample\\:id]').filter('[disabled]').length > 0) { return } // sample id is disabled, so no data has been saved - do nothing.\n    if (!jQuery('form#cc-1-collection-details > input').valid()) {\n    \tmyScrollToError();\n    \talert(\"" . lang::get('LANG_Unable_To_Reinit') . "\");\n        return ;\n  \t}\n\tif(confirm(\"" . lang::get('LANG_Confirm_Reinit') . "\")){\n\t\tjQuery('#cc-1-delete-collection').submit();\n\t}\n});\n\n";
        // Flower Station section.
        $options = iform_map_get_map_options($args, $readAuth);
        $olOptions = iform_map_get_ol_options($args);
        // The maps internal projection will be left at its default of 900913.
        $options['searchLayer'] = 'true';
        $options['initialFeatureWkt'] = null;
        $options['proxy'] = '';
        // Switch to degrees, minutes, seconds for lat long.
        $options['latLongFormat'] = 'DMS';
        $options['suffixTemplate'] = 'nosuffix';
        if (lang::get('msgGeorefSelectPlace') != 'msgGeorefSelectPlace') {
            $options['msgGeorefSelectPlace'] = lang::get('msgGeorefSelectPlace');
        }
        if (lang::get('msgGeorefNothingFound') != 'msgGeorefNothingFound') {
            $options['msgGeorefNothingFound'] = lang::get('msgGeorefNothingFound');
        }
        $extraParams = $readAuth + array('taxon_list_id' => $args['flower_list_id'], 'view' => 'detail', 'orderby' => 'taxonomic_sort_order', 'allow_data_entry' => 't');
        $species_ctrl_args = array('label' => lang::get('LANG_Flower_Species'), 'fieldname' => 'flower:taxa_taxon_list_id', 'table' => 'taxa_taxon_list', 'captionField' => 'taxon', 'valueField' => 'id', 'columns' => 2, 'blankText' => lang::get('LANG_Choose_Taxon'), 'extraParams' => $extraParams, 'suffixTemplate' => 'nosuffix');
        $r .= '
<div id="cc-2" class="poll-section">
  <div id="cc-2-title" class="ui-accordion-header ui-helper-reset ui-state-active ui-corner-all poll-section-title"><span>' . lang::get('LANG_Flower_Station') . '</span>
    <div class="right">
      <span id="cc-2-mod-button" class="ui-state-default ui-corner-all mod-button">' . lang::get('LANG_Modify') . '</span>
    </div>
  </div>
  <div id="cc-2-body" class="ui-accordion-content ui-helper-reset ui-widget-content ui-corner-top ui-accordion-content-active poll-section-body">
    <div id="cc-2-flower" >
	  <div id="cc-2-flower-title">' . lang::get('LANG_Upload_Flower') . '</div>
	  <form id="cc-2-flower-upload" enctype="multipart/form-data" action="' . iform_ajaxproxy_url($node, 'media') . '" method="POST">
    		<input type="hidden" id="website_id" name="website_id" value="' . $args['website_id'] . '" />
    		<input name="upload_file" type="file" class="required" />
     		<input type="submit" value="' . lang::get('LANG_Upload') . '" class="btn-submit" />
 	  		<div id="cc-2-flower-image" class="poll-image"></div>
      </form>
 	  <div id="cc-2-flower-identify" class="poll-dummy-form">
 	    <div class="id-tool-group">
          ' . iform_pollenators::help_button($use_help, "flower-help-button", $args['help_function'], $args['help_flower_arg']) . '
		  <p><strong>' . lang::get('LANG_Identify_Flower') . '</strong></p>
          <input type="hidden" id="flower:taxon_details" name="flower:taxon_details" />
          <input type="hidden" name="flower:determination_type" value="A" />  
   	      <label for="flower-id-button">' . lang::get('LANG_Flower_ID_Key_label') . ' :</label><span id="flower-id-button" class="ui-state-default ui-corner-all poll-id-button" >' . lang::get('LANG_Launch_ID_Key') . '</span>
		  <span id="flower-id-cancel" class="ui-state-default ui-corner-all poll-id-cancel" >' . lang::get('LANG_Cancel_ID') . '</span>
 	      <p id="flower_taxa_list"></p>
 	    </div>
 	    <div class="id-later-group">
 	      <label for="id-flower-later" class="follow-on">' . lang::get('LANG_ID_Flower_Later') . ' </label><input type="checkbox" id="id-flower-later" name="id-flower-later" /> 
 	    </div>
 	    <div class="id-specified-group">
 	      ' . data_entry_helper::select($species_ctrl_args) . '
          <label for="flower:taxon_extra_info" class="follow-on">' . lang::get('LANG_ID_More_Precise') . ' </label> 
          <input type="text" id="flower:taxon_extra_info" name="flower:taxon_extra_info" class="taxon-info" />
        </div>
      </div>
      <div class="id-comment">
        <label for="flower:comment" class="follow-on">' . lang::get('LANG_ID_Comment') . ' </label>
        <textarea id="flower:comment" name="flower:comment" class="taxon-comment" rows="5" columns="80"></textarea>
      </div>
    </div>
    <div class="poll-break"></div>
 	<div id="cc-2-environment">
	  <div id="cc-2-environment-title">' . lang::get('LANG_Upload_Environment') . '</div>
 	  <form id="cc-2-environment-upload" enctype="multipart/form-data" action="' . iform_ajaxproxy_url($node, 'media') . '" method="POST">
    	<input type="hidden" id="website_id" name="website_id" value="' . $args['website_id'] . '" />
    	<input name="upload_file" type="file" class="required" />
    	<input type="submit" value="' . lang::get('LANG_Upload') . '" class="btn-submit" />
 	  	<div id="cc-2-environment-image" class="poll-image"></div>
      </form>
 	</div>
 	<form id="cc-2-floral-station" action="' . iform_ajaxproxy_url($node, 'loc-smp-occ') . '" method="POST">
      <input type="hidden" id="website_id" name="website_id" value="' . $args['website_id'] . '" />
      <input type="hidden" id="location:id" name="location:id" value="" />
      <input type="hidden" id="location:name" name="location:name" value=""/>
      <input type="hidden" name="location:centroid_sref" />
      <input type="hidden" name="location:centroid_geom" />
      <input type="hidden" name="location:centroid_sref_system" value="4326" />
      <input type="hidden" id="location_image:path" name="location_image:path" value="" />
      <input type="hidden" id="sample:survey_id" name="sample:survey_id" value="' . $args['survey_id'] . '" />
      <input type="hidden" id="sample:id" name="sample:id" value=""/>
      <input type="hidden" name="sample:date" value="2010-01-01"/>
      <input type="hidden" name="determination:taxa_taxon_list_id" value=""/>  
      <input type="hidden" name="determination:taxon_details" value=""/>  
      <input type="hidden" name="determination:taxon_extra_info" value=""/>  
      <input type="hidden" name="determination:comment" value=""/>  
      <input type="hidden" name="determination:determination_type" value="A" />  
      <input type="hidden" name="determination:cms_ref" value="' . $uid . '" />
      <input type="hidden" name="determination:email_address" value="' . $email . '" />
      <input type="hidden" name="determination:person_name" value="' . $username . '" />  
      <input type="hidden" name="occurrence:use_determination" value="Y"/>    
      <input type="hidden" name="occurrence:record_status" value="C" />
      <input type="hidden" id="location_image:id" name="location_image:id" value="" disabled="disabled" />
      <input type="hidden" id="occurrence:id" name="occurrence:id" value="" disabled="disabled" />
      <input type="hidden" id="determination:id" name="determination:id" value="" disabled="disabled" />
      <input type="hidden" id="occurrence_image:id" name="occurrence_image:id" value="" disabled="disabled" />
      <input type="hidden" id="occurrence_image:path" name="occurrence_image:path" value="" />
      ' . str_replace("\n", "", data_entry_helper::outputAttribute($occurrence_attributes[$args['flower_type_attr_id']], $defNRAttrOptions)) . str_replace("\n", "", data_entry_helper::outputAttribute($location_attributes[$args['distance_attr_id']], $defNRAttrOptions)) . str_replace("\n", "", data_entry_helper::outputAttribute($location_attributes[$args['habitat_attr_id']], $checkOptions)) . '
    </form>
    <div class="poll-break"></div>
    <div id="cc-2-location-container">
      ' . iform_pollenators::help_button($use_help, "location-help-button", $args['help_function'], $args['help_location_arg']) . '
      <div id="cc-2-location-notes" >' . lang::get('LANG_Location_Notes') . '</div>
      <div id="cc-2-location-entry">
        ' . data_entry_helper::georeference_lookup(iform_map_get_georef_options($args)) . '
    	<span >' . lang::get('LANG_Georef_Notes') . '</span>
 	    <label for="place:INSEE">' . lang::get('LANG_Or') . '</label>
 		<input type="text" id="place:INSEE" name="place:INSEE" value="' . lang::get('LANG_INSEE') . '"
	 		onclick="if(this.value==\'' . lang::get('LANG_INSEE') . '\'){this.value=\'\'; this.style.color=\'#000\'}"  
            onblur="if(this.value==\'\'){this.value=\'' . lang::get('LANG_INSEE') . '\'; this.style.color=\'#555\'}" />
    	<input type="button" id="search-insee-button" class="ui-corner-all ui-widget-content ui-state-default search-button" value="' . lang::get('search') . '" />
 	    <label >' . lang::get('LANG_Or') . '</label>
    	' . data_entry_helper::sref_textbox(array('srefField' => 'place:entered_sref', 'systemfield' => 'place:entered_sref_system', 'id' => 'place-sref', 'fieldname' => 'place:name', 'splitLatLong' => true, 'labelLat' => lang::get('Latitude'), 'fieldnameLat' => 'place:lat', 'labelLong' => lang::get('Longitude'), 'fieldnameLong' => 'place:long', 'idLat' => 'imp-sref-lat', 'idLong' => 'imp-sref-long', 'suffixTemplate' => 'nosuffix')) . '
 	  </div>
 	  <div class="poll-map-container">';
        $tempScript = data_entry_helper::$onload_javascript;
        data_entry_helper::$onload_javascript = '';
        $r .= data_entry_helper::map_panel($options, $olOptions);
        $map1JS = data_entry_helper::$onload_javascript;
        data_entry_helper::$onload_javascript = $tempScript;
        $r .= '</div>
 	  <div id="cc-2-loc-description"></div>
    </div>
  </div>
  <div id="cc-2-footer" class="ui-accordion-content ui-helper-reset ui-widget-content ui-corner-bottom ui-accordion-content-active poll-section-footer">
    <div id="cc-2-valid-button" class="ui-state-default ui-corner-all save-button">' . lang::get('LANG_Validate_Flower') . '</div>
  </div>
</div>';
        // NB the distance attribute is left blank at the moment if unknown: TODO put in a checkbox : checked if blank for nsp
        data_entry_helper::$javascript .= "\n\nshowSessionsPanel = true;\n\nbuildMap = function (){\n\tif(jQuery('.poll-map-container:visible').length == 0) return; \n\tif(jQuery('#map').children().length == 0) {\n\t\t" . $map1JS . "\n  \t\tjQuery('#map')[0].map.searchLayer.events.register('featuresadded', {}, function(a1){\n\t\t\tif(inseeLayer != null) inseeLayer.destroyFeatures();\n\t\t});\n\t\tjQuery('#map')[0].map.editLayer.events.register('featuresadded', {}, function(a1){\n\t\t\tif(inseeLayer != null) inseeLayer.destroy();\n\t\t\tjQuery('#cc-2-loc-description').empty();\n\t\t  \tvar filter = new OpenLayers.Filter.Spatial({type: OpenLayers.Filter.Spatial.CONTAINS, property: 'the_geom', value: jQuery('#map')[0].map.editLayer.features[0].geometry});\n\t\t\tvar strategy = new OpenLayers.Strategy.Fixed({preload: false, autoActivate: false});\n\t\t\tvar styleMap = new OpenLayers.StyleMap({\"default\": new OpenLayers.Style({fillColor: \"Red\", strokeColor: \"Red\", fillOpacity: 0, strokeWidth: 1})});\n\t\t\tinseeLayer = new OpenLayers.Layer.Vector('INSEE Layer', {\n\t\t\t\tstyleMap: styleMap,\n\t\t\t\tstrategies: [strategy],\n\t\t\t\tdisplayInLayerSwitcher: false,\n\t\t\t\tprotocol: new OpenLayers.Protocol.WFS({\n\t\t\t\t\turl:  '" . str_replace("{HOST}", $_SERVER['HTTP_HOST'], $args['INSEE_url']) . "',\n\t\t\t\t\tfeaturePrefix: '" . $args['INSEE_prefix'] . "',\n\t\t\t\t\tfeatureType: '" . $args['INSEE_type'] . "',\n\t\t\t\t\tgeometryName:'the_geom',\n\t\t\t\t\tfeatureNS: '" . $args['INSEE_ns'] . "',\n\t\t\t\t\tsrsName: 'EPSG:900913',\n\t\t\t\t\tversion: '1.1.0'                  \n\t\t\t\t\t,propertyNames: ['the_geom', 'NOM', 'INSEE_NEW', 'DEPT_NUM', 'DEPT_NOM', 'REG_NUM', 'REG_NOM']\n\t\t\t\t})\n\t\t\t});\n\t\t    inseeLayer.events.register('featuresadded', {}, function(a1){\n    \t\t\tif(a1.features.length > 0)\n\t\t\t    \tjQuery('<span>'+a1.features[0].attributes.NOM+' ('+a1.features[0].attributes.INSEE_NEW+'), '+a1.features[0].attributes.DEPT_NOM+' ('+a1.features[0].attributes.DEPT_NUM+'), '+a1.features[0].attributes.REG_NOM+' ('+a1.features[0].attributes.REG_NUM+')</span>').appendTo('#cc-2-loc-description');\n\t\t    });\n\t\t\tjQuery('#map')[0].map.addLayer(inseeLayer);\n\t\t\tstrategy.load({filter: filter});\n\t\t});\n\t}\n}\n\nflowerIDstruc = {\n\ttype: 'flower',\n\tselector: '#cc-2-flower-identify',\n\tmainForm: 'form#cc-2-floral-station',\n\ttimeOutTimer: null,\n\tpollTimer: null,\n\tpollFile: '',\n\tinvokeURL: '" . $args['ID_tool_flower_url'] . "',\n\tpollURL: '" . str_replace("{HOST}", $_SERVER['HTTP_HOST'], $args['ID_tool_flower_poll_dir']) . "',\n\tname: 'flowerIDstruc',\n\ttaxaList: flowerTaxa\n};\n\ntoolPoller = function(toolStruct){\n\tif(toolStruct.pollFile == '') return;\n\ttoolStruct.pollTimer = setTimeout('toolPoller('+toolStruct.name+');', " . $args['ID_tool_poll_interval'] . ");\n\t\$.get(toolStruct.pollURL+toolStruct.pollFile, function(data){\n\t  pollReset(toolStruct);\n\t  var da = data.split('\\n');\n      jQuery(toolStruct.selector+' [name='+toolStruct.type+'\\:taxon_details]').val(da[2]); // Stores the state of identification, which details how the identification was arrived at within the tool.\n\t  da[1] = da[1].replace(/\\\\\\\\i\\{\\}/g, '').replace(/\\\\\\\\i0\\{\\}/g, '').replace(/\\\\/g, '');\n\t  var items = da[1].split(':');\n\t  var count = items.length;\n\t  if(items[count-1] == '') count--;\n\t  if(items[count-1] == '') count--;\n\t  if(count <= 0){\n\t  \t// no valid stuff so blank it all out.\n\t  \tjQuery('#'+toolStruct.type+'_taxa_list').append(\"" . lang::get('LANG_Taxa_Unknown_In_Tool') . "\");\n\t  \tjQuery(toolStruct.selector+' [name='+toolStruct.type+'\\:determination_type]').val('X'); // Unidentified.\n      } else {\n      \tvar resultsIDs = [];\n      \tvar resultsText = \"" . lang::get('LANG_Taxa_Returned') . "<br />{ \";\n      \tvar notFound = '';\n\t\tfor(var j=0; j < count; j++){\n\t\t\titemText = items[j].replace(/</g, '&lt;').replace(/>/g, '&gt;');\n\t\t\tvar found = false;\n\t\t\tfor(i = 0; i< toolStruct.taxaList.length; i++){\n  \t\t\t\tif(toolStruct.taxaList[i].taxon == itemText){\n\t  \t\t\t\tresultsIDs.push(toolStruct.taxaList[i].id);\n\t  \t\t\t\tresultsText = resultsText + (j == 0 ? '' : '<br />&nbsp;&nbsp;') + itemText;\n\t  \t\t\t\tfound = true;\n  \t\t\t\t}\n  \t\t\t};\n  \t\t\tif(!found){\n  \t\t\t\tnotFound = (notFound == '' ? '' : notFound + ', ') + itemText;\n  \t\t\t}\n  \t\t}\n\t\tjQuery('#'+toolStruct.type+'_taxa_list').append(resultsText+ ' }');\n\t\tjQuery('#'+toolStruct.type+'-id-button').data('toolRetValues', resultsIDs);\n\t  \tif(notFound != ''){\n\t\t\tvar comment = jQuery(toolStruct.selector+' [name='+toolStruct.type+'\\:comment]');\n\t\t\tcomment.val('" . lang::get('LANG_ID_Unrecognised') . " '+notFound+' '+comment.val());\n\t\t}\n  \t  }\n    });\n};\n\npollReset = function(toolStruct){\n\tclearTimeout(toolStruct.timeOutTimer);\n\tclearTimeout(toolStruct.pollTimer);\n\tjQuery('#'+toolStruct.type+'-id-cancel').hide();\n\tjQuery('#'+toolStruct.type+'-id-button').show();\n\tjQuery('#'+toolStruct.type+'-id-button').data('toolRetValues', []);\n\tjQuery(toolStruct.selector+' [name='+toolStruct.type+'\\:taxon_details]').val('');\n\tjQuery('#'+toolStruct.type+'_taxa_list').empty();\n\ttoolStruct.pollFile='';\n\ttoolStruct.timeOutTimer = null;\n\ttoolStruct.pollTimer = null;\n};\n\nidButtonPressed = function(toolStruct){\n\tjQuery(toolStruct.selector+' [name='+toolStruct.type+'\\:determination_type]').val('A');\n\tjQuery('#id-'+toolStruct.type+'-later').removeAttr('checked');\n\tjQuery('#'+toolStruct.type+'-id-button').data('toolRetValues', []);\n\tjQuery(toolStruct.selector+' [name='+toolStruct.type+'\\:taxon_details]').val('');\n\tjQuery('#'+toolStruct.type+'_taxa_list').empty();\n\tjQuery(toolStruct.selector+' [name='+toolStruct.type+'\\:taxa_taxon_list_id]').val('');\n\tjQuery('#'+toolStruct.type+'-id-cancel').show();\n\tjQuery('#'+toolStruct.type+'-id-button').hide();\n\tvar d = new Date;\n\tvar s = d.getTime();\n\ttoolStruct.pollFile = '" . session_id() . "_'+s.toString()\n\tclearTimeout(toolStruct.timeOutTimer);\n\tclearTimeout(toolStruct.pollTimer);\n\twindow.open(toolStruct.invokeURL+toolStruct.pollFile,'','');\n\ttoolStruct.pollTimer = setTimeout('toolPoller('+toolStruct.name+');', " . $args['ID_tool_poll_interval'] . ");\n\ttoolStruct.timeOutTimer = setTimeout('toolReset('+toolStruct.name+');', " . $args['ID_tool_poll_timeout'] . ");\n};\njQuery('#flower-id-button').click(function(){\n\tidButtonPressed(flowerIDstruc);\n});\njQuery('#flower-id-cancel').click(function(){\n\tpollReset(flowerIDstruc);\n});\n\njQuery('#flower-id-cancel').hide();\n\ntaxonChosen = function(toolStruct){\n  \tjQuery('#id-'+toolStruct.type+'-later').removeAttr('checked');\n\tjQuery('#'+toolStruct.type+'-id-button').data('toolRetValues', []);\n\tjQuery(toolStruct.selector+' [name='+toolStruct.type+'\\:taxon_details]').val('');\n\tjQuery('#'+toolStruct.type+'_taxa_list').empty();\n\tjQuery(toolStruct.selector+' [name='+toolStruct.type+'\\:comment]').val('');\n  \tjQuery(toolStruct.selector+' [name='+toolStruct.type+'\\:determination_type]').val('A');\n};\njQuery('#cc-2-flower-identify select[name=flower\\:taxa_taxon_list_id]').change(function(){\n\tpollReset(flowerIDstruc);\n\ttaxonChosen(flowerIDstruc);\n});\n\nidLater = function (toolStruct){\n\tif (jQuery('#id-'+toolStruct.type+'later').attr('checked') != '') {\n\t  \tjQuery(toolStruct.selector+' [name='+toolStruct.type+'\\:determination_type]').val('A');\n\t\tjQuery('#'+toolStruct.type+'-id-button').data('toolRetValues', []);\n\t\tjQuery(toolStruct.selector+' [name='+toolStruct.type+'\\:taxon_details]').val('');\n\t\tjQuery('#'+toolStruct.type+'_taxa_list').empty();\n\t\tjQuery(toolStruct.selector+' [name='+toolStruct.type+'\\:taxa_taxon_list_id]').val('');\n\t\tjQuery(toolStruct.selector+' [name='+toolStruct.type+'\\:taxon_extra_info]').val(''); // more precise info\n\t\tjQuery(toolStruct.selector+' [name='+toolStruct.type+'\\:comment]').val('');\n\t}\n};\njQuery('#id-flower-later').change(function (){\n\tpollReset(flowerIDstruc);\n\tidLater(flowerIDstruc);\n});\n\n\njQuery('#search-insee-button').click(function(){\n\tif(inseeLayer != null)\n\t\tinseeLayer.destroy();\n\tvar filters = [];\n  \tvar place = jQuery('input[name=place\\:INSEE]').val();\n  \tif(place == '" . lang::get('LANG_INSEE') . "') return;\n  \tfilters.push(new OpenLayers.Filter.Comparison({\n  \t\t\ttype: OpenLayers.Filter.Comparison.EQUAL_TO ,\n    \t\tproperty: 'INSEE_NEW',\n    \t\tvalue: place\n  \t\t}));\n  \tfilters.push(new OpenLayers.Filter.Comparison({\n  \t\t\ttype: OpenLayers.Filter.Comparison.EQUAL_TO ,\n    \t\tproperty: 'INSEE_OLD',\n    \t\tvalue: place\n  \t\t}));\n\n\tvar strategy = new OpenLayers.Strategy.Fixed({preload: false, autoActivate: false});\n\tvar styleMap = new OpenLayers.StyleMap({\n                \"default\": new OpenLayers.Style({\n                    fillColor: \"Red\",\n                    strokeColor: \"Red\",\n                    fillOpacity: 0,\n                    strokeWidth: 1\n                  })\n\t});\n\tinseeLayer = new OpenLayers.Layer.Vector('INSEE Layer', {\n\t\t  styleMap: styleMap,\n          strategies: [strategy],\n          displayInLayerSwitcher: false,\n\t      protocol: new OpenLayers.Protocol.WFS({\n              url:  '" . str_replace("{HOST}", $_SERVER['HTTP_HOST'], $args['INSEE_url']) . "',\n              featurePrefix: '" . $args['INSEE_prefix'] . "',\n              featureType: '" . $args['INSEE_type'] . "',\n              geometryName:'the_geom',\n              featureNS: '" . $args['INSEE_ns'] . "',\n              srsName: 'EPSG:900913',\n              version: '1.1.0'                  \n      \t\t  ,propertyNames: ['the_geom']\n  \t\t\t})\n    });\n\tinseeLayer.events.register('featuresadded', {}, function(a1){\n\t\tvar div = jQuery('#map')[0];\n\t\tdiv.map.searchLayer.destroyFeatures();\n\t\tvar bounds=inseeLayer.getDataExtent();\n    \tvar dy = (bounds.top-bounds.bottom)/10;\n    \tvar dx = (bounds.right-bounds.left)/10;\n    \tbounds.top = bounds.top + dy;\n    \tbounds.bottom = bounds.bottom - dy;\n    \tbounds.right = bounds.right + dx;\n    \tbounds.left = bounds.left - dx;\n    \t// if showing a point, don't zoom in too far\n    \tif (dy===0 && dx===0) {\n    \t\tdiv.map.setCenter(bounds.getCenterLonLat(), div.settings.maxZoom);\n    \t} else {\n    \t\tdiv.map.zoomToExtent(bounds);\n    \t}\n    });\n\tinseeLayer.events.register('loadend', {}, function(){\n\t\tif(inseeLayer.features.length == 0){\n\t\t\talert(\"" . lang::get('LANG_NO_INSEE') . "\");\n\t\t}\n    });\n    jQuery('#map')[0].map.addLayer(inseeLayer);\n\tstrategy.load({filter: new OpenLayers.Filter.Logical({\n\t\t\t      type: OpenLayers.Filter.Logical.OR,\n\t\t\t      filters: filters\n\t\t  \t  })});\n});\n\nvalidateStationPanel = function(){\n\tvar myPanel = jQuery('#cc-2');\n\tvar valid = true;\n\tclearErrors('form#cc-2-floral-station');\n\tclearErrors('#cc-2-flower-identify');\n\tif(myPanel.filter(':visible').length == 0) return true; // panel is not visible so no data to fail validation.\n\tif(myPanel.find('.poll-section-body:visible').length == 0) return true; // body hidden so data already been validated successfully.\n\t// If no data entered also return true: this can only be the case when pressing the modify button on the collections panel\n\tif(jQuery('form#cc-2-floral-station > input[name=location_image\\:path]').val() == '' &&\n\t\t\tjQuery('form#cc-2-floral-station > input[name=occurrence\\:id]').val() == '' &&\n\t\t\tjQuery('form#cc-2-floral-station > input[name=occurrence_image\\:path]').val() == '' &&\n\t\t\tjQuery('#cc-2-flower-identify select[name=flower\\:taxa_taxon_list_id]').val() == '' &&\n\t\t\tjQuery('[name=flower\\:taxon_details]').val() == '' &&\n\t\t\tjQuery('#cc-2-flower-identify [name=flower\\:taxon_extra_info]').val() == '' &&\n\t\t\tjQuery('[name=flower\\:comment]').val() == '' &&\n\t\t\tjQuery('[name=occAttr\\:" . $args['flower_type_attr_id'] . "],[name^=occAttr\\:" . $args['flower_type_attr_id'] . "\\:]').filter('[checked]').length == 0 &&\n    \t\tjQuery('[name=locAttr\\:" . $args['habitat_attr_id'] . "],[name^=locAttr\\:" . $args['habitat_attr_id'] . "\\:]').filter('[checked]').length == 0 &&\n    \t\tjQuery('[name=locAttr\\:" . $args['distance_attr_id'] . "],[name^=locAttr\\:" . $args['distance_attr_id'] . "\\:]').val() == '') {\n\t\tjQuery('#cc-2').foldPanel();\n\t\treturn true;\n\t}\n    if(jQuery('form#cc-2-floral-station > input[name=location_image\\:path]').val() == '' ||\n\t\t\t\t\tjQuery('form#cc-2-floral-station > input[name=occurrence_image\\:path]').val() == ''){\n\t\tif(jQuery('form#cc-2-floral-station > input[name=occurrence_image\\:path]').val() == '')\n\t\t\tmyScrollTo('#cc-2-flower-upload');\n\t\telse\n\t\t\tmyScrollTo('#cc-2-environment-upload');\n\t\talert(\"" . lang::get('LANG_Must_Provide_Pictures') . "\");\n\t\tvalid = false;\n\t}\n    if(jQuery('#imp-geom').val() == '') {\n\t\talert(\"" . lang::get('LANG_Must_Provide_Location') . "\");\n\t\tmyScrollTo('.poll-map-container');\n\t\tvalid = false;\n\t}\n\tif (jQuery('#id-flower-later').attr('checked') == '' &&\t jQuery('[name=flower\\:taxon_details]').val() == ''){\n\t\tif(!validateRequiredField('flower\\:taxa_taxon_list_id', '#cc-2-flower-identify')) { valid = false; }\n    }\n\tif (!jQuery('form#cc-2-floral-station > input').valid()) { valid = false; }\n\tif (!validateRadio('occAttr\\:" . $args['flower_type_attr_id'] . "', 'form#cc-2-floral-station')) { valid = false; }\n\tif (!validateOptInt('locAttr\\:" . $args['distance_attr_id'] . "', 'form#cc-2-floral-station')) { valid = false; }\n   \tif ( valid == false ) {\n   \t\tmyScrollToError();\n   \t\treturn valid;\n   \t}\n\tshowSessionsPanel = false;\n\tjQuery('form#cc-2-floral-station').submit();\n\treturn true;\n};\n\n// Flower upload picture form.\n\$('#cc-2-flower-upload').ajaxForm({ \n\t\tasync: false,\n\t\tdataType:  'json', \n        beforeSubmit:   function(data, obj, options){\n         \tif (!jQuery('form#cc-2-flower-upload').valid()) {\n   \t\t\t\treturn false;\n   \t\t\t}\n        \t\$('#cc-2-flower-image').empty();\n        \t\$('#cc-2-flower-image').addClass('loading')\n\t\t   \tjQuery('form#cc-2-floral-station input[name=occurrence_image\\:path]').val('');\n  \t\t},\n        success:   function(data){\n        \tif(data.success == true){\n\t        \t// There is only one file\n\t        \tjQuery('form#cc-2-floral-station input[name=occurrence_image\\:path]').val(data.files[0]);\n\t        \tinsertImage('med-'+data.files[0], jQuery('#cc-2-flower-image'), " . $args['Flower_Image_Ratio'] . ");\n\t\t\t\tjQuery('#cc-2-flower-upload input[name=upload_file]').val('');\n\t\t\t} else\n\t\t\t\talertIndiciaError(data);\n  \t\t},\n  \t\tcomplete: function(){\n\t\t\t\$('#cc-2-flower-image').removeClass('loading');\n  \t\t}\n});\n\n// Flower upload picture form.\n\$('#cc-2-environment-upload').ajaxForm({ \n\t\tasync: false,\n\t\tdataType:  'json', \n        beforeSubmit:   function(data, obj, options){\n         \tif (!jQuery('form#cc-2-environment-upload').valid()) {\n   \t\t\t\treturn false;\n   \t\t\t}\n        \t\$('#cc-2-environment-image').empty();\n        \t\$('#cc-2-environment-image').addClass('loading')\n\t       \tjQuery('form#cc-2-floral-station input[name=location_image\\:path]').val('');\n  \t\t},\n        success:   function(data){\n        \tif(data.success == true){\n\t        \t// There is only one file\n\t        \tjQuery('form#cc-2-floral-station input[name=location_image\\:path]').val(data.files[0]);\n\t        \tinsertImage('med-'+data.files[0], jQuery('#cc-2-environment-image'), " . $args['Environment_Image_Ratio'] . ");\n\t\t\t\tjQuery('#cc-2-environment-upload input[name=upload_file]').val('');\n\t\t\t} else\n\t\t\t\talertIndiciaError(data);\n        },\n  \t\tcomplete: function(){\n\t\t\t\$('#cc-2-environment-image').removeClass('loading');\n  \t\t}\n});\n\nfindID = function(name, data){\n\tfor(var i=0; i< data.length;i++){\n\t\tif(data[i].name == name) return i;\n\t}\n};\n\n\$('#cc-2-floral-station').ajaxForm({ \n\tasync: false,\n\tdataType:  'json', \n    beforeSubmit:   function(data, obj, options){\n\t\tvar valid = true;\n\t\tclearErrors('form#cc-2-floral-station');\n\t\tclearErrors('#cc-2-flower-identify');\n    \tif(jQuery('form#cc-2-floral-station > input[name=location_image\\:path]').val() == '' ||\n\t\t\t\t\tjQuery('form#cc-2-floral-station > input[name=occurrence_image\\:path]').val() == '' ){\n\t\t\tif(jQuery('form#cc-2-floral-station > input[name=occurrence_image\\:path]').val() == '')\n\t\t\t\tmyScrollTo('#cc-2-flower-upload');\n\t\t\telse\n\t\t\t\tmyScrollTo('#cc-2-environment-upload');\n\t\t\talert(\"" . lang::get('LANG_Must_Provide_Pictures') . "\");\n\t\t\tvalid = false;\n\t\t}\n\t\tif(jQuery('#imp-geom').val() == '') {\n\t\t\tmyScrollTo('.poll-map-container');\n\t\t\talert(\"" . lang::get('LANG_Must_Provide_Location') . "\");\n\t\t\tvalid = false;\n\t\t}\n\t\tif (!jQuery('form#cc-2-floral-station > input').valid()) { valid = false; }\n\t\tif (!validateRadio('occAttr\\:" . $args['flower_type_attr_id'] . "', 'form#cc-2-floral-station')) { valid = false; }\n\t\tif (!validateOptInt('locAttr\\:" . $args['distance_attr_id'] . "', 'form#cc-2-floral-station')) { valid = false; }\n\t\tdata[findID('location:centroid_sref', data)].value = jQuery('#imp-sref').val();\n\t\tdata[findID('location:centroid_geom', data)].value = jQuery('#imp-geom').val();\n\t\tif (jQuery('#id-flower-later').attr('checked') == ''){\n\t\t\tdata[findID('determination:taxa_taxon_list_id', data)].value = jQuery('#cc-2-flower-identify select[name=flower\\:taxa_taxon_list_id]').val();\n\t\t\tdata[findID('determination:taxon_details', data)].value = jQuery('#cc-2-flower-identify [name=flower\\:taxon_details]').val();\n\t\t\tdata[findID('determination:taxon_extra_info', data)].value = jQuery('#cc-2-flower-identify [name=flower\\:taxon_extra_info]').val();\n\t\t\tdata[findID('determination:comment', data)].value = jQuery('[name=flower\\:comment]').val();\n\t\t\tdata[findID('determination:determination_type', data)].value = jQuery('#cc-2-flower-identify [name=flower\\:determination_type]').val();\n\t\t\tif (jQuery('#cc-2-flower-identify [name=flower\\:taxon_details]').val() == ''){\n\t\t\t\tif (!validateRequiredField('flower\\:taxa_taxon_list_id', '#cc-2-flower-identify')) {\n\t\t\t\t\tvalid = false;\n  \t\t\t\t} else {\n\t\t\t\t\tdata.push({name: 'determination\\:taxa_taxon_list_id_list[]', value: ''});\n  \t\t\t\t}\n\t\t\t} else {\n\t\t\t\tvar toolValues = jQuery('#flower-id-button').data('toolRetValues');\n\t\t\t\tfor(var i = 0; i<toolValues.length; i++){\n\t\t\t\t\tdata.push({name: 'determination\\:taxa_taxon_list_id_list[]', value: toolValues[i]});\n\t\t\t\t}\t\t\t\n\t\t\t}\n\t\t} else {\n\t\t\tdata.splice(10,8); // remove determination entries.\n\t\t}\n   \t\tif ( valid == false ) {\n\t\t\tmyScrollToError();\n\t\t\treturn false;\n\t\t};\n  \t\tjQuery('#cc-2-valid-button').addClass('loading-button');\n   \t\treturn true;\n\t},\n    success:   function(data){\n       \tif(data.success == 'multiple records' && data.outer_table == 'sample'){\n       \t\t// the sample and location ids are already fixed, so just need to populate the occurrence and image IDs, and rename the location and occurrence attribute.\n\t\t    var location_id = jQuery('#cc-2-floral-station > input[name=location\\:id]').val();\n       \t\tloadAttributes('location_attribute_value', 'location_attribute_id', 'location_id', 'location\\:id', location_id, 'locAttr', true);\n       \t\t\$.getJSON(\"" . $svcUrl . "\" + \"/data/occurrence\" +\n\t\t          \"?mode=json&view=detail&nonce=" . $readAuth['nonce'] . "&auth_token=" . $readAuth['auth_token'] . "\" +\n\t\t          \"&sample_id=\"+data.outer_id+\"&deleted=f&callback=?\", function(occdata) {\n\t\t\t\tif(!(occdata instanceof Array)){\n   \t\t\t\t\talertIndiciaError(occdata);\n   \t\t\t\t} else if (occdata.length>0) {\n\t\t        \tjQuery('#cc-2-floral-station > input[name=occurrence\\:id]').removeAttr('disabled').val(occdata[0].id);\n       \t\t\t\tloadAttributes('occurrence_attribute_value', 'occurrence_attribute_id', 'occurrence_id', 'occurrence\\:id', occdata[0].id, 'occAttr', false);\n\t\t\t\t\t\$.getJSON(\"" . $svcUrl . "/data/occurrence_image/\" +\n       \t\t\t\t\t\t\"?mode=json&view=list&nonce=" . $readAuth['nonce'] . "&auth_token=" . $readAuth['auth_token'] . "\" +\n       \t\t\t\t\t\t\"&occurrence_id=\"+occdata[0].id+\"&callback=?\", function(imgdata) {\n\t\t\t\t\t    if(!(imgdata instanceof Array)){\n   \t\t\t\t\t\t\talertIndiciaError(imgdata);\n   \t\t\t\t\t\t} else if (imgdata.length>0) {\n\t\t        \t\t\tjQuery('#cc-2-floral-station > input[name=occurrence_image\\:id]').removeAttr('disabled').val(imgdata[0].id);\n\t\t        \t\t}});\n\t\t        }});\n\t\t\t\$.getJSON(\"" . $svcUrl . "/data/location_image/\" +\n       \t\t\t\t\"?mode=json&view=list&nonce=" . $readAuth['nonce'] . "&auth_token=" . $readAuth['auth_token'] . "\" +\n       \t\t\t\t\"&location_id=\"+location_id+\"&callback=?\", function(data) {\n\t\t\t\tif(!(data instanceof Array)){\n   \t\t\t\t\talertIndiciaError(data);\n   \t\t\t\t} else if (data.length>0) {\n\t\t        \tjQuery('#cc-2-floral-station > input[name=location_image\\:id]').removeAttr('disabled').val(data[0].id);\n\t\t        }});\n\t\t\tjQuery('#cc-2').foldPanel();\n\t\t\tif(showSessionsPanel) { jQuery('#cc-3').showPanel(); }\n\t\t\tshowSessionsPanel = true;\n        }  else {\n\t\t\tif(data.error){\n\t\t\t\tvar lastIndex = data.error.lastIndexOf('Validation error'); \n    \t\t\tif (lastIndex != -1 && lastIndex  == (data.error.length - 16)){ \n\t\t\t\t\tif(data.errors){\n\t\t\t\t\t\tif(data.errors['location:centroid_sref']){\n\t\t\t\t\t\t\tvar label = \$('<p/>')\n\t\t\t\t\t\t\t\t.addClass('inline-error')\n\t\t\t\t\t\t\t\t.html(\"" . lang::get('LANG_Invalid_Location') . "\");\n\t\t\t\t\t\t\tlabel.insertBefore('.latLongDiv:first');\n\t\t\t\t\t\t\tmyScrollToError();\n\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\talertIndiciaError(data);\n\t\t}\n\t},\n    complete: function (){\n  \t\tjQuery('.loading-button').removeClass('loading-button');\n  \t}\n});\n\n\$('#cc-2-valid-button').click(function() {\n\tjQuery('#cc-2-floral-station').submit();\n});\n\n";
        // Sessions.
        $r .= '
<div id="cc-3" class="poll-section">
  <div id="cc-3-title" class="ui-accordion-header ui-helper-reset ui-state-active ui-corner-all poll-section-title"><span id="cc-3-title-title" >' . lang::get('LANG_Sessions_Title') . '</span>
    <div id="cc-3-mod-button" class="right ui-state-default ui-corner-all mod-button">' . lang::get('LANG_Modify') . '</div>
  </div>
  <div id="cc-3-body" class="ui-accordion-content ui-helper-reset ui-widget-content ui-corner-top ui-accordion-content-active poll-section-body">
  </div>
  <div id="cc-3-footer" class="ui-accordion-content ui-helper-reset ui-widget-content ui-corner-bottom ui-accordion-content-active poll-section-footer">
	<div id="cc-3-add-button" class="ui-state-default ui-corner-all add-button">' . lang::get('LANG_Add_Session') . '</div>
    <div id="cc-3-valid-button" class="ui-state-default ui-corner-all save-button">' . lang::get('LANG_Validate_Session') . '</div>
  </div>
</div>
<div style="display:none" />
    <form id="cc-3-delete-session" action="' . iform_ajaxproxy_url($node, 'sample') . '" method="POST">
       <input type="hidden" name="website_id" value="' . $args['website_id'] . '" />
       <input type="hidden" name="sample:survey_id" value="' . $args['survey_id'] . '" />
       <input type="hidden" name="sample:id" value="" />
       <input type="hidden" name="sample:date" value="2010-01-01"/>
       <input type="hidden" name="sample:location_id" value="" />
       <input type="hidden" name="sample:deleted" value="t" />
    </form>
</div>';
        data_entry_helper::$javascript .= "\n\$('#cc-3-delete-session').ajaxForm({ \n\t\tasync: false,\n\t\tdataType:  'json', \n        beforeSubmit:   function(data, obj, options){\n  \t\t\t// Warning this assumes that the data is fixed position:\n       \t\tdata[4].value = jQuery('#cc-1-collection-details input[name=location\\:id]').val();\n        \tif(data[2].value == '') return false;\n        \treturn true;\n  \t\t},\n        success:   function(data){\n        \tif(data.success != 'multiple records' || data.outer_table != 'sample')\n\t\t\t\talertIndiciaError(data);\n  \t\t}\n        ,complete: function (){\n  \t\t\tjQuery('.loading-button').removeClass('loading-button');\n  \t\t}\n});\npopulateSessionSelect = function(){\n\tvar insectSessionSelect = jQuery('form#cc-4-main-form > select[name=occurrence\\:sample_id]');\n\tvar value = insectSessionSelect.val();\n\tinsectSessionSelect.empty();\n\t// NB at this point the attributes have been loaded so have full name.\n\t\$('.poll-session-form').each(function(i){\n\t\tjQuery('<option value=\"'+\n\t\t\t\tjQuery(this).children('input[name=sample\\:id]').val()+\n\t\t\t\t'\">'+\n\t\t\t\tjQuery(this).children('input[name=dummy_date]').val()+\n\t\t\t\t' : '+\n\t\t\t\tjQuery(this).children('[name=smpAttr\\:" . $args['start_time_attr_id'] . "],[name^=smpAttr\\:" . $args['start_time_attr_id'] . "\\:]').val()+\n\t\t\t\t' > '+\n\t\t\t\tjQuery(this).children('[name=smpAttr\\:" . $args['end_time_attr_id'] . "],[name^=smpAttr\\:" . $args['end_time_attr_id'] . "\\:]').val()+\n\t\t\t\t'</option>')\n\t\t\t.appendTo(insectSessionSelect);\n\t});\n\tinsectSessionSelect.find('option').each(function(i,obj){\n  \t\tif(i == 0 || jQuery(obj).val() == value)\n\t\t\tinsectSessionSelect.val(insectSessionSelect.find('option').filter(':first').val());\n  \t});\n}\n\nvalidateAndSubmitOpenSessions = function(){\n\tvar valid = true;\n\t// only check the visible forms as rest have already been validated successfully.\n\t\$('.poll-session-form:visible').each(function(i){\n\t\tclearErrors(this);\n\t    if (!jQuery(this).children('input').valid()) { valid = false; }\n   \t\tif (!validateTime('smpAttr\\:" . $args['start_time_attr_id'] . "', this)) { valid = false; }\n   \t\tif (!validateTime('smpAttr\\:" . $args['end_time_attr_id'] . "', this)) { valid = false; }\n   \t\tif (!validateRadio('smpAttr\\:" . $args['sky_state_attr_id'] . "', this)) { valid = false; }\n   \t\tif (!validateRadio('smpAttr\\:" . $args['temperature_attr_id'] . "', this)) { valid = false; }\n   \t\tif (!validateRadio('smpAttr\\:" . $args['wind_attr_id'] . "', this)) { valid = false; }\n    });\n\tif(valid == false) {\n\t\tmyScrollToError();\n\t\treturn false;\n\t};\n\t\$('.poll-session-form:visible').submit();\n\treturn true;\n}\n\naddSession = function(){\n\tsessionCounter = sessionCounter + 1;\n\t// dynamically build the contents of the session block.\n\tvar newSession = jQuery('<div id=\"cc-3-session-'+sessionCounter+'\" class=\"poll-session\"/>')\n\t\t.appendTo('#cc-3-body');\n\tvar newTitle = jQuery('<div class=\"poll-session-title\">" . lang::get('LANG_Session') . " '+sessionCounter+'</div>')\n\t\t.appendTo(newSession);\n\tvar newModButton = jQuery('<div class=\"right ui-state-default ui-corner-all mod-button\">" . lang::get('LANG_Modify') . "</div>')\n\t\t.appendTo(newTitle).hide();\n\tvar newDeleteButton = jQuery('<div class=\"right ui-state-default ui-corner-all delete-button\">" . lang::get('LANG_Delete_Session') . "</div>')\n\t\t.appendTo(newTitle);\t\n\tnewModButton.click(function() {\n\t\tif(!validateAndSubmitOpenSessions()) return false;\n\t\tvar session=\$(this).parents('.poll-session');;\n\t\tsession.show();\n\t\tsession.children().show();\n\t\tsession.children(':first').children(':first').hide(); // this is the mod button itself\n    });\n    var formContainer = jQuery('<div />').appendTo(newSession);\n    var newForm = jQuery('<form action=\"" . iform_ajaxproxy_url($node, 'sample') . "\" method=\"POST\" class=\"poll-session-form\" />').appendTo(formContainer);\n\tjQuery('<input type=\"hidden\" name=\"website_id\" value=\"" . $args['website_id'] . "\" />').appendTo(newForm);\n\tjQuery('<input type=\"hidden\" name=\"sample:survey_id\" value=\"" . $args['survey_id'] . "\" />').appendTo(newForm);\n\tjQuery('<input type=\"hidden\" name=\"sample:parent_id\" />').appendTo(newForm).val(jQuery('#cc-1-collection-details > input[name=sample\\:id]').val());\n\tjQuery('<input type=\"hidden\" name=\"sample:location_id\" />').appendTo(newForm).val(jQuery('#cc-1-collection-details > input[name=location\\:id]').val());\n\tjQuery('<input type=\"hidden\" name=\"sample:id\" value=\"\" disabled=\"disabled\" />').appendTo(newForm);\n";
        if ($use_help) {
            data_entry_helper::$javascript .= "\n\tvar helpDiv = jQuery('<div class=\"right ui-state-default ui-corner-all help-button\">" . lang::get('LANG_Help_Button') . "</div>');\n\thelpDiv.click(function(){\n\t\t" . $args['help_function'] . "(" . $args['help_session_arg'] . ");\n\t});\n\thelpDiv.appendTo(newForm);";
        }
        data_entry_helper::$javascript .= "\n\tvar dateID = 'cc-3-session-date-'+sessionCounter;\n\tvar dateAttr = '<label for=\"'+dateID+'\">" . lang::get('LANG_Date') . "</label><input type=\"text\" size=\"10\" class=\"vague-date-picker required\" id=\"'+dateID+'\" name=\"dummy_date\" value=\"" . lang::get('click here') . "\" /> ';\n\tdateAttr = dateAttr + '<input type=\"hidden\" id=\"real-'+dateID+'\" name=\"sample:date\" value=\"\" class=\"required\"/> ';\n    jQuery(dateAttr).appendTo(newForm);\n\tjQuery('#'+dateID).datepicker({\n\t\tdateFormat : 'dd/mm/yy',\n\t\tconstrainInput: false,\n\t\tmaxDate: '0',\n\t\taltField : '#real-'+dateID,\n\t\taltFormat : 'yy-mm-dd'\n\t});\n    jQuery('" . str_replace("\n", "", data_entry_helper::outputAttribute($sample_attributes[$args['start_time_attr_id']], $defAttrOptions)) . "').appendTo(newForm);\n\tjQuery('" . str_replace("\n", "", data_entry_helper::outputAttribute($sample_attributes[$args['end_time_attr_id']], $defAttrOptions)) . "').appendTo(newForm);\n\tjQuery('" . str_replace("\n", "", data_entry_helper::outputAttribute($sample_attributes[$args['sky_state_attr_id']], $defNRAttrOptions)) . "').appendTo(newForm);\n\tjQuery('" . str_replace("\n", "", data_entry_helper::outputAttribute($sample_attributes[$args['temperature_attr_id']], $defNRAttrOptions)) . "').appendTo(newForm);\n\tjQuery('" . str_replace("\n", "", data_entry_helper::outputAttribute($sample_attributes[$args['wind_attr_id']], $defNRAttrOptions)) . "').appendTo(newForm);\n\tjQuery('" . str_replace("\n", "", data_entry_helper::outputAttribute($sample_attributes[$args['shade_attr_id']], $defNRAttrOptions)) . "').appendTo(newForm);\n\tnewDeleteButton.click(function() {\n\t\tvar container = \$(this).parent().parent();\n\t\tjQuery('#cc-3-delete-session').find('[name=sample\\:id]').val(container.find('[name=sample\\:id]').val());\n\t\tjQuery('#cc-3-delete-session').find('[name=sample\\:date]').val(container.find('[name=sample\\:date]').val());\n\t\tjQuery('#cc-3-delete-session').find('[name=sample\\:location_id]').val(container.find('[name=sample\\:location_id]').val());\n\t\tif(container.find('[name=sample\\:id]').filter('[disabled]').length == 0){\n\t\t\tjQuery(this).addClass('loading-button');\n\t\t\t\$.getJSON(\"" . $svcUrl . "/data/occurrence/\" +\n\t\t\t\t\t\"?mode=json&view=detail&reset_timeout=true&nonce=" . $readAuth['nonce'] . "&auth_token=" . $readAuth['auth_token'] . "\" +\n\t\t\t\t\t\"&sample_id=\"+container.find('[name=sample\\:id]').val()+\"&deleted=f&callback=?\", function(insectData) {\n\t\t\t\tif(!(insectData instanceof Array)){\n   \t\t\t\t\talertIndiciaError(insectData);\n   \t\t\t\t} else if (insectData.length>0) {\n\t\t\t\t\tjQuery('.loading-button').removeClass('loading-button');\n\t\t\t\t\talert(\"" . lang::get('LANG_Cant_Delete_Session') . "\");\n\t\t\t\t} else if(confirm(\"" . lang::get('LANG_Confirm_Session_Delete') . "\")){\n\t\t\t\t\tjQuery('#cc-3-delete-session').submit();\n\t\t\t\t\tcontainer.remove();\n\t\t\t\t\tcheckSessionButtons();\n\t\t\t\t}\n\t\t\t});\n\t\t} else if(confirm(\"" . lang::get('LANG_Confirm_Session_Delete') . "\")){\n\t\t\tcontainer.remove();\n\t\t\tcheckSessionButtons();\n\t\t}\n    });\n    newForm.ajaxForm({\n   \t\tasync: false,\n    \tdataType:  'json',\n    \tbeforeSubmit:   function(data, obj, options){\n    \t\tvar valid = true;\n    \t\tclearErrors(obj);\n    \t\tif (!obj.find('input').valid()) {\n    \t\t\tvalid = false; }\n    \t\tif (!validateRadio('smpAttr\\:" . $args['sky_state_attr_id'] . "', obj)) { valid = false; }\n   \t\t\tif (!validateRadio('smpAttr\\:" . $args['temperature_attr_id'] . "', obj)) { valid = false; }\n   \t\t\tif (!validateRadio('smpAttr\\:" . $args['wind_attr_id'] . "', obj)) { valid = false; }\n   \t\t\t// shade is a boolean, and will always have one set, default no\n   \t\t\tdata[2].value = jQuery('#cc-1-collection-details > input[name=sample\\:id]').val();\n\t\t\tdata[3].value = jQuery('#cc-1-collection-details > input[name=location\\:id]').val();\n\t\t\tjQuery('#cc-3-valid-button').addClass('loading-button');\n\t\t\tif(!valid) myScrollToError();\n\t\t\treturn valid;\n\t\t},\n   \t    success:   function(data, status, form){\n   \t    \tvar thisSession = form.parents('.poll-session');\n    \t\tif(data.success == 'multiple records' && data.outer_table == 'sample'){\n   \t    \t    form.children('input[name=sample\\:id]').removeAttr('disabled').val(data.outer_id);\n   \t    \t    loadAttributes('sample_attribute_value', 'sample_attribute_id', 'sample_id', 'sample\\:id', data.outer_id, 'smpAttr', true);\n\t\t\t\tthisSession.show();\n\t\t\t\tthisSession.children(':first').show().find('*').show();\n\t\t\t\tthisSession.children().not(':first').hide();\n  \t\t\t} else \n\t        \talertIndiciaError(data);\n  \t\t},\n        complete: function (){\n  \t\t\tjQuery('.loading-button').removeClass('loading-button');\n  \t\t}\n\t});\n    return(newSession);\n};\n\nvalidateSessionsPanel = function(){\n\tif(jQuery('#cc-3:visible').length == 0) return true; // panel is not visible so no data to fail validation.\n\tif(jQuery('#cc-3').find('.poll-section-body:visible').length == 0) return true; // body hidden so data already been validated successfully.\n\tvar openSession = jQuery('.poll-session-form:visible');\n\tif(openSession.length > 0){\n\t\tif(jQuery('input[name=sample\\:id]', openSession).val() == '' &&\n\t\t\t\tjQuery('input[name=sample\\:date]', openSession).val() == '' &&\n\t\t\t\tjQuery('[name=smpAttr\\:" . $args['start_time_attr_id'] . "],[name^=smpAttr\\:" . $args['start_time_attr_id'] . "\\:]', openSession).val() == '' &&\n\t\t\t\tjQuery('[name=smpAttr\\:" . $args['end_time_attr_id'] . "],[name^=smpAttr\\:" . $args['end_time_attr_id'] . "\\:]', openSession).val() == '' &&\n\t\t\t\tjQuery('[name=smpAttr\\:" . $args['sky_state_attr_id'] . "],[name^=smpAttr\\:" . $args['sky_state_attr_id'] . "\\:]', openSession).filter('[checked]').length == 0 &&\n    \t\t\tjQuery('[name=smpAttr\\:" . $args['temperature_attr_id'] . "],[name^=smpAttr\\:" . $args['temperature_attr_id'] . "\\:]', openSession).filter('[checked]').length == 0 &&\n    \t\t\tjQuery('[name=smpAttr\\:" . $args['wind_attr_id'] . "],[name^=smpAttr\\:" . $args['wind_attr_id'] . "\\:]', openSession).filter('[checked]').length == 0) {\n\t\t\t// NB shade is a boolean, and always has one set (default no)\n    \t\tjQuery('#cc-3').foldPanel();\n\t\t\treturn true;\n\t\t}\n\t}\n\t// not putting in an empty data set check here - user can delete the session if needed, and there must be at least one.\n\tif(!validateAndSubmitOpenSessions()) return false;\n\tjQuery('#cc-3').foldPanel();\n\tpopulateSessionSelect();\n\treturn true;\n};\njQuery('#cc-3-valid-button').click(function(){\n\tif(!validateAndSubmitOpenSessions()) return;\n\tjQuery('#cc-3').foldPanel();\n\tjQuery('#cc-4').showPanel();\n\tpopulateSessionSelect();\n});\njQuery('#cc-3-add-button').click(function(){\n\tif(!validateAndSubmitOpenSessions()) return;\n\taddSession();\n\tcheckSessionButtons();\n});\n\njQuery('.mod-button').click(function() {\n\t// first close all the other panels, ensuring any data is saved.\n\tif(!validateCollectionPanel() || !validateStationPanel() || !validateSessionsPanel() || !validateInsectPanel())\n\t\treturn;\n\tjQuery('#cc-5').hidePanel();\n\tjQuery(this).parents('.poll-section-title').parent().unFoldPanel(); //slightly complicated because cc-1 contains the rest.\n});\n\n";
        $extraParams = $readAuth + array('taxon_list_id' => $args['insect_list_id'], 'view' => 'detail', 'orderby' => 'taxonomic_sort_order', 'allow_data_entry' => 't');
        $species_ctrl_args = array('label' => lang::get('LANG_Insect_Species'), 'fieldname' => 'insect:taxa_taxon_list_id', 'table' => 'taxa_taxon_list', 'captionField' => 'taxon', 'valueField' => 'id', 'columns' => 2, 'blankText' => lang::get('LANG_Choose_Taxon'), 'extraParams' => $extraParams, 'suffixTemplate' => 'nosuffix');
        $r .= '
<div id="cc-4" class="poll-section">
  <div id="cc-4-title" class="ui-accordion-header ui-helper-reset ui-state-active ui-corner-all poll-section-title">' . lang::get('LANG_Photos') . '
    <div id="cc-4-mod-button" class="right ui-state-default ui-corner-all mod-button">' . lang::get('LANG_Modify') . '</div>
  </div>
  <div id="cc-4-photo-reel" class="ui-accordion-content ui-helper-reset ui-widget-content ui-corner-top ui-accordion-content-active photoReelContainer" >
    <div class="photo-blurb">' . lang::get('LANG_Photo_Blurb') . '</div>
    <div class="blankPhoto thumb currentPhoto"></div>
  </div>
  <div id="cc-4-body" class="ui-accordion-content ui-helper-reset ui-widget-content ui-accordion-content-active poll-section-body">  
    <div id="cc-4-insect">
      <div id="cc-4-insect-title">' . lang::get('LANG_Upload_Insect') . '</div>
      <form id="cc-4-insect-upload" enctype="multipart/form-data" action="' . iform_ajaxproxy_url($node, 'media') . '" method="POST">
    	<input type="hidden" id="website_id" name="website_id" value="' . $args['website_id'] . '" />
    	<input name="upload_file" type="file" class="required" />
        <input type="submit" value="' . lang::get('LANG_Upload') . '" class="btn-submit" />
 	    <div id="cc-4-insect-image" class="poll-image"></div>
      </form>
      <div id="cc-4-insect-identify" class="poll-dummy-form">
 	    <div class="id-tool-group">
          ' . iform_pollenators::help_button($use_help, "insect-help-button", $args['help_function'], $args['help_insect_arg']) . '
          <p><strong>' . lang::get('LANG_Identify_Insect') . '</strong></p>
          <input type="hidden" id="insect:taxon_details" name="insect:taxon_details" />
          <input type="hidden" name="insect:determination_type" value="A" />  
		  <label for="insect-id-button">' . lang::get('LANG_Insect_ID_Key_label') . ' :</label><span id="insect-id-button" class="ui-state-default ui-corner-all poll-id-button" >' . lang::get('LANG_Launch_ID_Key') . '</span>
		  <span id="insect-id-cancel" class="ui-state-default ui-corner-all poll-id-cancel" >' . lang::get('LANG_Cancel_ID') . '</span>
 	      <p id="insect_taxa_list"></p> 
 	    </div>
 	    <div class="id-later-group">
 	      <label for="id-insect-later" class="follow-on">' . lang::get('LANG_ID_Insect_Later') . ' </label><input type="checkbox" id="id-insect-later" name="id-insect-later" />
 	    </div>
 	    <div class="id-specified-group">
 	      ' . data_entry_helper::select($species_ctrl_args) . '
          <label for="insect:taxon_extra_info" class="follow-on">' . lang::get('LANG_ID_More_Precise') . ' </label> 
    	  <input type="text" id="insect:taxon_extra_info" name="insect:taxon_extra_info" class="taxon-info" />
        </div>
      </div>
 	  <div class="id-comment">
        <label for="insect:comment" class="follow-on">' . lang::get('LANG_ID_Comment') . ' </label>
        <textarea id="insect:comment" name="insect:comment" class="taxon-desc" rows="5" columns="80" ></textarea>
      </div>
    </div>
    <div class="poll-break"></div> 
 	<form id="cc-4-main-form" action="' . iform_ajaxproxy_url($node, 'occurrence') . '" method="POST" >
    	<input type="hidden" id="website_id" name="website_id" value="' . $args['website_id'] . '" />
    	<input type="hidden" id="occurrence_image:path" name="occurrence_image:path" value="" />
    	<input type="hidden" id="occurrence:record_status" name="occurrence:record_status" value="C" />
        <input type="hidden" name="occurrence:use_determination" value="Y"/>    
        <input type="hidden" name="determination:taxa_taxon_list_id" value=""/> 
        <input type="hidden" name="determination:taxon_details" value=""/>  	
        <input type="hidden" name="determination:taxon_extra_info" value=""/>  	
        <input type="hidden" name="determination:comment" value=""/>  	
    	<input type="hidden" name="determination:determination_type" value="A" /> 
        <input type="hidden" name="determination:cms_ref" value="' . $uid . '" />
    	<input type="hidden" name="determination:email_address" value="' . $email . '" />
    	<input type="hidden" name="determination:person_name" value="' . $username . '" /> 
    	<input type="hidden" id="occurrence:id" name="occurrence:id" value="" disabled="disabled" />
	    <input type="hidden" id="determination:id" name="determination:id" value="" disabled="disabled" />
	    <input type="hidden" id="occurrence_image:id" name="occurrence_image:id" value="" disabled="disabled" />
	    <label for="occurrence:sample_id">' . lang::get('LANG_Session') . '</label>
	    <select id="occurrence:sample_id" name="occurrence:sample_id" value="" class="required" /></select>
	    ' . data_entry_helper::textarea(array('label' => lang::get('LANG_Comment'), 'fieldname' => 'occurrence:comment', 'suffixTemplate' => 'nosuffix')) . str_replace("\n", "", data_entry_helper::outputAttribute($occurrence_attributes[$args['number_attr_id']], $defNRAttrOptions)) . str_replace("\n", "", data_entry_helper::outputAttribute($occurrence_attributes[$args['foraging_attr_id']], $defNRAttrOptions)) . '
    </form>
    <span id="cc-4-valid-insect-button" class="ui-state-default ui-corner-all save-button">' . lang::get('LANG_Validate_Insect') . '</span>
    <span id="cc-4-delete-insect-button" class="ui-state-default ui-corner-all delete-button">' . lang::get('LANG_Delete_Insect') . '</span>
  </div>
  <div id="cc-4-footer" class="ui-accordion-content ui-helper-reset ui-widget-content ui-corner-bottom ui-accordion-content-active poll-section-footer">
    <div id="cc-4-valid-photo-button" class="ui-state-default ui-corner-all save-button">' . lang::get('LANG_Validate_Photos') . '</div>
  </div>
</div>
<div style="display:none" />
    <form id="cc-4-delete-insect" action="' . iform_ajaxproxy_url($node, 'occurrence') . '" method="POST">
       <input type="hidden" name="website_id" value="' . $args['website_id'] . '" />
       <input type="hidden" name="occurrence:use_determination" value="Y"/>    
       <input type="hidden" name="occurrence:id" value="" />
       <input type="hidden" name="occurrence:sample_id" value="" />
       <input type="hidden" name="occurrence:deleted" value="t" />
    </form>
</div>';
        data_entry_helper::$javascript .= "\n\ninsectIDstruc = {\n\ttype: 'insect',\n\tselector: '#cc-4-insect-identify',\n\tmainForm: '#cc-4-main-form',\n\ttimeOutTimer: null,\n\tpollTimer: null,\n\tpollFile: '',\n\tinvokeURL: '" . $args['ID_tool_insect_url'] . "',\n\tpollURL: '" . str_replace("{HOST}", $_SERVER['HTTP_HOST'], $args['ID_tool_insect_poll_dir']) . "',\n\tname: 'insectIDstruc',\n\ttaxaList: insectTaxa\n};\n\njQuery('#insect-id-button').click(function(){\n\tidButtonPressed(insectIDstruc);\n});\njQuery('#insect-id-cancel').click(function(){\n\tpollReset(insectIDstruc);\n});\njQuery('#insect-id-cancel').hide();\njQuery('#cc-4-insect-identify select[name=insect\\:taxa_taxon_list_id]').change(function(){\n\tpollReset(insectIDstruc);\n\ttaxonChosen(insectIDstruc);\n});\njQuery('#id-insect-later').change(function (){\n\tpollReset(insectIDstruc);\n\tidLater(insectIDstruc);\n});\n\n// Insect upload picture form.\n\$('#cc-4-insect-upload').ajaxForm({ \n\t\tasync: false,\n\t\tdataType:  'json', \n        beforeSubmit:   function(data, obj, options){\n        \tif(jQuery('#cc-4-insect-upload input[name=upload_file]').val() == '')\n        \t\treturn false;\n        \t\$('#cc-4-insect-image').empty();\n        \t\$('#cc-4-insect-image').addClass('loading');\n        \tjQuery('form#cc-4-main-form input[name=occurrence_image\\:path]').val('');\n        },\n        success:   function(data){\n        \tif(data.success == true){\n\t        \t// There is only one file\n\t        \tjQuery('form#cc-4-main-form input[name=occurrence_image\\:path]').val(data.files[0]);\n\t        \tinsertImage('med-'+data.files[0], jQuery('#cc-4-insect-image'), " . $args['Insect_Image_Ratio'] . ");\n\t\t\t\tjQuery('#cc-4-insect-upload input[name=upload_file]').val('');\n\t\t\t}  else\n\t\t\t\talertIndiciaError(data);\n  \t\t},\n  \t\tcomplete: function(){\n\t\t\t\$('#cc-4-insect-image').removeClass('loading');\n  \t\t}\n});\n\n\$('#cc-4-main-form').ajaxForm({ \n\tasync: false,\n\tdataType:  'json', \n    beforeSubmit:   function(data, obj, options){\n    \tvar valid = true;\n    \tclearErrors('form#cc-4-main-form');\n    \tclearErrors('#cc-4-insect-identify');\n    \tif (!jQuery('form#cc-4-main-form > input').valid()) { valid = false; }\n\t\tif (!validateRequiredField('occurrence\\:sample_id', 'form#cc-4-main-form')) { valid = false; }\n\t\tif (!validateRadio('occAttr\\:" . $args['number_attr_id'] . "', obj)) { valid = false; }\n    \tif(data[1].value == '' ){\n    \t\tmyScrollTo('#cc-4-insect-upload');\n\t\t\talert(\"" . lang::get('LANG_Must_Provide_Insect_Picture') . "\");\n\t\t\tvalid = false;\n\t\t}\n\t\tif (jQuery('#id-insect-later').attr('checked') == ''){\n\t\t\tdata[findID('determination:taxa_taxon_list_id', data)].value = jQuery('#cc-4-insect-identify select[name=insect\\:taxa_taxon_list_id]').val();\n\t\t\tdata[findID('determination:taxon_details', data)].value = jQuery('#cc-4-insect-identify [name=insect\\:taxon_details]').val();\n\t\t\tdata[findID('determination:taxon_extra_info', data)].value = jQuery('#cc-4-insect-identify [name=insect\\:taxon_extra_info]').val();\n\t\t\tdata[findID('determination:comment', data)].value = jQuery('[name=insect\\:comment]').val();\n\t\t\tdata[findID('determination:determination_type', data)].value = jQuery('#cc-4-insect-identify [name=insect\\:determination_type]').val();\n\t\t\tif (jQuery('#cc-4-insect-identify [name=insect\\:taxon_details]').val() == ''){\n\t\t\t\tif (!validateRequiredField('insect\\:taxa_taxon_list_id', '#cc-4-insect-identify')) {\n\t\t\t\t\tvalid = false;\n  \t\t\t\t} else {\n\t\t\t\t\tdata.push({name: 'determination:taxa_taxon_list_id_list[]', value: ''});\n  \t\t\t\t}\n\t\t\t} else {\n\t\t\t\tvar toolValues = jQuery('#insect-id-button').data('toolRetValues');\n\t\t\t\tfor(var i = 0; i<toolValues.length; i++){\n\t\t\t\t\tdata.push({name: 'determination:taxa_taxon_list_id_list[]', value: toolValues[i]});\n\t\t\t\t}\t\t\t\n\t\t\t}\n\t\t} else {\n\t\t\tdata.splice(4,8); // remove determination entries.\n\t\t}\n   \t\tif ( valid == false ) {\n\t\t\tmyScrollToError();\n\t\t\treturn false;\n\t\t};\n\t\tjQuery('#cc-4-valid-insect-button').addClass('loading-button');\n\t\treturn true;\n\t},\n    success:   function(data){\n       \tif(data.success == 'multiple records' && data.outer_table == 'occurrence'){\n       \t\tupdatePhotoReel(data.outer_id);\n\t\t\twindow.scroll(0,0);\n        } else\n\t\t\talertIndiciaError(data);\n\t},\n    complete: function (){\n  \t\tjQuery('.loading-button').removeClass('loading-button');\n  \t}\n});\n\nvalidateInsectPanel = function(){\n\tif(jQuery('#cc-4:visible').length == 0) return true; // panel is not visible so no data to fail validation.\n\tif(jQuery('#cc-4-body:visible').length == 0) return true; // body hidden so data already been validated successfully.\n\tif(!validateInsect()){ return false; }\n\tclearInsect();\n  \tjQuery('#cc-4').foldPanel();\n\treturn true;\n};\n\nclearInsect = function(){\n\tjQuery('#cc-4-main-form').resetForm();\n\tjQuery('#insect-id-button').data('toolRetValues',[]);\n\tjQuery('#insect_taxa_list').empty();\n\tjQuery('[name=insect\\:taxa_taxon_list_id],[name=insect\\:taxon_extra_info],[name=insect\\:comment],[name=insect\\:taxon_details]').val('');\n    jQuery('[name=insect\\:determination_type]').val('A'); \n\tjQuery('#id-insect-later').removeAttr('checked').removeAttr('disabled');\n    jQuery('#cc-4-main-form').find('[name=determination\\:cms_ref]').val('" . $uid . "');\n    jQuery('#cc-4-main-form').find('[name=determination\\:email_address]').val('" . $email . "');\n    jQuery('#cc-4-main-form').find('[name=determination\\:person_name]').val('" . $username . "'); \n    jQuery('#cc-4-main-form').find('[name=determination\\:determination_type]').val('A'); \n    jQuery('#cc-4-main-form').find('[name=occurrence_image\\:path]').val('');\n\tjQuery('#cc-4-main-form').find('[name=occurrence\\:id],[name=occurrence_image\\:id],[name=determination\\:id]').val('').attr('disabled', 'disabled');\n\tjQuery('#cc-4-main-form').find('[name^=occAttr\\:]').each(function(){\n\t\tvar name = jQuery(this).attr('name').split(':');\n\t\tjQuery(this).attr('name', name[0]+':'+name[1]);\n\t});\n    jQuery('#cc-4-insect-image').empty();\n    populateSessionSelect();\n\tjQuery('.currentPhoto').removeClass('currentPhoto');\n\tjQuery('.blankPhoto').addClass('currentPhoto');\n};\n\nloadInsect = function(id){\n\tclearInsect();\n\tjQuery('form#cc-4-main-form > input[name=occurrence\\:id]').removeAttr('disabled').val(id);\n\tloadAttributes('occurrence_attribute_value', 'occurrence_attribute_id', 'occurrence_id', 'occurrence\\:id', id, 'occAttr', true);\n\tloadImage('occurrence_image', 'occurrence_id', 'occurrence\\:id', id, '#cc-4-insect-image', " . $args['Insect_Image_Ratio'] . ");\n\t\$.getJSON(\"" . $svcUrl . "/data/occurrence/\" + id +\n          \"?mode=json&view=detail&nonce=" . $readAuth['nonce'] . "&auth_token=" . $readAuth['auth_token'] . "&callback=?\", function(data) {\n\t    if(!(data instanceof Array)){\n   \t\t\talertIndiciaError(data);\n   \t\t} else if (data.length>0) {\n\t        jQuery('form#cc-4-main-form > [name=occurrence\\:sample_id]').val(data[0].sample_id);\n\t\t\tjQuery('form#cc-4-main-form > textarea[name=occurrence\\:comment]').val(data[0].comment);\n  \t\t}\n\t});\n\t\$.getJSON(\"" . $svcUrl . "/data/determination?occurrence_id=\" + id +\n          \"&mode=json&view=list&nonce=" . $readAuth['nonce'] . "&auth_token=" . $readAuth['auth_token'] . "&orderby=id&deleted=f&callback=?\", function(data) {\n        if(!(data instanceof Array)){\n   \t\t\talertIndiciaError(data);\n   \t\t} else loadDetermination(data, insectIDstruc);\n\t});\t\n\tjQuery('.currentPhoto').removeClass('currentPhoto');\n\tjQuery('[occId='+id+']').addClass('currentPhoto');\n}\n\nupdatePhotoReel = function(occId){\n\tvar container = jQuery('[occId='+occId+']');\n\tif(container.length == 0)\n\t\tcontainer = jQuery('<div/>').addClass('thumb').insertBefore('.blankPhoto').attr('occId', occId.toString()).click(function () {setInsect(occId)});\n\telse\n\t\tcontainer.empty();\n\tjQuery('<span>?</span>').addClass('thumb-text').appendTo(container);\n\t// the picture can be async but the determination can't : we use the presence of the text to determine whether the \n\t// insect has been identified or not. NB an insect tagged as unidentified (type = 'X') has actually been through the ID\n\t// process, so is not unidentified!!!\n\tjQuery.ajax({ \n        type: \"GET\", \n        url: \"" . $svcUrl . "/data/determination\" + \n    \t\t\"?mode=json&view=list&nonce=" . $readAuth['nonce'] . "&auth_token=" . $readAuth['auth_token'] . "\" + \n    \t\t\"&reset_timeout=true&occurrence_id=\" + occId + \"&orderby=id&deleted=f&callback=?\", \n        data: {}, \n        success: function(detData) {\n\t    \tif(!(detData instanceof Array)){\n   \t\t\t\talertIndiciaError(detData);\n   \t\t\t} else if (detData.length>0) {\n\t    \t\tcontainer.find('.thumb-text').remove();\n\t    \t}\n  \t\t}, \n    \tdataType: 'json', \n\t    async: false \n    });\n\t\$.getJSON(\"" . $svcUrl . "/data/occurrence_image\" +\n\t\t\t\"?mode=json&view=list&nonce=" . $readAuth['nonce'] . "&auth_token=" . $readAuth['auth_token'] . "\" +\n\t\t\t\"&occurrence_id=\" + occId + \"&callback=?\", function(imageData) {\n\t\tif(!(imageData instanceof Array)){\n\t\t\talertIndiciaError(imageData);\n\t\t} else if (imageData.length>0) {\n\t\t\tvar img = new Image();\n\t\t\tjQuery(img).attr('src', '" . data_entry_helper::$base_url . data_entry_helper::$indicia_upload_path . "thumb-'+imageData[0].path)\n\t\t\t    .attr('width', container.width()).attr('height', container.height()).addClass('thumb-image').appendTo(container);\n\t\t}\n\t});\n}\n\nsetInsect = function(id){\n\t// first close all the other panels, ensuring any data is saved.\n\tif(!validateCollectionPanel() || !validateStationPanel() || !validateSessionsPanel())\n\t\treturn;\n\t\t\n\tif(jQuery('#cc-4-body:visible').length == 0)\n\t\tjQuery('div#cc-4').unFoldPanel();\n\telse\n\t\tif(!validateInsect()){ return ; }\n\tloadInsect(id);\n};\n\nsetNoInsect = function(){\n\t// first close all the other panels, ensuring any data is saved.\n\tif(!validateCollectionPanel() || !validateStationPanel() || !validateSessionsPanel())\n\t\treturn;\n\t\t\n\tif(jQuery('#cc-4-body:visible').length == 0)\n\t\tjQuery('div#cc-4').unFoldPanel();\n\telse\n\t\tif(!validateInsect()){ return ; }\n\tclearInsect();\n};\n\njQuery('.blankPhoto').click(setNoInsect);\n\n// TODO separate photoreel out into own js\nvalidateInsect = function(){\n    clearErrors('form#cc-4-main-form');\n    clearErrors('#cc-4-insect-identify');\n    if(jQuery('form#cc-4-main-form > input[name=occurrence\\:id]').val() == '' &&\n\t\t\tjQuery('form#cc-4-main-form > input[name=occurrence_image\\:path]').val() == '' &&\n\t\t\tjQuery('[name=insect\\:taxa_taxon_list_id]').val() == '' &&\n\t\t\tjQuery('[name=insect\\:taxon_details]').val() == '' &&\n\t\t\tjQuery('[name=insect\\:comment]').val() == '' &&\n\t\t\tjQuery('[name=insect\\:taxon_extra_info]').val() == '' &&\n\t\t\tjQuery('form#cc-4-main-form > textarea[name=occurrence\\:comment]').val() == '' &&\n\t\t\tjQuery('[name=occAttr\\:" . $args['number_attr_id'] . "],[name^=occAttr\\:" . $args['number_attr_id'] . "\\:]').filter('[checked]').length == 0){\n\t\treturn true;\n\t}\n\tvar valid = true;\n    if (!jQuery('form#cc-4-main-form > input').valid()) { valid = false; }\n  \tif (!validateRadio('occAttr\\:" . $args['number_attr_id'] . "', 'form#cc-4-main-form')) { valid = false; }\n\tif (jQuery('#id-insect-later').attr('checked') == '' && jQuery('[name=insect\\:taxon_details]').val() == ''){\n\t\tif (!validateRequiredField('insect\\:taxa_taxon_list_id', '#cc-4-insect-identify')) { valid = false; }\n\t}\n \tif (!validateRequiredField('occurrence\\:sample_id', 'form#cc-4-main-form')) { valid = false; }\n\tif(jQuery('form#cc-4-main-form input[name=occurrence_image\\:path]').val() == ''){\n    \tmyScrollTo('#cc-4-insect-upload');\n\t\talert(\"" . lang::get('LANG_Must_Provide_Insect_Picture') . "\");\n\t\tvalid = false;;\n\t}\n\tif(valid == false) {\n\t\tmyScrollToError();\n\t\treturn false;\n\t}\n\tjQuery('form#cc-4-main-form').submit();\n\tclearInsect();\n\tmyScrollTo('.blankPhoto')\n\treturn true;\n}\n\n\$('#cc-4-valid-insect-button').click(validateInsect);\n\n\$('#cc-4-delete-insect-button').click(function() {\n\tvar container = \$(this).parent().parent();\n\tjQuery('#cc-4-delete-insect').find('[name=occurrence\\:id]').val(jQuery('#cc-4-main-form').find('[name=occurrence\\:id]').val()).removeAttr('disabled');\n\tjQuery('#cc-4-delete-insect').find('[name=occurrence\\:sample_id]').val(jQuery('#cc-4-main-form').find('[name=occurrence\\:sample_id]').val()).removeAttr('disabled');\n\tif(confirm(\"" . lang::get('LANG_Confirm_Insect_Delete') . "\")){\n\t\tif(jQuery('#cc-4-main-form').find('[name=occurrence\\:id]').filter('[disabled]').length == 0){\n\t\t\tjQuery('#cc-4-delete-insect').submit();\n\t\t\tjQuery('.currentPhoto').remove();\n\t\t\tjQuery('.blankPhoto').addClass('currentPhoto');\n\t\t}\n\t\tclearInsect();\n\t\tmyScrollTo('.blankPhoto')\n\t}\n});\n\n\$('#cc-4-delete-insect').ajaxForm({ \n\t\tasync: false,\n\t\tdataType:  'json', \n        beforeSubmit:   function(data, obj, options){\n  \t\t\t// Warning this assumes that the data is fixed position:\n        \tif(data[2].value == '') return false;\n  \t\t\tjQuery('#cc-4-delete-insect').addClass('loading-button');\n        \treturn true;\n  \t\t},\n        success:   function(data){\n       \t\tif(data.success != 'multiple records' || data.outer_table != 'occurrence')\n        \t\talertIndiciaError(data);\n  \t\t},\n        complete: function (){\n  \t\t\tjQuery('.loading-button').removeClass('loading-button');\n  \t\t}\n});\n\n\$('#cc-4-valid-photo-button').click(function(){\n\tif(!validateInsect()) return;\n\tjQuery('#cc-4').foldPanel();\n\tjQuery('#cc-5').showPanel();\n\tvar numInsects = jQuery('#cc-4-photo-reel').find('.thumb').length - 1; // ignore blank\n\tvar numUnidentified = jQuery('#cc-4-photo-reel').find('.thumb-text').length;\n\tif(jQuery('#id-flower-later').attr('checked') != '' || numInsects==0 || (numUnidentified/numInsects > (1-(" . $args['percent_insects'] . "/100.0)))){\n\t\tjQuery('#cc-5-good').hide();\n\t\tjQuery('#cc-5-bad').show();\n\t\tjQuery('#cc-5-complete-collection').hide();\n\t\tjQuery('#cc-5-trailer').hide();\n    } else {\n    \tjQuery('#cc-5-good').show();\n\t\tjQuery('#cc-5-bad').hide();\n\t\tjQuery('#cc-5-complete-collection').show();\n\t\tjQuery('#cc-5-trailer').show();\n\t}\n});\n";
        $r .= '
<div id="cc-5" class="poll-section">
  <div id="cc-5-body" class="poll-section-body"> 
   <p id="cc-5-good">' . lang::get('LANG_Can_Complete_Msg') . '</p> 
   <p id="cc-5-bad">' . lang::get('LANG_Cant_Complete_Msg') . '</p> 
   <div style="display:none" />
    <form id="cc-5-collection" action="' . iform_ajaxproxy_url($node, 'sample') . '" method="POST">
       <input type="hidden" name="website_id" value="' . $args['website_id'] . '" />
       <input type="hidden" name="sample:survey_id" value="' . $args['survey_id'] . '" />
       <input type="hidden" name="sample:id" value="" />
       <input type="hidden" name="sample:date_start" value="2010-01-01"/>
       <input type="hidden" name="sample:date_end" value="2010-01-01"/>
       <input type="hidden" name="sample:date_type" value="D"/>
       <input type="hidden" name="sample:location_id" value="" />
       <input type="hidden" id="smpAttr:' . $args['complete_attr_id'] . '" name="smpAttr:' . $args['complete_attr_id'] . '" value="1" />
    </form>
   </div>
  </div>
  <div id="cc-5-trailer" class="poll-section-trailer">
    <p>' . lang::get('LANG_Trailer_Head') . '</p>
    <ul>
      <li>' . lang::get('LANG_Trailer_Point_1') . '</li>
      <li>' . lang::get('LANG_Trailer_Point_2') . '</li>
      <li>' . lang::get('LANG_Trailer_Point_3') . '</li>
      <li>' . lang::get('LANG_Trailer_Point_4') . '</li>
    </ul>
   <div id="cc-5-complete-collection" class="ui-state-default ui-corner-all complete-button">' . lang::get('LANG_Complete_Collection') . '</div>
  </div>
</div>';
        data_entry_helper::$javascript .= "\n\$('#cc-5-collection').ajaxForm({ \n\t\tasync: false,\n\t\tdataType:  'json', \n        beforeSubmit:   function(data, obj, options){\n  \t\t\tjQuery('#cc-5-complete-collection').addClass('loading-button');\n        \tdata[2].value = jQuery('#cc-1-collection-details input[name=sample\\:id]').val();\n\t\t\tdata[3].value = '';\n\t\t\tdata[4].value = '';\n\t\t\tdate_start = '';\n\t\t\tdate_end = '';\n\t\t\tjQuery('.poll-session-form').each(function(i){\n\t\t\t\tif(jQuery(this).find('input[name=sample\\:id]').val() != '') {\n\t\t\t\t\tvar sessDate = jQuery(this).find('input[name=sample\\:date]').val();\n\t\t\t\t\tvar sessDateDate = new Date(sessDate); // sessions are only on one date.\n\t\t\t\t\tif(date_start == '' || date_start > sessDateDate) {\n\t\t\t\t\t\tdate_start = sessDateDate;\n\t\t\t\t\t\tdata[3].value = sessDate;\n\t\t\t\t\t}\n\t\t\t\t\tif(date_end == '' || date_end < sessDateDate) {\n\t\t\t\t\t\tdate_end = sessDateDate;\n\t\t\t\t\t\tdata[4].value = sessDate;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t});\n\t\t\tif(data[3].value == '') {\n\t\t\t\talert(\"" . lang::get('LANG_Session_Error') . "\");\n\t\t\t\tjQuery('#cc-5-complete-collection').removeClass('loading-button');\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\tif(data[3].value == data[4].value){\n\t       \t\tdata[5].value = 'D';\n\t       \t} else {\n\t       \t\tdata[5].value = 'DD';\n  \t\t\t}\n\t       \tjQuery('#cc-1-collection-details,#cc-2').find('[name=sample\\:date]:hidden').val(data[3].value);\n  \t\t\tdata[6].value = jQuery('#cc-1-collection-details input[name=location\\:id]').val();\n       \t\tdata[7].name = jQuery('#cc-1-collection-details input[name^=smpAttr\\:" . $args['complete_attr_id'] . "\\:]').attr('name');\n       \t\treturn true;\n  \t\t},\n        success:   function(data){\n       \t\tif(data.success == 'multiple records' && data.outer_table == 'sample'){\n\t\t\t\t\$('#cc-6').showPanel();\n  \t\t\t}  else\n\t\t\t\talertIndiciaError(data);\n  \t\t},\n        complete: function (){\n  \t\t\tjQuery('.loading-button').removeClass('loading-button');\n  \t\t}\n});\n\$('#cc-5-complete-collection').click(function(){\n\tjQuery('#cc-5-complete-collection').addClass('loading-button');\n\tjQuery('#cc-2,#cc-3,#cc-4,#cc-5').hidePanel();\n\tjQuery('.reinit-button').hide();\n\tjQuery('.mod-button').hide();\n\tjQuery('#cc-5-collection').submit();\n});\n";
        $r .= '
<div id="cc-6" class="poll-section">
  <div id="cc-6-body" class="ui-accordion-header ui-helper-reset ui-state-active ui-corner-top poll-section-body"> 
   <p>' . lang::get('LANG_Final_1') . '</p> 
   <p>' . lang::get('LANG_Final_2') . '</p> 
   </div>
  <div id="cc-6-footer" class="ui-accordion-content ui-helper-reset ui-widget-content ui-corner-bottom ui-accordion-content-active poll-section-footer">
    <a id="cc-6-consult-collection" href="" class="ui-state-default ui-corner-all link-button">' . lang::get('LANG_Consult_Collection') . '</a>
    <a href="' . url('node/' . $node->nid) . '" class="ui-state-default ui-corner-all link-button">' . lang::get('LANG_Create_New_Collection') . '</a>
  </div>
</div>
</div></div>';
        data_entry_helper::$javascript .= "\n \t\t\t\nloadAttributes = function(attributeTable, attributeKey, key, keyName, keyValue, prefix, reset_timeout){\n\tvar form = jQuery('input[name='+keyName+'][value='+keyValue+']').parents('form');\n\tvar checkboxes = jQuery('[name^='+prefix+'\\:]', form).filter(':checkbox').removeAttr('checked');\n\tcheckboxes.each(function(){\n\t\tvar name = jQuery(this).attr('name').split(':');\n\t\tif(name.length > 2)\n\t\t\tjQuery(this).attr('name', name[0]+':'+name[1]+'[]');\n\t});\n    jQuery.ajax({ \n        type: \"GET\", \n        url: \"" . $svcUrl . "/data/\" + attributeTable + \"?mode=json&view=list\" +\n        \t(reset_timeout ? \"&reset_timeout=true\" : \"\") + \"&nonce=" . $readAuth['nonce'] . "&auth_token=" . $readAuth['auth_token'] . "\" +\n   \t\t\t\"&\" + key + \"=\" + keyValue + \"&callback=?\", \n        data: {}, \n        success: function(attrdata) {\n\t\t  if(!(attrdata instanceof Array)){\n   \t\t\talertIndiciaError(attrdata);\n   \t\t  } else if (attrdata.length>0) {\n\t\t\tvar form = jQuery('input[name='+keyName+'][value='+keyValue+']').parent();\n\t\t\tfor (var i=0;i<attrdata.length;i++){\n\t\t\t\tif (attrdata[i].id && (attrdata[i].iso == null || attrdata[i].iso == '' || attrdata[i].iso == '" . $language . "')){\n\t\t\t\t\tvar checkboxes = jQuery('[name='+prefix+'\\:'+attrdata[i][attributeKey]+'\\[\\]],[name^='+prefix+'\\:'+attrdata[i][attributeKey]+':]', form).filter(':checkbox');\n\t\t\t\t\tvar radiobuttons = jQuery('[name='+prefix+'\\:'+attrdata[i][attributeKey]+'],[name^='+prefix+'\\:'+attrdata[i][attributeKey]+':]', form).filter(':radio');\n\t\t\t\t\tif(radiobuttons.length > 0){\n\t\t\t\t\t\tradiobuttons\n\t\t\t\t\t\t\t.attr('name', prefix+':'+attrdata[i][attributeKey]+':'+attrdata[i].id)\n\t\t\t\t\t\t\t.filter('[value='+attrdata[i].raw_value+']')\n\t\t\t\t\t\t\t.attr('checked', 'checked');\n\t\t\t\t\t} else \tif(checkboxes.length > 0){\n\t\t\t\t\t\tvar checkbox = checkboxes.filter('[value='+attrdata[i].raw_value+']')\n\t\t\t\t\t\t\t.attr('name', prefix+':'+attrdata[i][attributeKey]+':'+attrdata[i].id)\n\t\t\t\t\t\t\t.attr('checked', 'checked');\n\t\t\t\t\t} else {\n\t\t\t\t\t\tjQuery('[name='+prefix+'\\:'+attrdata[i][attributeKey]+']', form)\n\t\t\t\t\t\t\t.attr('name', prefix+':'+attrdata[i][attributeKey]+':'+attrdata[i].id)\n\t\t\t\t\t\t\t.val(attrdata[i].raw_value);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t  }\n\t\t  checkProtocolStatus('leave');\n\t\t  populateSessionSelect();\n\t\t},\n\t\tdataType: 'json', \n\t    async: false  \n\t});\n}\n\nloadImage = function(imageTable, key, keyName, keyValue, target, ratio){\n\t\t\t\t\t// location_image, location_id, location:id, 1, #cc-4-insect-image\n\t\$.getJSON(\"" . $svcUrl . "/data/\" + imageTable +\n   \t\t\t\"?mode=json&view=list&nonce=" . $readAuth['nonce'] . "&auth_token=" . $readAuth['auth_token'] . "\" +\n   \t\t\t\"&\" + key + \"=\" + keyValue + \"&callback=?\", function(imageData) {\n\t\tif(!(imageData instanceof Array)){\n   \t\t\talertIndiciaError(imageData);\n   \t\t} else if (imageData.length>0) {\n\t\t\tvar form = jQuery('input[name='+keyName+'][value='+keyValue+']').parent();\n\t\t\tjQuery('[name='+imageTable+'\\:id]', form).val(imageData[0].id).removeAttr('disabled');\n\t\t\tjQuery('[name='+imageTable+'\\:path]', form).val(imageData[0].path);\n\t        insertImage('med-'+imageData[0].path, jQuery(target), ratio);\n\t\t}\n\t});\n}\n\nloadDetermination = function(detData, toolStruc){\n\tjQuery('#'+toolStruc.type+'_taxa_list').empty();\n\tjQuery('#'+toolStruc.type+'-id-button').data('toolRetValues', []);\n\tjQuery(toolStruc.mainForm+' input[name=determination\\:id]').val('').attr('disabled', 'disabled');\n\tjQuery('#id-'+toolStruc.type+'-later').removeAttr('checked').removeAttr('disabled');\n\tjQuery('[name='+toolStruc.type+'\\:determination_type]').val('A');\n\tjQuery(toolStruc.mainForm+' input[name=determination\\:determination_type]').val('A');\n\tjQuery('[name='+toolStruc.type+'\\:taxon_details],[name='+toolStruc.type+'\\:taxa_taxon_list_id],[name='+toolStruc.type+'\\:comment],[name='+toolStruc.type+'\\:taxon_extra_info]').val('');\n\n\tif (detData.length>0) {\n\t\tjQuery('#id-'+toolStruc.type+'-later').attr('disabled', 'disabled');\n\t\tjQuery(toolStruc.mainForm+' input[name=determination\\:id]').val(detData[0].id).removeAttr('disabled');\n\t\tjQuery('[name='+toolStruc.type+'\\:taxon_details]').val(detData[0].taxon_details);\n\t\tjQuery('[name='+toolStruc.type+'\\:determination_type]').val(detData[0].determination_type);\n\t\tjQuery('[name='+toolStruc.type+'\\:taxa_taxon_list_id]').val(detData[0].taxa_taxon_list_id == null ? '' : detData[0].taxa_taxon_list_id);\n\t\tjQuery('[name='+toolStruc.type+'\\:comment]').val(detData[0].comment);\n\t\tjQuery('[name='+toolStruc.type+'\\:taxon_extra_info]').val(detData[0].taxon_extra_info);\n\t\tif(detData[0].determination_type == 'X'){\n\t\t\tjQuery('#'+toolStruc.type+'_taxa_list').append(\"" . lang::get('LANG_Taxa_Unknown_In_Tool') . "\");\n\t\t} else {\n\t\t\tvar resultsIDs = [];\n\t\t\tif(detData[0].taxa_taxon_list_id_list != null && detData[0].taxa_taxon_list_id_list != ''){\n\t\t\t  \tvar resultsText = \"" . lang::get('LANG_Taxa_Returned') . "<br />{ \";\n\t\t\t  \tresultsIDs = detData[0].taxa_taxon_list_id_list.substring(1, detData[0].taxa_taxon_list_id_list.length - 1).split(',');\n\t\t\t  \tfor(var j=0; j < resultsIDs.length; j++){\n\t\t\t\t\tfor(i = 0; i< toolStruc.taxaList.length; i++)\n\t\t\t\t\t\tif(toolStruc.taxaList[i].id == resultsIDs[j])\n\t\t\t\t\t\t\tresultsText = resultsText + (j == 0 ? '' : '<br />&nbsp;&nbsp;') + toolStruc.taxaList[i].taxon;\n\t\t  \t\t}\n\t  \t\t\tif(resultsIDs.length>1 || resultsIDs[0] != '')\n\t\t\t\t\tjQuery('#'+toolStruc.type+'_taxa_list').append(resultsText+ ' }');\n\t\t\t}\n\t\t\tjQuery('#'+toolStruc.type+'-id-button').data('toolRetValues', resultsIDs);\n  \t\t}\n\t} else {\n\t\tjQuery('#id-'+toolStruc.type+'-later').attr('checked', 'checked');\n\t}\n};\n\n// load in any existing incomplete collection.\n// general philosophy is that you are taken back to the stage last verified.\n// Load in the first if there are more than one. Use the internal report which provides my collections.\n// Requires that there is an attribute for completeness, and one for the CMS\n// load the data in the order it is entered, so can stop when get to the point where the user finished.\n// have to reset the entire form first...\njQuery('.poll-section').resetPanel();\n// Default state: hide everything except the collection details block.\njQuery('.poll-section').hidePanel();\njQuery('#cc-1').showPanel();\njQuery('.reinit-button').hide();\naddSession();\njQuery('#flower-id-button').data('toolRetValues',[]);\njQuery('#insect-id-button').data('toolRetValues',[]);\njQuery('#flower_taxa_list').empty();\njQuery('#insect_taxa_list').empty();\n\t\njQuery.ajax({ \n    type: 'GET', \n    url: \"" . $svcUrl . "\" + \"/report/requestReport?report=poll_my_collections.xml&reportSource=local&mode=json\" +\n\t\t\t\"&auth_token=" . $readAuth['auth_token'] . "&reset_timeout=true&nonce=" . $readAuth["nonce"] . "\" + \n\t\t\t\"&survey_id=" . $args['survey_id'] . "&userID_attr_id=" . $args['uid_attr_id'] . "&userID=" . $uid . "&complete_attr_id=" . $args['complete_attr_id'] . "&callback=?\", \n    dataType: 'json', \n    success: function(data) {\n\t  if(!(data instanceof Array)){\n   \t\talertIndiciaError(data);\n   \t  } else if (data.length>0) {\n\t\tvar i;\n       \tfor ( i=0;i<data.length;i++) {\n       \t\tif(data[i].completed == '0'){\n       \t\t    jQuery('#cc-6-consult-collection').attr('href', '" . url('node/' . $args['gallery_node']) . "'+'?collection_id='+data[i].id);\n       \t\t\t// load up collection details: existing ID, location name and protocol\n       \t\t\tjQuery('#cc-1-collection-details,#cc-2').find('input[name=sample\\:id]').val(data[i].id).removeAttr('disabled');\n       \t\t\t// main sample date is only set when collection is completed, so leave default.\n       \t\t\tloadAttributes('sample_attribute_value', 'sample_attribute_id', 'sample_id', 'sample\\:id', data[i].id, 'smpAttr', false);\n  \t\t\t\tvar locData = [];\n  \t\t\t\tjQuery.ajax({ \n\t\t\t\t\ttype: 'GET', \n\t\t\t\t\turl: \"" . $svcUrl . "/data/location/\" + data[i].location_id +\n          \t\t\t\t\t\"?mode=json&view=detail&nonce=" . $readAuth['nonce'] . "&auth_token=" . $readAuth['auth_token'] . "\" +\n          \t\t\t\t\t\"&callback=?\", \n\t\t\t\t\tdataType: 'json', \n\t\t\t\t\tsuccess: function(locationdata) {\n\t\t    \t\t  if(!(locationdata instanceof Array)){\n   \t\t\t\t\t\talertIndiciaError(locationdata);\n   \t\t\t\t\t  } else if (locationdata.length>0) {\n   \t\t\t\t\t    locData = locationdata;\n\t\t    \t\t\tjQuery('input[name=location\\:id]').val(locationdata[0].id).removeAttr('disabled');\n\t    \t\t\t\tjQuery('input[name=location\\:name]').val(locationdata[0].name);\n       \t\t\t\t\tjQuery('input[name=sample\\:location_name]').val(locationdata[0].name); // make sure the 2 coincide\n\t    \t\t\t\tjQuery('input[name=locations_website\\:website_id]').attr('disabled', 'disabled');\n\t    \t\t\t\tloadAttributes('location_attribute_value', 'location_attribute_id', 'location_id', 'location\\:id', locationdata[0].id, 'locAttr');\n    \t   \t\t\t\tloadImage('location_image', 'location_id', 'location\\:id', locationdata[0].id, '#cc-2-environment-image', " . $args['Environment_Image_Ratio'] . ", false);\n  \t\t\t\t\t  }\n  \t\t\t\t\t}, \n\t\t\t\t\tdata: {}, \n\t\t\t\t\tasync: false \n\t\t\t\t});\n  \t\t\t\tjQuery.ajax({ \n\t\t\t\t\ttype: 'GET', \n\t\t\t\t\turl: \"" . $svcUrl . "/data/occurrence/\" +\n          \t\t\t\t\t\"?mode=json&view=detail&nonce=" . $readAuth['nonce'] . "&auth_token=" . $readAuth['auth_token'] . "\" +\n          \t\t\t\t\t\"&sample_id=\"+data[i].id+\"&deleted=f&callback=?\", \n\t\t\t\t\tdataType: 'json', \n\t\t\t\t\tsuccess: function(flowerData) {\n          \t\t\t  // there will only be an occurrence if the floral station panel has previously been displayed & validated. \n\t\t    \t\t  if(!(flowerData instanceof Array)){\n\t\t\t\t\t\talertIndiciaError(flowerData);\n\t\t\t\t\t  } else if (flowerData.length>0) {\n\t\t\t\t\t\t// The location only holds a valid place if the floral station has been saved: because \n\t\t\t\t\t\t// the location is saved on cc-1 (due to FK constraints), we use the presence of the flower\n\t\t\t\t\t\t// occurrence as the indicator of FS saving. Only load location location at this point.\n\t\t\t\t\t\t// NB the location geometry is stored in centroid, due to restrictions in location model.\n\t\t\t\t\t\tjQuery('input[name=location\\:centroid_sref]').val(locData[0].centroid_sref);\n\t\t\t\t\t\tjQuery('input[name=location\\:centroid_sref_system]').val(locData[0].centroid_sref_system);\n\t\t\t\t\t\tjQuery('input[name=location\\:centroid_geom]').val(locData[0].centroid_geom);\n\t\t\t\t\t\tjQuery('#imp-sref').change();\n\t\t\t\t\t\tvar parts=locData[0].centroid_sref.split(' ');\n\t\t\t\t\t\tjQuery('input[name=place\\:lat]').val(parts[0]);\n\t\t\t\t\t\tjQuery('input[name=place\\:long]').val(parts[1]);\n\n\t\t\t\t\t\t\$('#cc-1').foldPanel();\n\t\t\t\t\t\tcheckProtocolStatus(true);\n\t\t\t\t\t\t\$('#cc-2').showPanel();\n\t\t\t\t\t\tjQuery('form#cc-2-floral-station > input[name=occurrence\\:sample_id]').val(data[i].id);\n\t\t\t\t\t\tjQuery('form#cc-2-floral-station > input[name=occurrence\\:id]').val(flowerData[0].id).removeAttr('disabled');\n\t\t\t\t\t\tloadAttributes('occurrence_attribute_value', 'occurrence_attribute_id', 'occurrence_id', 'occurrence\\:id', flowerData[0].id, 'occAttr', false);\n\t\t\t\t\t\tloadImage('occurrence_image', 'occurrence_id', 'occurrence\\:id', flowerData[0].id, '#cc-2-flower-image', " . $args['Flower_Image_Ratio'] . ");\n\n\t\t\t\t\t\tjQuery.ajax({ \n\t\t\t\t\t\t\ttype: 'GET', \n\t\t\t\t\t\t\turl: \"" . $svcUrl . "/data/determination\" + \n\t\t\t\t\t\t\t\t\t\"?mode=json&view=list&nonce=" . $readAuth['nonce'] . "&auth_token=" . $readAuth['auth_token'] . "&occurrence_id=\"+flowerData[0].id+\"&orderby=id&deleted=f&callback=?\", \n\t\t\t\t\t\t\tdataType: 'json', \n\t\t\t\t\t\t\tsuccess: function(detData) {\n\t\t\t\t\t\t\t  if(!(detData instanceof Array)){\n   \t\t\t\t\t\t\t\talertIndiciaError(detData);\n   \t\t\t\t\t  \t\t  } else loadDetermination(detData, flowerIDstruc);\n  \t\t\t\t\t\t\t}, \n\t\t\t\t\t\t\tdata: {}, \n\t\t\t\t\t\t\tasync: false \n\t\t\t\t\t\t});\n    \t      \t\t\t\t  \n    \t   \t\t\t\tjQuery.ajax({ \n\t\t\t\t\t\t\ttype: 'GET', \n\t\t\t\t\t\t\turl: \"" . $svcUrl . "/data/sample\" + \n    \t      \t\t\t\t\t\"?mode=json&view=detail&nonce=" . $readAuth['nonce'] . "&auth_token=" . $readAuth['auth_token'] . "&parent_id=\"+data[i].id+\"&callback=?\", \n\t\t\t\t\t\t\tdataType: 'json', \n\t\t\t\t\t\t\tsuccess: function(sessiondata) {\n\t    \t\t\t  \t\t  if(!(sessiondata instanceof Array)){\n   \t\t\t\t\t\t\t\talertIndiciaError(sessiondata);\n   \t\t\t\t\t  \t\t  } else if (sessiondata.length>0) {\n\t\t\t\t\t\t\t\tjQuery('#cc-2').foldPanel();\n\t\t\t\t\t\t\t\tsessionCounter = 0;\n\t\t\t\t\t\t\t\tjQuery('#cc-3-body').empty();\n \t\t\t\t\t\t\t\t\$('#cc-3').showPanel();\n\t\t\t\t\t\t\t\tfor (var i=0;i<sessiondata.length;i++){\n\t\t\t\t\t\t\t\t\tvar thisSession = addSession();\n\t\t\t\t\t\t\t\t\tjQuery('input[name=sample\\:id]', thisSession).val(sessiondata[i].id).removeAttr('disabled');\n\t\t\t\t\t\t\t\t\tjQuery('input[name=sample\\:date]', thisSession).val(sessiondata[i].date_start);\n\t\t\t\t\t\t\t\t\tjQuery('input[name=dummy_date]', thisSession).datepicker('disable').datepicker('setDate', new Date(sessiondata[i].date_start)).datepicker('enable');\n\t\t\t\t\t\t\t\t\tloadAttributes('sample_attribute_value', 'sample_attribute_id', 'sample_id', 'sample\\:id', sessiondata[i].id, 'smpAttr', false);\n  \t\t\t\t\t\t\t\t\t// fold this session.\n  \t\t\t\t\t\t\t\t\tthisSession.show();\n\t\t\t\t\t\t\t\t\tthisSession.children(':first').show().children().show();\n\t\t\t\t\t\t\t\t\tthisSession.children().not(':first').hide();\n\t\t\t\t\t\t\t\t\t\$.getJSON(\"" . $svcUrl . "/data/occurrence/\" +\n          \t\t\t\t\t\t\t\t\t\"?mode=json&view=detail&nonce=" . $readAuth['nonce'] . "&auth_token=" . $readAuth['auth_token'] . "&orderby=id\" +\n          \t\t\t\t\t\t\t\t\t\"&sample_id=\"+sessiondata[i].id+\"&deleted=f&callback=?\", function(insectData) {\n\t\t    \t\t\t\t\t\t\tif(!(insectData instanceof Array)){\n   \t\t\t\t\t\t\t\t\t\t\talertIndiciaError(insectData);\n   \t\t\t\t\t  \t\t  \t\t\t} else if (insectData.length>0) {\n \t\t\t\t\t\t\t\t\t\t\tfor (var j=0;j<insectData.length;j++){\n\t\t\t\t\t\t\t\t\t\t\t\tupdatePhotoReel(insectData[j].id);\n\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t}\n\t\t    \t\t\t\t\t\t});\n\t\t\t\t\t\t\t\t}\n \t\t\t\t\t\t\t\t\$('#cc-3').foldPanel();\n \t\t\t\t\t\t\t\t\$('#cc-4').showPanel();\n\t\t\t\t\t\t\t\tpopulateSessionSelect();\n \t\t\t\t\t  \t\t  }\n \t\t\t\t\t  \t\t}, \n\t\t\t\t\t\t\tdata: {}, \n\t\t\t\t\t\t\tasync: false \n\t\t\t\t\t\t});\n    \t   \t\t\t  }\n  \t\t\t\t\t}, \n\t\t\t\t\tdata: {}, \n\t\t\t\t\tasync: false \n\t\t\t\t});\n  \t\t\t\t// only use the first one which is not complete..\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t  }}, \n    data: {}, \n    async: false \n});\n  ";
        // because of the use of getJson to retrieve the data - which is asynchronous, the use of the normal loading_block_end
        // is not practical - it will do its stuff before the data is loaded, defeating the purpose. Also it uses hide (display:none)
        // which is a no-no in relation to the map. This means we have to dispense with the slow fade in.
        // it is also complicated by the attibutes and images being loaded asynchronously - and non-linearly.
        // Do the best we can!
        data_entry_helper::loading_block_end();
        data_entry_helper::$onload_javascript = "jQuery('.my-loading-hide').addClass('loading-hide').removeClass('my-loading-hide');\n" . data_entry_helper::$onload_javascript . "\nbuildMap();";
        return $r;
    }