// Extend jQuery with a function to pre-load a list of images

jQuery.preloadImages = function() {
  for (var i = 0; i < arguments.length; i++) {
    jQuery("<img>").attr("src", arguments[i]);
  }
}

$(document).ready(function() {

  // Pre-load button hover images

  $.preloadImages(
    '/img/product-search-button-hover.png',
    '/img/shopping-basket-overview-view-basket-button-hover.png',
    '/img/dealer-login-button-hover.png'
  );

  // Init button hovers

  $('.hoverable').hover(
    function() {
      $(this).attr('src', $(this).attr('src').replace('.png', '-hover.png'));
    },
    function() {
      $(this).attr('src', $(this).attr('src').replace('-hover.png', '.png'));
    }
  );

  // Init external links

  $('a.external, div#footer ul.logos a').click(function() {
    window.open($(this).attr('href'));
    return false;
  });

  // Handle product category sub-menus

  $('div#product-categories li.expandable a.root').click(function() {
    if ($(this).parents('li').find('ul.sub').css('display') == 'block') {
      $(this).parents('li').find('ul.sub').slideUp({ duration: 500 });
    } else {
      $('div#product-categories ul.sub').slideUp({ duration: 500 });
      $(this).parents('li').find('ul.sub').slideDown({ duration: 500 });
    }
    return false;
  });

  // Initialize the product search fields

  $('input#product-search-text-field').focus(function() {
    $(this).val($(this).val() == 'Search Products' ? '' : $(this).val());
  });

  $('input#product-search-text-field').blur(function() {
    $(this).val($(this).val() == '' ? 'Search Products' : $(this).val());
  });

  $('select#product-search-type-field').change(function() {
    $('select#product-search-category-field').html('<option value="">- All Categories -</option>');
    if ($(this).val() != '') {
      now = new Date();
      $.getJSON('/ajax/get-categories.php', { timestamp: now.getTime(), type: $(this).val() }, function(categories) {
        for (id in categories) {
          $('select#product-search-category-field').append('<option value="' + id + '">' + categories[id] + '</option>');
        }
      });
      $('div#product-search-category').slideDown();
    } else {
      $('div#product-search-category').slideUp();
    }
  });

  // Dealer login fields functionality

  $('input#dealer-login-username-field').focus(function() {
    $(this).val($(this).val() == 'Username' ? '' : $(this).val());
  });

  $('input#dealer-login-username-field').blur(function() {
    $(this).val($(this).val() == '' ? 'Username' : $(this).val());
  });

  $('input#dealer-login-password-field').focus(function() {
    $(this).val($(this).val() == 'Password' ? '' : $(this).val());
  });

  $('input#dealer-login-password-field').blur(function() {
    $(this).val($(this).val() == '' ? 'Password' : $(this).val());
  });

});
