// Place your application-specific JavaScript functions and classes here
// This file is automatically included by javascript_include_tag :defaults

$(function() {
  $('a[rel*=facebox]').facebox();
  $('ul.years').columnize({ width: 70 });
  // Uniform
  $("select, :checkbox, :radio, :file").uniform();
  $('#add_photos_form a.add').click(function() {
    $("#add_photos_form :input[type=file]:last").uniform();
  })
  // Close buttons
  $('.close-btn').live("click", function() {
    if((document.all && !window.opera && window.XMLHttpRequest) ? false : true) {
      $(this).parent().stop().animate({margin: '0', padding: '0', border: 'none', opacity: 'hide', height: 'hide'}, 'fast');
    } else {
      $(this).parent().stop().fadeOut();
    }
    return false
  });

  // Tooltip
  $('.tooltip').live('mouseover',
    function() {
      $(this).after("<span class='tooltiptext'>" + $(this).text() + "</span>");
    }
  );
  $('.tooltip').live('mouseout',
    function() {
      $('.tooltiptext').remove();
    }
  );

  // Fluid textarea resize
  $('textarea').autoResize({
    extraSpace : 20,
    animateDuration : 100
  });

  // Comment Ajax spinner
  $('#comment_form').ajaxStart(function() {
    $(this).append('<img src="/images/icons/ajax-loader.gif" class="loader" alt="loading..."/>');
  });

  $('#comment_form').ajaxComplete(function() {
    $('.loader').fadeOut('fast', function() {
      $(this).remove();
    });
  });
  
  // Ajax Spinner
  $('.ajax-spinner').ajaxStart(function() {
    $(this).append('<img src="/images/icons/ajax-loader.gif" class="loader" alt="loading..."/>');
  });

  $('.ajax-spinner').ajaxComplete(function() {
    $('.loader').fadeOut('fast', function() {
      $(this).remove();
    });
  });  
  
  // Ride Parts and Dreamlist Parts
  $('.ride-actions a.sort.add').click(function() {
    var clicked = $(this);
    $('.active').next('.list_rides').fadeOut('fast', function() {
      $(this).prev('.active').removeClass('active');
    });
    $(clicked).addClass('active');
    if ($(clicked).next('.list_rides:visible').size() == 0) {
      $(clicked).next('.list_rides').fadeIn('fast');
    };
  });
  $('.ride-actions .active').click(function() {
    $(this).removeClass('active');
    $(this).next('.list-rides').fadeOut('fast');
  });
  

  // Parts search
  $('#results ul:last').columnize({ width: 80 });
  $('#parts ul[id!=drill_down] li a').live('click', function() {
    var answer = $(this).text();
    var definition = $(this).parent().parent().parent().attr('id');
    $(this).parent().parent().parent().fadeOut('fast');
    $('#results').fadeOut('fast');
    if (answer == 'Select All') {
      $('#breadcrumb').append("<span class='crumb' id='" + definition + "-crumb'><a href='#' class='sort'"  + ">All</a> > </span>" ).fadeIn();
    }
    else if(answer == 'Add to Cart') {
        // If this isn't here, and empty, adding to cart will stack up breadcrumbs.
    }
    else {
      $('#breadcrumb').append("<span class='crumb' id='" + definition + "-crumb'><a href='#' class='sort'"  + ">" + answer + "</a> > </span>" ).fadeIn();
    };

    $("#" + answer).next('ul').fadeIn('fast');
  });

  $('#breadcrumb span.crumb a').live('click', function() {
    var crumb = $(this).parent().attr('id');
    var trigger = $(this).parent().attr('id').split("-",1);
    $("span[id=" + crumb + "], span[id=" + crumb + "] ~ span.crumb").remove();
    $("#" + trigger + " ~ ul").remove();
    $('#results ul').hide();
    $("#" + trigger).fadeIn('fast', function() {
      $('#results').fadeIn('fast');
    });
    if ($(this).parent().attr('id') == 'generic_description-crumb') {
      $('#drill_down').show();
    };
    $('#parts').animate({
      height: $('#results ul:last').height() + 200
    }, 500, function() {
      $('#parts').css('overflow', 'visible');
    });

    return false
  });

  $('#parts').ajaxStart(function() {
    $('#loader').fadeIn('fast');
    $('#parts').height($('#parts').height());
  });
  $('#parts').ajaxComplete(function() {
    $('#loader').fadeOut('fast');
    $('#parts').css('overflow', 'hidden');
    $('#results').fadeIn('1000', function() {
      if ($('#results ul li:visible').size() == 0) {
        $('#parts').append('<h3><img src="/images/icons/ajax-loader.gif" /> Fetching your product results...</h3>');
      }
    });
    $('#results li').addClass("dontsplit");
//    $('#results ul:last[id!=drill_down]').columnize({ columns: 3, lastNeverTallest: true });
$('#results ul:last[id!=drill_down]').each(function()
{
	if(!$(this).parent().hasClass("part-details"))
	{
		$(this).columnize({ columns: 3, lastNeverTallest: true });
	}
});
    $('li a:contains("Select All")').css('background-color', '#ff8303');
      $('#parts').css('height','auto').show(500);
  });
  $('ul#drill_down li a').live('click', function() {
    $('ul#drill_down li a').removeClass('active');
    $(this).addClass('active');
  });

  // Parts shopping

  $('ul.dream_list_rides li').click(function() {
    $(this).fadeOut();
  });

  $('.part-info a.add.cart').click(function() {
    $(this).ajaxComplete(function() {
      $(this).replaceWith('<a href="' + $('#go_to_cart').attr('href') + '" class="cart orange sort">In Cart</a>');
      
    });
  });

  // Cart
  $('td.quantity').change(function() {
    $(this).append('<img src="/images/icons/ajax-loader.gif" class="loader" alt="loading..."/>');
  });

  $('td.quantity').ajaxComplete(function() {
    $('img.loader').fadeOut('fast', function() {
      $(this).remove();
    });
  });

  $('#shipping').ajaxStart(function() {
    $(this).append('<span class="loader"><img src="/images/icons/ajax-loader.gif" class="loader" alt="loading..."/> Calculating shipping rates. Please wait.</span>');
    $('#shipping .section input').attr('disabled', 'disabled');
  });

  $('#shipping').ajaxComplete(function() {
    $('.loader').fadeOut('fast', function() {
      $(this).remove();
    });
    $('#shipping .section input').attr('disabled', '');
  });

  $('#shipping_options input:radio').live('click', function() {
    var selectedShip = string_to_float($('input:checked').next('strong').text()) || 0;
    var partsPrice = string_to_float($('#parts_price h4 span').text());
    var appliedFunds = string_to_float($('#applied_funds h4 span').text()) || 0;
    var subTotal = (selectedShip + partsPrice - appliedFunds).toFixed(2);
    $('#order_total h2 span').text(subTotal).prepend('$');
    $('#shipping_total h4 span').text('$' + (selectedShip).toFixed(2));
    $('.total_orig').text(string_to_float($('#parts_price h4 span').text()) + selectedShip);
  });

  $('.total_orig').text(string_to_float($('h2#total span').text()));

  $('#funds_available input').keyup(function () {
    var enteredFunds = string_to_float($('#desired_amount').val());
    if (enteredFunds > string_to_float($('.total_orig').text())) {
      $('#desired_amount').addClass('error');
      $('#fund_error').text('You cannot apply more than the order subtotal.');
    }
    else if (enteredFunds > string_to_float($('#available').text())) {
      $('#desired_amount').addClass('error');
      $('#fund_error').text('You cannot apply more than the order subtotal.');
    }

    else {
      $('#desired_amount').removeClass('error');
      $('#applied_funds h4 span').text('$' + string_to_float($('#desired_amount').val() || '0').toFixed(2));
      $('#fund_error').text('');
    }

    if (enteredFunds == '') {
      $('#applied_funds h4 span').text('$0.00');
    }

    var selectedShip = string_to_float($('input:checked').next('strong').text()) || 0;
    var partsPrice = string_to_float($('#parts_price h4 span').text());
    var availableFunds = string_to_float($('#available').text());
    var appliedFunds = string_to_float($('#applied_funds h4 span').text()) || 0;
    var subTotal = (selectedShip + partsPrice - appliedFunds).toFixed(2);
    $('#order_total h2 span').text(subTotal).prepend('$');
    $('#shipping_total h4 span').text('$' + (selectedShip).toFixed(2));
    $('#order_applied_fund_desired_amt').val(enteredFunds);
  });

  $('#use_shipping_address_no').click(function() {
    $('#billing_address').show();
    $('#payment #current_address').hide();
  });
  $('#use_shipping_address_yes').click(function() {
    $('#billing_address').hide();
    $('#payment #current_address').show();
  });
  $('#use_new_card').click(function() {
    $('#new_card_form').slideDown();
    $(this).fadeOut();
    $('#authorize_net_info').fadeTo("fast", 0.33);
    $('#new_card h5#pay_new_card').prepend('<a href="#" id="cancel" class="right">cancel</a>');
    $('#new_card h5.option').fadeOut();
    return false
  });
  $('#new_card #cancel').live('click', function() {
    $(this).remove();
    $('#new_card_form').slideUp();
    $('#use_new_card').fadeIn();
    $('#authorize_net_info').fadeTo("fast", 1);
    $('#new_card h5.option').fadeIn();    
    return false
  });
  $('#payment input[type="text"]').each(function() {
    $(this).css('color', '#999').val($(this).attr('placeholder'));
    $(this).focus(function() {
      if ($(this).val() == $(this).attr('placeholder')) {
        $(this).val('').css('color', '#000');
      }
    });
    $(this).blur(function() {
      if ($(this).val() == '') {
        $(this).val($(this).attr('placeholder')).css('color', '#999'); 
      }
    });
  });

  $('#order #next').append('<p>Choose a Shipping option to continue.</p>');
  $('#order #next span').hide();
  $('#new_order :input').live('click', function() {
    $('#order #next p').remove();
    $('#order #next span').show('');
  })
  $('#order_submit').attr('disabled','disabled').css({opacity: .3, cursor: 'default'});
  
  $('#cc_form input').keyup(function() {
    if ($('#credit_card_number').val() !== '' &&
        $('#expiration_month').val() !== '' &&
        $('#expiration_year').val() !== '' &&
        $('#verification_value').val() !== '') {
      $('#order_submit').attr('disabled','').css({opacity: 1, cursor: 'pointer'});
    } else {
      $('#order_submit').attr('disabled','disabled').css({opacity: .3, cursor: 'default'});
    };
  });
  
  $('.transactions tr.order td.clickable').click(function() {
    $(this).parent('.order').children('.details').children('.info').click();
  });

  // Saved Credit Cards
  $('#authorize_net_info li.credit-card .address').hide();
  $('#authorize_net_info li.credit-card a.details, #authorize_net_info li.credit-card h4').click(function() {
    $(this).parent().toggleClass('active').children('.address').slideToggle('fast');
    return false
  });
  
  
  
  // Fake image upload spinner
  $('#add_photos_form .upload').click(function() {
    $(this).attr('disabled','disabled');
    $('#add_photos_form').append('<img src="/images/icons/ajax-loader.gif" class="loader"/>');
    $('#add_photos_form form').submit();
  });
  
  // Comment Replies
  $('.reply-button:not(.active)').hide().click(function() {
    $(this).toggleClass('active');
  });
  $('#comments li.comment').hover(
      function() {
        $(this).find('.reply-button:next').show();
      },
      function() {
        $(this).find('.reply-button:last:not(.active)').hide();
      }
    );

});

function string_to_float (s) {
  return parseFloat(s.replace(/[,$]/g,""))
}


