$(function() {
  if ($('#product-tools')[0]) {
    product_tools();
  }
  // 
  // $("select").focus(function(){
  //   $(this).css("width", "auto");
  // }).blur(function(){
  //   $(this).css("width", "240px");
  // });
});


function product_tools() {
  $('#variants .variant select').change(function() {
    update_product_price();
    
    $(this).parents('.variant').find('.variant-option-images img').hide();
    variant_option_image = $('#variant_option_image_' + $(this).find('option:selected').metadata().id).show();
    
    // Update Color on Main Product Image if Color
    if ($(this).parents('.variant').is('.color')) {
      $('a#photo-large img:first').attr('src', variant_option_image.attr('src').replace('_thumbnail', '_standard'));
    }
    
    // Show Luggage Tag Text if this is "Engraved Name Plate"
    if ($(this).parents('.variant').is('.engraved-name-plate')) {
      if (($(this).val() == 'No Name Plate Added') || ($(this).val() == 'No Luggage Tag Added')) {
        $('#luggage_tag').hide();
        $('#luggage_tag textarea').val('');
      } else {
        $('#luggage_tag').show();
      }
    }
  });
  
  update_product_price();
  
  $('form#add-to-cart-form').submit(validate_luggage_tag);
  
  $('ul#thumbs li a').click(function() {
    $('a#photo-large img:first').attr('src', $(this).attr('href'));
    $('a#photo-large').attr('href', $(this).attr('href').replace('_standard', ''));
    return false;
  });
}

function validate_luggage_tag() {
  if ($('#luggage_tag').length == 0) { return true; }
  
  max_lines = $('#luggage_tag').metadata().max_lines;
  max_length = $('#luggage_tag').metadata().max_length;
  
  lines = $('#luggage_tag textarea').val().split("\n");
  
  if (max_lines && lines.length > max_lines) {
    alert("Text on tag can be no more than " + max_lines + " lines.");
    return false;
  }
  
  for (i = 0; i < lines.length; i++) {
    line = lines[i];
    if (max_length && line.length > max_length) {
      alert("All text on tag lines must be less than " + max_length + " characters.");
      return false;
    }
  }
}

function update_product_price() {
  price = $('#pricing').metadata().price;
  
  $('#variants .variant select option:selected').each(function() { 
    price = price + $(this).metadata().price_modifier;
  });
  
  $('#final-price').text(format_price(price));
}


/** Helpers **/

function format_price(num) {
  num = Math.round(num * 100) /100;

	if (num - Math.floor(num) == 0) {
		num = num + ".00";
		
	} else {
		string = num.toString();
		parts = string.split(".");
		cents = parts[1];
		
		if (cents.length == 1) {
			num = num + "0";
		}
	}
  
  num = "$" + num;
  return num;
}