function switchCups(cup) {
  cup="#"+cup;
  $("#menuImageHolder img").hide();
  $(cup).show();
}

today = new Date();
function format_val(nStr, dollar, decimal) {
  if (decimal == null) {
    nStr = nStr.toFixed(0);
  } else {
    nStr = nStr.toFixed(decimal);
  }
  nStr += '';
  x = nStr.split('.');
  x1 = x[0];
  x2 = x.length > 1 ? '.' + x[1] : '';
  var rgx = /(\d+)(\d{3})/;
  while (rgx.test(x1)) {
    x1 = x1.replace(rgx, '$1' + ',' + '$2');
  }
  if (dollar) {
    return '$' + x1 + x2;
  }
  return x1 + x2;
}
jQuery.fn.ForceNumericOnly = function() {
    return this.each(function() {
        $(this).keydown(function(e) {
            var key = e.charCode || e.keyCode || 0;
            // allow backspace, tab, delete, arrows, numbers and keypad numbers ONLY
            return (
                key == 8 || 
                key == 9 ||
                key == 46 ||
                (key >= 37 && key <= 40) ||
                (key >= 48 && key <= 57) ||
                (key >= 96 && key <= 105));
        })
    })
};

function in_area(x,y,base,coords) {
  console.log(x , (base.left + parseInt(coords[0])), (base.left + parseInt(coords[2])), y , (base.top + parseInt(coords[1])), (base.top + parseInt(coords[3])));
  console.log(x > (base.left + parseInt(coords[0])), x < (base.left + parseInt(coords[2])), y > (base.top + parseInt(coords[1])), y < (base.top + parseInt(coords[3])));
  return (x > (base.left + parseInt(coords[0])) && x < (base.left + parseInt(coords[2])) && y > (base.top + parseInt(coords[1])) && y < (base.top + parseInt(coords[3])));
}

$(function() {
  // main nav
  $('.nav li a').each(function() {
    $(this).css('width', ($(this).width() + 4) + 'px');
  });

  // menu page
  $("#menuImageHolder img").hide();
  $("#vanilladream").show();
  $("#menuImageHolder").show();
      
  // order page
  tomorrow = new Date();
  tomorrow.setDate(today.getDate() + 1);
  $("#datepicker").datepicker({
    beforeShowDay: function(date) {
                     result = true;
                     selected_loc = $('#location_customselect').val()
		     if (locations[selected_loc]['hours'][date.getDay()].length < 1) result = false;
                     if (result) {
                       holidays = locations[selected_loc]['holidays'];
                       for(i=0; i < holidays.length; i++) {
                         if (result && date.getMonth() == holidays[i].month && date.getDate() == holidays[i].day) result = false;
                       }
                     }
                     return [result,'',''];
                   },
    minDate: tomorrow
  });
  $("#datepicker").focus(function() {
    $(this).blur();
    $(this).datepicker('show');
  });
  function update_times() {
    var p = $('#datepicker').datepicker('getDate');
    var d = 2;
    if(p != null) d = p.getDay();
    options = '';
    for (i=0; i < locations[$('#location_customselect').val()]['hours'][d].length; i++) {
      options = options + '<div title="' + locations[$('#location_customselect').val()]['hours'][d][i] + '" class="selectitems"><span>' + locations[$('#location_customselect').val()]['hours'][d][i] + '</span></div>';
    }
    $('#timepicker_options').html(options);
    var thisselection = $("#timepicker_options .selectitems").first().html();
    $("#timepicker_customselect").val($("#timepicker_options .selectitems").first().attr('title'));
    $("#timepicker_iconselect").html(thisselection);
  }
  $("#datepicker").change(update_times);
  function location_change(element) {
    if (element != '#location_customselect') return;
    $('#store_address').html(locations[$('#location_customselect').val()]['address']);
    if ($('#location_customselect').val() == 'delivery') {
      $('#orderForm').addClass('delivery');
      $('#q3,#q4').show();
      $('#q2 .type').html('Delivery');
      $('#q5 .type').html('Approximate Delivery');
      $('#q5 .warn').text('Delivery within 30 minutes of chosen time');
      $('.delivery_fee').show();
    } else {
      $('#orderForm').removeClass('delivery');
      $('#q3,#q4').hide();
      $('#q2 .type').html('Pick-Up');
      $('#q5 .type').html('Pick-Up');
      $('#q5 .warn').text('Must pick up no later than 6 p.m.');
      $('.delivery_fee').hide();
    }
    update_times();
    update_cost();
  }
  $.validator.addMethod(
    "requiredDelivery",
    function(value, element) {
      return $('#location_customselect').val() != 'delivery' || (value != '' && value != null);
    },
    ""
  );
  jQuery.validator.addMethod("phoneUS", function(phone_number, element) {
    phone_number = phone_number.replace(/\s+/g, ""); 
    return this.optional(element) || phone_number.length > 9 &&
      phone_number.match(/^(1-?)?(\([2-9]\d{2}\)|[2-9]\d{2})-?[2-9]\d{2}-?\d{4}$/);
  }, "Please specify a valid phone number");
  
  $('#orderForm').validate({
    errorPlacement: 
      function(error,element) {
      },
    invalidHandler: 
      function(form) {
        $("#errorMin").dialog({
          modal: 'true',
          width: 350
        });
      },
    rules: {
      phone: {
        required: true,
        phoneUS: true
      },
      altphone: {
        required: true,
        phoneUS: true
      },
      recipientphone: {
        required: true,
        phoneUS: true
      },
      recipientaltphone: {
        required: true,
        phoneUS: true
      },
      total: {
        required: true,
        min: 6
      }
    },
    errorContainer: $('#errorMin'),
    errorLabelContainer: $('#errorMin ul'),
    wrapper: 'li',
    meta: "validate"
  });
  function update_cost() {
    var total = 0;
    $('#orderForm input.cupcake').each(function() {
      v = parseInt($(this).val());
      if (v > 0) total = total + v;
    });
    $('#total .qty').html(total);
    $('#totalfield').val(total);
    if ($('#location_customselect').val() == 'delivery') {
      delivery = 10.0;
    } else {
      delivery = 0;
    }
    total = (total - Math.floor(total / 12.0)) * 3.00;
    $('#subtotal .amount').html(format_val(total, true, 0));
    $('#delivery_fee .amount').html(format_val(delivery, true, 0));

    platter_cnt = 0
    $('#orderForm input.platter').each(function() {
      v = parseInt($(this).val());
      if (v > 0) {
        platter_cnt = platter_cnt + v;
        $(this).closest('tr').find('td.amount').html(format_val(v * 5.00, true, 0));
      } else {
        $(this).closest('tr').find('td.amount').html('');
      }
    });
    total = total + platter_cnt * 5.00;
    v = parseInt($('#orderForm input.giftbox').val());
    if (v > 0) {
      total = total + v * 1.00;
      $('#orderForm input.giftbox').closest('tr').find('td.amount').html(format_val(v * 1.00, true, 0));
    } else {
      $('#orderForm input.giftbox').closest('tr').find('td.amount').html('');
    }
    $('#estimatefield').val(format_val(total + delivery, true, 0));
    $('#estimated_total').html(format_val(total + delivery, true, 0));
  }
  $('#orderForm table input').change(update_cost).ForceNumericOnly();
  update_cost();
  $('#same').change(function() {
    if ($(this).is(':checked')) {
      $('#recipientname').val($('#name').val()).attr('disabled','disabled');
      $('#recipientphone').val($('#phone').val()).attr('disabled','disabled');
      $('#recipientaltphone').val($('#altphone').val()).attr('disabled','disabled');
    } else {
      $('#recipientname').val('').removeAttr('disabled');
      $('#recipientphone').val('').removeAttr('disabled');
      $('#recipientaltphone').val('').removeAttr('disabled');
    }
  });
  $('#name').change(function() {
    if ($('#same').is(':checked')) {
      $('#recipientname').val($('#name').val());
    }
  });
  $('#phone').change(function() {
    if ($('#same').is(':checked')) {
      $('#recipientphone').val($('#phone').val());
    }
  });
  $('#altphone').change(function() {
    if ($('#same').is(':checked')) {
      $('#recipientaltphone').val($('#altphone').val());
    }
  });
  $('#orderForm .customselect').SelectCustomizer(location_change);
  if ($('#orderForm').length > 0) {
    location_change('#location_customselect');
  }
  $('textarea.has-max').keyup(function() {
    maxlen = parseInt($(this).attr('data-max'));
    if ($(this).val().length > maxlen) {
      $(this).val($(this).val().substr(0,maxlen));
    }
    $(this).closest('dd').find('.text_counter .count').html(maxlen - $(this).val().length);
  });

  $(window).resize(function() {
    $('#lightbox').css({
      width: $('html').width() + 'px',
      height: $('html').height() + 'px',
    });
    w = $('#lbcontent .wrap').width();
    h = $('#lbcontent .wrap').height();
    $('#lbcontent').css({
      width: w + 'px',
      height: h + 'px',
      'margin-left': '-' + Math.round(w / 2) + 'px',
      'margin-top': '-' + Math.round(h / 2) + 'px',
    });
  });
  
  close_lb = function() {
    $('#lbcontent').fadeOut('slow', function() {
      $('#lbcontent').html('');
      $('#lightbox').hide();
    });
    $('#lbcontent .close, #lightbox').unbind('click',close_lb);
  }
  $('#order-page a.lightbox').click(function() {
    $('#lbcontent').html('<a class="close" href="#" onclick="this.blur();"></a><img class="wrap" src="images/' + $(this).attr('data-image') + '" />').show();
    $('#lightbox .bg').css({ width: $(document).width(), height: $(document).height() });
    $('#lightbox').show();
    setTimeout('$(window).resize();', 100);
    $('#lbcontent .close, #lightbox').bind('click',close_lb);
    return false;
  });
  $('#orderForm .horncake .checkbox').click(function() {
    $('#orderForm .horncake .checkbox').not(this).removeAttr("checked");
    return true;
  });

  // locations page
  $('#locationmap area').bind('mouseover',function() {
    var id = $(this).attr('id').replace("area-","loc-");
    if(!($('#'+id).is(':visible'))) {
      $('#location-page .loc').hide();
      $("#"+id).show();
    }
  });

  /*
  location_map_base = $('#location-map').offset();
  $('#locationmap area').bind('mouseout',function(e) {
    coords = $(this).attr('coords').split(',');
    var id = $(this).attr('id').replace("area-","loc-");
    loc_coords = [$('#'+id).offset().left, $('#'+id).offset.left + $('#'+id).width(), $('#'+id).offset().top, $('#'+id).offset.top + $('#'+id).height()]; 
    if (!in_area(e.pageX,e.pageY,location_map_base,coords) && !in_area(e.pageX,e.pageY,location_map_base,loc_coords)) {
      $('#location-page .loc').hide();
    }
  });
  $('#location-page .loc').bind('mouseout',function(e) {
    var id = $(this).attr('id').replace("loc-","area-");
    coords = $('#'+id).attr('coords').split(',');
    this_coords = [$(this).offset().left, $(this).offset.left + $(this).width(), $(this).offset().top, $(this).offset.top + $(this).height()]; 
    if (!in_area(e.pageX,e.pageY,location_map_base,coords) && !in_area(e.pageX,e.pageY,location_map_base,this_coords)) {
      $('#location-page .loc').hide();
    }
  });
  */
  // slideshows
  if ($('#slideshow').length > 0) {
    slide_to = parseInt($('#slideshow').attr('data-timeout'));
    if (isNaN(slide_to) || slide_to < 1000) slide_to = 6000;
    if ($('#holiday_hours').length < 1) {
      setTimeout('next_slide();', slide_to);
    }
    $('#slide-nav a').click(function() {
      clearTimeout(slide_t);
      $('#slideshow .active').stop();
      $('#slideshow .next').removeClass('next');
      next_slide(parseInt($(this).attr('id').replace('slidenav-','')));
      return false;
    });
  }

  /* holiday stuff */
  if ($('#holiday_hours').length > 0) {
    $('#lbcontent').html($('#holiday_overlay').html());
    $('#holiday_hours').load(function() {
      $('#lightbox').fadeIn('fast');
      $(window).resize();
      $('#lbcontent .close, #lightbox').bind('click',close_lb);
      $('#lbcontent .close, #lightbox').bind('click',function() {
        setTimeout('next_slide();', slide_to);
      });
    });
  }

});
var slide_t = null;
var slide_to = null;
var next_slide = function(i) {
  if (i == null) {
    i = (parseInt($('#slideshow .active').attr('id').replace('slide-','')) + 1) % $('#slideshow').children().length;
    if (slide_to == null) slide_to = 6000;
    slide_t = setTimeout('next_slide();', slide_to);
  }
  $('#slide-'+i).addClass('next');
  $('#slide-nav a').removeClass('active');
  $('#slidenav-'+i).addClass('active');
  $('#slideshow .active').fadeOut(600, function() {
    $(this).removeClass('active').show();
    $('#slideshow .next').addClass('active');
    $('#slideshow .next').removeClass('next');
  });
}

