
/*
TGV - Client-side - Booking
*/

namespace('tgv.booking', function(exports) {
  var GetShowtimes, GetShowtimesFlag, bindBookingMovie, bindGetCinemas, bindGetMovies, bindGetSeats, bindGetVista, booking_movie, booking_seat, booking_topnav, checkingOut, countTotal, devModeLocal, devModeTGV, flagOne, initBookingMovie, ipay88, nextStep, prevStep, selection, sessionTimeOut, set_booking_page, tgvHomeURL, tgvPaymentURL, updateCheckout, updateSeats, updateTickets;
  $("a#seat-child-add").live("click", function() {
    var child, childQty, childTix, parent, parentQty, parentTix;
    parent = $(this).attr('parentSeat');
    parentTix = $("#booking_ticketsconfirm").find("tr:[data-ticket-type-id=ticket-" + parent + "]");
    parentQty = parseInt(parentTix.find(".quantity").text());
    child = $(this).attr('childId');
    childTix = $("#booking_ticketsconfirm").find("tr:[data-ticket-type-id=ticket-" + child + "]");
    childQty = parseInt(childTix.find(".quantity").text());
    if (parentQty !== 0) {
      _.once(childTix.find(".quantity").text(childQty + 1));
      _.once(parentTix.find(".quantity").text(parentQty - 1));
      return _.once(countTotal());
    }
  });
  $("a#seat-child-minus").live("click", function() {
    var child, childQty, childTix, parent, parentQty, parentTix;
    parent = $(this).attr('parentSeat');
    parentTix = $("#booking_ticketsconfirm").find("tr:[data-ticket-type-id=ticket-" + parent + "]").eq(0);
    parentQty = parseInt(parentTix.find(".quantity").text());
    child = $(this).attr('childId');
    childTix = $("#booking_ticketsconfirm").find("tr:[data-ticket-type-id=ticket-" + child + "]").eq(0);
    childQty = parseInt(childTix.find(".quantity").text());
    if (childQty !== 0) {
      _.once(childTix.find(".quantity").text(childQty - 1));
      _.once(parentTix.find(".quantity").text(parentQty + 1));
      return _.once(countTotal());
    }
  });
  exports.init = function() {
    booking_movie();
    set_booking_page();
    booking_topnav();
    return $('.next').click(function() {
      return nextStep();
    });
  };
  devModeLocal = false;
  devModeTGV = false;
  if (devModeLocal === true) {
    tgvHomeURL = "http://127.0.0.1:2000/#!/book";
    tgvPaymentURL = "http://127.0.0.1:2000/payment";
  } else if (devModeTGV === true) {
    tgvHomeURL = "http://tgvdev.motionworks.com.my/#!/book";
    tgvPaymentURL = "http://tgvdev.motionworks.com.my/payment";
  } else {
    tgvHomeURL = "http://tgv.com.my/#!/book";
    tgvPaymentURL = "http://202.190.77.108/payment";
  }
  selection = {
    'refNo': '',
    'name': 'Lyana Omar Hakim',
    'email': 'lyana@motionworks.com.my',
    'movie': '',
    'cinema': '',
    'session': '',
    'seats': [],
    'tickets': [],
    'totalPrice': '',
    'bookingFee': 1
  };
  ipay88 = {
    'ProdDesc': 'TGV Cinemas Online Ticket Payment',
    'MerchantCode': 'M03907',
    'MerchantKey': 'xxGbsfb0sd',
    'Currency': 'MYR',
    'Lang': 'UTF-8',
    'Remark': 'You should receive your booking details in your email. If you did not, please check your SPAM folder.',
    'ResponseURL': 'http://tgv.com.my/payment',
    'uri': 'https://www.mobile88.com/ePayment/entry.asp'
  };
  booking_topnav = function() {
    return $('#booking_progress a').click(function() {
      var current, href, id;
      href = $(this).attr('href');
      current = $('#booking>section:visible');
      if ($(href).index() < current.index()) {
        $(href).show().siblings('section').hide();
        id = href.substr(1);
        switch (id) {
          case 'booking_movie':
            $('#booking_progress').removeClass().addClass('step1');
            $('#booking_movie .loading').removeClass('loading');
            return booking_movie();
          case 'booking_seat':
            $('#booking_progress').removeClass().addClass('step2');
            return booking_seat();
        }
      }
    });
  };
  nextStep = function() {
    var currSection, nextSectionID;
    currSection = $('#booking>section:visible');
    $(currSection).next('section').show().siblings('section').hide();
    nextSectionID = $(currSection).next('section').attr('id');
    switch (nextSectionID) {
      case 'booking_seat':
        $('#booking_progress').removeClass().addClass('step2');
        return booking_seat();
      case 'booking_login':
        return $('#booking_progress').removeClass().addClass('step3');
      case 'booking_checkout':
        return updateCheckout();
    }
  };
  prevStep = function() {
    var currSection, prevSectionID;
    currSection = $('#booking>section:visible');
    $(currSection).prev('section').show().siblings('section').hide();
    prevSectionID = $(currSection).prev('section').attr('id');
    switch (prevSectionID) {
      case 'booking_movie':
        $('#booking_progress').removeClass().addClass('step1');
        $('#booking_movie .loading').removeClass('loading');
        return booking_movie();
      case 'booking_seat':
        $('#booking_progress').removeClass().addClass('step2');
        return booking_seat();
      case 'booking_login':
        return $('#booking_progress').removeClass().addClass('step3');
      case 'booking_checkout':
        return updateCheckout();
      default:
        $('#booking_progress').removeClass().addClass('step1');
        $('#booking_movie .loading').removeClass('loading');
        return booking_movie();
    }
  };
  $.fn.extend({
    breakText: function() {
      return this.each(function() {
        var newText;
        newText = $(this).text().split("").join("<br/>");
        return $(this).html(newText);
      });
    }
  });
  bindBookingMovie = function() {
    bindGetCinemas();
    bindGetMovies();
    return bindGetSeats();
  };
  initBookingMovie = _.once(bindBookingMovie);
  booking_movie = function() {
    $('#booking_select_session').addClass('loading');
    $("#booking_movie a[data-cinemaid=" + (tgv.user.info.get('cinema')) + "]").parent().addClass('active').prependTo('#booking_select_cinema ul');
    $("#booking_movie a[data-movieid=" + (tgv.user.info.get('movie')) + "]").parent().addClass('active').prependTo('#booking_select_movie ul');
    initBookingMovie();
    $('#booking_select_cinema li.active').trigger('click');
    return $('#booking_select_movie li.active').trigger('click');
  };
  set_booking_page = function() {
    var selected_cinema;
    selected_cinema = tgv.user.info.get('cinema');
    $("#filter_cinema").val(selected_cinema);
    GetShowtimes();
    return $('#booking_select_cinema').addClass('loading');
  };
  GetShowtimesFlag = 0;
  flagOne = false;
  GetShowtimes = function() {
    var cinemaID, movieID;
    if (typeof tgv.user.info.get("cinema") === "undefined") {
      tgv.user.info.set({
        cinema: "KLC",
        movie: $(".featured").attr("id")
      });
    }
    cinemaID = tgv.user.info.get("cinema");
    movieID = tgv.user.info.get("movie");
    if (GetShowtimesFlag !== 1) {
      GetShowtimesFlag = 1;
      $.getJSON("/book/" + cinemaID + "/" + movieID, function(data) {
        if (data != null) {
          tgv.booking.updateCinemas(data.cinemas);
          tgv.booking.updateMovies(data.movies);
          return tgv.booking.updateShowtimes(data.showtimes);
        }
      });
    }
    return $('#booking_select_session').addClass('loading');
  };
  bindGetCinemas = function() {
    return $('#booking_select_movie li').live('click', function(e) {
      $(this).addClass('active').siblings().removeClass('active');
      tgv.user.info.set({
        movie: $('#booking_select_movie .active a').data('movieid')
      });
      GetShowtimes();
      $('#booking_select_cinema').addClass('loading');
      return e.preventDefault();
    });
  };
  bindGetMovies = function() {
    return $('#booking_select_cinema li').live('click', function(e) {
      $(this).addClass('active').siblings().removeClass('active');
      tgv.user.info.set({
        cinema: $('#booking_select_cinema .active a').data('cinemaid')
      });
      GetShowtimes();
      $('#booking_select_movie').addClass('loading');
      $("#filter_cinema").val(tgv.user.info.get("cinema"));
      return e.preventDefault();
    });
  };
  bindGetSeats = function() {
    return $('#booking_select_session a').live('click', function(e) {
      var cinemaID, dataPrice, dataTicketTypeID, date, day, endLoop, price, priceGroup, session, sessionID, ticketTypeID, _i, _len, _ref;
      $('#booking_movie').addClass('loading');
      date = $(this).parents('.day').attr('id');
      day = exports.sessions[date];
      sessionID = $(this).data('sessionid') + '';
      session = _.detect(day, function(s) {
        return s.sessionID === sessionID;
      });
      cinemaID = tgv.user.info.get('cinema');
      $('#booking_seat').html();
      endLoop = false;
      dataTicketTypeID = [];
      dataPrice = [];
      _ref = session.priceGroups;
      for (_i = 0, _len = _ref.length; _i < _len; _i++) {
        priceGroup = _ref[_i];
        ticketTypeID = priceGroup.ticketTypeID;
        price = priceGroup.price;
        $.getJSON("/tickettype/" + ticketTypeID + "/" + cinemaID + "/" + price, function(data) {
          if ((data != null) && endLoop === false) {
            endLoop = true;
            dataTicketTypeID.push(data.ticketTypeID);
            return dataPrice.push(data.price);
          }
        });
      }
      setTimeout(function() {
        return $.ajax({
          url: "/getSeats/" + sessionID + "/" + cinemaID + "/" + dataTicketTypeID[0] + "/" + dataPrice[0],
          async: true,
          cache: true,
          success: function(data) {
            return updateSeats(data);
          }
        });
      }, 1000);
      tgv.user.info.set({
        sessionID: sessionID
      });
      return e.preventDefault();
    });
  };
  bindGetVista = function() {
    return $('#booking_select_session a').live('click', function(e) {
      var cinemaID, date, day, session, sessionID;
      $('#booking_movie').addClass('loading');
      date = $(this).parents('.day').attr('id');
      day = exports.sessions[date];
      sessionID = $(this).data('sessionid') + '';
      session = _.detect(day, function(s) {
        return s.sessionID === sessionID;
      });
      tgv.user.info.set({
        sessionID: sessionID
      });
      cinemaID = tgv.user.info.get('cinema');
      sessionID = tgv.user.info.get('sessionID');
      $('#booking_movie').removeClass('loading');
      nextStep();
      return e.preventDefault();
    });
  };
  countTotal = function() {
    var bookingFee, totalPrice;
    bookingFee = $("td:[id=bookingFeeFixed]").attr("booking-fee");
    totalPrice = 0 + parseInt(bookingFee);
    $("#booking_ticketsconfirm .subtotal .amount").each(function(i) {
      var name, price, quantity, sibling, ticket;
      sibling = $(this).parent().siblings();
      price = parseInt(sibling.find(".price").text().substring(3));
      quantity = parseInt(sibling.find(".quantity").text());
      name = sibling.find(".label").text();
      $(this).text('RM ' + (price * quantity).toFixed(2));
      if (quantity !== 0) {
        ticket = {
          'name': name,
          'quantity': quantity,
          'subtotal': price * quantity
        };
        selection.tickets.push(ticket);
      }
      return _.once(totalPrice += price * quantity);
    });
    selection.totalPrice = totalPrice;
    return $('span:[class=totalPrice]').text('RM ' + totalPrice.toFixed(2));
  };
  booking_seat = function() {
    $('.wall, .aisle.vert').breakText();
    window.location.replace("/#");
    selection.tickets.length = 0;
    selection.seats.length = 0;
    _.once(countTotal());
    $('#seats_chart td').click(function() {
      var areaCat, attr, attrRow, child, childNum, childOne, childTix, colLeft, colRight, leftHasSelected, num, parentId, parentRaw, rightHasSelected, seat, seatCol, seatLeft, seatRight, seatRow, ticketType, valid;
      if (!$(this).hasClass('unavailable')) {
        seat = $.trim($(this).siblings('.rowLabel').text()) + $.trim($(this).text());
        areaCat = $(this).attr('area-cat');
        ticketType = $("#booking_ticketsconfirm").find("tr[id=" + areaCat + "]").eq(0);
        num = parseInt(ticketType.find(".quantity").text());
        parentRaw = $("#booking_ticketsconfirm").find("tr[id=" + areaCat + "]").attr("data-ticket-type-id");
        parentId = parentRaw.split("-");
        childOne = $("a:[parentSeat=" + parentId[1] + "][class=add]");
        childTix = childOne.attr("childId");
        child = $("#booking_ticketsconfirm").find("tr[data-ticket-type-id=ticket-" + childTix + "]").eq(0);
        childNum = parseInt(child.find(".quantity").text());
        if ($(this).hasClass('selected') || $(this).hasClass("selected-left") || $(this).hasClass("selected-right")) {
          attr = $(this).attr("twinIdOne");
          attrRow = $(this).attr("data-row");
          valid = false;
          if (typeof attr !== "undefined" && attr !== false) {
            if (parseInt(attr) > parseInt($(this).attr("twinIdTwo"))) {
              $(this).removeClass("selected-right");
              $("td:[twinIdTwo=" + attr + "][data-row=" + attrRow + "]").removeClass("selected-left");
              valid = true;
            } else {
              $(this).removeClass("selected-left");
              $("td:[twinIdTwo=" + attr + "][data-row=" + attrRow + "]").removeClass("selected-right");
              valid = true;
            }
          } else {
            seatRow = $(this).attr("data-row");
            seatCol = $(this).attr("data-column");
            seatRight = parseInt(seatCol) + 1;
            seatLeft = parseInt(seatCol) - 1;
            if (num > 0 && $("td:[data-row=" + seatRow + "]").hasClass("selected")) {
              if (!$("td:[data-row=" + seatRow + "][data-column=" + seatRight + "]").hasClass("selected") || !$("td:[data-row=" + seatRow + "][data-column=" + seatLeft + "]").hasClass("selected")) {
                $(this).removeClass('selected');
                valid = true;
              }
            } else {
              $(this).removeClass('selected');
              valid = true;
            }
          }
          if (valid === true) {
            if (childNum > 0) {
              _.once(child.find(".quantity").text(childNum - 1));
            } else {
              _.once(ticketType.find(".quantity").text(num - 1));
            }
            return _.once(countTotal());
          } else {
            return alert("Please do not leave a single seat empty between your selection.");
          }
        } else {
          attr = $(this).attr("twinIdOne");
          attrRow = $(this).attr("data-row");
          valid = false;
          if (typeof attr !== "undefined" && attr !== false) {
            if (parseInt(attr) > parseInt($(this).attr("twinIdTwo"))) {
              $(this).addClass("selected-right");
              $("td:[twinIdTwo=" + attr + "][data-row=" + attrRow + "]").addClass("selected-left");
              valid = true;
            } else {
              $(this).addClass("selected-left");
              $("td:[twinIdTwo=" + attr + "][data-row=" + attrRow + "]").addClass("selected-right");
              valid = true;
            }
          } else {
            seatRow = $(this).attr("data-row");
            seatCol = $(this).attr("data-column");
            seatRight = parseInt(seatCol) + 1;
            seatLeft = parseInt(seatCol) - 1;
            rightHasSelected = $("td:[data-row=" + seatRow + "][data-column=" + (seatRight + 1) + "]").hasClass("selected");
            leftHasSelected = $("td:[data-row=" + seatRow + "][data-column=" + (seatLeft - 1) + "]").hasClass("selected");
            colRight = parseInt($("td:[data-row=" + seatRow + "][data-column=" + seatRight + "]").attr("data-column"));
            colLeft = parseInt($("td:[data-row=" + seatRow + "][data-column=" + seatLeft + "]").attr("data-column"));
            if (num > 0 && $("td:[data-row=" + seatRow + "]").hasClass("selected")) {
              if ($("td:[data-row=" + seatRow + "][data-column=" + seatRight + "]").hasClass("selected") || $("td:[data-row=" + seatRow + "][data-column=" + seatLeft + "]").hasClass("selected")) {
                if ($("td:[data-row=" + seatRow + "][data-column=" + seatLeft + "]").hasClass("selected") && rightHasSelected) {
                  valid = false;
                } else if ($("td:[data-row=" + seatRow + "][data-column=" + seatRight + "]").hasClass("selected") && leftHasSelected) {
                  valid = false;
                } else {
                  $(this).addClass('selected');
                  valid = true;
                }
              } else if (rightHasSelected || leftHasSelected) {
                if (isNaN(colRight) === false && isNaN(colLeft) === true && rightHasSelected === false || isNaN(colRight) === true && isNaN(colLeft) === false && leftHasSelected === false) {
                  $(this).addClass('selected');
                  valid = true;
                } else {
                  valid = false;
                }
              } else {
                $(this).addClass('selected');
                valid = true;
              }
            } else {
              $(this).addClass('selected');
              valid = true;
            }
          }
          if (valid === true) {
            _.once(selection.seats.push(seat));
            _.once(ticketType.find(".quantity").text(num + 1));
            return _.once(countTotal());
          } else {
            return alert("Please do not leave a single seat empty between your selection.");
          }
        }
      }
    });
    return $("a#navBookingMovie").live("click", function() {
      window.location.replace("/#!/book");
      return false;
    });
  };
  updateCheckout = function() {
    var appendList, grandTotal, randNum;
    $('#booking_progress').removeClass().addClass('step3');
    randNum = Math.random();
    selection.refNo = randNum.toFixed(6) * 1000000;
    grandTotal = parseInt(selection.totalPrice) + parseInt(selection.bookingFee);
    $('dd.refNo').text(selection.refNo);
    $('dd.cinema').text(selection.cinema);
    $('dd.email').text(selection.email);
    $('dd.movie').text(selection.movie);
    $('dd.name').text(selection.name);
    $('dd.seats').text(selection.seats.join(", "));
    $('dd.session').text(selection.session);
    $('dd.bookingfee').text("RM 1.00");
    $('dd.totalPrice').text("RM " + grandTotal + ".00");
    $('#MerchantCode').val(ipay88.MerchantCode);
    $('#MerchantKey').val(ipay88.MerchantKey);
    $('#RefNo').val(selection.refNo);
    $('#Amount').val(grandTotal + ".00");
    $('#totalPrice').val(grandTotal + "00");
    $('#Currency').val(ipay88.Currency);
    $('#ProdDesc').val(ipay88.ProdDesc);
    $('#Remark').val(ipay88.Remark);
    $('#Lang').val(ipay88.Lang);
    $('#ResponseURL').val(ipay88.ResponseURL);
    $('#UserSessionId').val(tgv.user.info.get('UserSessionId'));
    $('dd.tickets').html('<ul></ul>');
    appendList = function(item, elem) {
      var amount, name, subtotal;
      name = item.name;
      amount = item.quantity;
      subtotal = item.subtotal;
      return $(elem).find('ul').append("<li>" + amount + " x " + name + " (RM " + subtotal + ".00)</li>");
    };
    appendList(_.last(selection.tickets), 'dd.tickets');
    return $('#booking_btn_purchasenow').click(function() {
      if (selection.totalPrice !== '0') return nextStep();
    });
  };
  checkingOut = function(res) {
    if (res === "seat-taken") {
      alert("Sorry, the seat you selected has already been taken. Please try again.");
      return window.location.replace("/#!/book");
    } else if (res === "unavailable") {
      alert("Sorry, something went wrong; please try again.");
      return window.location.replace("/#!/book");
    } else {
      $("#booking_checkout").append('<form method="post" name="ePayment" action="https://www.mobile88.com/ePayment/entry.asp">\
        <input type="hidden"name="MerchantCode" value="' + res.iPay88.MerchantCode + '" />\
        <input type="hidden" name="PaymentId" value="' + res.userInfo.paymentType + '" />\
        <input type="hidden" name="RefNo" value="' + res.iPay88.RefNo + '" />\
        <input type="hidden" name="Amount" value="' + res.iPay88.totalPrice + '" />\
        <input type="hidden" name="Currency" value="' + res.iPay88.Currency + '" />\
        <input type="hidden" name="ProdDesc" value="' + res.iPay88.ProdDesc + '" />\
        <input type="hidden" name="UserSessionId" value="' + res.sessionId + '" />\
        <input type="hidden" name="UserName" value="' + res.userInfo.name + '" />\
        <input type="hidden" name="UserEmail" value="' + res.userInfo.email + '" />\
        <input type="hidden" name="UserContact" value="' + res.userInfo.phone + '" />\
        <input type="hidden" name="Remark" value="' + res.iPay88.Remark + '" />\
        <input type="hidden" name="Lang" value="' + res.iPay88.Lang + '" />\
        <input type="hidden" name="Signature" value="' + res.signature + '" />\
        <input type="hidden" name="ResponseURL" value="' + tgvPaymentURL + '" />\
        <input type="hidden" name="BackendURL" value="http://202.190.77.133/backend_payment" />\
        <input type="submit" value="Proceed with Payment" name="Submit" /></form>');
      return $("form").submit();
    }
  };
  exports.updateCinemas = function(res) {
    var cinema, _i, _len;
    $("#booking_select_cinema li").addClass('no-movie');
    $('#seat_cinemas').empty();
    for (_i = 0, _len = res.length; _i < _len; _i++) {
      cinema = res[_i];
      $("#booking_select_cinema a[data-cinemaid=" + cinema.cinemaID + "]").parent().removeClass('no-movie');
      if (cinema.cinemaID === tgv.user.info.get('cinema')) {
        $('#seat_cinemas').append("<p>" + cinema.cinemaName + "</p>");
      }
    }
    $("#booking a[data-cinemaid=" + (tgv.user.info.get('cinema')) + "]").parent().addClass('active');
    $("#selected-cinema-label").html($("#booking_select_cinema .active a").html());
    $('#booking_select_cinema').removeClass('loading');
    return GetShowtimes();
  };
  exports.updateMovies = function(res) {
    var movie, _i, _len;
    $("#booking_select_movie li").hide();
    $('#seat_movies').empty();
    for (_i = 0, _len = res.length; _i < _len; _i++) {
      movie = res[_i];
      $("#booking_select_movie a[data-movieid=" + movie.movieID + "]").parent().show();
      if (movie.movieID === tgv.user.info.get('movie')) {
        $('#seat_movies').append("<p>" + movie.movieTitle + " (" + movie.rating + ")</p>");
      }
    }
    $("#booking a[data-movieid=" + (tgv.user.info.get('movie')) + "]").parent().addClass('active');
    $("#selected-movie-label").html($("#booking_select_movie .active a").html());
    $('#booking_select_movie').removeClass('loading');
    return GetShowtimes();
  };
  exports.updateShowtimes = function(res) {
    var day, days, getCurrDate, getCurrDay, getCurrTime, getTime, i, newShowDate, noSessionMsg, recDateText, rectifiedText, rmShowtime, s, session, sessions, show, showDay, showDays, showtime, showtimes, t, timeShows, times, unique, _i, _j, _len, _len2, _len3, _len4;
    showtimes = res.showtimes;
    noSessionMsg = 'Oops, seems like there are no sessions for this movie in this cinema. Please choose another cinema or movie.';
    $('#booking_select_session .day').remove();
    if (showtimes === 'unavailable' || _.isEmpty(showtimes)) {
      $('#booking_select_session .section-inner').append("<div class='day'><h3>" + noSessionMsg + "</h3></div>");
    } else {
      exports.sessions = showtimes;
      days = [];
      for (day in showtimes) {
        rectifiedText = day.split(/\-/g);
        newShowDate = "" + rectifiedText[2] + rectifiedText[1] + rectifiedText[0];
        days.push(newShowDate);
      }
      showDays = days.sort();
      unique = function(origArr) {
        var found, newArr, origLen, x, y;
        newArr = [];
        origLen = origArr.length;
        found = void 0;
        x = void 0;
        y = void 0;
        x = 0;
        while (x < origLen) {
          found = undefined;
          y = 0;
          while (y < newArr.length) {
            if (origArr[x] === newArr[y]) {
              found = true;
              break;
            }
            y++;
          }
          if (!found) newArr.push(origArr[x]);
          x++;
        }
        return newArr;
      };
      for (_i = 0, _len = showDays.length; _i < _len; _i++) {
        show = showDays[_i];
        for (day in showtimes) {
          sessions = showtimes[day];
          if (sessions[0] !== void 0) {
            recDateText = day.split(/\-/g);
            showDay = "" + recDateText[2] + recDateText[1] + recDateText[0];
            if (parseInt(show) === parseInt(showDay)) {
              $('#booking_select_session .section-inner').append("                <div class='day' id='" + day + "'>                  <h3>" + day + " (" + sessions[0].dayName + ")</h3>                  <ul></ul>                </div>");
              times = [];
              for (i = 0, _len2 = sessions.length; i < _len2; i++) {
                s = sessions[i];
                times.push(s.time.replace(/\:/, ""));
              }
              timeShows = unique(times.sort());
              for (_j = 0, _len3 = timeShows.length; _j < _len3; _j++) {
                t = timeShows[_j];
                for (i = 0, _len4 = sessions.length; i < _len4; i++) {
                  session = sessions[i];
                  getTime = session.time.replace(/\:/, "");
                  getCurrDate = new Date();
                  getCurrTime = "" + (getCurrDate.getHours()) + (getCurrDate.getMinutes());
                  getCurrDay = "" + (getCurrDate.getDate()) + (getCurrDate.getMonth() + 1) + (getCurrDate.getFullYear());
                  if (getCurrDay === showDay) {
                    if (getTime === t && parseInt(getTime) > parseInt(getCurrTime)) {
                      $("#" + day + " ul").append("                        <li>                          <a data-sessionID='" + session.sessionID + "' href='#'>" + session.time + "</a>                        </li>");
                    }
                  } else {
                    if (getTime === t) {
                      $("#" + day + " ul").append("                        <li>                          <a data-sessionID='" + session.sessionID + "' href='#'>" + session.time + "</a>                        </li>");
                    }
                  }
                }
              }
            }
          }
        }
      }
      $(".day#" + (tgv.user.info.get('date'))).addClass('highlight');
    }
    if (typeof tgv.user.info.get("showtime") !== "undefined") {
      showtime = tgv.user.info.get("showtime");
      $("a:[data-sessionid=" + showtime + "]").trigger("click");
      rmShowtime = void 0;
      tgv.user.info.set({
        showtime: rmShowtime
      });
    }
    $('#booking_select_session').removeClass('loading');
    return GetShowtimesFlag = 0;
  };
  exports.updateAddTickets = function(res) {
    if (res === 'unavailable') {
      window.alert('This show-time is full & no longer available. Please choose another show-time.');
      return $('#booking_movie').removeClass('loading');
    }
  };
  updateSeats = function(res) {
    var layoutPlan, r;
    if (res === 'unavailable') {
      window.alert('This show-time is full & no longer available. Please choose another show-time.');
      return $('#booking_movie').removeClass('loading');
    } else {
      layoutPlan = res.seatMap[0].layoutPlan;
      $('#seat_session').append("<p>" + res.seatMap[0].showDayTime + "</p>");
      tgv.user.info.set({
        UserSessionId: res.seatMap[0].UserSessionId
      });
      r = Backbone.View.prototype.template.render('booking-seats', this, layoutPlan);
      $('#booking_seat_selection').empty().append(r);
      nextStep();
      $('#booking_movie, #booking_seat').removeClass('loading');
      $('section#booking_seat').css("display", "block");
      $('#horiz_container_outer').horizontalScroll();
      $('#timer').countdown({
        until: '+7m',
        format: 'YOWDHMS',
        significant: 2,
        compact: true,
        layout: '{mnn} {sep} {snn} {desc}',
        expiryUrl: tgvHomeURL,
        onExpiry: sessionTimeOut
      });
      return updateTickets(res.tickets);
    }
  };
  sessionTimeOut = function() {
    return alert("Your session has expired.");
  };
  updateTickets = function(res) {
    var r;
    r = Backbone.View.prototype.template.render('booking-tickets', this, res);
    $('#booking_ticket_selection').empty().append(r);
    return $('#booking_btn_checkout').click(function() {
      var addTickets, areaCat, bookingFee, coupleLeft, coupleRight, grandTotal, iPay88, randNum, regexEmail, regexName, regexPhone, seats, tix, totalPrice, userInfo, validation;
      if (validation === true) $('#booking_btn_checkout').css("display", "none");
      totalPrice = $("span.totalPrice").text().split("RM");
      if (parseInt(totalPrice[1]) > 1) {
        window.location.replace("/#");
        regexName = /^[A-Za-z\-\' ]{3,50}$/;
        regexEmail = /^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i;
        regexPhone = /^[0-9]*$/;
        validation = false;
        if ($('#UserName').val() !== "" && $('#UserEmail').val() !== "" && $('#UserContact').val() !== "") {
          if (regexName.test($("#UserName").val()) === false) {
            alert("Name must not contain numbers, symbols or less than 3 characters.");
            validation = false;
          } else if (regexEmail.test($("#UserEmail").val()) === false) {
            alert("Please enter a valid email address");
            validation = false;
          } else if (regexPhone.test($("#UserContact").val()) === false) {
            alert("Contact number must contain numbers only.");
            validation = false;
          } else {
            validation = true;
          }
          if (validation === true) {
            $('#booking_progress').removeClass().addClass('step3');
            $('section#booking_seat').removeClass().addClass("loading").css("display", "block");
            areaCat = $('#seats_chart .selected').attr('area-cat');
            coupleLeft = $('#seats_chart .selected-left').attr('area-cat');
            coupleRight = $('#seats_chart .selected-right').attr('area-cat');
            seats = [];
            bookingFee = $("td:[id=bookingFeeFixed]").attr("booking-fee");
            $('#seats_chart .selected').each(function() {
              var seat;
              seat = {
                areaCatCode: areaCat.substr(5),
                areaNum: $(this).data('areaNum'),
                row: $(this).data('row'),
                column: $(this).data('column')
              };
              return seats.push(seat);
            });
            $('#seats_chart .selected-left').each(function() {
              var seat;
              seat = {
                areaCatCode: coupleLeft.substr(5),
                areaNum: $(this).data('areaNum'),
                row: $(this).data('row'),
                column: $(this).data('column')
              };
              return seats.push(seat);
            });
            $('#seats_chart .selected-right').each(function() {
              var seat;
              seat = {
                areaCatCode: coupleRight.substr(5),
                areaNum: $(this).data('areaNum'),
                row: $(this).data('row'),
                column: $(this).data('column')
              };
              return seats.push(seat);
            });
            tix = [];
            $('#booking_ticketsconfirm .ticketline').each(function() {
              var quantity, tickets;
              quantity = parseInt($(this).find('.quantity').text());
              if (quantity !== 0) {
                tickets = {
                  quantity: quantity,
                  price: $(this).find('.price').text(),
                  ticketTypeId: $(this).data('ticketTypeId').substr(7),
                  description: $(this).find(".label").text()
                };
                return tix.push(tickets);
              }
            });
            randNum = Math.random();
            selection.refNo = Math.ceil(randNum.toFixed(8) * 10000000);
            grandTotal = parseInt(selection.totalPrice);
            iPay88 = {
              MerchantCode: ipay88.MerchantCode,
              MerchantKey: ipay88.MerchantKey,
              RefNo: "" + (tgv.user.info.get('cinema')) + selection.refNo,
              Amount: grandTotal + ".00",
              totalPrice: grandTotal + ".00",
              Currency: ipay88.Currency,
              ProdDesc: ipay88.ProdDesc,
              Remark: ipay88.Remark,
              Lang: ipay88.Lang,
              ResponseURL: ipay88.ResponseURL
            };
            userInfo = {
              name: $('#UserName').val(),
              email: $('#UserEmail').val(),
              phone: $('#UserContact').val(),
              paymentType: $('#PaymentId').val()
            };
            addTickets = {
              userSession: tgv.user.info.get("UserSessionId"),
              cinemaId: tgv.user.info.get('cinema'),
              sessionId: tgv.user.info.get('sessionID'),
              tickets: tix,
              seats: seats,
              iPay88: iPay88,
              userInfo: userInfo,
              bookingFee: bookingFee
            };
            return $.ajax({
              type: "POST",
              url: "/checkingOut",
              data: addTickets,
              success: function(data) {
                return checkingOut(data);
              }
            });
          }
        } else {
          return alert("Please fill in the required information.");
        }
      } else {
        return alert("Please select a seat.");
      }
    });
  };
  exports.updateOrder = function(res) {
    if (res === 'error') {
      window.alert('There seems to be a problem. Please try again.');
      return prevStep();
    } else {
      return nextStep();
    }
  };
  return exports.updateCancel = function(res) {};
});

