/**
 * Javascript interactions for the register page
 **/

var map; // this contains our GoogleMap instance

/**
 * Augment the GoogleMap class in home.js with some registration specific stuffs
 **/
var GoogleMapRegister = new Class({
  Implements:     GoogleMap,
  
  // Fetches lat/lng coords from Google (via our responder.php) for a place/postcode
  geocode:         function (term)
  {
    r = new Request.JSON({
      'url':      RESPONDER,
      'link':     'cancel',
      onSuccess:  function (response)
      {
        if($defined(response.error) && response.error)
        {
          if(!this.errored)
          {
            this.errored = true;
            error = new Element('p',
              {
                'html':     "Whoops, I can't find that address. Make sure your postcode has a space between the first and last part, and if that still doesn't work, just try putting in the name of your road and the town you live in.",
                'id':       'error-message'
              }
            );
        
            error = error.inject(this.container,'before');
          }
          error.highlight('#F91C01','#000');

          return false;
        }

        if($('error-message'))
        {
          $('error-message').dispose();
        }
        
        this.errored  = false;

        // cLat means centre latitude, meaning we're dealing with bounds not
        // an individual point (generally means a place search)
        if($defined(response.cLat))
        {
          bounds = new GLatLngBounds(
              new GLatLng(response.swLat,response.swLng),
              new GLatLng(response.neLat,response.neLng)
          );

          zoomLevel = this.map.getBoundsZoomLevel(bounds);
          zoomLevel = zoomLevel > 11 ? 11 : zoomLevel;

          point = new GLatLng(response.cLat,response.cLng);
        }
        // No cLat means we just have a single point to plot
        else
        {
          point = new GLatLng(response.latitude,response.longitude);
          zoomLevel = 11;
        }
        
        this.addDraggableMarker(point,zoomLevel);
      }.bind(this)
    }).get({
        'action':       'searchByTown',
        'term':         term
    });
  },
  
  /**
   * Add a draggable marker (duh)
   **/
  addDraggableMarker: function (point,zoomLevel)
  {
    // Get rid of any existing markers and set the zoom to 11 by default
    this.map.clearOverlays();
    if(!zoomLevel)
    {
      zoomLevel = 11;
    }
    
    var marker  = new GMarker(point, {draggable: true});

    // Update the form fields when dragging stops
    GEvent.addListener(marker, 'dragend', function ()
    {
      this.setPoint(marker.getPoint());
      // this.map.panTo(marker.getPoint());
    }.bind(this));

    this.map.addOverlay(marker);
    this.map.setCenter(point,zoomLevel);
    this.setPoint(point);
  },
  
  // Update the (hidden) lat/lng fields with the data in `point'
  setPoint:           function (point)
  {
    $('field_latitude').set('value',point.lat());
    $('field_longitude').set('value',point.lng());
  },
  
  // The inverse of the above: set the marker at the point in the lat/lng
  // hidden fields
  setFromForm:        function ()
  {
    if($('field_latitude').get('value').length)
    {
      point = new GLatLng(
        $('field_latitude').get('value'),
        $('field_longitude').get('value')
      );
      this.addDraggableMarker(point);
    }
  }
});

window.addEvents({
  'domready': function ()
  {
    // Set up the map
    map = new GoogleMapRegister('google-map');
    map.setFromForm();
    
    // Bind a click event to the link next to the Location field
    // so the map's location can be altered
    $('search-map').addEvent('click',
      function (ev)
      {
        ev.preventDefault();
        map.geocode($('field_location').value);
      }
    );
    
    /**
     * Show and hide the different elements of the form
     **/
    $$('.kinds input').each(
      function (i)
      {
        i.addEvent('click',
          function ()
          {
            if(this.id == 'field_kind_seller')
            {
              $('seller-fields').reveal();
              $('host-fields').setStyle('display','none');
              $('diner-fields').setStyle('display','none');
            }
            if(this.id == 'field_kind_host')
            {
              $('host-fields').reveal();
              $('diner-fields').setStyle('display','none');
              $('seller-fields').setStyle('display','none');
            }
            if(this.id == 'field_kind_diner')
            {
              $('diner-fields').reveal();
              $('host-fields').setStyle('display','none');
              $('seller-fields').setStyle('display','none');
            }
          }.bind(i)
        );
        if(i.checked)
        {
          i.fireEvent('click');
        }
      }
    );

  },
  'load':     function ()
  {
    // Set up the Facebook connect stuffs
    FB_RequireFeatures(['XFBML','Api'], function()
    {
      FB.Facebook.init(FB_API_KEY, "/xd_receiver.htm",{ "reloadIfSessionStateChanged": false, "doNotUseCachedConnectState":true });
      FB.Facebook.get_sessionState().waitUntilReady(
        function() {
          FB.ensureInit ( function () {
            FB.Connect.ifUserConnected(fb_login);
          });
        }
      );
    });
    
    // Default options for the Mootools form hints
    overTextOpts = {
      'positionOptions':  {
        'offset':           {
          y:                  5
        }
      }
    };
    
    // Tweak the position of the location/name fields so they line up
    offset = $('field_location').getParent('dd').getPosition($('field_name').getParent('dd')).y;
    offset = offset * -1;
    if(offset !== 0)
    {
      $('field_location').getParent('dd').getPrevious('dt').setStyle('margin-top',offset);
    }

    new OverText($('field_name'),overTextOpts);
    new OverText($('field_location'),overTextOpts);
  }
});

// Update the form fields with data from Facebook connect, called by fb_login in global.js
var updateForm = function (uid)
{
  if($('facebook-connect-button'))
  {
    $('facebook-connect-button').destroy();
  }
  FB.ensureInit ( function () {
    
    FB.Facebook.apiClient.users_getInfo(
      uid,
      ['first_name','last_name','hometown_location','current_location','website','about_me'],
      function (d)
      {
        if(!$('field_dinerProfile').get('value').length)
        {
          $('field_dinerProfile').set('value',d[0].about_me);
        }
        if(!$('field_name').get('value').length)
        {
          $('field_name').set('value',d[0].first_name+' '+d[0].last_name);
        }
        if(!$('field_location').get('value').length)
        {
          if($defined(d[0].current_location) && $chk(d[0].current_location.city))
          {
            $('field_location').set('value',d[0].current_location.city);
            map.geocode(d[0].current_location.city);
          }
          else if($defined(d[0].hometown_location) && $chk(d[0].hometown_location.city))
          {
            $('field_location').set('value',d[0].hometown_location.city);
            map.geocode(d[0].hometown_location.city);
          }
        }
        if(!$('field_website').get('value').length && d[0].website)
        {
          $('field_website').set('value',d[0].website);
        }
        $('field_fbUid').set('value',uid);
        $('field_name').retrieve('OverText').reposition();
        $('field_location').retrieve('OverText').reposition();
      }
    );
  });
};