$(document).ready(function() {  

  if ($('form#start-booking-form').length) {
    $('form#start-booking-form').validationEngine();
  }
  
  if ($('form#booking-form').length) {
    $('form#booking-form').validationEngine();
  }  

  if ($('form#contact-form').length) {
    $('form#contact-form').validationEngine();
  } 
  
  // Grabs latest tweets via Google Feed
  if ($('div#twitter-feed').length) {
    $.jGFeed('http://twitter.com/statuses/user_timeline/cab4one.rss', function(feeds) {
      if(!feeds){
        return false;
      }
      for(var i = 0; i < feeds.entries.length; i++){
        entry = feeds.entries[i];
        $('div#twitter-feed div.body ul').append('<li><span>' + entry.title + '</span><a href="' + entry.link + '" target="_blank">' + jQuery.timeago(new Date(entry.publishedDate)) + '</a></li>')
      }
    }, 2);
  }  
    
  // Grabs latest blog posts via Google Feed
  if ($('div#blog-latest').length) {
    $.jGFeed('http://cab4one.wordpress.com/feed/', function(feeds) {
      if(!feeds){
        return false;
      }
      for(var i = 0; i < feeds.entries.length; i++){
        entry = feeds.entries[i];
        $('div#blog-latest div.body').append('<div class="blog-post"><p><strong><a href="' + entry.link + '" target="_blank">' + entry.title + '</a></strong></p><p style="margin:8px 0;"><em>' + entry.contentSnippet + '</em></p><p><strong style="float:left;width:165px;">Posted by: ' + entry.author + '</strong><a href="' + entry.link + '" style="float:right;text-align:right;width:85px;" target="_blank">Read more...</a></p><div class="clearfix"></div>')
      }
    }, 2);
  }

  // Adds fancybox to classed links
  if($('a.fancybox').length) {
    $('a.fancybox').fancybox({
      'hideOnContentClick': false
    });
  }

  // Adds date picker to booking form
  if($('input#booking-date').length) {
    $('input#booking-date').datepicker({
      dateFormat: 'DD, d MM yy',
      minDate: new Date
    });
  }
  
  // Adds submit functionality to booking form button
  if($('a#btn-lets-go').length) {
    $('a#btn-lets-go').click(function(){
      $('form#start-booking-form').submit();
      return false;
    });
  }
  
  // Adds submit functionality to booking page form button
  if($('a#btn-book').length) {
    $('a#btn-book').click(function(){
      $('form#booking-form').submit();
      return false;      
    });
  }  
  
  // Adds submit functionality to contact form button
  if($('a#btn-send').length) {
    $('a#btn-send').click(function(){
      $('form#contact-form').submit();
      return false;
    });
  }  
  
  // Adds tooltip effect to booking 'from' field
  if($('a#btn-lets-go').length) {
    $('input#booking-from').snapForm();  
  }

  // Adds tooltip effect to booking 'to' field
  if($('a#btn-lets-go').length) {
    $('input#booking-to').snapForm();
  }
  
  // Adds tooltip effect to booking 'to' field
  if($('a#btn-book').length) {
    $('input#booking-from-detail').snapForm();
    $('input#booking-to-detail').snapForm();
  }

  // Changes value of textbox depending on select value, showing textbox as appropriate
  if($('select#booking-from-select').length) {
    $('select#booking-from-select').change(function(){
      if ($('select#booking-from-select').val() === 'choose') {
        $('input#booking-from').val('Full Address & Postcode');
      } else if ($('select#booking-from-select').val() === 'other') {
        $('input#booking-from').val('Full Address & Postcode');
        $('select#booking-from-select').hide();
        $('input#booking-from').fadeIn('quick');
      } else {    
        $('input#booking-from').val($('select#booking-from-select').val());
      }
    });
  }  
  
  if($('select#booking-to-select').length) {
    $('select#booking-to-select').change(function(){
      if ($('select#booking-to-select').val() === 'choose') {
        $('input#booking-to').val('Full Address & Postcode');
      } else if ($('select#booking-to-select').val() === 'other') {
        $('input#booking-to').val('Full Address & Postcode');
        $('select#booking-to-select').hide();
        $('input#booking-to').fadeIn('quick');
      } else {    
        $('input#booking-to').val($('select#booking-to-select').val());
      }
    });
  }
  
  // Used for displaying the map on the booking page and calculating the distance
  if ($('a#calculate-cost').length > 0) {
    var latlng = new google.maps.LatLng(51.90361280788357, 0.19466400146484375);
    var map = new google.maps.Map(document.getElementById("map-canvas"), {
      zoom: 10, 
      center: latlng, 
      mapTypeId: google.maps.MapTypeId.ROADMAP
    });
  
    var directionsService = new google.maps.DirectionsService();
    var directionsDisplay = new google.maps.DirectionsRenderer();  
    directionsDisplay.setMap(map);
    
    var geocoder = new google.maps.Geocoder();         
    
    google.maps.event.addListener(directionsDisplay, 'directions_changed', function() {
      var totalMiles = calculateTotalDistance(directionsDisplay.directions);
      var costPerMile;
      
      if ($('select#booking-passengers').val() > 1) {
        // Multi-person pricing
        if (totalMiles > 88) {
          costPerMile = 1.20;     
       } else if (totalMiles > 60) {
          costPerMile = 1.25;     
       } else if (totalMiles > 50) {
          costPerMile = 1.30;     
        } else if (totalMiles > 40) {
          costPerMile = 1.35;                       
        } else if (totalMiles > 29.9) {
          costPerMile = 1.40;      
        } else if (totalMiles > 20) {
          costPerMile = 1.50;      
        } else if (totalMiles > 12.5) {
          costPerMile = 2;            
        } else if (totalMiles > 7.5) {
          costPerMile = 2.3;            
        } else if (totalMiles > 3) {
          costPerMile = 2.80;            
        } else if (totalMiles > 2.5) {
          costPerMile = 3.40;            
        } else {
          costPerMile = 5.70;      
        }
      } else {
        // Single-person pricing
        if (totalMiles > 75) {
          costPerMile = 1.18;      
        } else if (totalMiles > 75) {
          costPerMile = 1.20;     
        } else if (totalMiles > 50) {
          costPerMile = 1.22;
       } else if (totalMiles > 40) {
          costPerMile = 1.23;      
        } else if (totalMiles > 30) {
          costPerMile = 1.22;      
        } else if (totalMiles > 20) {
          costPerMile = 1.25;      
        } else if (totalMiles > 12.5) {
          costPerMile = 1.35;            
        } else if (totalMiles > 7.5) {
          costPerMile = 1.50;            
        } else if (totalMiles > 3) {
          costPerMile = 2.5;            
        } else if (totalMiles > 2.5) {
          costPerMile = 2.6;            
        } else {
          costPerMile = 5;      
        }
      }
        
      var totalCost = totalMiles * costPerMile;
      
      if (($('select#booking-time-hours').val() < 6) || ($('select#booking-time-hours').val() === '23')) {
        totalCost = (totalCost * 1).toFixed(2);
      } else {
        totalCost = totalCost.toFixed(2);
      }
      
      
      
      // Output origin
      geocoder.geocode({'address': $('input#booking-from').val() + ', uk'}, function(results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
          if (results[0]) {
            $('span#origin').empty();
            $('span#origin').append(results[0].formatted_address);
          }
        }
      });      
      
      // Output destination
      geocoder.geocode({'address': $('input#booking-to').val() + ', uk'}, function(results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
          if (results[0]) {
            $('span#destination').empty();
            $('span#destination').append(results[0].formatted_address);
          }
        }
      });       
      
      // Output journey summary
      $('span#collection-time').empty();
      $('span#collection-time').append($('select#booking-time-hours').val() + ':' + $('select#booking-time-minutes').val() + ' on ' + $('input#booking-date').val());
      $('span#distance').empty();
      $('span#distance').append(totalMiles);      
      $('span#total-cost').empty();
      $('span#total-cost').append(totalCost);
      $('input#quoted-price').val('&pound;' + $('span#total-cost').text());
      // Show summary
      $('div#journey-summary div.body p#instructions').hide();
      $('div#journey-summary div.body fieldset').show();
      $('div#journey-summary div.body p#terms').show();      
      $('div#journey-summary div.body').css('height', 'auto');
      $('div#journey-summary div.body').animate({
        'min-height': '220px'
      }, 300);

    });
    
    setTimeout(function() {
      var from = $('input#booking-from').val() + ', uk';
      var to = $('input#booking-to').val() + ', uk';
      displayRouteBetween(from, to);
    }, 1500);
    
    $('a#calculate-cost').click(function(){
      var from = $('input#booking-from').val() + ', uk';
      var to = $('input#booking-to').val() + ', uk';
      displayRouteBetween(from, to);
      return false;
    });
    
    // Hides the journey summary if either the origin or destination change
    $('input#booking-from').keydown(function() {
      hideJourneySummary();
    });
    
    $('input#booking-to').keydown(function() {
      hideJourneySummary();
    });    
    
    $('select#booking-time-hours').change(function() {
      hideJourneySummary();
    });
    
    $('select#booking-time-minutes').change(function() {
      hideJourneySummary();
    });   
    
    $('select#booking-passengers').change(function() {
      hideJourneySummary();
    });
    
    $('select#booking-bags').change(function() {
      hideJourneySummary();
    });     
    
    // Hides the journey summary box
    function hideJourneySummary() {
      $('div#journey-summary div.body p#instructions').show();
      $('div#journey-summary div.body fieldset').hide();
      $('div#journey-summary div.body p#terms').hide();  
      $('div#journey-summary div.body').css('height', '30px');
      $('div#journey-summary div.body').animate({
        'min-height': '0'
      }, 300);
    }
    
    // Alters the route displayed on the Google map
    function displayRouteBetween(from, to) {
      var request = {
        origin:from, 
        destination:to,
        travelMode: google.maps.DirectionsTravelMode.DRIVING,
        unitSystem: google.maps.UnitSystem.IMPERIAL
      };
      directionsService.route(request, function(response, status) {
        if (status == google.maps.DirectionsStatus.OK) {
          directionsDisplay.setDirections(response);
        }
      });
    }
    
    // Calculates the total distance between the points shown on the map
    function calculateTotalDistance(result) {
      var total = 0;
      var chosenRoute = result.routes[0];
      for (i = 0; i < chosenRoute.legs.length; i++) {
        total += chosenRoute.legs[i].distance.value;
      }
      total = Math.round(total * 0.00062137119223733390);
      return total;
    }
  }
  
  function roundNumber(num, dec) {
    var result = Math.round(num*Math.pow(10,dec))/Math.pow(10,dec);
    return result;
  }
  
});

