
google.load("maps", "2.x");

$(document).ready(function () {
 
  var directions = new Directions();
 
  /* Add ON CLICK event to form button */
  $('#getDirections_form').submit(function() {
  
    // Check there's anything in the address field
    var address = $('input#directionsAddress').val();
    
    /* Smile Artistry address */
    var destination = '31 Sherwood Road Toowong Queensland Australia';
      
    if (address.length > 0) {
      directions.getDirections(address, destination);
    }    
    
    return false;
    
  });
  
  
});

function Directions() {

  this.directions = null;
  this.dirOpen = false;
  
  this.mapLink = $('#getDirections_map').attr('href');
  
  this.getDirections = function(address, destination) {  
    
    object = this;
    
    if (this.directions != null) {
      this.directions.clear();
    }
    
    // Get directions 
    directionsPanel = $('#directionsPanel')[0];
    this.directions = new GDirections('', directionsPanel);
    this.directions.load("from: "+address+" to: "+destination);
      
    // Once the directions are loaded...
    GEvent.addListener(this.directions, "load", function() {
      object.displayDirections();
      
      // Set up "View map" button
      var mapLink = $('#getDirections_map');
      var mapVars = $(mapLink).attr('href',object.mapLink+'?address='+address+'&iframe=true&height=570&width=700');
      $(mapLink).show().css('display','block');
    }); 

  };
  
  this.displayDirections = function() {
  
    object = this;
  
    if (this.dirOpen == false) {
      this.openPanel();
    }
    
    // Set up close/open button
    $('#getDirections_close').show().css('display','block');
    
    $('#getDirections_close').click(function() {
        
        if (object.dirOpen == true) {
        
          object.closePanel();
          
          return false;
          
        } else if (object.dirOpen == false) {
        
          object.openPanel();
          
          return false;
        
        }
      });
  };
  
  this.openPanel = function() {
    object = this;
    
    $(directionsPanel).slideDown('normal', function() {
       $('#getDirections_close').text('[ Close Directions ]');
       object.dirOpen = true;
    });
  };
  
  this.closePanel = function() {
    object = this;
    
    $(directionsPanel).slideUp('normal', function() {
       $('#getDirections_close').text('[ Open Directions ]');
       object.dirOpen = false;
    });
  };
}
