var requestedSeats = 0;
var timeRemaining
//var reservation;

$(document).ready(function() {
  if (window.location.pathname == "/") {
    $("#circles").fadeIn(1200, function(){
      $("#name").fadeIn(1000, function(){
        $("#bowl").fadeIn(1200, function(){
          $("#bottom").fadeIn("slow", function(){
    			});
    		});
    	});
    }); 		
  };
  
  loadSiteBehaviors();
  if (window.location.pathname.match(/admin/)) {return;};
  loadReservationBehaviors();
});

function loadSiteBehaviors () {

}

function loadReservationBehaviors () {
  $(".disclaimer #terms_and_conditions").click(function() {
    $(".pay a").toggleClass("disabled");

    if ($(".pay a").hasClass("disabled")) {
      $(".pay a img").attr({src:"/images/paypal-express-checkout-grey.gif"});
    } else {
      $(".pay a img").attr({src:"/images/paypal-express-checkout.gif"});
    }
  });
  
  $(".pay a").click(function(e) {
    if ($(this).hasClass("disabled")) {
      e.stopPropagation();
      return false;
    }
  });
  
  if ($(".disclaimer #terms_and_conditions:checked").length == 0) {
    $(".pay a").addClass("disabled");
    $(".pay a img").attr({src:"/images/paypal-express-checkout-grey.gif"});
  } else {
    $(".pay a").removeClass("disabled");
    $(".pay a img").attr({src:"/images/paypal-express-checkout.gif"});
  }
  
  // form input behaviors
    // number of seats.  If the number of seats requested is larger than available, disable row.
    $("#reservation_seats").change(function(e) {
      var seat_val = parseInt($(this).val(),10);
      requestedSeats = isNaN(seat_val) ? 0 : seat_val;
      
      requestedSeats && $(".seats_required").hide() || $(".seats_required").show();
      updateSeatAvailability();
      updatePricing();
    });

    // change week
    $("#reservation_seating_week").change(function(e) {
      updateNavLinks();

      refreshSeatings();

    });

    // seating table behaviors
    $("#seatings tbody tr").hover(function() {
      if (!$(this).hasClass("disabled")) {
        $(this).addClass("hover");
      };},function() {
      $(this).removeClass("hover");
    });

    // jqueryUI buttons
    //$("#seatings .actions a").button();

    // prev/next navigation links
    $("table#nav_links td a").click(function(e) {
      if ($(this).parent().hasClass("disabled")) {
        e.stopPropagation();
        return false;
      };

      // setup some parameters
      var currentSel = $("#reservation_seating_week option:selected");
      var currentIndex = $("#reservation_seating_week option").index(currentSel);
      var optionsLength = $("#reservation_seating_week option").length;
      var direction = $(this).parent().attr("class") == "prev" && -1 || 1;
      if ((currentIndex + direction) >= 0 && (currentIndex + direction) < optionsLength) {
        $("#reservation_seating_week").attr({selectedIndex:(currentIndex + direction)}).change();
      }

      updateNavLinks();

      return false;
    });

    // reserve now clicked.
    $("table#seatings a.reserve").click(function(e) {
      if ($(this).parents("tr").hasClass("disabled")) { return false;};
      // collect selected day
      var selectedDate = $(this).siblings().val();

      $("#reservation_seating_date").val($.trim(selectedDate));


      // disable this reserve button to prevent double-clicks.
      $(this).parents("tr").addClass("disabled");
      toggleReserveButton($(this).parents("tr")[0], "processing.jpg");

      // post form
      $("form#new_reservation").submit();

      //postReservation();
      return false;
    });

    // initial change events

    $("#reservation_seating_week, #reservation_seats").change();
  
  initReservationTimer();
}

// update the timer live on the page.  Also, cancel reservation if it hits zero and notify user.
function initReservationTimer() {
  timeRemaining = parseInt($("#timer .deadline").text(),10) * 1000;
  setTimeout(updateCountdown, 1000);
}

function updateCountdown() {
  countdown = $("#timer");
  if (countdown.filter(":visible").length) {
    if (0 < timeRemaining) {
      timeRemaining -= 1000;
      $("#timer .label").text(genTimeString(Math.round(timeRemaining/1000)));
      $("#timer .deadline").text(timeRemaining);
      setTimeout(updateCountdown, 1000); // recalc each time, due to possible latency
    } else { // expired
      countdown.addClass("expired");
      //expireReservation();
    }
  }
};


function expireReservation () {
  // inform user
  $("#timer .label").html("Your reservation was not completed in the allotted time and has been cancelled.  <br/>" +
                          "You may <a href='/'> click here</a> to return to the home page or wait 30 seconds to be redirected.");
  
  // block paypal button
  $("#checkout .pay a").css("opacity", ".25");
  $("#checkout .pay a").click(function(e) {
    e.stopPropagation();
    return false;
  });

  // cancel reservation
  //console.log("cancelling");
  setTimeout(function() {
    // override confirm()
    window.confirm = function() {return true;};
    
    $("#checkout td.cancel a").click();
  },5*1000)
  
}

function genTimeString(seconds) {
  var minutes = parseInt(seconds / 60);
  seconds = (seconds % 60);

  var hours = parseInt(minutes / 60);
  minutes = (minutes % 60);

  var text = addZero(minutes) + ":" + addZero(seconds);
  if (hours != "00") {text = hours + ":" + text};
  return "You have " + text + " left to complete your reservation.";
}

function addZero(num) {
  return ((num >= 0) && (num < 10)) ? "0" +num : num + "";
}

function refreshSeatings (force) {
  force = force || false;
  var sel = "#reservation_seating_week";
  
  var start_day = $(sel).val();
  var new_label = $(sel).find("option:selected").attr("text");
  var start_label = new_label.split(" - ")[0];
  var current_date = $.trim($("table#seatings td.date:first").text());
  
  if (!start_day || ((start_label == current_date) && !force)) {return false;};
  $.ajax({
    url: "/weeks/seats_left.json",
    dataType: 'json',
    data: {week: start_day},
    cache: false,
    success: function(data) { refreshSeatingRows(data,new_label);}
  });
}



function updateNavLinks () {
  // should we now disable any links?  first, reset them
  $("table#nav_links td").removeClass("disabled");
  
  var currentWeek = $("#reservation_seating_week").attr("selectedIndex");
  if (currentWeek == 0) { // disable prev
    $("table#nav_links td.prev").addClass("disabled");
  } else if (currentWeek == ($("#reservation_seating_week option").length - 1)) { // disable next
    $("table#nav_links td.next").addClass("disabled");
  }
  
}

function refreshSeatingRows (data,label) {
  //$("#seatings .weeklabel h5").text(label);
  
  $.each(data,function(i,day) {
    var tgt = "#seatings tr#weekday_" + i;

    var dbDate = day[0]
    var resDate = day[1];
    var seats = day[2];
    $(tgt + " #db_date_"+i).val(dbDate);
    $(tgt + " .date").text(resDate);
    $(tgt + " .seats").html(seatImages(seats));
  });
  updateSeatAvailability(); // refresh buttons and disable state
}

function seatImages (seats) {
  if (!$.isArray(seats)) {
    return '<span>' + seats + '</span>';
  } else {
    var seatCode =  '<span>' + seats[0] + '</span>' +
                    '<img class="left" src="/images/seats/' + seats[0] + 'l.png"/>';

    if (seats.length == 2) {
      seatCode +=  '<img class="right" src="/images/seats/' + seats[1] + 'r.png"/>' +
                    '<span>' + seats[1] + '</span>';
    };
    return seatCode; 
  }
}

function updateSeatAvailability () {
  $("#seatings tbody tr").each(function() {
    var seatings = [];
    $(this).find(".seats span").each(function() {
      seatings.push($(this).text());
    });
    availableSeats = 0;
    $.each(seatings,function(i,n) {
      availableSeats += parseInt(n,10);
    });

    if (isNaN(availableSeats)) {availableSeats = -999;};
    if (availableSeats == 0 || requestedSeats == 0 || (availableSeats < requestedSeats)) {
      unavailable = true;
    } else {
      unavailable = false;
    }

    if (unavailable) {
      $(this).addClass("disabled");
      toggleReserveButton(this, "unavailable.jpg", availableSeats);
    } else {
      $(this).removeClass("disabled");
      toggleReserveButton(this, "reserve-now.jpg", availableSeats);
    }
  });
}

// toggle seating row reservation buttons
function toggleReserveButton(row,label, seats) {
  label = label || "unavailable.jpg"; 
  if ($("#reservation_seats").val() == "" && seats != -999 && seats != 0) {
    availMessage = "You must select how many seats you want first."
    label = "select-seats.jpg";
  } else if (label == "unavailable.jpg") {
    availMessage = "No seats available for this date."
  } else {
    availMessage = "Click here to make your reservation."
  }
  $(row).find(".actions a img").attr({src: "/images/" + label, title: availMessage});
  // $(row).find("a.reserve").each(function() {
  //     $(this).qtip({
  //       style: {
  //         name: "light"
  //       },
  //       position: {
  //         type: "fixed",
  //         adjust: { screen: true },
  //         corner: {
  //           tooltip: "bottomMiddle",
  //           target: "topMiddle"
  //         }
  //       },
  //       show: {delay: 500}
  //     });
  //   });
}

// update the pricing table based upon current selections
function updatePricing () {
  $("table#pricing .seats").text(requestedSeats);
  
  // subtotal
  $("table#pricing .off_peak .value").text("$" + (price * parseFloat(requestedSeats)).toFixed(2));
  $("table#pricing .peak .value").text("$"+(peak_price * parseFloat(requestedSeats)).toFixed(2));
  
  
  // tax
  // var taxRate = parseFloat($("table#pricing .tax .label .amount").text());
  // var taxTotal = (subtotal * (taxRate/100));
  // $("table#pricing .tax .value").text("$"+taxTotal.toFixed(2));
  // 
  // var total = (subtotal + taxTotal);
  // $("table#pricing .total .value").text("$" + total.toFixed(2));
}