try {
    console.log("init");
} catch(e) {
    console = { log: function() {} };
}

function get_base_name(img) {
    fname = img.find('img').attr('src');
    return fname.substring(0, fname.lastIndexOf('_'));
}

var images = new Array();
$(function() {
    console.log("ready()");

    $('#header').pngfix();

    $('#search-box').defaultvalue('enter search terms');
    $('#large-search-box').defaultvalue('please enter your search terms');
    $('form.selectsubmit select').selectsubmit();

    /* For additional large product images, we want to do this:
     * 1 - Eager load all _detail.jpg image sizes in the background after the
     *     rest of the page has finished loading.
     * 2 - When a thumbnail is clicked, check to see if the large image has
     *     finished loading:
     *      - If it is loaded, crossfade to it.
     * 3 - If not loaded, fade to white and set a loading indicator.
     * 4 - When the image loads, hide the loading indicator and fade in the
     *     image.
     */

    function gallery(selector, variant) {
      $(selector).each(function() {
          /* Preload each detail image. */
          fname = get_base_name($(this)) + variant;
          images[fname] = $("<img>").attr("src", fname);
      }).click(function() {
          console.log("Clicked! [" + $(this) + "]");
          /* Set the border of the clicked thumbnail. */
          $(this)
              .closest('table')
                  .find('img')
                      .css('border', '1px solid #bbb')
                  .end()
              .end()
              .find('img')
                  .css('border', '1px solid #000');

          /* Fade the current image out to white. */
          base = get_base_name($(this));
          console.log("switching to " + base);
          $('div.product-image-thumb img')
              .attr("src", base + variant)
          return false;
      }).slice(0,1)
          /* Darken the border on the first image, since it's the default. */
          .find('img').css('border', '1px solid #000');
    }

    gallery('table#product-other-more-images a', '_detail.jpg');
    gallery('table#product-table-more-images a', '_full.jpg');

    $('select#form-option-engraving').change(function() {
        /* Check to see if new form value isn't "No Engraving", and if so
         * make the engraving text box visible. */
        row = $('input#form-option-engrave-text').parent().parent();
        if($(this).find('option')[this.selectedIndex].text != 'No Engraving') {
            $(this).parent().parent().after(row);
            row.show();
        } else {
            row.hide();
        }
    }).trigger('change');
    
    /* Cart page */
    $('table#shipping-quotes input').change(function() {
        $(this)
            .parent()
                .parent()
                    .parent()
                        .addClass('shipping-method-selected')
                        .siblings()
                            .removeClass('shipping-method-selected');

    });
    $('table#shipping-quotes input:checked').trigger('change');
    /* Make it so that clicking anywhere on the row changes the radio. */
    $('table#shipping-quotes td').click(function() {
        $(this)
            .parent()
                .find('input')
                    .trigger('change')
                        .attr("checked", "checked");
    });

    /* Checkout page */
    function toggle_billing() {
        if($(this).attr("checked")) {
            $('table#billing-address-fields').hide();
        } else {
            $('table#billing-address-fields').show();
        }
    }
    $('input#billingsame_as_shipping').change(toggle_billing).click(toggle_billing).trigger('change');

    $('select#cctype').change(function() {
        if($(this).find('option')[this.selectedIndex].value != 'giftcode') {
            $('div#credit-card-fields').show();
        } else {
            $('div#credit-card-fields').hide();
        }
    }).trigger('change');

    $(window).load(function() {
        console.log("window.load()");
    });

    $('div.product-image-thumb').click(function() {
        $('a#tab-large').trigger('click');
        return false;
    });
    $('a#tab-thumb').click(function() {
        $(this).addClass("selected").siblings().removeClass("selected");
        $('div.product-image-large').hide();
        $('div.product-image-thumb').show();
        return false;
    });
    $('a#tab-large').click(function() {
        $(this).addClass("selected").siblings().removeClass("selected");
        imageh = $('div.product-image-thumb').height();
        $('div.product-image-large')
            .height(imageh)
            .show()
            .pannable();
        $('div.product-image-thumb').hide();
        return false;
    });

    /* Update price and availability with selected options. */
    if($('p.product-out-of-stock').length < 1) {
      $('div.product-options select').change(function() {
          /* Set AJAX loading indicator. */
          console.log("Updating...");
          $('p.product-lead').html('<img src="/static/images/availability-loader.gif"> Checking availability...');
          $('p.product-lead').addClass('product-in-stock');
          
          /* Make AJAX request for availability and price. */
          selections = [];
          $('div.product-options select').each(function(i) {
              console.log("got value " + $(this).val());
              selections.push($(this).val());
          });
          pid = $('div.product-ordering input[name=product_id]').val();

          $.ajax({
              type: "GET",
              url: "/products/ajax_price_availability",
              data: {
                  val: selections,
                  product_id: pid
              },
              success: function(data, ts) {
                  console.log("success, got " + data);
                  avail = data.split('|');
                  price = avail[0];
                  stock_status = avail[1];
                  if(price != $('td.price').text()) {
                      $('td.price-options').text(price);
                      $('tr.price-options-row').show();
                  } else {
                      $('tr.price-options-row').hide();
                  }
                  $('p.product-lead').text(stock_status);
                  if(stock_status != 'In Stock') {
                      $('p.product-lead').removeClass('product-in-stock');
                  }
              },
              error: function(xhr, ts, err) {
                  console.log("error, got " + ts);
                  $('p.product-lead').text("Error checking availability. Try adding this item your cart.");
              }
          });
      });
    }

    $('input.cant-checkout-button').click(function() {
        $('input#postal_code').focus();
        return false;
    }).removeAttr('disabled');

    $('#instant-price-match').historycheck([
        'http://www.cuesight.com',
        'http://www.cuesight.com/pool-cues.html',
        'http://www.ozonebilliards.com',
        'http://www.rockwellbilliards.com/pilot.asp',
        'http://www.pooldawg.com',
        'http://www.cheapcues.com',
        'http://www.cheapcues.com/Pool_Cues.asp',
        'http://www.cuestore.com'
    ]);

    console.log("ready() done");
});

