//= require custom.js

$(function() {
  $("#discount").hide();
  $(".expected_time").hide();
  $('#accepted').hide();
  $('#cancel').hide();
  $(".tbl_customer").hide();
  $(".order_close_cashier").hide();
  $(".order_payment_type").hide();
  $(".accepted_time").hide();
  $(".kitchen_time").hide();
  $(".ready_time").hide();
  $(function() {
    $('.first-1').click();
  });

  customTableClick();

  $(".nav-item").on("click", function(){
   	var type = $(this).attr("data-type");
    $('#accepted').hide();
    $('#cancel').hide();
    $(".tbl_customer").hide();
    $(".order_close_cashier").hide();
    $(".order_btns").show();
    refreshDetailData();
   	if (type == "pending") {
      $(".first-1").click();
   	  $('#accepted').text("ACCEPT");
   	  $('#accepted').attr("data-value","accepted");
   	}else if(type == "processing"){
      $(".second-1").click();
   		$('#accepted').text("SEND TO KITCHEN");
   		$('#accepted').attr("data-value","processed");
   	}else if(type == "delivery"){
      $(".third-1").click();
   		$('#accepted').text("READY TO DELIVERY");
   		$('#accepted').attr("data-value","delivery");
   	}else if(type == "completed"){
      // $('#cancel').hide();
      $(".fourth-1").click();
   		$('#accepted').text("COMPLETE");
   		$('#accepted').attr("data-value","completed");
   	}else if(type == "processed"){
      $(".fifth-1").click();
      $(".order_close_cashier").show();
      $(".order_btns").hide();
      // $('#accepted').hide();
      // $('#cancel').hide();
    }
   	// console.log(type);
  });

  $("#accepted").on("click", function(){
    if($(this).text().trim() == "ACCEPT"){
      $("#status").text($(this).attr("data-value"));
      var requested_time = $("#requested_time").text();
      $("#requested_order_time").text(requested_time);
      $("#waiting_timeModal").modal({show : true, backdrop: false, keyboard : false});
    }else{
      var status    = $(this).attr("data-value");
      var order_id  = $('#order_id').text();
      var callback  = $('#callback_url').text();
      var ref_no    = $('#ref_no').text();
      callback_url(callback,ref_no,order_id,status);
    }
  });

  $("#cancel").on("click", function(){
    var order_status    = $("#order_status").text();
    $("#status").text($(this).attr("data-value"));
    if(order_status!="new" && order_status!= "accepted" && order_status!="send_to_kitchen"){
      $("#AccessCodeModal").modal({show: true, backdrop: false, keyboard: false});
    }else{
      $("#rejected_reasonModal").modal({show: true, backdrop: false, keyboard: false});
    }
  });

  $(".send_status").on("click",function(){
    $("#reject_reasonErr").html("");
    if($('#reject_reason').val() != ""){
      var order_status    = $("#order_status").text();
      var status    = $("#status").text();
      var order_id  = $('#order_id').text();
      var callback  = $('#callback_url').text();
      var ref_no    = $('#ref_no').text();
      var reason    = "";
      var approved_code    = $("#approved_code").text();
      if(order_status == 'ready_to_delivery'){
        reason = "VOID || " + $('#reject_reason').val();
      }else{
        reason = $('#reject_reason').val();
      }
      callback_url(callback,ref_no,order_id,status,"","","",reason,approved_code);
    }else{
      $("#reject_reasonErr").html("This is required field");
    }
  });

  $(".timer_type").on("click",function(){
    if($(this).hasClass("selected-item")){
      $(this).removeClass("selected-item");
    }else{
      $(this).addClass("selected-item");
    }
  });

  $(".time_interval").on("click",function(){
    var type = '';
    if($(".timer_type").hasClass("selected-item")){
      type = 'after';
    }
    var minutes = $(this).attr("data-value");
    // console.log(type);
    // console.log($(this).attr("data-value"));

    var status    = $("#status").text();
    var order_id  = $('#order_id').text();
    var ref_no    = $('#ref_no').text();
    var callback  = $('#callback_url').text();
    // var requested_time = new Date($("#requested_date_time").text());
    // if(type == 'after'){
    //   requested_time.setMinutes(requested_time.getMinutes() + minutes);
    // }else{
    //   requested_time.setMinutes(requested_time.getMinutes() - minutes);
    // }
    // console.log(requested_time);
    callback_url(callback,ref_no,order_id,status,type,minutes);
  });

  $('#order_close_cashier').on('click',function(e){
    e.preventDefault(); // Prevent the href from redirecting directly
    var linkURL = '/origami/shift/ordering/close';
    warnBeforeRedirect(linkURL);
  });

  $(document).on('click','.access_number', function(event){
    if(event.handled !== true) {
      var original_value = $('#access_code').val();
      var input_type = $(this).attr("data-type");

      switch (input_type) {
          case 'num':
            var input_value = $(this).attr("data-value");
            if (original_value){
              $('#access_code').val(original_value + input_value);
            }else{
              $('#access_code').val(original_value + input_value);
            }
            break;
          case 'ok':
            var type = $(this).attr("data-action");
            code = $('#access_code').val();
            check_emp_access_code(code,type)
            break;
          case 'clr':
            $('#access_code').val("");
            break;
      }
      event.handled = true;
    } else {
        return false;
    }
  });


  // $('button[data-dismiss="modal"]').on('click', function(){ $(this).parent().parent().parent().parent().modal('hide'); });

  $(".new_order_close").on("click",function(){
    var code = $(this).attr("data-value");
    $("#"+code+"_doemal_new_order").modal("hide");
  });

  $(".notify_new_close").on("click",function(){
    var code = $(this).attr("data-value");
    $("#"+code+"_notify_new_order").modal("hide");
  });

  $(".notify_order_send_close").on("click",function(){
    var code = $(this).attr("data-value");
    $("#"+code+"_notify_order_send_to_kitchen").modal("hide");
  });

  $(".notify_order_ready_close").on("click",function(){
    var code = $(this).attr("data-value");
    $("#"+code+"_notify_order_ready_to_delivery").modal("hide");
  });

  // $("[data-dismiss='modal']").on('click', function() {
  //     $('body').addClass('modal-open-fix');
  //     if($('body').css("padding-right") == '15px') {
  //         $('body').addClass('modal-open-fix-pad');
  //     }
  //     setTimeout(function() {
  //         if($('body').hasClass('modal-open-fix-pad')) {
  //             $('body').css('padding-right', '15px');
  //         }
  //         $('body').addClass('modal-open').removeClass('modal-open-fix, modal-open-fix-pad');
  //     }, 1000);
  // });

  //print pdf function
  $("#print_receipt_pdf").on('click touchstart', function(event){
    $(this).off("click touchstart touchend");
    print_receipt();
  });

  $(".btn_pdf_close").on('click',function(){
    window.location.href = '/origami/order_reservation';
  });
});

function warnBeforeRedirect(linkURL) {
  swal({
    title: "Alert!",
    text: "Are you sure you want to close cashier?",
    type: "warning",
    showCancelButton: true
  }, function() {
    // Redirect the user
    window.location.href = linkURL;
  });
}

function check_emp_access_code(access_code,type) {
    var url = "/origami/check_emp_access_code/" + access_code ;
    $.ajax({
        type: 'POST',
        url: url,
        data: {},
        success: function (result) {
          // console.log(result)
           if (result.status == true) {
            // createAccessCode(code);
            $("#approved_code").text(code);
            $('#AccessCodeModal').modal('hide');
            $("#rejected_reasonModal").modal({show: true, backdrop: false, keyboard: false});
           }else{
             swal("Opps",result.message,"warning")
           }
        }
    });
}

function customTableClick(){
  $(".custom-table .custom-tr").on("click", function(){
    $(".custom-tr").removeClass("tr-active");
    $(this).addClass("tr-active");
    var order_id  = $(this).attr("data-id");
    var sr_no = $(this).attr("data-sr-no");
    var url       = "order_reservation/get_order/"+order_id;
    show_order_detail(url,sr_no);
  });
}

function refreshDetailData(){
  $("#ref_no").text("");
  $("#callback_url").text("");
  $("#order_id").text("");
  $("#status").text("");

  $('#requested_date_time').text("");
  $("#sr_number").text("");
  $("#delivery_info").text("");
  $("#contact_info").text("");
  $("#invoice_no").text("");
  $('.summary-items').html("");
  $('#sub_total').text("0.00");
  $('#delivery_fee').text("0.00");
  $('#total_charges').text("0.00");
  $('#discount_amount').text("0.00");
  $('#total_tax').text("0.00");
  $('#grand_total').text("0.00");
  $(".tbl_customer").hide();
  $(".order_close_cashier").hide();
  $(".order_payment_type").hide();
  $("#payment_type").text("");
}

//show order list
function show_order_detail(url,sr_no){
  // $('.summary-items').html("");
  //Start Ajax
  $.ajax({
    type: "GET",
    url: url,
    data: {},
    dataType: "json",
    success: function(data) {
      var scrollTo = document.getElementById('div_card_order');
      $("HTML, body").animate({scrollTop: scrollTo.offsetTop - 60 }, 500 );
      // console.log(data);
      $("#order_remark").text("");
      $(".tbl_customer").show();
      if(data.status != "delivered"){
       $('#accepted').show();
       if(data.status != "ready_to_delivery" && data.status != "send_to_kitchen"){
          $('#cancel').show();
       }
      }else{
       $('#accepted').hide();
       $('#cancel').hide();
      }
      var delivery = data["delivery"];
      var items    = data["order_items"];
      var item_list = $('.summary-items');
      var action_times = "";
      $("#accepted_time").html("");
      $("#send_kitchen_time").html("");
      $("#ready_delivery_time").html("");
      if((data["action_times"]!=undefined) && (data["action_times"]!=null)){
        action_times = JSON.parse(data["action_times"]);
        if((action_times.accepted_time!=undefined) && (action_times.accepted_time!="")){
          $(".accepted_time").show();
          var acceptedDate = new Date(action_times.accepted_time);
          var acceptedTime = timeFormat(acceptedDate);
          var accepted_time = getOrderMonth(acceptedDate.getMonth()) +' '+ (acceptedDate.getDate() >= 10? acceptedDate.getDate() : '0' + acceptedDate.getDate()) +', '+acceptedDate.getFullYear()+'('+getOrderDay(acceptedDate.getDay())+')'+' '+acceptedTime;
          $("#accepted_time").html(accepted_time);
        }
        if((action_times.kitchen_time!=undefined) && (action_times.kitchen_time!="")){
          $(".kitchen_time").show();
          var kitchenDate = new Date(action_times.kitchen_time);
          var kitchenTime = timeFormat(kitchenDate);
          var kitchen_time = getOrderMonth(kitchenDate.getMonth()) +' '+ (kitchenDate.getDate() >= 10? kitchenDate.getDate() : '0' + kitchenDate.getDate()) +', '+kitchenDate.getFullYear()+'('+getOrderDay(kitchenDate.getDay())+')'+' '+kitchenTime;
          $("#send_kitchen_time").html(kitchen_time);
        }

        if((action_times.ready_time!=undefined) && (action_times.ready_time!="")){
          $(".ready_time").show();
          var readyDate = new Date(action_times.ready_time);
          var readyTime = timeFormat(readyDate);
          var ready_time = getOrderMonth(readyDate.getMonth()) +' '+ (readyDate.getDate() >= 10? readyDate.getDate() : '0' + readyDate.getDate()) +', '+readyDate.getFullYear()+'('+getOrderDay(readyDate.getDay())+')'+' '+readyTime;
          $("#ready_delivery_time").html(ready_time);
        }
      }

      var newDate = new Date(data.requested_time);
      var time = timeFormat(newDate);
      // var requested_date = newDate.getFullYear() + '-' + (newDate.getMonth() >= 10? newDate.getMonth() : '0' + (newDate.getMonth() + 1)) +'-'+ (newDate.getDate() >= 10? newDate.getDate() : '0' + newDate.getDate()) +' '+time;
      var requested_date = getOrderMonth(newDate.getMonth()) +' '+ (newDate.getDate() >= 10? newDate.getDate() : '0' + newDate.getDate()) +', '+newDate.getFullYear()+'('+getOrderDay(newDate.getDay())+')'+' '+time;

      if((data.expected_waiting_time!=undefined) && (data.expected_waiting_time!=null)){
        // var expDate = new Date(data.expected_waiting_time);
        // var exptime = timeFormat(expDate);
        // var expected_time = expDate.getFullYear() + '-' + (expDate.getMonth() >= 10? expDate.getMonth() : '0' + (expDate.getMonth() + 1)) +'-'+ (expDate.getDate() >= 10? expDate.getDate() : '0' + expDate.getDate()) +' '+exptime;
        $('.expected_time').show();
        $('#expected_time').text(data.expected_waiting_time? data.expected_waiting_time : '');
      }else{
        $('.expected_time').hide();
        $('#expected_time').text('');
      }

      if((data.pickup_time!=undefined) && (data.pickup_time!=null)){
        var newPickupDate = new Date(data.pickup_time);
        var pickup_time = timeFormat(newPickupDate);
        var pickup_datetime = getOrderMonth(newPickupDate.getMonth()) +' '+ (newPickupDate.getDate() >= 10? newPickupDate.getDate() : '0' + newPickupDate.getDate()) +', '+newPickupDate.getFullYear()+'('+getOrderDay(newPickupDate.getDay())+')'+' '+pickup_time;

        $('.pickup-time').show();
        $('#pickup_time').text(pickup_datetime? pickup_datetime : '');
      }else{
        $('.pickup-time').hide();
        $('#pickup_time').text('');
      }

      item_list.empty();

      if(items!=undefined && items!=""){
        if(items.length > 0){
          for(var i in items) {
            var item_price = 0;
            if(items[i].price > 0){
              item_price = items[i].price;
            }else{
              item_price = items[i].unit_price;
            }
            var total = items[i].qty * item_price;
             var check_mobile =document.getElementsByName("summary_items_mobile")[0].value;
            if (check_mobile == "true"){
                if(items[i].options!='[]' && items[i].options!="" && items[i].options!=null){
                row =
                '<tr>'
                   +'<td width ="70%" class="body-td align-left">'+items[i].item_name
                    +' <br>'
                    +' <i><span class="font-12">'+items[i].options+'</span></i></td>'+
                    '<td><span class="font-13">'+items[i].qty+ '</span>'
                  +'</td>'
                  +'<td width ="30%" class="body-td align-right">'+ total +'</td>'
                +'</tr>';
              }else{
                row = '<tr>'
                   +'<td width ="70%" class="body-td align-left">'+items[i].item_name
                    +' </td>'+
                    '<td><span class="font-13">'+items[i].qty+ '</span></td>'
                  +'<td width ="30%" class="body-td align-right">'+ total +'</td>'
                +'</tr>';
              }
            }
            else{
              if(items[i].options!='[]' && items[i].options!="" && items[i].options!=null){
                row = '<tr>'
                   +'<td width ="70%" class="body-td align-left">'+items[i].item_name
                    +' <br>'
                    +' <i><span class="font-12">'+items[i].options+'</span></i><br>'+
                    '<span class="font-13">'+items[i].qty+ '<span class="col-blue"> <b>X</b>'+items[i].unit_price+'</span></span>'
                  +'</td>'
                  +'<td width ="30%" class="body-td align-right">'+ total +'</td>'
                +'</tr>';
              }else{
                row = '<tr>'
                   +'<td width ="70%" class="body-td align-left">'+items[i].item_name
                    +' <br>'+
                    '<span class="font-13">'+items[i].qty+ '<span class="col-blue"> <b>X</b>'+items[i].unit_price+'</span></span>'
                  +'</td>'
                  +'<td width ="30%" class="body-td align-right">'+ total +'</td>'
                +'</tr>';
              }
            }



            $('.summary-items').append(row);
          }

          if(data.discount_amount > 0){
            $("#discount").show();
          }

          //customer info detail
          // $('#requested_date_time').text(requested_date);
          $('#sub_total').text(data.total_amount);
          $('#delivery_fee').text((parseFloat(delivery.delivery_fee) > 0)? delivery.delivery_fee : '0.0');
          $('#total_charges').text((parseFloat(data.convenience_charge) > 0)? data.convenience_charge : '0.0');
          $('#discount_amount').text((parseFloat(data.discount_amount) > 0)? data.discount_amount : '0.0');
          $('#total_tax').text(data.total_tax);
          $('#grand_total').text(data.grand_total);

          var address = delivery.address;
          if(delivery.township != null && delivery.township!=""){
            address += ', ' +delivery.township;
          }else if(delivery.direction_address!=null && delivery.direction_address!=""){
            address += ", (" +delivery.direction_address+")";
          }
          $('#requested_time').text(requested_date);
          $('#customer_name').text(data.customer_name);
          $('#phone').text(data.phone);
          $('#address').text(address);

          $(".order_payment_type").show();
          if(data.payment_type == "cash_on_delivery"){
            $("#payment_type").text("COD");
          }else if(data.payment_type == "dinga"){
            $("#payment_type").text("DINGA");
          }

          $('#ref_no').text(data.transaction_ref);
          $('#callback_url').text(data.callback_url);
          $('#order_id').text(data.order_reservation_id);

          $("#trans_ref").text(data.transaction_ref);
          if(delivery.provider == "food2u" || delivery.provider == "yangondoor2door"){
            $("#delivery_info").text("(DELIVERY)");
            $("#delivery_to").text("DELIVERY");
          }else if(delivery.provider == "pick_up"){
            $("#delivery_info").text("(PICK-UP)");
            $("#delivery_to").text("PICK-UP");
          }else if(delivery.provider == "turbo"){
            $("#delivery_info").text("(TURBO)");
            $("#delivery_to").text("TURBO");
          }else{
            $("#delivery_info").text("(DIRECT DELIVERY)");
            $("#delivery_to").text("DIRECT DELIVERY");
          }

          if(data.order_remark!=null && data.order_remark!=""){
            $("#order_remark").text(data.order_remark);
          }else if(data.reservation_remark!=null && data.reservation_remark!=""){
            $("#order_remark").text(data.reservation_remark);
          }

          if(data.remark!=null && data.remark!=""){
            var doemal_remark = data.remark.split("||");
            var remark = doemal_remark[0] +", "+ doemal_remark[1];
            $("#remark").text(remark);
          }else{
            $("#remark").text("");
          }

          //no and order id info
          $("#sr_number").text("NO."+sr_no);
          $("#order_status").text(data.status);
          if (data["receipt_no"]) {
            $("#invoice_no").text(data["receipt_no"]);
          }else{
            $("#invoice_no").text(data["order_reservation_id"]);
          }

        }
      }
    }
  });
  //end Ajax
}


function callback_url(callback,ref_no,order_id,status,min_type,time,exptime,reason,approved_code){
  var url       = 'order_reservation/update';
  var post_url = "order_reservation/send_status";
  var waiting_time = "";
  var expected_time = "";
  var type = "";
  var reject_reason = "";
  var access_code = "";
  if(time!=undefined && time!=""){
    waiting_time = time;
  }
  if(exptime!=undefined && exptime!=""){
    expected_time = exptime;
  }
  if(min_type!=undefined && min_type!=""){
    type = min_type;
  }
  if(reason!=undefined && reason!=""){
    reject_reason = reason;
  }
  if(approved_code!=undefined && approved_code!=""){
    access_code = approved_code;
  }

  // $.ajax({
  //   type: "POST",
  //   url: post_url,
  //   data: {url: callback, ref_no: ref_no, status: status, waiting_time: waiting_time, min_type: type, reason: reject_reason},
  //   dataType: "json",
  //   success: function(data) {
      // if(data.status){
        $.ajax({
          type: "POST",
          url: url,
          data: {order_id: order_id, ref_no: ref_no, status: status, min_type: min_type, expected_time: waiting_time, remark: reason, access_code: access_code},
          dataType: "json",
          success: function(data) {
            console.log(data);
            if (data.status) {
              if(status != "completed"){
                swal({
                  title: 'Information',
                  text: "Order has been "+data.message,
                  type: 'success',
                  html: true,
                  closeOnConfirm: false,
                  closeOnCancel: false,
                  allowOutsideClick: false
                }, function () {
                  window.location.href = '/origami/order_reservation';
                });
              }else{
                if((data.filepath != undefined) && (data.filepath != "")){
                  //PDF lightbox data
                  var pdfPath = "/en/pdfjs/minimal?file=" + data.filepath.substring(6);
                  $("#sale_id").val(data.sale_id);
                  $("#sale_receipt_no").val(data.receipt_no);
                  $("#filename").val(data.filepath);
                  $("#printer_name").val(data.printer_name);
                  $("#receipt_pdf").attr("src", pdfPath);

                  $("#receiptpdfModal").modal({show : true, backdrop : false, keyboard : false});
                  $("#receiptpdfModalLabel").text("Receipt: " + data.receipt_no);
                }else{
                  swal({
                    title: 'Information',
                    text: "Order has been "+data.message,
                    type: 'success',
                    html: true,
                    closeOnConfirm: false,
                    closeOnCancel: false,
                    allowOutsideClick: false
                  }, function () {
                    window.location.href = '/origami/order_reservation';
                  });
                }
              }
            }else{
              swal({
                title: 'Oops',
                text: data.message,
                type: 'error',
                html: true,
                closeOnConfirm: false,
                closeOnCancel: false,
                allowOutsideClick: false
              }, function (isConfirm) {
                if(isConfirm){
                  window.location.href = '/origami/order_reservation';
                }
              });
            }
          }
        });
    //   }else{
    //     swal({
    //       title: 'Oops',
    //       text: data.message,
    //       type: 'error',
    //       html: true,
    //       closeOnConfirm: false,
    //       closeOnCancel: false,
    //       allowOutsideClick: false
    //     }, function () {
    //       window.location.href = '/origami/order_reservation';
    //     });
    //   }
    // }
  // });
  if(parseInt(getOnlineOrderCount()) > 0){
      $('.order_no').addClass("order-badge");
      $('.order_no').html(parseInt(getOnlineOrderCount()));
  }
}

function showNewOrderAlert(order_reservation,shop_code){
  if((order_reservation!=undefined) && (order_reservation!=null) && (order_reservation!="")){
    var date = new Date(order_reservation.requested_time);
    var time = timeFormat(date);
    var requested_date = date.getFullYear() + '-' + (date.getMonth() >= 10? (date.getMonth()+1) : '0' + (date.getMonth()+1)) +'-'+ (date.getDate() >= 10? date.getDate() : '0' + date.getDate()) +' '+time;
    $('.first-1').click();

    swal({
      title: 'Information',
      target: document.getElementById(shop_code+"_notify_new_order"),
      text: "You have new order "+
            "<b>"+order_reservation.order_reservation_id+"</b> requested for "+requested_date+"?",
      type: 'success',
      html: true,
      closeOnConfirm: false,
      closeOnCancel: false,
      allowOutsideClick: false
    }, function (isConfirm) {
      if(isConfirm){
        swal.close();
      }
    });
  }
}

function checkNewOrderAlert(shop_code, order_lists){
  swal({
    title: 'Information',
    target: document.getElementById(shop_code+"_notify_new_order"),
    text: "You have new orders <br/>"+
          "Are you accept or reject for these orders <b>"+order_lists+"</b>?",
    type: 'success',
    html: true,
    closeOnConfirm: false,
    closeOnCancel: false,
    allowOutsideClick: false
  }, function (isConfirm) {
    if(isConfirm){
      swal.close();
    }
  });
}

function checkOrderSendToKitchen(shop_code, order_lists){
  swal({
    title: 'Information',
    target: document.getElementById(shop_code+"_notify_order_send_to_kitchen"),
    text: "You have to send order to kitchen <br/>"+
          "Could you send these orders <b>"+order_lists+"</b> to kitchen?",
    type: 'success',
    html: true,
    closeOnConfirm: false,
    closeOnCancel: false,
    allowOutsideClick: false
  }, function (isConfirm) {
    if(isConfirm){
      swal.close();
    }
  });
}

function checkOrderReadyToKitchenAlert(shop_code, order_lists){
  swal({
    title: 'Information',
    target: document.getElementById(shop_code+"_notify_order_ready_to_delivery"),
    text: "You have orders that are ready to deliver <br/>"+
          "Could you ready these orders <b>"+order_lists+"</b> to deliver?",
    type: 'success',
    html: true,
    closeOnConfirm: false,
    closeOnCancel: false,
    allowOutsideClick: false
  }, function (isConfirm) {
    if(isConfirm){
      swal.close();
    }
  });
}

function getOrderMonth(month){
  var MONTHS = ["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sept","Oct","Nov","Dec"];
  return MONTHS[month];
}

function getOrderDay(day){
  var DAYS = ["Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"];
  return DAYS[day - 1];
}

/* start order reservation function */
function timeFormat(date){
  var isPM = date.getHours() >= 12;
  var isMidday = date.getHours() == 12;
  var time = [(date.getHours()>10? date.getHours() : '0'+date.getHours()) - (isPM && !isMidday ? 12 : 0),
          (date.getMinutes()>10? date.getMinutes() : '0'+date.getMinutes()) || '00'].join(':') +
         (isPM ? ' PM' : ' AM');
  return time;
}
/* end order reservation function */

/* online order count*/
function getOnlineOrderCount(){
  var count = 0;
  //Start Ajax
  $.ajax({
    async: false,
    type: "GET",
    url: "/origami/get_order_info",
    dataType: "json",
    success: function(data){
      if(parseInt(data) > 0){
        count = parseInt(data);
      }
    }
  });
  //end Ajax
  // alert(count);
  return count;
}
/* online order count*/

/* pdf print out */
function print_receipt(){
    var sale_id   = $('#sale_id').val();
    var filename = $("#filename").val();
    var printer_name = $("#printer_name").val();
    var receipt_no = $("#sale_receipt_no").val();
    var params = { 'filename':filename, 'receipt_no':receipt_no, 'printer_name':printer_name };
    console.log(params);
    $.ajax({
      type: "POST",
      url: "/origami/sale/"+sale_id+"/doemal_order/payment/print",
      data: params,
      success:function(result){
        if (!$('#print_settings').data('action-cable')) {
          // For Server Print - from jade
          if ($("#server_mode").val() == "cloud") {
            if(typeof code2lab != 'undefined'){
              code2lab.printFile(result.filepath.substr(6), result.printer_url);
            }
            window.location.href = '/origami/order_reservation';
          }
          else{
            swal({
                title: "Print Success",
                text: "Complete Order",
                type: 'success',
                html: true,
                closeOnConfirm: false,
                closeOnCancel: false,
                allowOutsideClick: false
              }, function () {
                  window.location.href = '/origami/order_reservation';
            });
          }
        }
      }
    });
}
/* pdf print out */
