﻿$(document).ready(function() {

  var gmap;
  var infoWindow;
  var stores = [];
  var $map = $('#map');
  var $stores = $('#stores');
  var $storeInfo = $('#storeInfo');

  // load stores
  $.each(areas, function(i, area) {
    $('<h3></h3>').html(area.Name).addClass('header').appendTo($stores);
    $('<div></div>').attr('id', area.Ref).appendTo($stores);
    $.each(area.Stores, function(i, store) {
      stores.push(store);
      $('<p></p>').html(store.Name).appendTo('#' + area.Ref).click(function(e) {
        gmap.panTo(new google.maps.LatLng(store.Latitude, store.Longitude));
        gmap.setZoom(14);
        $storeInfo.html(store.Info);
      });
    });
  });

  // initialize accordion
  $stores.accordion({
    animated: true,
    autoHeight: false,
    collapsible: true, 
    active: false
  });

  if (initPostcode) {
    new google.maps.Geocoder().geocode({ address: initPostcode + ', UK' }, initialiseMap);
  }
  else {
    initialiseMap();
  }

  // initialize map
  function initialiseMap(results, status) {

    var initZoom = 6;
    var initLatlng = new google.maps.LatLng(54.033586, -4.394531); // (uk)
    if (status == google.maps.GeocoderStatus.OK) {
      initLatlng = results[0].geometry.location;
      initZoom = 8;
    }

    var initOptions = {
      zoom: initZoom,
      center: initLatlng,
      mapTypeId: google.maps.MapTypeId.ROADMAP,
      navigationControl: true,
      disableDefaultUI: true
    }
    gmap = new google.maps.Map($map.get(0), initOptions);

    // initialize map info window
    infoWindow = new google.maps.InfoWindow({});

    // initialize map markers
    $.each(stores, function(i, store) {

      var marker = new google.maps.Marker({
        map: gmap,
        position: new google.maps.LatLng(store.Latitude, store.Longitude),
        title: store.Name
      });

      google.maps.event.addListener(marker, 'click', function() {
        displayMarkerInfo(i);
      });

      function displayMarkerInfo(index) {
        var infoText = store.Url ?
        '<div id="bubble">' + store.Address + '<a href="' + store.Url + '" target="_blank">' + store.Url + '</a></div>' :
        '<div id="bubble">' + store.Address + '</div>';
        infoWindow.setContent(infoText);
        infoWindow.open(gmap, marker);
        gmap.panTo(marker.getPosition());
        $storeInfo.html(store.Info);
      }

    });
  }

});
