var sighting_dont_show_hotspot = false;

/* validate the sighitng data
------------------------------------------*/
function sighting_validate() {

  var valid=true;

  var title = $('sighting_title').value.trim();
  var sighting_date = $('sighting_date').value.trim();

  if (!title || title == 'enter a title...' ) {

    $('sighting_title').style.borderColor='red';
    valid = false;

  } else {

    $('sighting_title').style.borderColor='';
    $('sighting_title').className='';
  }


  if (!sighting_date || sighting_date == 'enter a date' ) {

    $('sighting_date').style.borderColor='red';
    valid = false;

  } else {

    $('sighting_date').style.borderColor='';
    $('sighting_date').className='';
  }

  return valid;
}

function sighting_save() {

  if (sighting_validate()) {

    $('sight_sightings_prog').style.display='';

    var species_data = new Array();
    var species_deleted = new Array();

    for(var species_id in sighting_form_data) {

      var species = sighting_form_data[species_id];

      if ( species.row.cells[0].childNodes[0].checked ) {

        var tmp = new Object();
        tmp.id = species.id.toString();
        tmp.species_id = species.species_id.toString();
        tmp.count = species.row.cells[2].childNodes[0].value.toString();
        tmp.notes = species.notes;

        tmp.cf_juv = species.cf_juv.toString();
        tmp.cm_juv = species.cm_juv.toString();
        tmp.cu_juv = species.cu_juv.toString();

        tmp.cf_imm = species.cf_imm.toString();
        tmp.cm_imm = species.cm_imm.toString();
        tmp.cu_imm = species.cu_imm.toString();

        tmp.cf_adu = species.cf_adu.toString();
        tmp.cm_adu = species.cm_adu.toString();
        tmp.cu_adu = species.cu_adu.toString();

        tmp.cf_unk = species.cf_unk.toString();
        tmp.cm_unk = species.cm_unk.toString();
        tmp.cu_unk = species.cu_unk.toString();


        species_data.push(tmp);
      } else if (species.id) {

        species_deleted.push(species.id);
      }
    }
    var species_data_str = Json.toString(species_data);
    var species_deleted_str = Json.toString(species_deleted);


    var data = $('sighting').toQueryString();

    data += '&birds=' + species_data_str;
    data += '&deleted=' + species_deleted_str;

  // add additional info

  	var myXHR = new XHR({method:'post',onSuccess: function(response){

      $('sight_sightings_prog').style.display='none';

  		var ro = Json.evaluate(response);

  		if (ro['success']==true){

  		  active_species_id = ro['newid'];
  	    sighting_view(active_species_id, active_hotspot_id);

  // update hotspot sightings

        if ($('hp-tc-checklists-data')) {

        	var myXHR = new XHR({method:'post',onSuccess:function(response){

          	var data = Json.evaluate(response);

          	if (data['success']==true) {

          	  $('hp-tc-checklists-data').innerHTML = data['sightings'];
          	  $('hp-tc-species-count').innerHTML = data['count'] + ' Species Reported';

          	} else {

          	  alert(data['message']);
          	}

          }}).send('/php/controller_hotspot.php?action=getsightings', 'hotspotid=' + active_hotspot_id );
        }
  // update account area

        if ( $('accmnu_tallies').className == 'sel') {

          if ( $('mnutallies-sightings').hasClass('sel') ) {

            user_area_show_tallies();

          } else if ( $('mnutallies-lifelist').hasClass('sel') ) {

            user_area_show_lifelist();
          }
        } else if (  $('accmnu_hotspots').className == 'sel' ) {

            user_area_show_hospots();
        }
  	  }

  	}}).send('/php/controller_sighting.php?action=save', data );

// clear out form data
    for(var species_id in sighting_form_data) {
      delete sighting_form_data[species_id];
    }
    sighting_form_data = new Object();
  }
}


/* data for sighted species
-----------------------------------------------------*/
var SightedSpecies = new Class(
  {
    initialize: function(row, species_id){

      this.row = row;
      this.id = '';
      this.species_id = species_id;
      this.notes='';

      this.cf_juv='';
      this.cm_juv='';
      this.cu_juv='';

      this.cf_imm='';
      this.cm_imm='';
      this.cu_imm='';

      this.cf_adu='';
      this.cm_adu='';
      this.cu_adu='';

      this.cf_unk='';
      this.cm_unk='';
      this.cu_unk='';
    },

    check: function() {

      this.row.cells[0].childNodes[0].checked = true;
      this.row.cells[2].style.visibility = 'visible';
      this.row.cells[3].style.visibility = 'visible';
      this.row.cells[2].childNodes[0].focus();

    },

    update_state: function() {

      if ( this.row.cells[0].childNodes[0].checked ) {

        this.row.cells[2].style.visibility = 'visible';
        this.row.cells[3].style.visibility = 'visible';

        this.row.cells[2].childNodes[0].focus();

      } else {

        this.row.cells[2].style.visibility = 'hidden';
        this.row.cells[3].style.visibility = 'hidden';
      }
    },

    show: function() {

      active_species_id = this.species_id;
    // pass species count along to form
      $('species_count').value = this.row.cells[2].childNodes[0].value;
      $('species_name').innerHTML = this.row.cells[1].childNodes[0].nodeValue ;


    	this.row.cells[2].childNodes[0].value = $('species_count').value;

    	$('sight_sighting_note_text').value = this.notes;

      $('cf_juv').value = this.cf_juv > 0 ? this.cf_juv : '';
      $('cm_juv').value = this.cm_juv > 0 ? this.cm_juv : '';
      $('cu_juv').value = this.cu_juv > 0 ? this.cu_juv : '';

      $('cf_imm').value = this.cf_imm > 0 ? this.cf_imm : '';
      $('cm_imm').value = this.cm_imm > 0 ? this.cm_imm : '';
      $('cu_imm').value = this.cu_imm > 0 ? this.cu_imm : '';

      $('cf_adu').value = this.cf_adu > 0 ? this.cf_adu : '';
      $('cm_adu').value = this.cm_adu > 0 ? this.cm_adu : '';
      $('cu_adu').value = this.cu_adu > 0 ? this.cu_adu : '';

      $('cf_unk').value = this.cf_unk > 0 ? this.cf_unk : '';
      $('cm_unk').value = this.cm_unk > 0 ? this.cm_unk : '';
      $('cu_unk').value = this.cu_unk > 0 ? this.cu_unk : '';


    	var div = $('sight_sighting_notes').setStyles({
    		display:'block',
    		opacity: 0
    	});
    	new Fx.Style(div, 'opacity', {duration: 250} ).start(1);


    },

    done: function() {

      active_species_id = null;

      var div = $('sight_sighting_notes').setStyles({
    		display:'none',
    		opacity: 1
    	});
    	new Fx.Style(div, 'opacity', {duration: 125} ).start(0);

    	this.row.cells[2].childNodes[0].value = $('species_count').value;

    	this.notes = $('sight_sighting_note_text').value;

      this.cf_juv = $('cf_juv').value;
      this.cm_juv = $('cm_juv').value;
      this.cu_juv = $('cu_juv').value;

      this.cf_imm = $('cf_imm').value;
      this.cm_imm = $('cm_imm').value;
      this.cu_imm = $('cu_imm').value;

      this.cf_adu = $('cf_adu').value;
      this.cm_adu = $('cm_adu').value;
      this.cu_adu = $('cu_adu').value;

      this.cf_unk = $('cf_unk').value;
      this.cm_unk = $('cm_unk').value;
      this.cu_unk = $('cu_unk').value;

    },

    cancel: function() {

      active_species_id = null;

      var div = $('sight_sighting_notes').setStyles({
    		display:'none',
    		opacity: 1
    	});
    	new Fx.Style(div, 'opacity', {duration: 125} ).start(0);
    }
  }
);


var calDatePicker = null;
var searchTimerId = null;
var sighting_form_data=new Object();
var active_species_id = null;
var active_sighting_id = null;
var active_hotspot_id = null;
var sighting_additonal_fields = null;

var SightingAdditionalFields = new Class(
  {
    initialize: function(){

      this.complete = true;
      this.hour = '-';
      this.min = '-';
      this.ampm= 'AM';
      this.duration = '';
      this.duration_units = 'hours';
      this.area = '';
      this.area_units = 'acres';
      this.distance = '';
      this.distance_units = 'miles';

    },

    updateform: function() {

      $('saf_comp_yes').checked = this.complete;
      $('saf_comp_no').checked = !this.complete;
      $('saf_hour').value = this.hour;
      $('saf_min').value = this.min;
      $('saf_ampm').value = this.ampm;
      $('saf_duration').value = this.duration;
      $('saf_duration_units').value = this.duration_units;
      $('saf_area').value = this.area;
      $('saf_area_units').value = this.area_units;
      $('saf_distance').value = this.distance;
      $('saf_distance_units').value = this.distance_units;

    },

    save: function() {

      this.complete = $('saf_comp_yes').checked;
      this.hour = $('saf_hour').value;
      this.min = $('saf_min').value;
      this.ampm = $('saf_ampm').value;
      this.duration = $('saf_duration').value;
      this.duration_units = $('saf_duration_units').value;
      this.area = $('saf_area').value;
      this.area_units = $('saf_area_units').value;
      this.distance = $('saf_distance').value;
      this.distance_units = $('saf_distance_units').value;

    }
  }
);

var SpeciesSearchMatch = new Class(
  {
    initialize: function(item, species_id, family_name, family_sort, species_name, species_sort ){

      this.item = item;
      this.species_id = species_id;
      this.family_name = family_name;
      this.family_sort = family_sort;
      this.species_name = species_name;
      this.species_sort = species_sort;

      this.item.addEvent('click', this.add.bind(this) );
      this.item.addEvent('mouseover', this.highlight.bind(this) );
      this.item.addEvent('mouseout', this.unhighlight.bind(this) );
    },

    highlight: function() {

      for(; i < species_search_matches.length; ++i) {
        species_search_matches[i].unhighlight();
      }

      this.item.className = 'sighting_species_match';
    },

    unhighlight: function() {
      this.item.className = '';
    },

    add: function() {
      sighting_add_species(this);
      if ( $('sighting-no-species-msg') ) $('sighting-no-species-msg').remove();
    },

    selected: function() {
      return this.item.className == 'sighting_species_match';
    },
    select: function() {
      this.item.className = 'sighting_species_match';

      var off = $(this.item).getPosition().y - ($(this.item.parentNode).getPosition().y * 1.5);

      if (off > 0) {

        $(this.item.parentNode).scrollTo( 0,  off);

      } else if ( $(this.item.parentNode).getPosition().y > 0 ) {

        $(this.item.parentNode).scrollTo( 0,  0);
      }
    }
  }
);


/*description: enables onclick sighting-adding event for map
---------------------------------------------------------------*/
function sighting_enable_add_mode(){

	if (undefined_sighting) {
	  map.removeOverlay(undefined_sighting);
	  undefined_sighting=null;
	}

	var myXHR = new XHR({method:'post',onSuccess:function(response){

			var ro = Json.evaluate(response);

			if (ro['success']==true){

			  map_tool_mode = MAP_TOOL_ADD_SIGHTING;

      	eventListenerClick = GEvent.addListener(map, "click", function(marker, point) {

      		if (!marker) {

        	  if (map.getZoom() >= ADD_HOTSPOT_THRESHOLD) {

        	    if (!undefined_sighting) {

                msg = "<p>Please confirm you've located the sighting correctly.</p>";
                msg += "<p><a href=\"javascript: sighting_add(null, null, undefined_sighting.getPoint().lat(),undefined_sighting.getPoint().lng());\">OK</a>";
                msg += "<a href=\"javascript: reset_map_mode();\">Cancel</a></p>";
              	$('quick-message').innerHTML = msg;
              	$('quick-message').style.display = "block";
        	    }

        			undefined_sighting = new GMarker(point, { icon:iconSighting, draggable:true } );
        			undefined_sighting.enableDragging();
        			map.addOverlay(undefined_sighting);

              if(eventListenerClick) {

                GEvent.removeListener(eventListenerClick);
                eventListenerClick=null;
              }
              map_tool_mode = MAP_TOOL_PAN;
        		}
      	  }
    	  });

// check the zoom level

        validate_tool_mode(map.getZoom());

			} else {

			  ShowLoginPrompt("Please login or register if you'd like to add a sighting.");
			}
		}
	}).send('/php/check_login.php',"");
}



/*description: show the sighting view
---------------------------------------------------------------*/
function sighting_view(sighting_id, hotspot_id) {

//  map.closeInfoWindow();
  $('progress').style.display='';

  if(active_hotspot_id != hotspot_id && $('sighting')) {

    $('sighting').remove();
  }

  active_sighting_id = sighting_id;
  active_hotspot_id = hotspot_id;

  TB_remove();
  $('hotspot-popup').style.display = "none";

	var myXHR = new XHR({method:'post',onSuccess:function(response){

		var ro = Json.evaluate(response);

		if (ro['success']==true){

		  if ( $('sighting') ) {

// div already exists so just update it's content
		    $('sighting').innerHTML = ro['view'];

		  } else {

		    if (!hotspot_id) {
// it's a standalone sighting.  create a temporary map marker

        	if (undefined_sighting) {
        	  map.removeOverlay(undefined_sighting);
        	  undefined_sighting=null;
        	}

    			undefined_sighting = new GMarker(new GLatLng(ro['lat'], ro['lng']), { icon:iconSighting, draggable:false } );
    			map.addOverlay(undefined_sighting);
		    }


        closeevent = GEvent.addListener(map, "infowindowclose", function() {

          GEvent.removeListener(closeevent);
          closeevent=null;

        	if (undefined_sighting) {
        	  map.removeOverlay(undefined_sighting);
        	  undefined_sighting=null;
        	}

        });

// open a new infowindow

  		  sighting_center_offset(  new GLatLng(ro['lat'], ro['lng']) );
        map.openInfoWindow( new GLatLng(ro['lat'], ro['lng']), '<div id="sighting">' + ro['view'] + '</div>', { noCloseOnClick:true } );
		  }

      $('progress').style.display='none';

	  }

  }}).send('/views/sighting.php','sighting_id='+sighting_id+'&hotspot_id='+hotspot_id);
}

var closeevent=null;

/*description: close hotspot and show sighting form
---------------------------------------------------------------*/
function sighting_add_to_hotspot(hotspot_id, hotspot_name, lat, lng) {

  if ($('TB_overlay'))  $('TB_overlay').remove();
  hotspot_close();
  profile_close();

  if (map_mode != MAP_MODE_HOTSPOT) {

    set_mode_hotspot();

  } else {

  // center on the hotspot
  	var myXHR = new XHR({method:'post',onSuccess:function(response){

    	var data = Json.evaluate(response);

    	if (data['success']==true) {

        var lat = parseFloat(data['lat']);
        var lng = parseFloat(data['lng']);

  // set map center which will guarantee the hotspots is on the map

        map.setCenter(new GLatLng(lat, lng), 12);


      	var myXHR = new XHR({method:'post',onSuccess:function(results){

      		$('hotspot-popup-content').innerHTML = results;
      		$('hotspot-popup').style.display = "none";

          center_hotspot();

          $('progress').style.display='none';

      	}}).send("/views/hotspot.php","hotspot_id="+hotspot_id);

        sighting_add(hotspot_id, hotspot_name, lat, lng);

    	} else {

    	  alert('hotspot not found!');
    	}

    }}).send('/php/controller_hotspot.php?action=getcoordfromid', 'id=' + hotspot_id );
  }

}

/*description: close hotspot and show sighting form
---------------------------------------------------------------*/
function sighting_add(hotspot_id, hotspot_name, lat, lng, dont_show_hotspot ) {

  if (map.getZoom() < 10)   map.setZoom( 10 );
  sighting_dont_show_hotspot =  dont_show_hotspot;

	$('quick-message').innerHTML = '';
	$('quick-message').style.display = 'none';

  active_sighting_id = null;
  active_hotspot_id = hotspot_id;

// check for a login
	var myXHR = new XHR({method:'post',onSuccess:function(resp){

		var res = Json.evaluate(resp);
		if (res['success']==true){

      $('progress').style.display = '';

    	var myXHR = new XHR({method:'post',onSuccess:function(resp){

    // hide the hotspot and lightbox
        TB_remove();
        $('hotspot-popup').style.display = "none";

        var openevent = GEvent.addListener(map, "infowindowopen", function() {

          GEvent.removeListener(openevent);
          if (hotspot_name) {
            $('sighting_title').value = hotspot_name;
            $('sighting_title').className = '';
          }

          sighting_initialze_form();

          $('progress').style.display = 'none';

        });

        closeevent = GEvent.addListener(map, "infowindowclose", function() {

          GEvent.removeListener(closeevent);
          closeevent=null;

          if (active_hotspot_id) {

            if(calDatePicker) {
              delete calDatePicker;
              calDatePicker = null;
            }

            for(var species_id in sighting_form_data) {
              delete sighting_form_data[species_id];
            }
            sighting_form_data = new Object();

            if(active_hotspot_id && !dont_show_hotspot) {

              $('hotspot-popup').style.display = "";
              TB_show();

            } else {

              $('hotspot-popup').style.display = "none";
            }
            active_sighting_id = null;
            active_hotspot_id = null;

          	if (undefined_sighting) {
          	  map.removeOverlay(undefined_sighting);
          	  undefined_sighting=null;
          	}

          }

        	if (undefined_sighting) {
        	  map.removeOverlay(undefined_sighting);
        	  undefined_sighting=null;
        	}

        });

        sighting_center_offset(new GLatLng(lat, lng));

    		var ro = Json.evaluate(resp);

        map.openInfoWindow( new GLatLng(lat, lng), '<div id="sighting">' + ro['view'] + '</div>', { noCloseOnClick:true } );

      }}).send('/views/sighting_form.php','hotspot_id='+hotspot_id+'&lat='+lat+'&lng='+lng);


		} else {

      ShowLoginPrompt("Please login or register if you'd like to add a sighting to this hotspot.");
		}

	}}).send('/php/check_login.php',"");

}

function sighting_edit(sighting_id, lat, lng) {

  $('progress').style.display='';

	var myXHR = new XHR({method:'post',onSuccess:function(resp){

		var ro = Json.evaluate(resp);

		$('sighting').empty();
    $('sighting').innerHTML = ro['view'];

    for(var species_id in sighting_form_data) {
      delete sighting_form_data[species_id];
    }
    sighting_form_data = new Object();

    var species = ro['species'];

    for(var i = 0; i < species.length; ++i) {

      var row = 'sspec'+species[i].species_order;
      row = document.getElementById(row);
      var sp = new SightedSpecies(row, species[i].species_id);

      sp.id = species[i].id;
      sp.notes = species[i].notes;
      sp.cf_juv = species[i].cf_juv;
      sp.cm_juv = species[i].cm_juv;
      sp.cu_juv = species[i].cu_juv;
      sp.cf_imm = species[i].cf_imm;
      sp.cm_imm = species[i].cm_imm;
      sp.cu_imm = species[i].cu_imm;
      sp.cf_adu = species[i].cf_adu;
      sp.cm_adu = species[i].cm_adu;
      sp.cu_adu = species[i].cu_adu;
      sp.cf_unk = species[i].cf_unk;
      sp.cm_unk = species[i].cm_unk;
      sp.cu_unk = species[i].cu_unk;

      sighting_form_data[ species[i].species_id ] = sp;
    }

    sighting_initialze_form();

    sighting_additonal_fields.complete = ro['complete'];
    sighting_additonal_fields.hour = ro['start_hours'];
    sighting_additonal_fields.min = ro['start_minutes'];
    sighting_additonal_fields.ampm= ro['start_ampm'];
    sighting_additonal_fields.duration = ro['duration'];
    sighting_additonal_fields.durationunits = ro['duration_units'];
    sighting_additonal_fields.area = ro['area'];
    sighting_additonal_fields.area_units = ro['area_units'];
    sighting_additonal_fields.distance = ro['distance'];
    sighting_additonal_fields.distance_units = ro['distance_units'];

    sighting_additonal_fields.updateform();

    $('progress').style.display='none';

  }}).send('/views/sighting_form.php','sighting_id='+sighting_id+'&lat='+lat+'&lng='+lng);
}

/* cancel sighting add and restore hotspot and lightbox
------------------------------------------------------*/
function sighting_cancel_add() {

	if (undefined_sighting) {
	  map.removeOverlay(undefined_sighting);
	  undefined_sighting=null;
	}

  if(closeevent) {
    GEvent.removeListener(closeevent);
    closeevent=null;
  }

  if(calDatePicker) {
    delete calDatePicker;
    calDatePicker = null;
  }

  $('sighting').empty();

  for(var species_id in sighting_form_data) {
    delete sighting_form_data[species_id];
  }
  sighting_form_data = new Object();


  if(active_sighting_id) {

    sighting_view(active_sighting_id, active_hotspot_id);

  } else if(!sighting_dont_show_hotspot && active_hotspot_id) {

    map.closeInfoWindow();
    $('hotspot-popup').style.display = "";
    TB_show();

  } else {

    map.closeInfoWindow();
  }

}


function sighting_close() {

  map.closeInfoWindow();

	if (undefined_sighting) {
	  map.removeOverlay(undefined_sighting);
	  undefined_sighting="";
	}

	$('quick-message').innerHTML = "";
	$('quick-message').style.display = "none";

}


function sighting_menu_show() {  $('sighting-submenu').className='submenu_show';  }
function sighting_menu_hide() {  $('sighting-submenu').className='submenu_hide';  }


function sighting_tab_select(tab) {

  switch(tab.id) {

    case 'mnu-sight-sightings':

      $('mnu-sight-sightings').addClass('sel');
      $('mnu-sight-notes').removeClass('sel');

      $('sight_sightings').style.display='block';
      $('sight_notes').style.display='none';
      break;

    case 'mnu-sight-notes':

      $('mnu-sight-notes').addClass('sel');
      $('mnu-sight-sightings').removeClass('sel');

      $('sight_sightings').style.display='none';
      $('sight_notes').style.display='block';
      break;

  }
}

function sighting_show_notes(id) {

	var myXHR = new XHR({method:'post',onSuccess: function(response){

		var res = Json.evaluate(response);

		if (res['success']==true){

		  var data = res['data'];

      var tmp = '<table><tr><th></th><th>Female</th><th>Male</th><th>Unknown</th></tr>';
      tmp += '<tr><th>Juvenile</th><td>' + data.cf_juv + '</td>';
      tmp += '<td>' + data.cm_juv + '</td>';
      tmp += '<td>' + data.cu_juv + '</td></tr>';

      tmp += '<tr><th>Immature</th><td>' + data.cf_imm + '</td>';
      tmp += '<td>' + data.cm_imm + '</td>';
      tmp += '<td>' + data.cu_imm + '</td></tr>';

      tmp += '<tr><th>Adult</th><td>' + data.cf_adu + '</td>';
      tmp += '<td>' + data.cm_adu + '</td>';
      tmp += '<td>' + data.cu_adu + '</td></tr>';

      tmp += '<tr><th>Unknown</th><td>' + data.cf_unk + '</td>';
      tmp += '<td>' + data.cm_unk + '</td>';
      tmp += '<td>' + data.cu_unk + '</td></tr></table>';
      tmp += '<h3>Notes:</h3>';
      tmp += '<div id="sight_sighting_notes_note">'+ data.note +'</div>';

      $('sight_sightings_bdy').innerHTML = tmp;


      $('sight_sightings_count').innerHTML = data.count + ' ' + data.species;

    	var div = $('sight_sighting_notes').setStyles({
    		display:'block',
    		opacity: 0
    	});
    	new Fx.Style(div, 'opacity', {duration: 250} ).start(1);

		} else {

		  alert(res['message']);

		}
	}}).send('/php/controller_sighting.php',"action=getnotes&id="+id);
}

function sighting_hide_notes() {
  $('sight_sighting_notes').style.display = 'none';
}

/* toggle species as selected or unselected
------------------------------------------------------*/
function sighting_toggle_species_byname(row, species_id) {

  row.cells[0].childNodes[0].checked = !row.cells[0].childNodes[0].checked;

  if (sighting_form_data[species_id] == undefined )
    sighting_form_data[species_id] = new SightedSpecies(row, species_id);

  sighting_form_data[species_id].update_state();
}
/* toggle species as selected or unselected
------------------------------------------------------*/
function sighting_toggle_species(row, species_id) {

  if (sighting_form_data[species_id] == undefined )
    sighting_form_data[species_id] = new SightedSpecies(row, species_id);

  sighting_form_data[species_id].update_state();
}

function sighting_notes_form_show(species_id) {
  sighting_form_data[species_id].show();
}

function sighting_notes_form_cancel() {
  sighting_form_data[active_species_id].cancel();
}

function sighting_notes_form_done() {
  sighting_form_data[active_species_id].done();
}

function toggle_new_species_drawer() {


 if ( $('sighting-list-new').style.width == '145px' ) {

    mapMove = new Fx.Style('sighting-list-new', 'width', {duration: 500} );
    mapMove.start(0);
  } else {

    mapMove = new Fx.Style('sighting-list-new', 'width', {duration: 500} );
    mapMove.start(145);
    $('species-search-input').focus();
  }
}

/* ensure the sighting dialog is completely visible
------------------------------------------------------*/
function sighting_center_offset(latlng) {

// center the map so that the waypoint info window fits

//  pnt = map.getCurrentMapType().getProjection().fromLatLngToPixel( pnt, map.getZoom() );

  var pnt = map.fromLatLngToContainerPixel(latlng);
  var cpnt = map.fromLatLngToContainerPixel(map.getCenter());
  var move = false;

// move the center a bit to the right
  if (pnt.x < 325) {

    move = true;
    cpnt.x -= (325 - pnt.x);
    offctr = map.fromContainerPixelToLatLng( cpnt );
  }

// move the center a bit to the left

  if (map.getSize().width - pnt.x < 550) {

    move = true;
    cpnt.x += (550 - (map.getSize().width - pnt.x));
    offctr = map.fromContainerPixelToLatLng( cpnt );
  }

// move the center a bit down
  if (pnt.y < 525) {

    move = true;
    cpnt.y -= (525 - pnt.y);
    offctr = map.fromContainerPixelToLatLng( cpnt );
  }

  if (move) {

    map.setCenter( offctr );
  }
}


/* add a little delay before searching in case the user
 is still typing more letters
------------------------------------------------------*/
function sighting_species_search(match) {

  if(searchTimerId) {
    clearTimeout(searchTimerId);
    searchTimerId=null;
  }

  searchTimerId = setTimeout ( 'sighting_species_search_go("'+match+'")', 500 );
}


/* toggle the bird family on/off
------------------------------------------------------*/
function sighting_toggle_family(el) {

  var li = el.parentNode;

  if (li.className=='sight_sightings_species_open') {

    li.className='sight_sightings_species_close';

  } else {

    li.className='sight_sightings_species_open';
  }
}

var species_search_matches = Array();

/* search for bird species
------------------------------------------------------*/
function sighting_species_search_go(match) {

  if(searchTimerId) {
    clearTimeout(searchTimerId);
    searchTimerId=null;
  }

  $('species_matches').empty();

  if (match) {

    species_search_matches = Array();

    var world = $('link_toggle_regional_world_list').innerHTML == 'Return to regional list';

    $('sighting-list-new-prog').style.display='';

  	var myXHR = new XHR({method:'post',onSuccess: function(response){

  		var res = Json.evaluate(response);

  		if (res['success']==true){

  		  var matches = res['matches'];

  		  if(matches.length > 0) {

    		  for(var i = 0; i < matches.length; ++i) {

            var li = new Element('li').injectInside( $('species_matches') ).setText( matches[i].name );

            if(i == 0) li.className = 'sighting_species_match';

            var species_id = matches[i].id;

            species_search_matches.push(new SpeciesSearchMatch(
              li,
              matches[i].id,
              matches[i].family,
              matches[i].fo,
              matches[i].name,
              matches[i].so
            ));
    		  }

  		  } else {

          var li = new Element('li', { 'class' : 'species-no-match' }) .injectInside( $('species_matches') ).setText('no matches found');
  		  }

        $('species_matches').scrollTo( 0,  0);
        $('sighting-list-new-prog').style.display='none';

  		} else {

  		  alert(res['message']);
  		}

  	}}).send('/php/controller_sighting.php?action=search',$('sighting').toQueryString() + "&match="+match+'&hotspotid='+active_hotspot_id + '&world=' + world);
  }
}

function species_select_match(species_id) {


}

function sighting_add_species(species) {

  var handled = false;

  var families = $('sighting-families').getChildren();

  for(var i = 0; i < families.length; ++i) {

    var family = families[i];

    var fo = parseInt(family.id.substring(5));

    if (fo == species.family_sort) {

// this family is already in the list, check for the species

      var table = family.childNodes[1];
      var j = 0;

      for(; j < table.rows.length; ++j) {

        var row = table.rows[j];

        var so = parseInt(row.id.substring(5));

        if (so == species.species_sort) {

// this species is already in the list, check it off

          if (sighting_form_data[species.species_id] == undefined )
            sighting_form_data[species.species_id] = new SightedSpecies(row, species.species_id);

          if(family.className=='sight_sightings_species_close')  family.className = 'sight_sightings_species_open';
          sighting_form_data[species.species_id].check();
          handled = true;
          break;

        } if (so > species.species_sort) {

// this species is not in the list, add it just before this species
          break;
        }
      }

      if (!handled) {
// add species at 'j' insertion point

        var newrow = table.insertRow(j);
        newrow.id = "sspec" + species.species_sort;
        sighting_add_species_row(newrow, species.species_id, species.species_name);
        handled = true;
      }

      handled = true;
      break;

    } else if (fo > species.family_sort) {

// this family is not in the list, add it just before this family

      var li = new Element('li', { 'class' : 'sight_sightings_species_open'} ).injectBefore(family);
      li.id = 'ssfam' + species.family_sort;
      var p = new Element('p').injectInside(li).setText(species.family_name);
      p.onclick= function() { sighting_toggle_family(this); }

      var table = new Element('table', { 'class' : 'species_family_table' } ).injectInside(li);
      var newrow = table.insertRow(0);
      newrow.id = "sspec" + species.species_sort;
      sighting_add_species_row(newrow, species.species_id, species.species_name);
      handled = true;
      break;
    }
  }
  if(!handled) {

// add a new family and species to the end of the list
    var li = new Element('li', { 'class' : 'sight_sightings_species_open'} ).injectInside( $('sighting-families') );
    li.id = 'ssfam' + species.family_sort;
    var p = new Element('p').injectInside(li).setText(species.family_name);
    p.onclick= function() { sighting_toggle_family(this); }

    var table = new Element('table', { 'class' : 'species_family_table' } ).injectInside(li);
    var newrow = table.insertRow(0);
    newrow.id = "sspec" + species.species_sort;
    sighting_add_species_row(newrow, species.species_id, species.species_name);
  }
}

/* add a new row to the sighting checklist
------------------------------------------------------*/
function sighting_add_species_row(newrow, species_id, species_name) {

  var cell = newrow.insertCell(0);
  cell.className = 'species-form-check';
  cell.innerHTML = '<input type="checkbox" checked onclick="sighting_toggle_species(this.parentNode.parentNode, '+species_id+')">';

  var cell = newrow.insertCell(1);
  cell.className = 'species-form-name';
  cell.innerHTML = species_name;
//  cell.onclick = function() { sighting_toggle_species_byname(this.parentNode, species_id); }

  var cell = newrow.insertCell(2);
  cell.className = 'species-form-number';
  cell.innerHTML = '<input type="text" size="3" onfocus="this.style.borderColor=\'#000\'" onblur="this.style.borderColor=\'#CCC\'">';

  var cell = newrow.insertCell(3);
  cell.className = 'species-notes';
  cell.onclick = function() { sighting_notes_form_show(species_id); }
  cell.innerHTML='&nbsp;';

  sighting_form_data[species_id] = new SightedSpecies(newrow, species_id);
  sighting_form_data[species_id].update_state();

}


/* show additional form
------------------------------------------------------*/
function sighting_additional_show() {
  sighting_additonal_fields.updateform();
  $('saf-container').style.display = 'block';
}

/* close additional form
------------------------------------------------------*/
function sighting_additional_close() {
  $('saf-container').style.display = 'none';
}

/* close additional form
------------------------------------------------------*/
function sighting_additional_save() {
  $('saf-container').style.display = 'none';
  sighting_additonal_fields.save();
}


function sighting_initialze_form() {

  if(calDatePicker) delete calDatePicker;

  calDatePicker = new Calendar( { 'sighting_date': 'm/d/Y' }, { classes: ['alternate'], navigation: 2, direction : -1, 'onHideStart' : sighting_validate} );

  $('species-search-input').onkeyup = function(event) {

    event = new Event(event);

    switch (event.key) {

      case 'enter':
// move selection down

        var i = 0;
        for(; i < species_search_matches.length; ++i) {
          if (species_search_matches[i].selected()) break;
        }

        if (species_search_matches.length > 0) {

// select this species
          sighting_add_species(species_search_matches[i]);
        }
        event.stop();
        break;

      case 'up':
// move selection up

        var i = 0;
        var found = false;
        for(; i < species_search_matches.length; ++i) {
          if (species_search_matches[i].selected()) {
            found = true;
            break;
          }
        }

        if (found) {

          species_search_matches[i].unhighlight();
          species_search_matches[i-1].select();

        } else if (!found && species_search_matches.length > 0) {
          species_search_matches[0].select();
        }

        event.stop();
        break;

      case 'down':
// move selection down

        var i = 0;
        var found = false;
        for(; i < species_search_matches.length; ++i) {
          if (species_search_matches[i].selected()) {
            found = true;
            break;
          }
        }

        if (i < species_search_matches.length - 1) {

          species_search_matches[i].unhighlight();
          species_search_matches[i+1].select();

        } else if (!found && species_search_matches.length > 0) {
          species_search_matches[0].select();
        }

        event.stop();
      break;

      default:

        sighting_species_search($('species-search-input').value);
      break;

    }

  };

  $('species-search-input').focus();

  var options = '-- 1 2 3 4 5 6 7 8 9 10 11 12'.split(' ');
  var spin = new SpinnerControl('saf_hour', 'upHr', 'dnHr', { data: options });

//  var options = '-- 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59'.split(' ');
  var options = '-- 5 10 15 20 25 30 35 40 45 50 55'.split(' ');
  var spin = new SpinnerControl('saf_min', 'upMn', 'dnMn', { data: options });

  var options = 'AM PM'.split(' ');
  var spin = new SpinnerControl('saf_ampm', 'upAP', 'dnAP', { data: options });

  var options = 'days hours minutes'.split(' ');
  var spin = new SpinnerControl('saf_duration_units', 'upDu', 'dnDu', { data: options });

  var options = 'acres hectares sqyd sqmi sqm sqkm'.split(' ');
  var spin = new SpinnerControl('saf_area_units', 'upAr', 'dnAr', { data: options });

  var options = 'miles kms'.split(' ');
  var spin = new SpinnerControl('saf_distance_units', 'upDC', 'dnDC', { data: options });

  if(sighting_additonal_fields)  delete sighting_additonal_fields;
    sighting_additonal_fields = new SightingAdditionalFields();
}

/*  after a confirmation, delete the checked sightings
-------------------------------------------------------------*/
function sighting_delete_one(id) {

  if (confirm('Are you sure you want to delete this sighting?') ) {

  	var myXHR = new XHR({method:'post',onSuccess: function(response){

  		var res = Json.evaluate(response);

  		if (res['success']==true){

	      map.closeInfoWindow();

        if ( $('accmnu_tallies').className == 'sel') {

          if ( $('mnutallies-sightings').hasClass('sel') ) {

            user_area_show_tallies();

          } else if ( $('mnutallies-lifelist').hasClass('sel') ) {

            user_area_show_lifelist();
          }
        }

  		} else {

  		  alert(res['message']);
  		}

  	}}).send('/php/controller_sighting.php?action=delete',"id="+id);
  }
}


/*  after a confirmation, delete the checked sightings
-------------------------------------------------------------*/
function sightings_delete() {

  var sightings = document.getElementsByName('usersightingchecked');

  if (sightings.length > 0) {

    if (sightings.length > 1) {

      var msg='Are you sure you want to delete these sightings?';

    } else {

      var msg='Are you sure you want to delete this sighting?';
    }

    if (confirm(msg) ) {

      for(var i = 0; i < sightings.length; ++i) {

        if (sightings[i].checked) {

          var parent = sightings[i].parentNode.parentNode;

          var sightingid = parent.id.substring(4);

        	var myXHR = new XHR({method:'post',onSuccess: function(response){

        		var res = Json.evaluate(response);

        		if (res['success']==true){

              $('asid' + res['id']).remove();

        		} else {

        		  alert(res['message']);
        		}

        	}}).send('/php/controller_sighting.php?action=delete',"id="+sightingid);
        }
      }
    }
  }
}

/*  toggle the search results between regional and world
-------------------------------------------------------------*/
function sighting_toggle_regional_world_list() {

  if ( $('link_toggle_regional_world_list').innerHTML == 'Return to regional list' ) {

    $('link_toggle_regional_world_list').innerHTML = 'Draw from world list';

  } else {

    $('link_toggle_regional_world_list').innerHTML = 'Return to regional list';
  }

  sighting_species_search_go( $('species-search-input').value );
}

/*  email a formatted version of the sighting to the user
-------------------------------------------------------------*/
function sighting_email(id) {

	var myXHR = new XHR({method:'post',onSuccess: function(response){

		var res = Json.evaluate(response);

		if (res['success']==true){

      alert('A copy of this sightings record has been sent to your e-mail');

		} else {

		  alert(res['message']);
		}

	}}).send('/php/controller_sighting.php?action=email',"id="+id);

}