//middle edit
$(function() {
  var role = $('#role').val();
  var second_display_lookup = $("#display_type").val();
  type = window.location.href.indexOf("quick_service") || window.location.href.indexOf("food_court");
  modify_order = window.location.href.indexOf("modify_order");

  //click menu sidebar menu category
  $(".product").on("click", function(){
    var url = $(this).attr('data-ref');
    show_product_list(url);
  });
  //show menu item list when click menu category
  function show_product_list(url_item){

    var menu_list = $('.menu_items_list');
    menu_list.empty();

        if (type != -1 && modify_order != -1) {
          url_item = '../../../../../'+url_item;
        }
        if(modify_order == -1 && type != -1){
          url_item = '../../../../'+url_item;
        }
        if (type ==-1 && modify_order == -1){
          url_item = url_item
        }
    //Start Ajax
    $.ajax({
      type: "GET",
      url: url_item,
      data: {},
      dataType: "json",
      success: function(data) {

        var menu_items_list = $('.menu_items_list');
        menu_items_list.empty();
        product = data;

        for(var field in product) {
          if (product[field].unit_price > 0) {
            qty             = 1;
            options         = [];
            item_attributes = [];

            if (product[field].image_path.url) {
              if (type != -1 && modify_order != -1) {
                image_path = '../../'+product[field].image_path.url;
              }
              if(modify_order == -1 && type != -1){
               image_path = '../../../../'+product[field].image_path.url;
              }
              if (type ==-1 && modify_order == -1){
                image_path = product[field].image_path.url;
              }


            row = '<div class="col-md-6 col-sm-6 col-lg-3 mt-3">'
                  +'<div class="card custom-card testimonial-card fadeInRight" style="height:100%;background-image:url(../../'+image_path+');background-repeat: no-repeat;">'
                   +'<div class="custom-card-head card-head row" style="line-height:14px;margin:0px;" style="">'
                      +'<div class="col-md-10">'+ product[field].name +'</div>'

                     +'</div>'

                  +"<div class='add_icon p-t-65 p-b-65'  data-item-code='"
                        + product[field].item_code +"' data-name='"
                        + product[field].name +"' data-qty = '"+ qty +"' data-price = '"
                        + product[field].unit_price +"' data-instance-code = '"+ product[field].item_code +"' data-instance = '"
                        + product[field].name +"' data-promotion-price = '"+ 1 +"' data-attributes = '"
                        + JSON.stringify(item_attributes) +"' data-options = '"
                          + JSON.stringify(options) +"' data-opt = '"
                          + JSON.stringify(options) +"' data-image='"+image_path+"'>"
                  +'</div>'
                    +'<div class="card-footer custom-card-footer custom-flex-footer">'
                      +'<span style="font-weight:900;flex-grow:1;">'+ product[field].unit_price +'</span>'
                      +"<div class='offset-4 col-2 menu_item_box' data-item-code='"
                          + product[field].item_code +"' data-instance = '"
                          +JSON.stringify(item_attributes)+"' data-id = '"
                          +JSON.stringify(item_attributes)+"' data-item = '"
                          +JSON.stringify(item_attributes)+"' data-option = '"
                          +JSON.stringify(options)+"'data-opt = '"
                          +JSON.stringify(options)+"' data-item-sets = '"
                          +JSON.stringify(item_attributes)+"' data-image='"+image_path+"' data-toggle='modal' data-target='.sx_item_detailModal'>"
                            +"<i class='fa fa-bars material-icons m-l--10'>"
                            +'view_list</i>'
                      +'</div>'
                    +'</div>'

                  +'</div>';
                }
                else
                {
                  row = '<div class="col-md-6 col-sm-6 col-lg-3 mt-1">'
                  +'<div class="card custom-card testimonial-card fadeInRight" style="height:100%;">'
                   +'<div class="custom-card-head custom-card-no-img-head card-head row" style="margin:0px;display:flex;!important">'
                      +"<div class='col-12 add_icon  p-t-65 p-b-65'  data-item-code='"
                        + product[field].item_code +"' data-name='"
                        + product[field].name +"' data-qty = '"+ qty +"' data-price = '"
                        + product[field].unit_price +"' data-instance-code = '"+ product[field].item_code +"' data-instance = '"
                        + product[field].name +"' data-promotion-price = '"+ 1 +"' data-attributes = '"
                        + JSON.stringify(item_attributes) +"' data-options = '"
                          + JSON.stringify(options) +"' data-opt = '"
                          + JSON.stringify(options) +"' data-image=''>"
                    +'<div class="product_box">'+ product[field].name +'</div>'
                    +'</div>'


                     +'</div>'

                  +"<div class='add_icon'  data-item-code='"
                        + product[field].item_code +"' data-name='"
                        + product[field].name +"' data-qty = '"+ qty +"' data-price = '"
                        + product[field].unit_price +"' data-instance-code = '"+ product[field].item_code +"' data-instance = '"
                        + product[field].name +"' data-promotion-price = '"+ 1 +"' data-attributes = '"
                        + JSON.stringify(item_attributes) +"' data-options = '"
                          + JSON.stringify(options) +"' data-opt = '"
                          + JSON.stringify(options) +"' data-image=''>"

                  +'</div>'

                    +'<div class="card-footer custom-card-no-img-footer custom-flex-footer">'
                      +'<span style="font-weight:900;flex-grow:1;">'+ product[field].unit_price +'</span>'
                      +"<div class='offset-4 col-2 menu_item_box menu_item_no_img_box' data-item-code='"
                          + product[field].item_code +"' data-instance = '"
                          +JSON.stringify(item_attributes)+"' data-id = '"
                          +JSON.stringify(item_attributes)+"' data-item = '"
                          +JSON.stringify(item_attributes)+"' data-option = '"
                          +JSON.stringify(options)+"'data-opt = '"
                          +JSON.stringify(options)+"' data-item-sets = '"
                          +JSON.stringify(item_attributes)+"' data-image='' data-toggle='modal' data-target='.sx_item_detailModal'>"
                            +"<i class='fa fa-bars material-icons m-l--10'>"
                            +'view_list</i>'
                      +'</div>'
                    +'</div>'

                  +'</div>';
                }
            $('.menu_items_list').append(row);
          }
        }
      }
    });
    //end Ajax
  }
  //end show list function
  //click menu sidebar menu category
  $(document).on('click', '.menu_category', function(e){
    e.preventDefault();
    $('.sub_category_list').addClass("hidden");
    var menu_id = $(this).attr("data-id");
    var url     = "get_menu_category/"+menu_id;
    show_menu_item_list(url,menu_id);
    var sub_id  = $(this).attr("data-sub-id");
    if (sub_id == "true") {
      var sub_url = "get_menu_sub_category/"+menu_id;
      sub_category = $(this).siblings('.sub_category_list');
      show_sub_category_list(sub_url,sub_category,menu_id);
    }
  });
  //End menu category Click

  //click menu sidebar menu category
  $(document).on('click', '.menu_sub_category', function(event){
  //   event.preventDefault();
  // $(".menu_sub_category").on("click", function(){
    $('.sub_category_list').addClass("hidden");
    var menu_id = $(this).attr("data-id");
    var url     = "get_menu_category/"+menu_id;
    show_menu_item_list(url,menu_id);
  });
  //End menu category Click

  //show menu item list when click menu category
  function show_menu_item_list(url_item,menu_id){
    var menu_list = $('.menu_items_list');
    menu_list.empty();

    menus = JSON.parse(localStorage.getItem("menus"));
    if (menus != null) {
      for(var i in menus) {
        var categories = menus[i]["categories"];
        for(var ii in categories) {
          if (categories[ii]["id"] == menu_id) {
            var menu_items = categories[ii]["items"];
            show_menu_list(menu_items);
          }
        }
      }
    }else{

      type = window.location.href.indexOf("quick_service") || window.location.href.indexOf("food_court");
      modify_order = window.location.href.indexOf("modify_order");

      if (type != -1 && modify_order != -1) {
        url_item = '../../../addorders/'+url_item;
      }if(modify_order == -1 && type != -1){
        url_item = 'addorders/'+url_item;
      }
      if (type ==-1 && modify_order == -1){
        url_item = url_item;
      }

      //Start Ajax
      $.ajax({
        type: "GET",
        url: url_item,
        data: {},
        dataType: "json",
        success: function(data) {
          var menu_items_list = $('.menu_items_list');
          menu_items_list.empty();
          menu_items = data.menu_items;
          show_menu_list(menu_items);
        }
      });
      //end Ajax
    }
  }
  //end show list function
  //click item row for item set
  $(document).on('click', '.set_item_box', function(event){
    $(".instance-list").empty();
    $(".options-list").empty();
    $(".selected-set-list").empty();
    $('.set_change_qty').val(1);
    change_qty_plus_minus("set_count","set_plus","set_minus");
    data =  $(this).parent().children().children('.add_icon');
    // data =  $(this).parent().siblings('.add_icon');
    //instances          = $(this).data('instance');
    item_sets          = $(this).data('item-sets');
    instances          = $(this).data('instances');
    item_options       = $(this).data('options');

    for(var field in item_sets) {

      $('.set_order').attr('data-min-qty',item_sets[field]["min_selectable_qty"]);

      value = item_sets[field]["instances"];

      $(value).each(function(i){
        menus = JSON.parse(localStorage.getItem("menus"));
        if (menus != null) {
          for(var j in menus) {
            var categories = menus[j]["categories"];
            for(var ii in categories) {
              var items = categories[ii]["items"];
              for(var iii in items) {
                var result = items[iii]["instances"];
                for(var v in result) {

                 if (value[i]["id"] == result[v]["id"]) {

                   row = '<div class="col-md-4 " >'
                          +"<div class='card custom-card instance_box' data-name='"+result[v]["name"]
                              +"' data-code='"+result[v]["code"]
                              +"' data-price='"+result[v]["price"]
                              +"' data-option='"+JSON.stringify(items[iii]["options"])
                              +"' data-min-qty='"+item_sets[field]["min_selectable_qty"]
                              +"' data-max-qty='"+item_sets[field]["max_selectable_qty"]
                              +"' data-parent-code='"+instances[0]['code']
                              +"' data-parent-id='"+instances[0]['id']
                              +"' data-sub-item='true"
                              +"'>"
                            +'<div class="custom-card-head card-head" style="line-height:14px;">'
                               +'<span class="">'+result[v]["name"]+'</span>'
                            +'</div>'
                            +'<div class="card-block custom-card-block">'
                              +'<img id="" src="/image/logo.png" height="40px">'
                              +' <small style="float:" id="instance_option"></small>'
                            +'</div>'
                            +'<div class="card-footer custom-card-footer">'
                               +' <span>'+result[v]["price"]+'</span>'
                               // +' <small style="float:right" id="instance_option"></small>'
                            +'</div>'
                          +'</div>'
                        +' </div>'
                    $(".instance-list").append(row);
                 }
                }
              }
            }
          }
        }else{
          type = window.location.href.indexOf("quick_service") || window.location.href.indexOf("food_court");
         modify_order = window.location.href.indexOf("modify_order");
          if (type != -1 && modify_order != -1) {
            url = '../../../addorders/get_item_instance/'+value[i]["id"];
          }
          if(modify_order == -1 && type != -1){
            url = 'addorders/get_item_instance/'+value[i]["id"] ;
          }
          if (type ==-1 && modify_order == -1){
            url   = '../addorders/get_item_instance/'+value[i]["id"];
          }
          $.ajax({
            type: "GET",
              url: url,
              // data: {id:value[i]},
              success:function(result){

                  row = '<div class="col-md-4 " >'
                          +"<div class='card custom-card instance_box' data-name='"+result["name"]
                              +"' data-code='"+result["code"]
                              +"' data-price='"+result["price"]
                              +"' data-option='"+JSON.stringify(result["options"])
                              +"' data-min-qty='"+item_sets[field]["min_selectable_qty"]
                              +"' data-max-qty='"+item_sets[field]["max_selectable_qty"]
                              +"' data-parent-code='"+instances[0]['code']
                              +"' data-parent-id='"+instances[0]['id']
                              +"' data-sub-item='true"
                              +"'>"
                            +'<div class="custom-card-head card-head" style="line-height:14px;">'
                               +'<span class="">'+result["name"]+'</span>'
                            +'</div>'
                            +'<div class="card-block custom-card-block">'
                              +'<img id="" src="/image/logo.png" height="40px">'
                              +' <small style="float:" id="instance_option"></small>'
                            +'</div>'
                            +'<div class="card-footer custom-card-footer">'
                               +' <span>'+result["price"]+'</span>'
                               // +' <small style="float:right" id="instance_option"></small>'
                            +'</div>'
                          +'</div>'
                        +' </div>'

                $(".instance-list").append(row);
              }
          });
        }
      });
    }
    for(var j in item_options) {
      value = item_options[j]["values"];
      type  = item_options[j]["type"];
      row = "<h4>"+type+"</h4>"
      $(value).each(function(i){
        row +="<button class='btn btn- waves-effect check_option_btn "+ type +"' data-type='"
        +type+"' data-value='"+value[i]+"' data-group='set_menu_default'>"+value[i]+"</button>";
      });
      $(".options-list").append(row);
    }
     $('.set-item').attr('data-code',instances[0]['code']);
     $('.set-item').attr('data-name',instances[0]['name']);
     $('.set-item').attr('data-price',instances[0]['price']);
     $('.set-item').attr('data-options','');
     $('.set-item').attr('data-parent',true);

    $('#set_change_qty').val(1);
    $('#set_item_instances').text(instances);
    $('#set_name').text($(this).attr('data-name'));
    $('#set_item_code').text($(this).attr('data-item-code'));
     $('#set_total_price').text($(this).attr('data-price'));
    // $('#set_total_price').text(0);
    $('#set_unit_price').text($(this).attr('data-price'));
    // $('#set_unit_price').text(0);
  });
  // click instance for add item set
  $(document).on('click', '.instance_box', function(event){

      $(".options-list").empty();

      rowCount     = $('.selected-instance');
      setCount     = $('.selected-set');
      item_options = $(this).data('option');

      min_qty      = $(this).data('min-qty');
      max_qty      = $(this).data('max-qty');

      code = $(this).data('code');

      if (rowCount.length+1 <= max_qty) {
        for(var field in item_options) {
            value = item_options[field]["values"];
            type  = item_options[field]["type"];
            row = "<p style='font-size:16px;margin-bottom:3px'>"+type+"</p>"
            $(value).each(function(i){
              row +="<button class='btn btn-default btn-sm check_option_btn"+ type +"' data-type='"
              +type+"' data-value='"+value[i]+"' data-code='"+code+"' data-group='set_menu'>"
              +value[i]+"</button>";
            });
            $(".options-list").append(row);
        }
      }
        // if($(this).hasClass('selected-instance') == true){
        //   sub_total       = $('#set_total_price').text();
        //   name            = $(this).data('name');
        //   price           = $(this).data('price');
        //   // qty             = $('#set_change_qty').val();
        //   qty             = document.getElementById("set_count").value;
        //   total           = qty*price;
        //   var total_price = +sub_total - +total;
        //   $(this).removeClass('selected-instance');
        //   $(".options-list").empty();
        //   $(this).removeAttr('data-options');
        //   $('#instance_option').text('')
        // }else {
          if (setCount.length+1 <= max_qty) {
            sub_total       = $('#set_total_price').text();
            name            = $(this).data('name');
            price           = $(this).data('price');
            options         = $(this).attr('data-options','[]');
            // qty             = $('#set_change_qty').val();
            qty             = document.getElementById("set_count").value;
            total           = qty*price;
            var total_price = +sub_total + +total;
            $(this).addClass('selected-instance');

            set = "<div class='selected-set card custom-card' style='margin-bottom:10px !important'"
                            +"' data-name='"+$(this).data('name')
                            +"' data-code='"+code
                            +"' data-price='"+$(this).data('price')
                            +"' data-option='[]"
                            +"' data-options='"+JSON.stringify($(this).data('options'))
                            +"' data-min-qty='"+$(this).data('min-qty')
                            +"' data-max-qty='"+$(this).data('max-qty')
                            +"' data-parent-code='"+$(this).data('parent-code')
                            +"' data-parent-id='"+$(this).data('parent-id')
                            +"' data-sub-item='true"
                            +"'>"

                          +'<div class="card-block" style="background-color:#54A5AF;">'
                          +' <button type="button" class="close" id="remove_set" style="font-size: 20px;">&times;</button>'
                             +'<span style="color:#fff">'+$(this).data('name')+'</span>'
                          +'</div>'
                          +'<div class="card-block custom-card-block">'

                            +' <small style="float:" id="instance_option"></small>'
                          +'</div>'
                          // +'<div class="card-footer custom-card-footer">'
                          //    +' <span>'+$(this).data('price')+'</span>'
                          //    // +' <small style="float:right" id="instance_option"></small>'
                          // +'</div>'
                        +'</div>'
              $(".selected-set-list").append(set);
          }else{
             swal("Alert !", 'Maximum Select is  ' + max_qty + "  items", "warning");
          }
        // }
        $('#set_unit_price').text(price);
        $('#set_total_price').text(total_price);

  }); //End selecct attribute buttom

  // click add order
  $(document).on('click', '#remove_set', function(event){
    code = $(this).parent().parent('.selected-set').attr('data-code');
     instance    = $(".selected-instance");
       $(instance).each(function(i){
         if ($(instance[i]).attr('data-code')==code){
           $(instance[i]).removeClass("selected-instance")
        }
       });
       $(this).parent().parent('.selected-set').remove();
  });

  // click add order
  $(document).on('click', '.set_order', function(event){
    total_price   = $('#set_total_price').text();
    qty           = parseInt($('#set_count').val());
    item_code     = $('#set_item_code').text();
    item_name     = $('#set_name').text();
    min_qty       = $(this).data('min-qty');

    default_instance = $('.set-item');

    var items  = $('.selected-set');
    if (items.length >= min_qty) {
     if ($('#server_mode').val() != "cloud" && second_display_lookup == 2) {
      item = get_set_item(items);
      customer_display_view(item,"set_add");
     }
      var option = []
      attribute_arr = []

      var rowCount = $('.summary-items tbody tr').length+1;
        code          = $('.set-item').attr('data-code');
        name          = $('.set-item').attr('data-name');
        price         = $('.set-item').attr('data-price');
        option_name   = ($('.set-item').attr('data-options') === 'undefined') ? ' ' :$('.set-item').attr('data-options');
        option        = ($('.set-item').attr('data-options') === '') ? '[]' :$('.set-item').attr('data-options');
        parent        = $('.set-item').attr('data-parent');
        total         = qty * price ;
        row ="<tr class='item_box' data-price ='"
              +price+ "' data-toggle='modal' data-target='#sx_itemModal' 'data-instance ='"
              +name+ "' data-code='"+item_code+"' data-instance-code='"
              +code+"' data-attributes='"
              +attribute_arr+"' data-options ='"
              +option+"' data-row ='"+rowCount+ "' data-parent ='"+parent+ "'>"
          +'<td class="item-cell-no">'+rowCount+'</td>'
          +'<td class="item-cell-name" id="item_name" >' + item_name+ ' ' + name +' ' + option_name +'</td>'
          +'<td class="item-cell-qty" id="item_qty">' + qty + '</td>'
          +'<td class="item-cell-price" id="item_price">'
          + parseFloat(total).toFixed(2)
          +'</td>'
          +'</tr>';
          $(".summary-items tbody").append(row);
      var rowCount = $('.summary-items tbody tr').length+1;
      var set_option = []
      $(items).each(function(i){
        code              = $(items[i]).attr('data-code');
        name              = $(items[i]).attr('data-name');
        price             = $(items[i]).attr('data-price');
        set_option_name   = ($(items[i]).attr('data-options') === 'undefined') ? '' :$(items[i]).attr('data-options');
        set_option        = ($(items[i]).attr('data-options') === 'undefined') ? '[]' :$(items[i]).attr('data-options');
        sub_item          = $(items[i]).attr('data-sub-item');
        total             = qty * price ;

        row ="<tr class='item_box' data-price ='"
              +price+ "' data-toggle='modal' data-target='#sx_itemModal' 'data-instance ='"
              +name+ "' data-code='"+item_code+"' data-instance-code='"
              +code+"' data-attributes='"
              +attribute_arr+"' data-options ='"
              +set_option+"' data-row ='"+rowCount+ "' data-sub-item ='"+sub_item+ "'>"
          +'<td class="item-cell-no">'+rowCount+'</td>'
          +'<td class="item-cell-name" id="item_name" >' + item_name+ ' ' + name +' ' + set_option_name +'</td>'
          +'<td class="item-cell-qty" id="item_qty">' + qty + '</td>'
          +'<td class="item-cell-price" id="item_price">'
          + parseFloat(total).toFixed(2)
          +'</td>'
          +'</tr>';
          $(".summary-items tbody").append(row);
        rowCount = rowCount + 1;
      });

      calculate_sub_total();
      $(".sx_item_set_detailModal").css({ 'display': "none" });
    }else{
      $(".sx_item_set_detailModal").css({ 'display': "block" });
      swal("Alert !", 'Please Select Minimum ' + min_qty + " items", "warning");
     //  $.alert({
     //     title: 'Alert!',
     //     content: 'Please Select Minimum ' + min_qty + " items",
     //     type: 'red',
     //     typeAnimated: true,
     //     btnClass: 'btn-danger',
     // });
    }

  }); //End add order  Click

  //click item row for add order
  $(document).on('click', '.menu_item_box', function(event){
    $('.attributes-list').empty();
    $('.options-list').empty();
    $('#modal_box_img').empty();
    $('.attr-alert').addClass('hide');
    $('.add_to_order').removeAttr('data-instance-code');
    $('.add_to_order').removeAttr('data-instance');
    $('.add_to_order').removeAttr('data-price');
    $('.add_to_order').removeAttr('data-promotion-price');
    $('.add_to_order').removeAttr('data-item-code');
    $('.add_to_order').removeAttr('data-qty');
    $('.add_to_order').removeAttr('data-name');
    $('.add_to_order').removeAttr('data-attributes');
    $('.add_to_order').removeAttr('data-options');

     $('#count').val(1);
    change_qty_plus_minus("count","plus","minus");

    // data =  $(this).parent().children().children('.add_icon');
    data =  $(this).parent().siblings('.add_icon');

    $('#total_price').text(data.attr('data-price'));
    attributes         = $(this).data('id');
    selected_item      = $(this).data('item');
    instances          = $(this).data('instance');
    item_options       = $(this).data('option');

    if (data.attr('data-image')) {
      if (modify_order) {
        image = "<img id='' width='200px' src='../../"+data.attr('data-image')+"'>";
      }else{
        image = "<img id='' width='200px' src='"+data.attr('data-image')+"'>";
      }

    }else{
      if (modify_order) {
        image = "<img id='' width='200px' src='../../image/logo.png'>";
      }else{
        image = "<img id='' width='200px' src='/image/logo.png'>";
      }

    }

    $('#modal_box_img').append(image);

    instance_attributes = []
    for(var field in instances) {
      value = instances[field].values;
      $(value).each(function(i){
         options = value[i];
         instance_attributes.push(options);
        // $.ajax({
        //   type: "GET",
        //   url: '../../api/restaurant/menu_item_attributes/'+value[i],
        //   data: {id:value[i]},
        //   success:function(result){

        //     options = result["name"];
        //     instance_attributes.push(options);
        //   }
        // });
      });
    }

    // selected_arr = []
    // $(selected_item).each(function(i){
    //   $.ajax({
    //     type: "GET",
    //     url: '../../api/restaurant/menu_item_attributes/'+selected_item[i],
    //     data: {id:selected_item[i]},
    //     success:function(result){
    //       name = result["name"];
    //       selected_arr.push(name);
    //     }
    //   });
    // });


    for(var field in attributes) {
      value = attributes[field]["values"];
      type  = attributes[field]["type"]
      row = "<h5>"+attributes[field]["type"]+"</h5>";

      $(value).each(function(i){
        disabled = ""
        status ="";
        if(parseInt(jQuery.inArray(value[i], selected_item)) !== -1){
          status = "selected-attribute";
        }
        if(parseInt(jQuery.inArray(value[i], instance_attributes)) == -1){
          disabled = "disabled";
        }
        row +="<button id='selected-attribute' data-instances='"+JSON.stringify(instances)+"' data-type='"
        +type+"' data-value='"+value[i]+"' class='btn btn- waves-effect attribute_btn "
        + status +" "+ type +" '"+ disabled +" >"
        +value[i]
        +"</button>";
      });
      $(".attributes-list").append(row);
    }

    for(var field in item_options) {
      value = item_options[field]["values"];
      type  = item_options[field]["type"];
      row = "<h4>"+type+"</h4>"
      $(value).each(function(i){
        row +="<button class='btn btn- waves-effect check_option_btn "+ type +"' data-type='"
        +type+"' data-value='"+value[i]+"' data-group='simple_menu'>"+value[i]+"</button>";
      });
      $(".options-list").append(row);
    }

   // $('#count').val(1);
    $('#item_instances').text(instances);
    $('#title_name').text(data.attr('data-name'));
    $('#item_code').text(data.attr('data-item-code'));
    $('#instance_name').text(data.attr('data-instance'));
    $('#instance_code').text(data.attr('data-instance-code'));
    $('#promotion_price').text(data.attr('data-promotion-price'));
    $('#total_price').text(data.attr('data-price'));
    $('#unit_price').text(data.attr('data-price'));
  });

  // click select option icon for add
  $(document).on('click', '.attribute_btn', function(event){

    // $('.change_qty').val(1);
    value      = $(this).data('value');
    type       = $(this).data('type');
    instances  = $(this).data('instances');

    attributes = $(".attribute_btn");
    $(attributes).each(function(i){
      if ($(attributes[i]).attr('data-type')==type){
        $('.'+type).removeClass("selected-attribute");
      }
    });
    $(this).addClass('selected-attribute');

    // if ($(".attribute_btn").attr("data-type")==type){
    //   $('.'+type).removeClass("selected-attribute");
    // }
    // $(this).addClass('selected-attribute');

    var selected_attr = get_selected_attributes('selected-attribute');

    qty = $('.change_qty').val();

    for(var field in instances) {
      item_attr = instances[field].values;

      if(JSON.stringify(item_attr) == JSON.stringify(selected_attr)){
        unit_price = instances[field].price ;
        total_price = qty * unit_price ;
        $('#instance_name').text(instances[field].name);
        $('#instance_code').text(instances[field].code);
        $('#promotion_price').text(instances[field].promotion_price);
        $('#total_price').text(total_price);
        $('#unit_price').text(unit_price);
      }
    }

  }); //End selecct attribute buttom

  // click select option icon for add
  $(document).on('click', '.option_btn', function(event){
    active =$(this).hasClass('selected-option');
    value      = $(this).data('value');
    type       = $(this).data('type');
    group      = $(this).data('group');
    console.log(group);
    options    = $(".option_btn");
    $(options).each(function(i){
      if ($(options[i]).attr('data-type')==type){
        $('.'+type).removeClass("selected-option");
      }
    });
    if (active) {
      $(this).removeClass('selected-option');
    }else{
      $(this).addClass('selected-option');
    }


    if(group == "set_menu"){
      option_arr    = get_selected_attributes('selected-option');
          $(".selected-set:last").attr('data-options',JSON.stringify(option_arr));
          $(".selected-set:last").children().children('#instance_option').text(option_arr);
      // instance    = $(".selected-instance");
      // $(instance).each(function(i){
      //   if ($(instance[i]).attr('data-code')==code){
          // option_arr    = get_selected_attributes('selected-option');
          // $(instance[i]).attr('data-options',JSON.stringify(option_arr));
          // $(instance[i]).children().children('#instance_option').text(option_arr);
      //   }
      // });
    }

    if(group == "set_menu_default"){
          option_arr    = get_selected_attributes('selected-option');
          $('.set-item').attr('data-options',JSON.stringify(option_arr));
          $('.set_default_option').text(option_arr);
    }

  }); //End selecct attribute buttom
   // click select option icon for add
  $(document).on('click', '.check_option_btn', function(event){
    active =$(this).hasClass('selected-option');
    value      = $(this).data('value');
    type       = $(this).data('type');
    group      = $(this).data('group');
    if (active) {
      $(this).removeClass('selected-option');
    }else{
      $(this).addClass('selected-option');
    }
    if(group == "set_menu"){
      option_arr    = get_selected_attributes('selected-option');
          $(".selected-set:last").attr('data-options',JSON.stringify(option_arr));
          $(".selected-set:last").children().children('#instance_option').text(option_arr);
      // instance    = $(".selected-instance");
      // $(instance).each(function(i){
      //   if ($(instance[i]).attr('data-code')==code){
          // option_arr    = get_selected_attributes('selected-option');
          // $(instance[i]).attr('data-options',JSON.stringify(option_arr));
          // $(instance[i]).children().children('#instance_option').text(option_arr);
      //   }
      // });
    }

    if(group == "set_menu_default"){
          option_arr    = get_selected_attributes('selected-option');
          $('.set-item').attr('data-options',JSON.stringify(option_arr));
          $('.set_default_option').text(option_arr);
    }

  }); //End selecct attribute buttom
  // click add order
  $(document).on('click', '.add_to_order', function(event){
    total_price   = $('#total_price').text();
    qty           = parseInt($('#count').val());

    var item_row  = $('.selected-attribute');

    attribute_arr = get_selected_attributes('selected-attribute');
    option_arr    = get_selected_attributes('selected-option');
    if (item_row.length>0) {
      var instances = jQuery.parseJSON(item_row.attr('data-instances'));


      for(var field in instances) {

        attrbu = JSON.stringify(attribute_arr);
        instan = JSON.stringify(instances[field].values);
        var newarr = new Set(instan);

        result = false;
        for(var i in attrbu) {
            if (newarr.has(attrbu[i])) {
              result = true;
              break;
            }

        }
        if (JSON.stringify(attribute_arr) === JSON.stringify(instances[field].values)) {
          $('.add_to_order').attr('data-instance-code',instances[field].code);
          $('.add_to_order').attr('data-instance',instances[field].name);
          $('.add_to_order').attr('data-price',instances[field].price);
          $('.add_to_order').attr('data-promotion-price',instances[field].promotion_price);
        }
      }
    }else{
      $('.add_to_order').attr('data-instance-code',$('#instance_code').text());
      $('.add_to_order').attr('data-instance',$('#instance_name').text());
      $('.add_to_order').attr('data-price',$('#unit_price').text());
      $('.add_to_order').attr('data-promotion-price',$('#promotion_price').text());
    }

    $('.add_to_order').attr('data-item-code',$('#item_code').text());
    $('.add_to_order').attr('data-qty',qty);
    $('.add_to_order').attr('data-name',$('#title_name').text());
    $('.add_to_order').attr('data-attributes',JSON.stringify(attribute_arr));
    $('.add_to_order').attr('data-options',JSON.stringify(option_arr));
    $('.add_to_order').attr('data-opt',JSON.stringify(option_arr));
    var item_data = $(this);
    if ($('#server_mode').val() != "cloud" && second_display_lookup == 2) {
      item = get_item(item_data,"add_to_order");
      customer_display_view(item,"add");
    }
    show_item_detail(item_data,"add_to_order");
    calculate_sub_total();

  }); //End add order  Click

  // click plus icon for add
  $(document).on('click', '.add_icon', function(event){
    var item_data = $(this);
    if ($('#server_mode').val() != "cloud" && second_display_lookup == 2) {
      item = get_item(item_data,"add_icon");
      customer_display_view(item,"add");
    }
    show_item_detail(item_data,"add_icon");
    calculate_sub_total();
  }); //End Add Icon Click

  function show_item_detail(data,click_type){
    testqty = parseInt($('.item_box').children('data_qty').text());
    qty           = parseInt(data.attr('data-qty'));
    append        = 0;
    price         = data.attr('data-price');

    instance_name = data.attr('data-instance');
    if (instance_name == "undefined"){
      instance = '';
    }else{
      instance = "("+data.attr('data-instance')+")";
    }
    d_option = data.attr('data-opt');
    if (click_type != "add_icon"){
      option_name = "-"+data.attr('data-options');
      data_option =  data.attr('data-options')  ;
    }else{
      option_name = ' ';
      data_option = '[]';
    }
    var rowCount = $('.summary-items tbody tr').length+1;
    var item_row = $('.summary-items tbody tr');

    $(item_row).each(function(i){
      item_code = $(item_row[i]).attr('data-code');
      instance_code = $(item_row[i]).attr('data-instance-code');
      r_option = $(item_row[i]).attr('data-opt');

      if (item_code == data.attr('data-item-code') && instance_code == data.attr('data-instance-code')&&r_option == d_option) {
        if (qty > 1) {
          qty = parseInt($(item_row[i]).children('#item_qty').text()) + qty;
        }else{
          qty = parseInt($(item_row[i]).children('#item_qty').text()) + 1;
        }

        $(item_row[i]).children('#item_qty').text(qty);
        parseFloat($(item_row[i]).children('#item_price').text(parseFloat(price*qty).toFixed(2)));
        append =1;
      }else{
        if (qty > 1) {
          qty = qty;
        }else{
          qty = 1;
        }
      }
    });
    if (append===0) {
      row ="<tr class='item_box' data-price ='"
          +price+ " 'data-toggle='modal' data-target='#sx_itemModal' 'data-instance ='"
          +instance+ "' data-qty='"+qty +"' data-code='"+data.attr('data-item-code')+"' data-instance-code='"
          +data.attr('data-instance-code')+"' data-attributes='"
          +data.attr('data-attributes')+"' data-options ='"
          +data_option+"' data-opt ='"
          +data.attr('data-options')+"' data-row ='"+rowCount+ "'>"
      +'<td class="item-cell-no">'+rowCount+'</td>'
      +'<td class="item-cell-name" id="item_name" >' + data.attr('data-name')+ ' ' + instance +''+option_name+'</td>'
      +'<td class="item-cell-qty" id="item_qty">' + qty + '</td>'
      +'<td class="item-cell-price" id="item_price">'
      + parseFloat(price).toFixed(2)
      +'</td>'
      +'</tr>';
      $(".summary-items tbody").append(row);
    }
  }

  // Create Order
  $("#create_order").on('click', function(e){

    $(this).attr('disabled', 'disabled');
    e.preventDefault();
    $("#oqs_loading_wrapper").show();
    var cashier_type = $("#link_type").val();
    localStorage.setItem('cashier_type',cashier_type);
    quick_service = window.location.href.indexOf("quick_service");
    localStorage.setItem('quick_service',quick_service);
    food_court = window.location.href.indexOf("food_court");
    localStorage.setItem('food_court',food_court);
    if (quick_service != -1 || food_court != -1) {
      type = cashier_type;
      var table_type  = $('#table_type').text();
      var table_id    = $('#table_id').val();
      var customer_id = $('#customer_id').val();
      var booking_id  = $('#booking_id').text();
      var ajax_url = 'addorders/create';
    }else{
      type = 'cashier';
      var table_type  = $('#table_type').text();
      var table_id    = $('#table_id').text();
      var customer_id = $('#customer_id').text();
      var booking_id  = $('#booking_id').text();
      var ajax_url = '../addorders/create';
    }
    var order_items = JSON.stringify(get_order_item_rows());
    if (booking_id.length > 0) {

      var params = {'order_source': type, 'order_type': "dine_in",
                  'customer_id': customer_id, 'guest_info': "",'booking_id':booking_id,
                  'table_id': table_id,
                  'order_items': order_items,'create_type' : "create_only" };
    }else{
      var params = {'order_source': type, 'order_type': "dine_in",
                  'customer_id': customer_id, 'guest_info': "",
                  'table_id': table_id,
                  'order_items': order_items,'create_type' : "create_only" };
    }

      // if (table_id.length>0 || role == 'waiter') {
        $.ajax({
          type: "POST",
          url: ajax_url,
          data: params,
          dataType: "json",
           success:function(result){
              if (type == "quick_service" || type=="food_court") {
                   window.location.href = "/origami/"+type;
              }else{
                if(table_type == "Table"){
                   window.location.href = "/origami/table/" + table_id;
                }
                else {
                   window.location.href = "/origami/room/" + table_id;
                }
              }
              if ($('#server_mode').val() != "cloud" && second_display_lookup == 2){
                customer_display_view(null,"reload");
              }
           }
        });
      // }else{
      //   $(this).removeAttr('disabled', '');
      //   $("#oqs_loading_wrapper").hide();

      //   swal("Opps","Please Select Table or Room","warning");
      // }
  });


  // Pay Discount for Payment
  $("#create_pay_order").on('click', function(e){
    $(this).attr('disabled', 'disabled');
    e.preventDefault();
    type = $("#link_type").val();
    modify_order = window.location.href.indexOf("modify_order");
    $("#oqs_loading_wrapper").show();
      if (modify_order !=-1) {
        var ajax_url   = '../../../'+type+'/update_modify_order';
        var table_type = $('#table_type').text();
        var table_id    = $('#table_id').text();
        var customer_id = $('#customer_id').text();
        var booking_id  = $('#booking_id').text();
        var sale_id     = $('#sale_id').text();
      }else{
        var ajax_url = 'addorders/create';
        var table_type = $('#table_id').find("option:selected").data('type');
        var table_id    = $('#table_id').val();
        var customer_id = $('#customer_id').val();
        var booking_id  = $('#booking_id').text();
        var sale_id     = ""
      }
    var order_items = JSON.stringify(get_order_item_rows());
    if (booking_id.length > 0) {

      var params = {'order_source': type, 'order_type': "dine_in",
                  'customer_id': customer_id, 'guest_info': "",'booking_id':booking_id,
                  'table_id': table_id,
                  'order_items': order_items,'sale_id': sale_id,'create_type': "create_pay"  };
    }else{
      var params = {'order_source': type, 'order_type': "dine_in",
                  'customer_id': customer_id, 'guest_info': "",
                  'table_id': table_id,
                  'order_items': order_items,'sale_id': sale_id,'create_type': "create_pay" };
    }

    $.ajax({
      type: "POST",
      url: ajax_url,
      data: params,
      dataType: "json",
       success:function(result){
          if (result.status) {
            if (result.data == null){
               swal({
                  title: "Please Open Shift !",
                  text: result.status,
                  type: "warning",
                  confirmButtonColor: "#DD6B55",
                  confirmButtonText: "Ok",
                  closeOnConfirm: false
              }, function () {
                 window.location.href = '/origami/'+type+'/pending_order/' + $('#sale_id').text();
              });

            }else if(result.data == 'OK'){
              window.location.href = '/origami/'+type+'/pending_order/' + $('#sale_id').text();
            }else{
              window.location.href = "/origami/sale/"+result.data["sale_id"]+"/"+type+"/payment";
            }
          }
       }
    });
  });

  //click item row for update qty
  $('.summary-items').on('click', '.item_box', function(){
    $(this).attr('data-active',true);
    name =  $(this).children('#item_name').text();
    qty  =  $(this).children('#item_qty').text();
    $('#modal-item-name').text(name);
    $('#modal-qty').val(qty);
  });

  //click remove buttom in modal box
  $('#sx_itemModal').on('click','#remove', function(){
    $('.summary-items tr').filter(function(){
      if ($(this).attr('data-active') == 'true'){
        if ($('#server_mode').val() != "cloud" && second_display_lookup == 2) {
          var item_data = $(this);
          item = get_item(item_data,"remove_icon");
          customer_display_view(item,"remove");
        }
        $(this).remove();
      }
    });
    calculate_sub_total();
  });

  //click close
  $('#sx_itemModal').on('click','#close', function(){
    $(".item_box").removeAttr("data-active");
  });

  $('#sx_item_set_detailModal').on('click','#close', function(){
    $("#sx_item_set_detailModal").css({ 'display': "none" });
  });
  //click save buttom after change qty
  $('#sx_itemModal').on('click','#save', function(){
    if ($('#modal-qty').val()>0) {
      summary_items_filter();
      calculate_sub_total();

    }else{
      swal("Opps", "Please enter number for qty ","warning");
    }

  });

  //calculate subtotal
  function calculate_sub_total(){
    var total_price    = 0;
    var total_qty      = 0;
    var taxable_amount = 0;
    var item_row       = $('.summary-items tbody tr');

    $(item_row).each(function(i){
      var unit_price = parseFloat($(item_row[i]).attr('data-price'));
      var qty        = parseFloat($(item_row[i]).children('#item_qty').text());
      total_qty += qty;
      total_price += qty*unit_price;
    });
    var fixed_total_price    = parseFloat(total_price).toFixed(2);
    var fixed_taxable_amount = parseFloat(taxable_amount).toFixed(2);

    $('#sub_total').empty();
    $('#sub_total').append(fixed_total_price);

    $('#total_qty').empty();
    $('#total_qty').append(total_qty);

    if (item_row.length > 0) {
      $('.create').removeAttr("disabled", false);
    }else{
      $('.create').attr("disabled", true);
    }
  }

  function summary_items_filter(){
    $('.summary-items tr').filter(function(){
      if ($(this).attr('data-active') == 'true'){
        qty   = $('#modal-qty').val();
        $(this).attr('data-qty',qty);
        price = parseFloat($(this).attr('data-price'));
        total_price = parseFloat(price*qty).toFixed(2);

        $(this).find('#item_qty').text(qty);
        $(this).find('.item-cell-price').text(total_price);

        $(this).removeAttr('data-active');

        if ($('#server_mode').val() != "cloud" && second_display_lookup == 2) {
          var item_data = $(this);
          item = get_item(item_data,"update_icon");
          customer_display_view(item,"update_qty");
        }
      }
    });
  }

  /* Get Item rows */
  function get_order_item_rows(){
    var order_items = [];
    var item_row    = $('.summary-items tbody tr');
    $(item_row).each(function(i){
      var order_item = {};

      order_item.order_item_id      = $(item_row[i]).attr('data-row');
      order_item.item_instance_code = $(item_row[i]).attr('data-instance-code');
      order_item.quantity           = $(item_row[i]).children('#item_qty').text();
//parent id
      if ($(item_row[i]).attr('data-parent')=="true") {
       parent_id = $(item_row[i]).attr('data-row');
      }
      if ($(item_row[i]).attr('data-sub-item')=="true") {
        order_item.parent_order_item_id = parent_id
      }
//end parent id
      order_item.options            = $(item_row[i]).attr('data-options');
      order_items.push(order_item);
    });
    return order_items;
  }
  // Get Selected Class
  function get_selected_attributes(selected_class) {
    var item_row      = $('.'+selected_class);
    var attribute_arr = [];
    $(item_row).each(function(i){
      value = $(item_row[i]).attr('data-value');
      str = value;
      attribute_arr.push(str);
    });
    return attribute_arr;
  }

  //click menu sidebar menu category
  $("#back").on("click", function(){
    var table_id   = $('#table_id').text();
    var table_type = $('#table_type').text();
    var cashier_type = $("#link_type").val();
    type = window.location.href.includes("quick_service") || window.location.href.includes("food_court");
    if (type == true) {
      var table_type = $('#table_id').find("option:selected").data('type');
      var table_id    = $('#table_id').val();
      if(window.location.href.includes("modify_order")){
        var link_url = window.location.href.split("/");
        window.location.href = "/origami/"+cashier_type+"/pending_order/"+link_url[link_url.length - 1];
      }else{
        window.location.href = "/origami/dashboard";
      }
    }else{
      var table_type = $('#table_type').text();
      var table_id    = $('#table_id').text();

      if(table_type == "Table"){
        window.location.href = "/origami/table/" + table_id;
      }else {
        window.location.href = "/origami/room/" + table_id;
      }
    }
  });

  // Get Selected Class
  function change_qty_plus_minus(id,plus,minus) {
    var count = parseInt($('#'+id).val());

    $('#'+plus).on("click", function(){
      count++;
      $('#'+id).val(count);

      if (id == "count") {
        price = $("#unit_price").text();
        $("#total_price").text(count*price);
      }else{
        var item_row      = $('.selected-instance');
        price             = $("#set_unit_price").text();
        set_total_price   = $("#set_total_price").text();

        if (item_row.length > 1) {
          total = 0 ;
          $(item_row).each(function(i){
            total += count * $(item_row[i]).attr('data-price');
            total_price = total;
          });
        }else{
          total_price     = count*price;
        }

        $("#set_total_price").text(total_price);
      }
    });

    $('#'+minus).on("click", function(){

      // var count   = parseInt($('#'+id).val());
      // var countEl = document.getElementById(id);

      if (count > 1) {
        count--;
        $('#'+id).val(count);

        if (id=="count") {
          price = $("#unit_price").text();
          $("#total_price").text(count*price);
        }else{
          var item_row      = $('.selected-instance');
          price             = $("#set_unit_price").text();
          set_total_price   = $("#set_total_price").text();

          if (item_row.length > 1) {
            total = 0 ;
            $(item_row).each(function(i){
              total += count * $(item_row[i]).attr('data-price');
              total_price = total;
            });
          }else{
            total_price     = count*price;
          }
          $("#set_total_price").text(total_price);
        }
      }
    })
  }

  $(".keypress_qty").on('keyup change', function (){
   // $('.keypress_qty').keyup(function(e){
        id    = $(this).attr('id');
        value = $(this).val();

        if ($.isNumeric(value)) {
          if (id=="count") {
            $('#count').attr('value',value);
            price = $("#unit_price").text();
            $("#total_price").text(value*price);
          }else{
            var item_row      = $('.selected-instance');
            price             = $("#set_unit_price").text();
            set_total_price   = $("#set_total_price").text();
            $(".set_change_qty").val(value);
            if (item_row.length > 1) {
              total = 0 ;
              $(item_row).each(function(i){
                total += value * $(item_row[i]).attr('data-price');
                total_price = total;
              });
            }else{
              total_price     = value*price;
            }
            $("#set_total_price").text(total_price);
          }
        }else{
          $('#'+id).val(1);
          swal("Opps","Please enter number for qty","warning");
        }
    });

   //click menu sidebar menu category

   $(document).on('click', '.sub_clickssss', function(event){
     event.preventDefault();
    var menu_id = $(this).attr("data-id");
    var url = "get_menu_sub_category/"+menu_id;
    sub_category = $(this).find('.sub_category_list');
    show_sub_category_list(url,sub_category,menu_id);
  });
  //End menu category Click

  //show menu item list when click menu category
  function show_sub_category_list(url,sub_category,menu_id){

    var sub_category_list = $('.sub_category_list');
     sub_category_list.empty();

    menus = JSON.parse(localStorage.getItem("menus"));
    if (menus != null) {
      for(var j in menus) {
        var categories = menus[j]["categories"];
        for(var ii in categories) {
          if (menu_id == categories[ii]["parent_id"]) {
            $(sub_category).removeClass('hidden');
            row = '<li class="menu_sub_category fadeInTop" data-id="'+categories[ii].id+'">'
              +'<a class="nav-link" data-toggle="tab" href="" role="tab">'+ categories[ii].name+'</a>'
            +'</li>' ;
            $(sub_category).append(row);
          }
        }
      }
    }else{
      if (type != -1 && modify_order != -1) {
        var url = "../../../addorders/"+url;
      }if(modify_order== -1 && type != -1){
        var url = 'addorders/'+url;
      }
      if (type ==-1 && modify_order == -1){
        var url = url;
      }
      //Start Ajax
      $.ajax({
        type: "GET",
        url: url,
        data: {},
        dataType: "json",
        success: function(data) {
          var sub_category_list = $('.sub_category_list');
          sub_category_list.empty();
          data = data.sub_category;
          if (data.length > 0) {
            // if ((sub_category.hasClass('hidden'))) {
              $(sub_category).removeClass('hidden');
            // }else{
              // $(sub_category).addClass('hidden');
            // }
            for(var i in data) {

                  row = '<li class="menu_sub_category fadeInTop" data-id="'+data[i].id+'">'
                           +'<a class="nav-link" data-toggle="tab" href="" role="tab">'+ data[i].name+'</a>'
                         +'</li>' ;
                  $(sub_category).append(row);
              //end is_sub_item false
            }
          }
        }
      });
      //end Ajax
    }
  }

  /* Get  Item rows */
  function get_item(data,click_type){
  var sale_items = [];

    var sale_item = {};
    sale_item.qty = parseInt(data.attr('data-qty'));
    sale_item.name =  data.attr('data-name');
    sale_item.price = data.attr('data-price');
    sale_item.item_code  = data.attr('data-item-code')
    sale_item.instance_code  = data.attr('data-instance-code')
    sale_item.attributes  = data.attr('data-attributes')
    sale_item.options  = data.attr('data-options')
    sale_item.opt  = data.attr('data-opt')
    sale_item.click_type  = click_type
    sale_item.instance  = data.attr('data-instance')
    sale_items.push(sale_item);
  return sale_items;

 }

 /* Get  Item rows */
 function get_set_item(items){
  var sale_items = [];
     var item = {};
        item.code          = $('.set-item').attr('data-code');
        item.name          = $('.set-item').attr('data-name');
        item.item_name     = $('#set_name').text();
        item.qty           = parseInt($('#set_count').val());
        item.item_code     = $('#set_item_code').text();
        item.price         = $('.set-item').attr('data-price');
        item.option        = $('.set-item').attr('data-options');
        item.parent        = $('.set-item').attr('data-parent');

    sale_items.push(item);

    $(items).each(function(i){
      var sale_item = {};
        sale_item.code          = $(items[i]).attr('data-code');
        sale_item.name          = $(items[i]).attr('data-name');
        sale_item.item_name     = $('#set_name').text();
        sale_item.qty           = parseInt($('#set_count').val());
        sale_item.item_code     = $('#set_item_code').text();
        sale_item.price         = $(items[i]).attr('data-price');
        sale_item.option        = $(items[i]).attr('data-options');
        sale_item.sub_item      = $(items[i]).attr('data-sub-item');
        sale_items.push(sale_item);
    });


  return sale_items;
 }

 function customer_display_view(data,status) {
  if (type != -1 && modify_order != -1) {
    url = '../../../../origami/customer_view';
  }
  if(modify_order == -1 && type != -1){
    url = '../../origami/customer_view';
  }
  if (type ==-1 && modify_order == -1){
    url = '../../origami/customer_view';
  }
   $.ajax({
          type: "POST",
          url: url,
          data: {"data":data,"status":status},
          dataType: "json",
           success:function(result){
           }
        });
 }
 /*  $("input").keypress(function(){
    $("span").text(i += 1);
});*/
  // $("#set_change_qty").change(function(){
  //   qty = $(this).val();
  //   price = $("#set_total_price").text();
  //   $("#set_total_price").text(qty*price);
  // });

 // $(".change_qty").change(function(){
  //   qty = $(this).val();
  //   price = $("#unit_price").text();
  //   $("#total_price").text(qty*price);
  // });
  function show_menu_list(menu_items) {
    var menu_list = $('.menu_items_list');
    menu_list.empty();
    for(var field in menu_items) {
      console.log(menu_items[field].instances);
            if (menu_items[field].is_sub_item == false) {
              instances = menu_items[field].instances ;

              if (!instances.length > 0) {
                swal("Hello Please Check!","Does not have instance item in this menu items ("+ menu_items[field].name+")","warning");
              }
              if (instances.length > 0) {
                qty = 1;
                options = [];
                price = 0;

                if (JSON.stringify(menu_items[field].item_sets)!='[]') {
                  fa_plus = '';
                  add = '';
                  menu_item_box = 'set_add_icon';
                  data_target = 'sx_item_set_detailModal';
                  data_modal = 'modal'
                  add_icon = "set_item_box"
                     code            =  menu_items[field].code;
                     name            =  menu_items[field].name;
                     instances       =  menu_items[field].instances;
                      $(instances).each(function(i){
                        if (instances[i].is_default == true) {
                          price           = parseFloat(instances[i].price).toFixed(2);
                        }else{
                          price = 0;
                        }
                      });
                     is_available    = menu_items[field].is_available ;
                     is_on_promotion = 0;
                     item_attributes = menu_items[field].attributes;
                     promotion_price =  menu_items[field].promotion_price;
                }else{
                  fa_plus = 'material-icons';
                  add = 'view_list'
                  menu_item_box = 'menu_item_box';
                  data_target = 'sx_item_detailModal';
                  data_modal  = ''
                  add_icon = "add_icon"

                  $(instances).each(function(i){
                    if (instances[i].is_default === true) {
                     code            = instances[i].code;
                     name            = instances[i].name;
                     price           = parseFloat(instances[i].price).toFixed(2);
                     is_available    = instances[i].is_available ;
                     is_on_promotion = instances[i].is_on_promotion;
                     item_attributes = instances[i].values;
                     promotion_price = instances[i].promotion_price;
                     code            = instances[i].code;
                   }
                  });
                }

                if (menu_items[field].image) {
                  if (modify_order) {
                    image_path = "../../"+menu_items[field].image;
                  }else{
                    image_path = menu_items[field].image;
                  }
                  row = '<div class="col-md-6 col-sm-6 col-lg-3">'
                            +'<div class="card custom-card testimonial-card fadeInRight" style="height:100%;background-image:url(../../'+image_path+');background-repeat: no-repeat;">'
                                      +'<div class="custom-card-head card-head row" style="line-height:14px;margin:0px;" >'
                                        +'<div class="col-md-10 " style="padding:0px !important;">'+ menu_items[field].name +'</div>'

                                       +'</div>'
                                      +"<div  class='"+add_icon+" p-t-65 p-b-65 m-r-' "
                                                    +" data-item-code='"+ menu_items[field].code +"' "
                                                    +" data-name='"+ menu_items[field].name +"' "
                                                    +" data-qty = '"+ qty +"' "
                                                    +" data-price = '" + price +"' "
                                                    +" data-instance-code = '"+ code +"' "
                                                    +" data-instance = '" + name +"' "
                                                    +" data-promotion-price = '"+ promotion_price +"' "
                                                    +" data-attributes = '" + JSON.stringify(item_attributes) +"' "
                                                    +" data-options = '"+ JSON.stringify(menu_items[field].options) +"' "
                                                    +" data-opt = '" + JSON.stringify(menu_items[field].options) +"' "
                                                    +" data-image='"+image_path+"' "
                                                    +" data-toggle='"+data_modal+"' "
                                                    +" data-target='."+data_target+"' "
                                                    +" data-item-sets = '"+JSON.stringify(menu_items[field].item_sets)+""
                                                    +" 'data-instances = '"+JSON.stringify(menu_items[field].instances)+"'>"
                                        +'</div>'
                                        +'<div class="card-footer custom-card-footer custom-flex-footer" style="opacity:0.7">'
                                          +'<span style="font-weight:900;flex-grow:1;">'+ price +'</span>'
                                          + "<div class='offset-4 col-2 "+menu_item_box
                                          + "' data-item-code='" + menu_items[field].code
                                          + "' data-instance='" + JSON.stringify(menu_items[field].instances)
                                          + "' data-id='" + JSON.stringify(menu_items[field].attributes)
                                          + "' data-item='" + JSON.stringify(item_attributes)
                                          + "' data-option='" + JSON.stringify(menu_items[field].options)
                                          + "' data-opt='" + JSON.stringify(menu_items[field].options)
                                          + "' data-item-sets='" + JSON.stringify(menu_items[field].item_sets)
                                          + "' data-toggle='modal'"
                                          + "  data-target='." + data_target +"'"
                                          + "  style='padding:0px 5px 0px 5px' >"
                                              + "<i class='m-l--5 fa " + fa_plus + "'>"
                                              + add
                                              + "</i>"
                                          +'</div>'

                                      +'</div>'
                                  +'</div>'; ;
                            }else{
                                  row = '<div class="col-md-6 col-sm-6 col-lg-3 mt-1">'
                                          +'<div class="card custom-card testimonial-card fadeInRight" style="height:100%;">'
                                              +'<div class="custom-card-no-img-head card-head '+add_icon+' " style="margin:0px;display:flex;!important "'
                                                    +" data-item-code='"+ menu_items[field].code +"' "
                                                    +" data-name='" + menu_items[field].name +"' "
                                                    +" data-qty = '"+ qty +"' "
                                                    +" data-price = '" + price +"' "
                                                    +" data-instance-code = '"+ code +"' "
                                                    +" data-instance = '" + name +"' "
                                                    +" data-promotion-price = '"+ promotion_price +"' "
                                                    +" data-attributes = '" + JSON.stringify(item_attributes) +"' "
                                                    +" data-options = '"+ JSON.stringify(menu_items[field].options) +"' "
                                                    +" data-opt = '"+ JSON.stringify(menu_items[field].options) +"' "
                                                    +" data-image='' data-toggle='"+data_modal+"' "
                                                    +" data-target='."+data_target+"' "
                                                    +" data-item-sets = '"+JSON.stringify(menu_items[field].item_sets)+"'"
                                                    +" data-instances = '"+JSON.stringify(menu_items[field].instances)+"'>"

                                                    +'<div class="product_box" style="width:100%;"><span>'+ menu_items[field].name +'<span></div>'
                                              +'</div>'
                                              +"<div  class='"+add_icon+"' "
                                                    +" data-item-code='"+ menu_items[field].code +"' "
                                                    +" data-name='" + menu_items[field].name +"' "
                                                    +" data-qty = '"+ qty +"' "
                                                    +" data-price = '" + price +"' "
                                                    +" data-instance-code = '"+ code +"' "
                                                    +" data-instance = '" + name +"' "
                                                    +" data-promotion-price = '"+ promotion_price +"' "
                                                    +" data-attributes = '" + JSON.stringify(item_attributes) +"' "
                                                    +" data-options = '"+ JSON.stringify(menu_items[field].options) +"' "
                                                    +" data-opt = '"+ JSON.stringify(menu_items[field].options) +"' "
                                                    +" data-image='' data-toggle='"+data_modal+"' "
                                                    +" data-target='."+data_target+"' "
                                                    +" data-item-sets = '"+JSON.stringify(menu_items[field].item_sets)+"'"
                                                    +" data-instances = '"+JSON.stringify(menu_items[field].instances)+"'>"
                                                 +'</div>'
                                                  +'<div class="card-footer custom-card-no-img-footer custom-flex-footer">'
                                                      +'<span style="font-weight:900;flex-grow:1;">'+ price + '</span>'
                                                      +" <div class='offset-4 col-2 menu_item_no_img_box "+menu_item_box+" ' "
                                                        +" data-item-code='"+ menu_items[field].code +"' "
                                                        +" data-instance = '" +JSON.stringify(menu_items[field].instances)+"' "
                                                        +" data-id = '"+JSON.stringify(menu_items[field].attributes)+"' "
                                                        +" data-item = '" +JSON.stringify(item_attributes)+"' "
                                                        +" data-option = '"+JSON.stringify(menu_items[field].options)+"'"
                                                        +" data-opt = '"+JSON.stringify(menu_items[field].options)+"' "
                                                        +" data-item-sets = '"+JSON.stringify(menu_items[field].item_sets)+"' "
                                                        +" data-toggle='modal' "
                                                        +" data-target='."+data_target+"' "
                                                        +" style='padding:0px 5px 0px 5px'>"
                                                                  +"<i class='m-l--5 fa "+fa_plus+" '>"
                                                                  +add+ '</i>'
                                                  +'</div>'
                                                  +'</div>'


                                            +'</div>'
                                        +'</div>';
                    }

                $('.menu_items_list').append(row);
              }
              //end instances in menu-items alest 1 instance
            }
            //end is_sub_item false
          }
  }
});
