/* use in tandem with apply_placeholders (as per jquery.util.js) to validate and handle prompts */
var validateGlobalForm = function(form, msg)
{
  var $input = $('input.apply_placeholder', form);
  var val = $.trim($input.val());
  
	if (!val.length || val == $input.attr('prompt'))
	{
		$.prompt(msg);
		return false;
	}
	return true;
};

var submitGlobalForm = function(form, msg) {
  if (validateGlobalForm(form, msg))
    $(form).submit();
}

var submitSearch = function() {
  submitGlobalForm(document.searchForm, 'Please enter a keyword');
}

var submitEmail = function() {
  submitGlobalForm(document.ccoptin, 'Please enter your e-mail address');
}

$(function() {
  $('form.handle-enter-key :text, form.handle-enter-key :password').keypress(function(e) { if (e.keyCode == 13) { this.form.submit(); } });
});

var applyTransitTimesToCart = function(arrival_date) {
  $('#cart .time-in-transit').html('Receive on <span class="x-alert"><em><strong>' + arrival_date + '</strong></em></span> with currently selected shipping option.');
}

var loadShippingTransitTimes = function(city, state, zip, weight, selectedMethod){
    $.post('/ext/cfc/ups/timeInTransit.cfc?method=getTransitTimes&returnformat=json', {
        city: city,
        state: state,
        zip: zip,
        weight: weight
    }, function(data){
        if (data.DATA && data.DATA.length) { //<!--- If no weight - no in stock items --->
            // console.log(data.DATA);
            if (weight) {
                // Set all Ship Options rows to "unavailable" by default
                $('#shippingOption td.time-in-transit').html('Shipping option not available for currently selected address').closest('tr').removeClass('available').addClass('unavailable');
                
                /* Loop through each Ship Method returned by the call to the 
                 * Time in Transit API
                 */ 
                $.each(data.DATA, function(i, method){
                    /* Update the row for the specified Ship Method to 
                     * "available" and add a message about the Time in Transit
                     */ 
                    $('#ship-method-' + method[0] + ' td.time-in-transit').html('Receive in-stock items on <span class="x-alert"><em><strong>' + method[2] + '</strong></em></span>').parents('tr').eq(0).addClass('available').removeClass('unavailable');
                    
                    if (selectedMethod && selectedMethod == method[0]) {
                        applyTransitTimesToCart(method[2]);
                    }
                    else 
                        if ($('#ship-method-' + method[0] + ' :radio:checked').length) {
                            applyTransitTimesToCart(method[2]);
                        }
                        
                    // Fade in all Time in Transit table cells
                    $('.time-in-transit').fadeIn();
                });
                
                $('.unavailable :radio:checked').removeAttr('checked');
                
                // Disable the radio button for all unavailable Ship Methods
                $('.unavailable').find(':radio').attr('disabled', 'disabled'); //.end().find('.rates-wrapper').fadeOut();
                
                // Enable the radio button for all available Ship Method
                $('.available').find(':radio').removeAttr('disabled'); //.end().find('.rates-wrapper').fadeIn();
                
                /*  If no ship method is selected, initiate a click event on 
                 *  the first available one, which will trigger a submit 
                 */
                if (!$('.available :radio:checked').length) {
                    $('.available:first :radio').focus().click();
                }
                
                // Fade out the costs for all unavailable Ship Methods
                $('#shippingOption td.time-in-transit').parent('tr.unavailable').find('td span.rates-wrapper').fadeOut();
                
                // Fade in the costs for all available Ship Methods
                $('#shippingOption td.time-in-transit').parent('tr.available').find('td span.rates-wrapper').fadeIn();
            }
        }
        else {
            // console.log('No data');
            // if (city && state && zip) {
            //   $.prompt("We were unable to match your shipping address with our records. Please double check your order before submitting.");
            // }
            $('.time-in-transit').fadeOut();
        }
    }, 'json');
}


var loadShippingRates = function(address1, address2, city, state, zip, weight, value) {
  $.post(
    '/ext/cfc/ups/Rates.cfc?method=getRates&returnformat=json', 
    { 
      addressLine1  : address1,
      addressLine2  : address2,
      city          : city,
      state         : state,
      postalCode    : zip,
      countryCode   : 'US',
      packageWeight : weight,
      packageValue  : value
    },      
    function(data) {
      if (data.DATA && data.DATA.length) { //<!--- If no weight - no in stock items --->
        // console.log(data.DATA);
        // return;        
        var total = parseFloat($('#orderSummary .total .price').text().replace('$', ''));
        var subtotal = total;
        var adjustTotal = !$('#orderSummar .ship_discount').length; //if shipping discount is not applied we need to apply this dynamic change to the total
        
        if (adjustTotal) {
          var currShip = parseFloat($('#orderSummary .shipping .price').text().replace('$', ''));
          subtotal -= currShip;
        }        
        //console.log("curr ship: " + currShip + ", subtotal = " + subtotal);
        
        $.each(data.DATA, function(i, method) {
          var newRate = method[4].toFixed(2);
          $('#ship-method-' + method[1] + ' .rates:not(.no-charge), #orderSummary .price .rate-' + method[1]).fadeOut().text('$'+ newRate).fadeIn();
          if (adjustTotal && $('#orderSummary .price .rate-' + method[1]).length) {
            total = subtotal + parseFloat(newRate);
            //console.log('New rate=' + newRate + ', New total=' + total);
            $('#orderSummary .total .price').text('$' + total.toFixed(2));
          }
        });        
      }
      else {
        //console.log('No data');
        // $('#shippingOption .rates').fadeOut().text('No rates available').fadeIn();  
      }
    },
    'json'
  );    
}

var addSystemMessage = function(msg, id) {
  var $msg;   
  if (id && ($msg = $('#' + id)) && $msg.length) {
    $msg.text(msg);
    return;
  } 
  var $m = $('#systemMessage');
  if (!$m.length) {
    $m = $('<div id="systemMessage"></div>').insertAfter($('h1').eq(1));    
  }
  var $ul = $m.find('ul');
  if ($ul.length) {
    $msg = $('<li/>').text(msg); //.hide();
    $ul.eq(0).append($msg);
  }
  else {
    $msg = $('<p/>').text(msg).hide();
    $m.append($msg);
    $msg.fadeIn(); //fade in only on standalone elements - li's don't play well with animated block display
  }
  if (id)
    $msg.attr('id', id);  
}


var removeSystemMessage = function(id) {
  $('#systemMessage #' + id).remove();
}

