(function($){
  $.wizard = function(step, steps){
    var steps = (steps || 3) + 1;
    for(var i=1;i<steps;i++){
      var id = '#step'+i;
      if(i != step){
        $(id).hide()
      }
    }
    $('#step'+step).trigger('wizard:show').show();
  }
})(jQuery);

$(function(){
  
  // Universal UJS controller
  $('form.ajax').live('submit', function(){
    var form = $(this),
        url = form.attr('action'),
        data = form.serialize(),
        method = form.attr('method');
    $.ajax({
      url: url,
      type: method,
      data: data,
      success: function(data) {
        form.trigger('ajax:success', [data]);
      },
      error: function(xhr, message){
        form.trigger('ajax:error', [xhr, message]);
      },
      beforeSend: function(){
        form.trigger('ajax:loading');
      },
      complete: function(){
        form.trigger('ajax:complete')
      }
    });
    return false;
  });
  
  var gmaps_link = "http://maps.google.com/maps";
  
  $('form#create_user').bind('ajax:error', function(){
    $.wizard(1)
  });
  $('form#create_user').bind('ajax:loading', function(){
    $.wizard(2)
  });
  $('form#create_user').bind('ajax:success', function(event, user_name){
    var href = 'http://' + document.location.host + '/' + user_name;
    $('#map_link').attr('href', href);
    $('#gmaps_link').attr('href', gmaps_link);
    var body = "See me on Google Maps: " + gmaps_link + " See me on IAmHere: " + href;
    $('#email_button').attr('href', 'mailto:?subject=I am here&body=' + body);
    $('h1').html('Location found');
    $.wizard(3)
  });
  
  var setCoords = function(){
    if(typeof navigator.geolocation != 'undefined'){
  	  navigator.geolocation.getCurrentPosition(function(position){
        $('#user_latitude').val(position.coords.latitude);
        $('#user_longitude').val(position.coords.longitude);
        gmaps_link += "?q=" + position.coords.latitude + "+" + position.coords.longitude;
    	});
    } else {
      $('#coords').show();
    }
  }
  
  $('#reset_button').live('click', function(){
    setCoords();
    $.wizard(1);
    return false;
  });
  
  $('#step1').bind('wizard:show', function(){
    $('#user_status').val('');
  })
  
  setCoords();
});

