// On document ready...
$(function(){
  
  $(".member-login form a").fancybox({type: 'iframe',width: 400, height: 200});
  
  $.ajax({
    url: "https://mgauth.heroku.com/availability",
    dataType: "jsonp",
    success: function(data){
      el = $("#mdrivestatus");
      console.log(data);
      if(!data){
        el.text("DOWN").css('color','red');
      } else {
        el.text("UP").css('color','green');
      }
    }
  });
  
  // YouTube tour video
  // Retrieve our tour button
  var tourButton = $('a.tour');
  // Get our youtube video url based on button href
  var youtubeURL = tourButton.attr('href').replace('/watch?v=','/v/');
  // Update our tour button href
  tourButton.attr('href',youtubeURL);
  // Initialize fancybox on tour button link
  tourButton.fancybox({
    // Do not show the title
    'titleShow'     : false,
    // Transition fancybox in with fancy elastic animation
    'transitionIn'  : 'elastic',
    // Transition fancybox out with fancy elastic animation
    'transitionOut' : 'elastic',
    // Set our type to SWF as youtube player is flash
    'type'          : 'swf',
    // Set some safety requirements to make sure our flash player shows correctly
    'swf'           : {'wmode':'transparent','allowfullscreen':'true'}
  });
  
  
  // Free trial form and submission
  var startNowButton = $('.startnow');
  // Initialize fancybox on our start now button
  startNowButton.fancybox({
    // We do not want your fancybox to include scrolling
    'scrolling'       : 'no',
    // Auto size our fancybox to include all content
    'autoDimensions'  : true,
    // Disable padding as we are adding this ourselves
    'padding'         : 0,
    // Auto scale our fancybox to include all content
    'autoScale'       : true,
    // We are using inline content so be sure to specify the type of content
    'type'            : 'inline',
    // Catch our fancybox complete event, this occurs when all content is displayed correctly
    'onComplete'      : showingFreeTrialForm
  });
  
  // Get the add m:drive to cart button
  var cartButton = $('#add_to_cart_39');
  // Change the href to point to our inline terms and conditions div
  cartButton.attr('href','#termsconditions');
  // Finally, initialize fancybox
  cartButton.fancybox({
    // We do not want your fancybox to include scrolling
    'scrolling'       : 'no',
    // Auto size our fancybox to include all content
    'autoDimensions'  : true,
    // Disable padding as we are adding this ourselves
    'padding'         : 0,
    // Auto scale our fancybox to include all content
    'autoScale'       : true,
    // We are using inline content so be sure to specify the type of content
    'type'            : 'inline',
    // Catch our fancybox complete event, this occurs when all content is displayed correctly
    onComplete: showingTermsAndConditions
  });
  
  // Retrieve both our news and software updates content from old website and display on page
  var host = window.location.hostname;
  // We are only able to do this if we are on the same domain. Check for this first...
  if(host == 'www.agrimaster.com.au') {
    // Get our news and populate the box on this page
    $("#newsdl").load("http://www.agrimaster.com.au/pages/support #news-updates");
    // Get our software updated and populate the box on this page
    $("#software_updates").load("http://www.agrimaster.com.au/pages/support #software-updates");
  } else {
    // If we are not on the same domain then we will hide the relevant boxes
    $('#newsdl').closest('li').remove();
    $('#software_updates').closest('div').remove();
  }
  
  // Get our testimonials listing and cycle between each of them
  $(".testimonials ul").cycle({
    // Before changing testimonial we need to change the height of the container
    before: beforeChangingTestimonial,
    // Make testimonials appear randomly
    random: 1,
    // Testimonials show for 8 seconds before changing
    timeout: 8000
  });
  
  // Get our farm tested element and cycle images with default options
  $('ul.farmtested').cycle();
});

showingFreeTrialForm = function(event) {
  // Assign variables for our most common items
  var fancybox        = $('#fancybox-content'),
      form            = fancybox.find('form'),
      tradingName     = form.find('#tradingname'),
      enterprise      = form.find('#typeofenterprise'),
      otherEnterprise = form.find('#typeofenterpriseother');
  
  // Apply some simple styling. Not sure why this was previously done in javascript but not willing to change
  otherEnterprise.css('margin-left','153px');
  
  // Method for showing our other enterprise input
  showOtherEnterprise = function() {
    otherEnterprise.show();
    enterprise.val('other');
  }
    
    // Method for resetting our other enterprise input
    resetOtherEnterprise = function() {
      otherEnterprise.hide();
      enterprise.val('');
    };
  
  // Reset our other enterprise select field each time fancybox is displayed
  resetOtherEnterprise();
  
  // When enterprise is changed check if 'changed' option was selected
  enterprise.change(function(){
    // Check what has been selected for our enterprise select field
    if(enterprise.val() == 'Other') {
      // If other has been selected...
      showOtherEnterprise();
    } else {
      // If any other option has been selected then make sure our other enterprise input is hidden
      otherEnterprise.hide();
    }
  });
  
  // When free trial form is submitted...
  form.submit(function(event){
    // Prevent the default action of a form
    event.preventDefault();
    // Check that a trading name has been provided
    if(tradingName.val() == '') {
      // If it is blank, then inform the user we require a trading name
      window.alert('Trading name can not be blank.');
    } else {
      // If a trading name has been provided we can submit the form correctly.
      sendFreeTrial(form);
    }
  });
};

sendFreeTrial = function(form) {
  // Make an an AJAX request
  $.ajax({
    // Make a post request to the form action provided
    url  : form.attr('action'),
    // Serialize our data to send to our page
    data : form.serializeArray(),
    // Make sure our request is sent as a POST request
    type : 'post',
    // On success...
    success: function(data) {
      // If there are no errors returned...
      if(data.errors == null) {
        // Set our form to display a message
        $('#trialform').html('<h2 style="font-size: 1.4em; font-weight: bold; margin-bottom: 0.5em;color: #2e390f;">Thankyou</h2><p style="font-size: 1.2em; line-height: 1.6em;">Your free trial submission has been entered. We will be in touch soon. Redirecting you now...</p>');
        // Close our fancybox 2 seconds after message is displayed
        setTimeout($.fancybox.close, 2000);
      }
    }
  });
}
  
  beforeChangingTestimonial = function(currSlideElement, nextSlideElement, options, forwardFlag) {
    // Get the next testimonial to be shown and our full testimonial listing
    var el = $(nextSlideElement), ul = $(".testimonials ul");
    // Change the height of our testimonial listing to accomodate testimonial text
    ul.animate({height: el.height()});  
  };

showingTermsAndConditions = function(event) {  
  // Get current available form elements
  var button      = $('#add_to_cart_39'),
      form        = button.closest('form'),
      variant     = form.find('#line_item_item_id').val();
  
  // Get target form and relevant elements
  var fancybox     = $('#fancybox-content'),
      targetForm   = $('#termsconditions-form'),
      targetInput  = targetForm.find('#item_id');
  
  // Transfer our previously selected variant across to the new terms and conditions fancybox form
  targetInput.val(variant);
  
  // Hook into target form submit action to check that all terms and conditions are accepted
  targetForm.submit(function(event){
    // Get the form that is being submitted and number of checked terms and condition statements
    var form                       = $(event.currentTarget),
        acceptedTermsAndConditions = form.find('input:checked').length;
    
    // Check if all terms and conditions have been accepted.
    if(acceptedTermsAndConditions == 5) {
      // They have accepted all the terms and conditions. Submit the form
      return true;
    } else {
      // Let the user know that they need to accept all terms and conditions using an obnoxious window.alert
      window.alert('You must agree to all terms and conditions');
      // Return false so we do not follow the form action
      return false;
    }
  });
};
