var city_map, geocoder;

$(document).ready(function()
{
  setupFooterInfo();
  tabs();
  setupAutoComplete();
  setupWorldMap();
  try
  {
    gpCreateMap(map); // passed from info template
  }
  catch(e) {}


  // Report an issue button - opens the issue page in an fancybox IFRAME.
  $('div.issue-button a').each(function()
  {
    var $this = $(this);
    $this.attr('href', $this.attr('href') + '/iframe');
  }).fancybox({
		fitToView:    false,
		width:        600,
		height:       400,
		autoSize:     false,
		closeClick:   true,
		openEffect:   'none',
		closeEffect:  'none'
  });


  $.fn.qtip.styles.govform = { // Last part is the name of the style
    width: 400,
    background: '#60606F',
    border: { width: 0 },
    color: '#FFF',
    padding: 10,
    tip: { corner: 'leftMiddle', color: '#60606F' },
  }

  $('span.tooltip').each(function()
  {
    var $this = $(this);
    $this.qtip({
      content: { text: $this.next('.tip') },
      position: { corner: { target: 'rightMiddle', tooltip: 'leftMiddle' }, adjust: { x: 15 }},
      style: 'govform'
    });
  });

});


function setupFooterInfo()
{
  var $footer = $('footer');
  $('div.copyright a.more', $footer).bind('click', function()
  {
    record_action('footer_more');
    var $div = $('div.more', $footer);
    $div.toggle();
    $(this).html($div.is(':visible') ? 'close' : 'more...');
  });
}

function setupAutoComplete()
{
  // "Search term" autocomplete field.
  $search_field = $('#search-term');
  $('#search-form').bind('submit', function()
  {
    if ($search_field.val() = '')
    {
      alert('Please enter a search term.');
      return false;
    }
  });
  if ($search_field.length)
  {
    $search_field.autocomplete(
    {
      serviceUrl:     'home/search_complete',
      minChars:       3,
      maxHeight:      120,
      deferRequestBy: 200, //miliseconds
      onSelect:       function(value, data)
      {
        // Jump to the relevant info page.
        window.location = 'world/' + data.replace("%7C","/");
      },
    });
  }
}

function gpCreateMap(map_json)
{
  if (!map_json)
  {
    return;
  }

  city_map  = new GMap2(document.getElementById("map"));

  // Set the Google Maps UI.
  var customUI = city_map.getDefaultUI();
  customUI.controls.scalecontrol = false;
  //customUI.controls.overviewmapcontrol = true;
  customUI.maptypes.hybrid = false;
  customUI.maptypes.physical = false;
  customUI.zoom.doubleclick = false;
  city_map.setUI(customUI);

  geocoder  = new GClientGeocoder();

  try
  {
    if (map.lat == 'ERROR' || map.lat == undefined)
    {
      throw('error');
    }
    // Mark an existing point on the map.
    var marker_point = new GLatLng(map.lat, map.lng);
    _mark_point(map.id, marker_point, map_json.type);
  }
  catch(err)
  {
    // Find the latitude and longitude of our address (city and country).
    // The reason we put this in a catch is to handle unknown coordinates as well as previous failed
    // attempts.
    geocoder.getLatLng(map.query, function(point) {
      _mark_point(map.id, point, map_json.type);
    });
  }
}

function _mark_point(city_id, point, type)
{
  if (!point)
  {
    // For whatever reason we do not have the point on the main map - so mark it as an
    // "error".
    alert('Could not locate this '+type+'.');
    if (type == 'city')
    {
      $.post('/random/update_coords', { id: city_id, latitude: 'ERROR', longitude: 'ERROR' });
    }
  }
  else
  {
    // Mark the point on the map using a custom pointer.
    var baseIcon = new GIcon(G_DEFAULT_ICON);

    var gpIcon = new GIcon(baseIcon);
    gpIcon.image = "/images/geo_marker.png";
    gpIcon.iconSize = new GSize(30, 38);
    gpIcon.iconAnchor = new GPoint(15, 37);
    gpIcon.shadow = "/images/geo_marker_shadow.png";
    gpIcon.shadowSize = new GSize(38, 38);

    markerOptions = { icon: gpIcon };
    var marker = new GMarker(point, markerOptions);

    var zoom = (type == 'city') ? 10 : 5;

    city_map.setCenter(point, zoom);
    city_map.addOverlay(marker);

    if (type == 'city')
    {
      $.post('/random/update_coords',{ id: city_id, latitude: point.lat(), longitude: point.lng() });
    }
  }
}

function tabs()
{
  $('div.tabs').each(function() {
    var $element = $(this);
    var $tabs = $element.children('ul:first');
    var $content = $element.children('div.tab');

    $content.not(':first').hide();
    $('a', $tabs).bind('click', function() {
      $content.hide();
      var id = $(this).attr('href');
      $(id).show();
      return false;
    })
  });
}


function record_action(action_id, param1, param2, param3)
{
  var url = '/action/'+action_id;
  if (param1) $url += '/' + param1;
  if (param2) $url += '/' + param2;
  if (param3) $url += '/' + param3;
  $.get(url);
}


// Google Analytics tracking.
function track(category, action, value)
{
  try
  {
    _gaq.push(['_trackEvent', category, action, value]);
  }
  catch (e)
  {}
}



function setupWorldMap()
{
  var $parent = $('#world');
  if (!$parent) { return; }

  // Hide the lists of continents and countries.
  $('#continents').hide();

  $parent.prepend('<div id="world-map" />');
  $map = $('#world-map', $parent);

  $map.append('<span class="north-america" href="#north-america" />');
  $map.append('<span class="south-america" href="#south-america" />');
  $map.append('<span class="europe" href="#europe" />');
  $map.append('<span class="asia" href="#asia" />');
  $map.append('<span class="africa" href="#africa" />');
  $map.append('<span class="oceania" href="#oceania" />');

  $('#world-map-caption').hover(function() { return false; }, function() { return false; });

  $('span', $map).fancybox({
    autoSize: false,
    height: 360,
    width: 700,
    wrapCSS: 'continents-box',
    closeSpeed: 'fast'
  });

  $('span', $map).hover(
    function()
    {
      var $this = $(this);
      $map.addClass($this.attr('class'));
    },
    function()
    {
      var $this = $(this);
      $map.removeClass($this.attr('class'));
    }
  );
}



