var xmldoc;

$(document).ready(function() {
  $('.state-form .go-btn').bind('click',function(e) {
    var stateID = $('.state-form select').val();
    if (stateID == 0) {
      return;
    }
    if (xmldoc == null) {
      $.ajax({
        type: "GET",
        url: "xml/preseason_population_estimate.xml",
        dataType: "xml",
        success: function(xml) {
            xmldoc = xml;
            loadState(xmldoc, stateID);
			$('.state-form').after('<p class="state-footer">Information provided by Quality Deer Management Association</p>');
          }
        });
    } else {
      loadState(xmldoc, stateID);
    }
  });
});

function loadState(xmldoc, stateID) {
  $(xmldoc).find('state').each(function(){
    var id_text = $(this).attr('id');
    if (id_text == stateID) {
		var name_text = $(this).find('name').text();
		$('.state-form .results').empty().append('<table></table>');
		$('.state-form .results table').append('<tr id="years"></tr><tr id="values"></tr>');
		var noDataFlag = false;
		$(this).find('population').each(function(){
			var year = $(this).find('year').text();
			var pop = $(this).find('value').text();
			$('.state-form .results table tr#years').append('<th>' + year + '</th>');      
			$('.state-form .results table tr#values').append('<td>' + addCommas(pop) + '</td>');      
			if (pop == '*') {
				noDataFlag = true;
			}
		});
		$('#nd').remove();
		if (noDataFlag == true) {
			$('.state-form').parent().append('<p class="state-footer" id="nd">* Information Not Available</p>');
		}
		$('.state-form .results').animate({opacity: 'show', height: 'show'}, 'normal');
    }
  });
}

function addCommas(nStr)
{
	nStr += '';
	x = nStr.split('.');
	x1 = x[0];
	x2 = x.length > 1 ? '.' + x[1] : '';
	var rgx = /(\d+)(\d{3})/;
	while (rgx.test(x1)) {
		x1 = x1.replace(rgx, '$1' + ',' + '$2');
	}
	return x1 + x2;
}
