var offer_made = false;

$(document).ready(function(){
  
  $('#bidSubmit').click(function(){
    
    offer_made = false;
    
  });
  
  // setup cycle
  $('#listingGalleryStage').cycle({
    fx: 'scrollLeft',
    speed: 'fast',
    timeout: 0,
    pager: '#listingGalleryThumbWrap',
    pagerAnchorBuilder: function(idx, slide){
      return '#listingGalleryThumbWrap > div:eq(' + idx + ')';
    }
  });
  
  // hide thumb scroller if not needed
  if($('#listingGalleryThumbWrap div.imageThumb').length < 5)
  {
    $('a#listingGalleryThumbScroller').hide();
  }
  
  // add expander button functionality
  $('div#listingGalleryExpandButt').click(function(){
    
    $('#listingGalleryStage a:visible').trigger('click');
    
  });
  
});

/**
 * scroll the thumnails; move first thumb to end
 */
function nextThumb()
{
  var first_thumb = $('#listingGalleryThumbWrap div.imageThumb:first');
  
  $('#listingGalleryThumbWrap').append(first_thumb);
}

/**
 * makes AJAX query to get shipping quote
 */
function getOfferQuote()
{
  // validate bid amount
  if($('#bid_amount').val() == '')
  {
    alert('You must enter a bid amount!');
  }
  else if(isNaN(parseFloat($('#bid_amount').val())) || $('#bid_amount').val() < 0)
  {
    alert('Bid must be a number greater than 0!');
  }
  else
  {
    // if offer set the sub form
    if(offer_made)
    {
      return true;
    }
    
    // show loading screen
    $('#infoArea').show();
    $('#offerLoadingWrap').show();
    
    // hide any existing quote
    $('#summaryWrap').hide();
    
    $.get(
      '/transaction/getOfferQuote',
      {
        amount: $('#bid_amount').val(),
        pcode: $('#pcode').val(),
        country_id: $('#country_id').val(),
        item_id: $('#item_id').val(),
        shipping_product: $('#shipping_product').val()
      },
      function(data)
      {
        // hide secure area
        $('#infoArea').hide();
        
        // load summary
        $('#summaryWrap').html(data);
        $('#summaryWrap').show();
        
        offer_made = true;
      }
    );
  }
  
  // stop form submit
  return false;
}

/**
 * submits the offer once you have a quote
 */
function submitOffer()
{
  $('#offerForm').trigger('submit');
}

/**
 * validate pcode and country entry
 */
function validatePcode()
{
  if($('#pcode').val() == '')
  {
    alert('You must enter your postal code / zipcode!');
    
    // stop form validation
    return false;
  }
  
  if($('#country_id').val() == '')
  {
    alert('You must select your country!');
    
    // stop form validation
    return false;
  }
  
  // validation passed, submit form
  return true;
}