var states = [];
var countyel;

function updateCounties(el, id) {
  var newcountyel = countyel.cloneNode(false);
  countyel.parentNode.replaceChild(newcountyel, countyel);
  countyel = newcountyel;
  while(countyel.options.length) {
    countyel.remove(0);
  }
  if (el.selectedIndex > -1) {
    var state = el.options[el.selectedIndex].value;
    for (var i = 0; i < states[state].length; i++) {
      countyel.options.add(new Option(states[state][i][1], states[state][i][0]));
      if (states[state][i][0] == id) {
        countyel.options[countyel.options.length - 1].selected = 'selected';
      }
    }
  }
  else {
    countyel.options.add(new Option('Choose a State', ''));
  }
}

function updateCountiesEvent() {
  updateCounties(this, -1);
}

function countyList(el) {
  countyel = el;
  el.multiple = false;
  var stateselector = document.createElement('select');
  var selectedId = -1;
  for (var i = 0; i < countyel.options.length; i++) {
    var id = countyel.options[i].value;
    var split = countyel.options[i].text.split(', ', 2);
    var state = split[0];
    var county = split[1];
    if (states[state] === undefined) {
      states[state] = [];
      stateselector.options.add(new Option(state, state));
    }
    if (countyel.options[i].selected) {
      stateselector.options[stateselector.options.length - 1].selected = 'selected';
      selectedId = el.options[i].value;
    }
    states[state].push([id, county]);
  }
  stateselector.onchange = updateCountiesEvent;
  stateselector.className = 'stateselector';
  updateCounties(stateselector, selectedId);
  countyel.parentNode.insertBefore(stateselector, countyel);
}

function createMarker(map, lat, lon, name) {
  if (map) {
    var point = new GLatLng(lat, lon);
    var marker = new GMarker(point, {});
    // save the info we need to use later for the side_bar
    map.addOverlay(marker);
    map.setCenter(point);
    map.setZoom(12);
  }
}

function createGoogleMap(id) {
  if (GBrowserIsCompatible()) {
    // create the map
    var gmap = new GMap2(document.getElementById(id));
    gmap.enableScrollWheelZoom();
    return gmap;
  }
  return false;
}

function setStartEndDates(startdate, enddate) {
  document.getElementById('UserStartDate').value = startdate;
  document.getElementById('UserEndDate').value = enddate;
}

function calculateRemaining () {
  var remaining = document.getElementById('remaining');
  var description = document.getElementById('UserDescription');
  var charsRemaining = 4000 - description.value.length;
  if (charsRemaining < 0) {
    description.value = lastDescription;
    alert('Your description cannot exceed 4000 characters.');
  }
  else {
    remaining.innerHTML = String(charsRemaining) +  '/4000 characters remaining';
    lastDescription = description.value; 
  }
}

function setupCalculateRemaining () { 
  var description = document.getElementById('UserDescription');
  description.onkeyup = calculateRemaining;
  calculateRemaining();
}

