function log() {
  if ( window.console && window.console.firebug )
    console.debug.apply( console, arguments );
  else
    alert( [].join.apply( arguments, [' '] ) );
}

HolidayChecker = {
  counter : 0,

  loadNextHoliday: function(element, value) {
    HolidayChecker.counter += 1;
    var current_counter = HolidayChecker.counter;
    getHoliday(element, value, current_counter);
  }
}


function getHoliday(element, value, current_counter) {
  var url = '/index.php/holiday/next';
  new Ajax.Updater('nothing', url, {
    asynchronous:true,
    evalScripts:false,
    onComplete:function(request, json) {
      if (HolidayChecker.counter == current_counter) {
        if (json.success) {
          $('results').style.display='block';
          Element.update('next_holiday_date', json.message);
          selectCountry(json.country_id);

          new Effect.Fade('indicator');
        } else {
          // error
        }
      }

    }, onLoading:onLoading(),
    parameters:'country_id=' + value
    });
}


function selectCountry(country_id) {
  // loop through all country values
  var i = 0;
  $$('#country_id option').each(function(e) {
    if (e.value == country_id) {
      $('country_id').selectedIndex = i;
    }
    i++;
  });
}

function onLoading(request, json) {
  $('indicator').show();
}


// locate the country!
var latitude;
var longitude;
function locate() {
  var my_counter = HolidayChecker.counter;
  // geolocation
  if (navigator.geolocation) {
    if (latitude == null) {
      navigator.geolocation.getCurrentPosition(function(position) {
        latitude = position.coords.latitude;
        longitude = position.coords.longitude;
        var url = '/index.php/holiday/country?lat=' + position.coords.latitude + '&lon=' + position.coords.longitude;

        new Ajax.Request(url, {
          method: 'get',
          onSuccess: function(transport, json) {
            var country = eval(json);
            //selectCountry(country.id);
            getHoliday("country_id", country.id, my_counter);
            new Effect.Fade('indicator');
          }
        });

      }, function(error){
        // permission denied, timeout, etc.
      });
    }
  } else { // by ip
    // load country by ip on page load
    HolidayChecker.loadNextHoliday("country_id");
  }

  // watch for country change
  new Form.Element.EventObserver("country_id", HolidayChecker.loadNextHoliday);
}
