google.load("maps", "2");

// google maps var
var map = null;
// google geocoder
var geocoder = null;
// if set specifies the address that was search for. JSON
var searchAddress = null;
// if set specifies an arrach of centre details results. JSON
var centres = null;
// if set specifies an arrach of location details results. JSON
var locations = null;


/**
 * Initialise the google objects
 */
function initialize() {
  if (GBrowserIsCompatible()) {
    map = new google.maps.Map2($("googleMap"));

    var customUI = map.getDefaultUI();

    // Set default map
    map.setCenter(new GLatLng(54.3630848, -4), 5);

    map.setUI(customUI);


    geocoder = new google.maps.ClientGeocoder();

    if (typeof(printpage) != 'undefined' && printpage) {

      GEvent.addListener(map, "tilesloaded", printPage());
    }
//		geocoder.setBaseCountryCode('uk');
  }
}

function printPage() {
  setTimeout(printNow, 500);
}

function printNow() {
  window.print();
}


/**
 * add a location marker
 * @parame object location google placemark
 */
function addLocationMarker(location) {

  var point = new google.maps.LatLng(location.Point.coordinates[1], location.Point.coordinates[0]);

  var customIcon = new google.maps.Icon(G_DEFAULT_ICON);
  customIcon.image = WEB_ROOT + "images/blue-dot.png";

  var markerOptions = { title: location.address, icon:customIcon };
  marker = new GMarker(point, markerOptions);

  google.maps.Event.addListener(marker, "click", function() {
    var myHTML = '<a href="' + WEB_ROOT + '?lat=' + location.Point.coordinates[1] + '&amp;lng=' + location.Point.coordinates[0] + '&amp;address=' + location.address + '">' + location.address + '</a>';
    map.openInfoWindowHtml(point, myHTML, {maxWidth:'200px'});
  });

  map.addOverlay(marker);
}


function initSearchInput() {

  var defaultValue = "postcode or town/city";

  if (typeof(single) == 'undefined' || !single) {
    $('q').value = defaultValue;
    $('q').setStyle('color', '#aaa');
    $('q').addEvent('focus', function() {
      if ($('q').value == defaultValue) {
        $('q').value = '';
        $('q').setStyle('color', '#000');
      }

    });
  }
}

// NB: This function is converted from PHP in index.php
function isUkCoordinate(latitude, longitude) {
  // These are just estimates
  if (latitude < 59.0 && latitude > 49.5 && longitude > -11.0 && longitude < 2.5) {
    return true;
  }
  return false;
}

/**
 * Initialise everything
 */
window.addEvent('domready', function() {

  initialize();
  initSearchInput();

  var customIcon = new google.maps.Icon(G_DEFAULT_ICON);


  // if centres defined display centre markers
  if (centres) {

    var sumOfDistance = 0
    for (var i = 0; i < centres.length; i++) {
      // change marker icon if gold
      customIcon.image = WEB_ROOT + "images/pink-dot.png";

      if (centres[i].firstclick == '1') {
        customIcon.image = WEB_ROOT + "images/bbc-dot.png";
      }

      /*if (centres[i].springonline == '1') {
       customIcon.image = WEB_ROOT +"images/spring-dot.png";
       } */

      if (centres[i].ukoc == '1') {
        customIcon.image = WEB_ROOT + "images/pink-dot.png";
      }

      if (centres[i].accesspoint == '1') {
        customIcon.image = WEB_ROOT + "images/accesspoint-dot.png";
      }

      if (centres[i].newyear == '1') {
        customIcon.image = WEB_ROOT + "images/newyearmarker.png";
        //customIcon.image = WEB_ROOT +"images/pink-dot.png";
      }


      var markerOptions = { title: centres[i].name, icon:customIcon};
      var point = new google.maps.LatLng(centres[i].Latitude, centres[i].Longitude);
      var marker = new google.maps.Marker(point, markerOptions);
      marker.bindInfoWindow(document.getElementById('markerInfo' + centres[i].client_id));
      map.addOverlay(marker);
      map.setCenter(point, 16);
      sumOfDistance += parseInt(centres[i].distance)
    }

  }

  if (locations) {
    for (var i = 0; i < locations.length; i++) {
      addLocationMarker(locations[i]);
    }
  }


  // if searchAddress defined then set that as centre, and add marker
  if (searchAddress) {
    if (typeof(single) == 'undefined' || !single) // centre map on search term rather than individual centre
      var point = new google.maps.LatLng(searchAddress.latitude, searchAddress.longitude)

    var averageDistance = (sumOfDistance / centres.length);
    if (typeof(single) != 'undefined' && single)
      zoom = 16;
    else
      zoom = 8;

    if (averageDistance < 15)
      zoom = 9;
    if (averageDistance < 10)
      zoom = 10;
    if (averageDistance < 5)
      zoom = 11;
    if (averageDistance < 2)
      zoom = 12;

//		console.log("averageDistance = "+ averageDistance);
//		console.log("zoom = "+zoom);

    map.setCenter(point, zoom);

//		customIcon.image = WEB_ROOT +"images/green-dot.png";
//		var markerOptions = { title: searchAddress.address, icon:customIcon };
//		var marker = new google.maps.Marker(point, markerOptions);
//		map.addOverlay(marker);
  } else {
    var placePoint = new google.maps.LatLng(54.7, -2.5474009);
  }


  if (typeof(single) != 'undefined' && single) {
    map.setCenter(point, 16);
  }

  // add an event to search for submit
  $('searchform').addEvent('submit', function(e) {
    // Prevent the submit event
    new Event(e).stop();

    // remove space from postcode as google isn;t as accurate with a postcode with a space in. NB this also removes spaced from town/city names, but doesn't seem o cause a problem
    var address = $('q').value.replace(/ /g, '') + ", UK";
    var template = $('t').value;
    // console.log(template);
    map.clearOverlays();

    geocoder.getLocations(
        address,
        function(response) {
          var html = '<div class="top"></div>';
          // NB This HTML is repeated on the index.php page, if changed remember to change both!
          switch (response.Status.code) {
            case G_GEO_SUCCESS:
              if (response.Placemark.length == 1) {
                var lat = response.Placemark[0].Point.coordinates[1];
                var lng = response.Placemark[0].Point.coordinates[0];
                if (isUkCoordinate(lat, lng)) {
                  // using timeout here, stop FF from not putting page into history
                  str = 'location.href = WEB_ROOT +"?lat=' + lat + '&lng=' + lng + '&address=' + $('q').value + '&t=' + template + '"';
                  window.setTimeout(str, 10);
                  break;
                }
              } else {
                var buffer = new Array();
                for (var i = 0; i < response.Placemark.length; i++) {
                  var lat = response.Placemark[i].Point.coordinates[1];
                  var lng = response.Placemark[i].Point.coordinates[0];
                  if (isUkCoordinate(lat, lng)) {
                    buffer.push('<li><a href="' + WEB_ROOT + '?lat=' + lat + '&amp;lng=' + lng + '&amp;address=' + response.Placemark[i].address + '">' + response.Placemark[i].address + '</a></li>');
                    addLocationMarker(response.Placemark[i]);
                  }
                }

                if (buffer.length >= 1) {
                  var placePoint = new google.maps.LatLng(54.7, -2.5474009)
                  map.setCenter(placePoint, 5);
                  html += '<p><strong>We have found multiple places that match your search. Did you mean one of the following?</strong></p>'
                  html += '<ul>';
                  html += buffer.join('');
                  html += '</ul>';
                  break;
                }
              }
            // No break is deliberate - we need to fall through if results are not within UK

            case G_GEO_UNKNOWN_ADDRESS :
              html += "<p><strong>Cannot find '" + address + "'</strong></p>";
              break;
            default :
              html = "<p><strong>Error '" + response.Status.code + "'</strong></p>";
              break;
          }

          html += '<div class="bottom"></div>';
          $('searchResults').innerHTML = html
        }
    )
  });


});


jQuery(document).ready(function() {
  // hide all infos

  var slideSpeed = 100;

  jQuery('#centre_search.firstplaces:not(.result) .center_details').click(function() {
    window.location = jQuery(this).children('a.fp_select_centre').attr("href");
    return false;
  });

  // catch real links and load appropriate page
  jQuery('#centre_search .center_details a').not('.showmore,.comments')
      .click(function() {
        window.location = jQuery(this).attr("href");
        return false;
      });

  // hide all the extended infos
  jQuery('.extrainfo').hide();

  // change cursor to pointer when hovering over div to indicate that it is clickable
  jQuery('#centre_search:not(.single, .result) .center_details').css('cursor', 'pointer');
  // add click event to center header to show full center information

  //add hover highlight to each centre div
  jQuery('#centre_search:not(.single, .result) .center_details').hover(
      function() {
        jQuery(this).addClass('hover')
      },
      function() {
        jQuery(this).removeClass('hover')
      });

  //slidedown to reveal extended centre info when clicking div
  jQuery('#centre_search:not(.single, .result) .center_details').click(function() {
    // if already showing full info slide up
    if (jQuery(this).hasClass('selected')) {
      jQuery(this).children('.extrainfo')
          .slideUp(slideSpeed).parent('#centre_search .center_details')
          .removeClass('selected');
      jQuery(this).children('a.showmore').removeClass('up').addClass('down').html('More');
      return false;
    }

    // else slide up any open infos
    jQuery('.selected .extrainfo').slideUp(slideSpeed);
    jQuery('.selected a.showmore.up').removeClass('up').addClass('down').html('More');
    jQuery('#centre_search .center_details').removeClass('selected');

    // slide down clicked center to display full info and add .selected class so we can highlight it
    jQuery(this).addClass('selected').children('.extrainfo').slideDown(slideSpeed);
    jQuery(this).children('a.showmore').removeClass('down').addClass('up').html('Hide');
    return false;
  });


  /*
   * New functions for displaying comments form - JS 09/08/10
   */
//TODO: Maybe set a cookie once they have submitted a comment to stop them doing it again from the same location
  // generate markup
  jQuery(".commentsDiv a").click(function(e) {

    // Get the ID of the commentsDiv that has been opened & get the centre ID from it
    // var divID = this.parentElement.id;
    var divID = jQuery(this).parent().attr('id');
    var centreID = (divID.split("_"))[1];

    // Stop the link doing anything else
    e.preventDefault();

    // Define the various IDs to be used in page
    var cfDivID = "commentsForm_" + centreID;
    var cfFormID = "commentsPostForm_" + centreID;
    var cfTextID = "commentsText_" + centreID;
    var cfSubmitID = "commentsSubmit_" + centreID;
    var cfCloseID = "commentsClose_" + centreID;

    // JQuery selectors for the above
    var cfDivID_select = "#" + cfDivID;
    var cfFormID_select = "#" + cfFormID;
    var cfTextID_select = "#" + cfTextID;
    var cfSubmitID_select = "#" + cfSubmitID;
    var cfCloseID_select = "#" + cfCloseID;

    // Remove from page if already added for this centre
    if (jQuery(cfDivID_select).length > 0) {
      if (jQuery(cfDivID_select + ':hidden').length == 0) {
        jQuery("a").removeClass("tab");
        jQuery(cfDivID_select).slideUp();
      } else {
        jQuery("a").removeClass("tab");
        jQuery('.commentsForm').slideUp();
        jQuery(this).addClass("tab");
        jQuery(cfDivID_select).slideDown();
      }

      // Otherwise remove any other comments div and show the form
    } else {
      // Hide any other visible forms
      jQuery("a").removeClass("tab");
      jQuery('.commentsForm').slideUp();

      // Show the comments form
      jQuery(this).addClass("tab");
      var commentsForm = jQuery('<div class="commentsForm" id="' + cfDivID + '"><form id="' + cfFormID + '"><span>If these details are incorrect please help us by telling us what is wrong:</span><input type="hidden" name="centre_id" value="' + centreID + '" /><textarea id="' + cfTextID + '" name="comments"></textarea><br/><a href="#" id="' + cfSubmitID + '">submit</a></form></div>').hide();
      commentsForm.appendTo(jQuery("#" + divID)).slideDown();
    }

    // Post comments to server
    jQuery(cfSubmitID_select).click(function(e) {
      e.preventDefault();
      // Show error if no message entered
      if (jQuery(cfTextID_select).val() == "") {
        jQuery(cfFormID_select + " span").replaceWith('<span class="warning">Please type your comments in the box below before sending:</span>');
      } else {
        // save data to database
        jQuery.post("savecomments.php", jQuery(cfFormID_select).serialize(), function(data) {
          //alert(data);
          var responseMessage = "Sorry there has been a problem saving your comment. Please try again later.";
          if (data == "success") {
            responseMessage = "Thanks for your comments. We will ensure our records are updated as soon as possible.";
          }
          response = '<div class="commentsForm" id="' + cfDivID + '">' + responseMessage + '<br /><a id="' + cfCloseID + '" href="#">close</a></div>';
          jQuery(cfDivID_select).replaceWith(response);

          // To close the div
          jQuery(cfCloseID_select).click(function(e) {
            e.preventDefault();
            jQuery("a").removeClass("tab");
            jQuery(cfDivID_select).slideUp();
          });
        });
      }
    });

    // stop click triggering parent div click event
    return false;
  });
});




