jQuery.expr[':'].regex = function(elem, index, match) {
    var matchParams = match[3].split(','),
        validLabels = /^(data|css):/,
        attr = {
            method: matchParams[0].match(validLabels) ?
                        matchParams[0].split(':')[0] : 'attr',
            property: matchParams.shift().replace(validLabels,'')
        },
        regexFlags = 'ig',
        regex = new RegExp(matchParams.join('').replace(/^\s+|\s+$/g,''), regexFlags);
    return regex.test(jQuery(elem)[attr.method](attr.property));
}

$(function() {
  var form_step = $('.multipage-steps li.active').prevAll('li').length + 1;
  var form_type = window.location.pathname.replace(/^\/shipping\//, '').replace(/\/quote.*$/, '');

  switch (form_step) {

    case 1:
      var check = function() {
        var from_port = $('#form_from_port').val();
        var from_country = from_port == 'Other...' ? $('#form_other_from_country').val() : from_port.replace(/ -.*$/, '');
        var to_port = $('#form_to_port').val();
        var to_country = to_port == 'Other...' ? $('#form_other_to_country').val() : to_port.replace(/ -.*$/, '');

        //$('.form-popup').hide();
        $('.form-popup').remove();

        show_popup(
          (from_port == "Other..."),
          'shipping_from',
          'Use one of the provided ports to get an instant online quote.'
        );

        show_popup(
          (to_port == "Other..."),
          'shipping_to',
          'Use one of the provided ports to get an instant online quote.'
        );

        show_popup(
          (
            from_country == to_country ||
            (from_country == 'USA' && to_country == 'United States') ||
            (to_country == 'USA' && from_country == 'United States')
          ),
          to_port == 'Other...' ? 'other_to_country' : 'to_port',
          'Sorry, we only handle international shipping.'
        );
      };
      $('select').change(check);
      check();
      break;

    case 2:
      switch (form_type) {

        case 'car':
          var check = function() {
            var to_port = $('#form_to_port').val();
            var to_country = to_port == 'Other...' ? $('#form_other_to_country').val() : to_port.replace(/ -.*$/, '');
            if (to_country == 'Australia') {
              show_popup(
                $('#form_owned_12_months_no:checked').length && $('#form_manufactured_before_1989_no:checked').length,
                'manufactured_before_1989',
                "Unfortunately, if you have not owned the car for more than 12 months, " +
                "and it is not a pre-1989 vehicle, you can't import it into Australia." +
                '<a href="/info/faq/car#q420" target="_blank">Click here to read more</a>'
              );
              show_popup(
                $('#form_import_permit_no:checked').length,
                'import_permit',
                "We can send you a quotation, but we can't ship until you have the approved permit." +
                '<a href="/info/faq/car#q431" target="_blank">Click here to read more</a>'
              );
            } else if (to_country == 'New Zealand') {
              show_popup(
                $('#form_complies_with_new_zealand_regulations_no:checked').length,
                'complies_with_new_zealand_regulations',
                'You should first check the following regulations to ensure you will be able to import your car:' +
                '<ul><li><a href="http://www.landtransport.govt.nz/publications/infosheets/infosheet-2-08.html" target="_blank">Exhaust emissions</a></li><li><a href="http://www.landtransport.govt.nz/importing/frontal-impact-compliance-status.html" target="_blank">Frontal impact</a></li></ul>' +
                'We can import any car for you, but it is up to you to ensure you can drive it on the road.' +
                '<a class="more" href="/info/faq/car#q435" target="_blank">Click here to read more</a>'
              );
            }
          };
          $('input[type=radio]').bind('change, click', check);
          check();

          break;

        case 'motorbike':
          var check = function() {
            var to_port = $('#form_to_port').val();
            var to_country = to_port == 'Other...' ? $('#form_other_to_country').val() : to_port.replace(/ -.*$/, '');
            if (to_country == 'Australia') {
              show_popup(
                $('#form_owned_12_months_no:checked').length && $('#form_manufactured_before_1989_no:checked').length,
                'manufactured_before_1989',
                "Unfortunately, if you have not owned the bike for more than 12 months, " +
                "and it is not a pre-1989 motorbike, you can't import it into Australia." +
                '<a href="/info/faq/car#q457" target="_blank">Click here to read more</a>'
              );
              show_popup(
                $('#form_import_permit_no:checked').length,
                'import_permit',
                "We can send you a quotation, but we can't ship until you have the approved permit." +
                '<a href="/info/faq/car#q431" target="_blank">Click here to read more</a>'
              );
            } else if (to_country == 'New Zealand') {
              show_popup(
                $('#form_complies_with_new_zealand_regulations_no:checked').length,
                'complies_with_new_zealand_regulations',
                'You should first check the following regulations to ensure you will be able to import your car:' +
                '<ul><li><a href="http://www.landtransport.govt.nz/publications/infosheets/infosheet-2-08.html" target="_blank">Exhaust emissions</a></li><li><a href="http://www.landtransport.govt.nz/importing/frontal-impact-compliance-status.html" target="_blank">Frontal impact</a></li></ul>' +
                'We can import any car for you, but it is up to you to ensure you can drive it on the road.' +
                '<a class="more" href="/info/faq/car#q435" target="_blank">Click here to read more</a>'
              );
            }
          };
          $('input[type=radio]').bind('change, click', check);
          check();
          break;

        case 'boat':
          var check = function() {
            show_popup(
              $('#form_yacht_dimensions_estimates:checked').length,
              'yacht_dimensions',
              'The dimensions are critical to ensure we provide you with an accurate quote. ' +
              'A small change in height, width or length can make a big difference: ' +
              'sometimes tens of thousands of dollars. We may call you to discuss further.'
            );
          };
          $('input[type=radio]').bind('change, click', check);
          check();

          var fixInput = function() {
            var meters = $(this).parent().find("ul li:last input:radio");
            var feet = $(this).parent().find("ul li:first input:radio");

            if($(this).val().match(/\./) != null){
              meters.attr('checked', 'checked');
            }

            if($(this).val().match(/\'|\"/) != null){
              feet.attr('checked', 'checked');
            }

          };
          $('#form_yacht_length, #form_yacht_width, #form_yacht_height, #form_mast_length').bind('keyup', fixInput);
          break;
        case 'machinery':
        case 'project-cargo':
          var check = function() {
            show_popup(
              $('#form_dimensions_estimates:checked').length,
              'dimensions',
              'The dimensions are critical to ensure we provide you with an accurate quote. ' +
              'A small change in height, width or length can make a big difference: ' +
              'sometimes tens of thousands of dollars. We may call you to discuss further.'
            );
          };
          $('input[type=radio]').bind('change, click', check);
          check();
          break;

      }
      break;
  }

  $('.application-form .next').click(function() {
    $(this).hide().after('Please wait...');
    return true;
  });
});

function show_popup(value, field, message) {
  var $wrapper = $('#form_field_wrapper_' + field);
  if (!value) {
    $('.form-popup', $wrapper).slideUp(function() { $(this).remove() });
  } else {
    if (!$('.form-popup', $wrapper).length) {
      if (value) $('<div class="form-popup"></div>').html(message).hide().appendTo($wrapper).slideDown();
    }
  }
}

function currency_check_for_links() {

}

function approximate_value_in_new_zealand_dollars() {
  var v = parseFloat($('#form_approximate_value').val());
  if (v) {
    if ((c = $('#form_approximate_value_currency').val()) != 'NZD') {
      v = v * rates[c] / rates['NZD'];
    }
    return v;
  } else {
    return false;
  }
}


// Numeric only control handler
jQuery.fn.ForceNumericOnlyWithDecimalPoint = function() {
    return this.each(function() {
        $(this).keydown(function(e) {
            var key = e.charCode || e.keyCode || 0;
            //alert(key);

            // allow backspace, tab, delete, arrows, numbers and keypad numbers ONLY
            return (
                key == 190 ||
                key == 110 ||
                key == 8 ||
                key == 9 ||
                key == 46 ||
                (key >= 37 && key <= 40) ||
                (key >= 48 && key <= 57) ||
                (key >= 96 && key <= 105));
        })
    })
};

// Numeric only control handler
jQuery.fn.ForceNumericOnly = function() {
    return this.each(function() {
        $(this).keydown(function(e) {
            var key = e.charCode || e.keyCode || 0;
            //alert(key);

            // allow backspace, tab, delete, arrows, numbers and keypad numbers ONLY
            return (
                key == 8 ||
                key == 9 ||
                (key >= 37 && key <= 40) ||
                (key >= 48 && key <= 57) ||
                (key >= 96 && key <= 105));
        })
    })
};

var convertDimensions = function() {
  metersElement = $(this).parent().parent().find("input").get(2);
  feetElement = $(this).parent().parent().find("input").get(0);
  inchesElement = $(this).parent().parent().find("input").get(1);
  hiddenElement = $(this).parent().parent().find("input").get(3);

  if($(this).attr('id').match(/.*_meters$/)){
    // meters was changed
    meters = $(this).val();

    feet = meters * 3.2808299;
    flooredFeet = Math.floor(feet);
    inchesRemainder = feet - flooredFeet;

    $(feetElement).val(flooredFeet);

    inches = Math.round(inchesRemainder * 12);
    $(inchesElement).val(inches)

  } else if ($(this).attr('id').match(/.*_feet$/)) {
    // feet was changed
    feet = $(this).val();

    meters = (feet / 3.2808299) + ($(inchesElement).val() * 0.0254);
    $(metersElement).val(Math.round(meters* 100) / 100);

  } else {
    if($(this).val() > 12){
      $(this).val("12");
    }

    // inches was changed
    feet = $(feetElement).val();

    meters = (feet / 3.2808299) + ($(inchesElement).val() * 0.0254);
    $(metersElement).val(Math.round(meters* 100) / 100);
  }

  $(hiddenElement).val($(metersElement).val());
}

var convertWeight = function() {
  poundsElement = $(this).parent().parent().find("input").get(0);
  kgsElement = $(this).parent().parent().find("input").get(1);
  hiddenElement = $(this).parent().parent().find("input").get(2);

  if($(this).attr('id').match(/.*_pounds$/)){
    kgs = $(this).val() * 0.45359237;
    $(kgsElement).val(Math.round(kgs * 10) / 10);
  } else {
    pounds = $(this).val() * 2.20462262;
    $(poundsElement).val(Math.round(pounds));
  }

  $(hiddenElement).val($(kgsElement).val());
}

$(document).ready(function() {
  $(".dimension_field input:regex(id, .*(feet|inches)$)").ForceNumericOnly();
  $(".dimension_field input:regex(id, .*(meters)$)").ForceNumericOnlyWithDecimalPoint();

  $(".dimension_field input").change(convertDimensions);
  $(".weight_field input").change(convertWeight);

  $(".dimension_field input").keyup(convertDimensions);
  $(".weight_field input").keyup(convertWeight);

  $(".dimension_field input:regex(id, .*_meters$)").each(function(){
    hiddenElement = $(this).parent().find("input").get(3);

    $(this).val($(hiddenElement).val());
  });

  $(".weight_field input:regex(id, .*_kgs$)").each(function(){
    hiddenElement = $(this).parent().find("input").get(2);
    $(this).val($(hiddenElement).val());
  });

  $(".dimension_field input:regex(id, .*_meters$)").trigger('keyup');
  $(".weight_field input:regex(id, .*_kgs$)").trigger('keyup');
});
