$(document).ready(function() {
    checkSessionStat();
    load_item();
    setValueOrderType();
});
$("#input-type").change(function(){
    var type = $("#input-type").val();
    $("#excel-type").val(type);
    load_item();
    $("#marketplace-group").hide();
    $("#input-mname").val("");
    if(type == "in"){
        $("#address-head").text("Pick Up From");
        $("#label-type").text("Inbound");
        setValueOrderType();
    } else {
        $("#address-head").text("Deliver To");
        $("#label-type").text("Outbound");
        setValueOrderType();
    }
}); 
function setValueOrderType(){
    var type = $("#input-type").val();
    var resultHTML = "";
    if(type == "out"){
        resultHTML += "<option value=''>-Order Type-</option>";
        resultHTML += "<option value='website'>Website</option>";
        resultHTML += "<option value='marketplace'>Marketplace</option>";
        resultHTML += "<option value='wholesale'>Wholesale</option>";
        resultHTML += "<option value='consignment'>Consignment</option>";
        resultHTML += "<option value='endorsement'>Endorsement</option>";
        resultHTML += "<option value='store'>Store</option>";
        resultHTML += "<option value='deptstore'>Deptstore</option>";
        resultHTML += "<option value='expo'>Expo</option>";
        resultHTML += "<option value='sample'>Sample</option>";
        resultHTML += "<option value='employee'>Employee Purchase</option>";
        resultHTML += "<option value='office'>Office</option>";
        resultHTML += "<option value='modern'>Modern Trade</option>";
        resultHTML += "<option value='surabaya'>Surabaya</option>";
        resultHTML += "<option value='sirclo'>Sirclo</option>";
        resultHTML += "<option value='outright'>Marketplace Outright</option>";
    } else {
        resultHTML += "<option value=''>-Order Type-</option>";
        resultHTML += "<option value='retur'>Retur</option>";
        resultHTML += "<option value='purchasing'>Purchasing</option>";
        resultHTML += "<option value='expo'>Expo</option>";
        resultHTML += "<option value='reject'>Reject</option>";
        resultHTML += "<option value='other'>Other</option>";
    }
    $('#input-otype').html(resultHTML);
}
$("#input-via").change(function(){
    var via = $("#input-via").val();
    if(via == "self"){
        $("#deliver-group").hide();
        $("#row-courier").hide();
    } else if(via == "3rd"){
        //$("#deliver-group").show();
        $("#row-courier").show();
    } else {
        //$("#deliver-group").show();
        $("#row-courier").hide();
    }
}); 
$("#input-otype").change(function(){
    var otype = $("#input-otype").val();
    if(otype == "marketplace"){
        $("#marketplace-group").show();
    } else {
        $("#marketplace-group").hide();
        $("#input-mname").val("");
    }
}); 
$(function () {
    $('#input-pickup_date').datetimepicker({
        format: 'DD-MM-YYYY hh:mm',
    });
    $('#input-deliver_date').datetimepicker({
        format: 'DD-MM-YYYY hh:mm',
    });
});
$('#input-uexcel').change(function() {
    var i = $(this).prev('label').clone();
    var file = $('#input-uexcel')[0].files[0].name;
    var val_exc = $('#input-uexcel').val();
    $("#mimp-file").text(file);
    $(".mimp-load").fadeIn();
    $("#label-uexcel").addClass("disable-state");
    if(file != ""){
        if (!(/\.(xlsx|xls|xlsm)$/i).test(val_exc)) {
            setTimeout(
                function(){ 
                    errorAlert("Please upload valid excel file .xlsx, .xlsm, .xls only.");
                    $("#label-uexcel").removeClass("disable-state");
                    $(".mimp-load").hide();
                    $("#mimp-file").text("");
                    $('#input-uexcel').val("");
                }, 1000
            );
        } else {
            setTimeout(
                function(){ 
                    $("#form-upload").submit();
                }, 1500
            );
        }
    } else {
        setTimeout(
            function(){ 
                errorAlert("Please upload valid excel file.");
                $("#label-uexcel").removeClass("disable-state");
                $(".mimp-load").hide();
                $("#mimp-file").text("");
                $('#input-uexcel').val("");
            }, 1000
        );
    }
});
$('#modalAdd').on('show.bs.modal', function () {
    $("#table-mlist").html("");
    load_item_modal(1);
    get_brand();
    get_category();
});
$('#modalAdd').on('hidden.bs.modal', function (e) {
    $("#table-mlist").html("");
    $("#search-input").val("");
    $("#brand-select").val("");
    $("#category-select").val("");
});
$("#search-input").keyup(function(){
    load_item_modal(1);
});
function load_item_modal(page){
    if(page != 1){
        $("#table-mloader").fadeIn();
    } else {
        $('#table-mlist').html("");
        $("#table-mloader").show();
    }
    get_item_modal(page);
    $("#madd-page").val(page);
}
function load_item(){
    $('#table-list').html("");
    $("#table-loader").show();
    get_item_list();
}
function get_item_modal(page){
    var item_perpage = 10;//item perpage

    var url = api_inv_shipment;
    var session_id = $("#session-id").val();
    var search_key = $("#search-input").val();
    var brand = $("#brand-select").val();
    var category = $("#category-select").val();
    
    var data = {
        user_id : session_id,
        item : item_perpage,
        brand : brand,
        category : category,
        keyword : search_key,
        page : page
    }

    $.ajax({type: "POST",url: url,data : data, success:function(result){
        $("#cur-page").val(page);
        var total_data = result.total_data;
        var remaining = result.remaining;
        $("#madd-remaining").val(remaining);
        if(total_data > 0){
            var total_page = result.total_page;
            setTimeout(function() {
                if(page == 1){
                    $('#table-mlist').html("");
                }
                var datas = result.data;
                $("#table-mloader").hide();
                $('#table-mlist').append(show_data_modal(datas, page, item_perpage));
            }, 300);
        } else {
            setTimeout(function() {
                if(page == 1){
                    emptyItemModal();
                    $("#table-mloader").fadeOut();
                }
            }, 300);
        }
    }});
};
function get_item_list(){

    var url = api_ats_list;
    var session_id = $("#session-id").val();
    var session_token = $("#session-token").val();
    var shipment_type = $("#input-type").val();
    
    var data = {
        user_id : session_id,
        token : session_token,
        type : shipment_type
    }

    $.ajax({type: "POST",url: url,data : data, success:function(result){
        var total_data = result.num_data;
        if(total_data > 0){
            setTimeout(function() {
                var datas = result.data;
                $("#table-loader").hide();
                $('#table-list').html(show_data(datas));
            }, 300);
        } else {
            setTimeout(function() {
                emptyItem();
                $("#table-loader").fadeOut();
            }, 300);
        }
    }});
};
function show_data(datas){
    var resultHTML='';
    if(datas != null){
        var obj = datas;
        var num = 1;
        var row_warning = "";
        var disable_qty = "";
        for(var i=0;i < obj.length;i++){

            if(obj[i].ats_ref_product === ""){
                row_warning = "class='danger'";
                disable_qty = "disable-input2";
                class_qty = "";
                warning_text = "<tr class='danger row-error'><td colspan='15'><i class='fa fa-arrow-circle-up'></i><span>This product is not registered in our system</span><i class='fa fa-arrow-circle-up'></i></td></tr>";
            } else {
                row_warning = "";
                disable_qty = "";
                warning_text = "";
                class_qty = "rqty";
            }

            resultHTML += "<tr id='atrow-"+obj[i].ats_id+"' "+row_warning+">";
            resultHTML += "<td class='text-center'>"+num+"</td>";
            resultHTML += "<td class='text-center'>";
            resultHTML += obj[i].ats_sku;
            resultHTML += "</td>";
            resultHTML += "<td class='text-center'>";
            resultHTML += obj[i].ats_variant;
            resultHTML += "</td>";
            resultHTML += "<td class='text-center'>";
            resultHTML += obj[i].ats_barcode;
            resultHTML += "</td>";
            resultHTML += "<td>";
            resultHTML += obj[i].ats_product_name;
            resultHTML += "</td>";
            resultHTML += "<td class='text-center'>";
            if(obj[i].stock != null){
            resultHTML += obj[i].stock+" PCS";
            } else {
            resultHTML += "-";
            }
            resultHTML += "</td>";
            resultHTML += "<td class='text-center'>";
            resultHTML += "<div class='group-qty'>";
            resultHTML += "<div class='input-group'>";
            resultHTML += "<input id='qty-"+obj[i].ats_id+"' type='number' onchange='updateQty(&apos;"+obj[i].ats_id+"&apos;,&apos;"+obj[i].ats_ref_product+"&apos;,&apos;"+obj[i].ats_sku+"&apos;)' class='form-control "+class_qty+" "+disable_qty+"' min='1' value='"+obj[i].ats_qty+"' placeholder='0'>";
            resultHTML += "<div class='input-group-addon'>PCS</div>";
            resultHTML += "</div>";
            resultHTML += "</div>";
            resultHTML += "<input type='hidden' id='oqty-"+obj[i].ats_id+"' value='"+obj[i].ats_qty+"'>";
            resultHTML += "</td>";
            resultHTML += "<td class='text-center'>";
            resultHTML += "<a href='javascript:void(0);' onclick='confirmDelete(&apos;"+obj[i].ats_id+"&apos;,&apos;"+obj[i].ats_sku+"&apos;)' class='btn btn-danger btn-sm'>";
            resultHTML += "<i class='fa fa-trash'></i> Delete";
            resultHTML += "</a>";
            resultHTML += "</td>";
            resultHTML += "</tr>";
            resultHTML += warning_text;
            num++;
        }
    }
    return resultHTML;
}
function show_data_modal(datas,page,item_perpage){
    var resultHTML='';
    var row_warning = "";
    var disable_qty = "";
    var disable_btn = "";
    var set_val = "1";

    var type = $("#input-type").val();

    if(datas != null){
        var obj = datas;
        var num = 1;
        for(var i=0;i < obj.length;i++){
            var number = (page-1)*item_perpage+num;

            if(obj[i].stock < 1){
                row_warning = "class='danger'";
                if(type != "in"){
                    disable_qty = "disable-input2";
                    disable_btn = "disable-state";
                    set_val = "0";
                } else {
                    disable_qty = "";
                    disable_btn = "";
                    set_val = "1";
                }
            } else {
                row_warning = "";
                set_val = "1";
                disable_qty = "";
                disable_btn = "";
            }

            resultHTML += "<tr "+row_warning+">";
            resultHTML += "<td class='text-center'>"+number+"</td>";
            resultHTML += "<td class='text-center'>"+obj[i].sku+"</td>";
            resultHTML += "<td class='text-center'>"+obj[i].variant+"</td>";
            resultHTML += "<td class='text-center'>"+obj[i].barcode+"</td>";
            resultHTML += "<td>"+obj[i].product_name+"</td>";
            resultHTML += "<td class='text-center'>"+obj[i].stock+" PCS</td>";
            resultHTML += "<td class='text-center'>";
            resultHTML += "<div class='input-group group-maddqty'>";
            resultHTML += "<input id='mqty-"+obj[i].product_id+"' type='number' class='form-control mqty "+disable_qty+"' min='"+set_val+"' max='"+obj[i].stock+"' value='"+set_val+"' placeholder='0'>";
            resultHTML += "<div class='input-group-btn'>";
            resultHTML += "<button onclick='confirmOrder(&apos;"+obj[i].product_id+"&apos;,&apos;"+obj[i].sku+"&apos;)' class='btn btn-success btn-order "+disable_btn+"'>Order</button>";
            resultHTML += "</div>";
            resultHTML += "</div>";
            resultHTML += "</td>";
            resultHTML += "</tr>";
            num++;
        }
    }
    return resultHTML;
}
function updateQty(ats_id,product,sku){
    var url = api_ats_update_qty;
    var session_id = $("#session-id").val();
    var session_token = $("#session-token").val();
    var order_type = $("#input-type").val();
    var order_qty = $("#qty-"+ats_id).val();
    var old_qty = $("#oqty-"+ats_id).val();

    var settings = {
      "async": true,
      "crossDomain": true,
      "url": url,
      "method": "POST",
      "headers": {
        "content-type": "application/x-www-form-urlencoded"
      },
      "data": {
        "user_id": session_id,
        "token": session_token,
        "type": order_type,
        "product_id": product,
        "qty": order_qty,
      }
    }
    $.ajax(settings).done(function (result) {
        if(result.code == "200"){
            //Register Success
            successAlert("Item quantity <i><b>"+sku+"</b></i> succesfully updated to <i><b>"+order_qty+"</b></i> PCS.");
            $("#oqty-"+ats_id).val(order_qty);
        } else if(result.code == "401"){
            //Exceed stock
            errorAlert("Failed to edit quantity,<br> Total items quantity have exceeded the stock.");
            $("#qty-"+ats_id).val(old_qty);
        } else if(result.code == "402"){
            //Unauthorized
            errorAlert("Unauthorized access");
            $("#qty-"+ats_id).val(old_qty);
        } else if(result.code == "403"){
            //Unauthorized
            errorAlert("Minimal Order Quantity is 1");
            $("#qty-"+ats_id).val(old_qty);
        } else {
            //Something When Wrong
            errorAlert("Failed to add item,<br> something when wrong.");
            $("#qty-"+ats_id).val(old_qty);
        }
    });

}
function confirmOrder(product,sku){
    win_loader('open');
    var url = api_ats_insert;
    var session_id = $("#session-id").val();
    var session_token = $("#session-token").val();
    var order_type = $("#input-type").val();
    var order_qty = $("#mqty-"+product).val();

    if(order_qty > 0){
        var settings = {
          "async": true,
          "crossDomain": true,
          "url": url,
          "method": "POST",
          "headers": {
            "content-type": "application/x-www-form-urlencoded"
          },
          "data": {
            "user_id": session_id,
            "token": session_token,
            "type": order_type,
            "product_id": product,
            "qty": order_qty,
          }
        }
        $.ajax(settings).done(function (result) {
            if(result.code == "200"){
                win_loader('close');
                //Register Success
                successAlert("Item <i><b>"+sku+"</b></i> succesfully added to shipment.");

                $('.mqty').each(function(){
                    if($(this).hasClass("disable-input2")){
                        $(this).val("0");
                    } else {
                        $(this).val("1");
                    }
                 });
                load_item();
            } else if(result.code == "410"){
                win_loader('close');
                //Exceed stock
                win_loader('close');
                errorAlert("Failed to Add Item,<br> Data Product Not Found.");
            } else if(result.code == "401"){
                win_loader('close');
                //Exceed stock
                errorAlert("Failed to Add Item,<br> Total items quantity have exceeded the stock.");
            } else if(result.code == "402"){
                win_loader('close');
                //Unauthorized
                errorAlert("Unauthorized access");
            } else {
                win_loader('close');
                //Something When Wrong
                errorAlert("Failed to add item,<br> something when wrong.");
            }
        });
    } else {
        win_loader('close');
        //Exceed stock
        errorAlert("Failed to add item,<br> Quantity is 0.");
    }
}
function confirmOrderBarcode(barcode){
    var url = api_ats_insert_barcode;
    var session_id = $("#session-id").val();
    var session_token = $("#session-token").val();
    var order_type = $("#input-type").val();
    var order_qty = "1";

    if(order_qty > 0){
        var settings = {
          "async": true,
          "crossDomain": true,
          "url": url,
          "method": "POST",
          "headers": {
            "content-type": "application/x-www-form-urlencoded"
          },
          "data": {
            "user_id": session_id,
            "token": session_token,
            "type": order_type,
            "barcode": barcode,
            "qty": order_qty,
          }
        }
        $.ajax(settings).done(function (result) {
            if(result.code == "200"){
                //Register Success
                successAlert("Item <i><b>"+result.sku+"</b></i> succesfully added to shipment.");

                $('.mqty').each(function(){
                    if($(this).hasClass("disable-input2")){
                        $(this).val("0");
                    } else {
                        $(this).val("1");
                    }
                 });
                load_item();
            } else if(result.code == "410"){
                //Exceed stock
                errorAlert("Failed to Add Item,<br> Data Product Not Found.");
            } else if(result.code == "401"){
                //Exceed stock
                errorAlert("Failed to Add Item,<br> Total items quantity have exceeded the stock.");
            } else if(result.code == "402"){
                //Unauthorized
                errorAlert("Unauthorized access");
            } else {
                //Something When Wrong
                errorAlert("Failed to add item,<br> something when wrong.");
            }
        });
    } else {
        //Exceed stock
        errorAlert("Failed to add item,<br> Quantity is 0.");
    }

}
$(document).scannerDetection({

    timeBeforeScanTest: 200, // wait for the next character for upto 200ms
    avgTimeByChar: 40, // it's not a barcode if a character takes longer than 100ms
    preventDefault: false,
    onComplete: function(barcode, qty){
        validScan = true;
        confirmOrderBarcode(barcode);
    },
    onKeyDetect: function(event){console.log(event.which); return false;},
});
function delete_item(ats_id,sku){
    var url = api_ats_delete;
    var session_id = $("#session-id").val();

    var settings = {
      "async": true,
      "crossDomain": true,
      "url": url,
      "method": "POST",
      "headers": {
        "content-type": "application/x-www-form-urlencoded"
      },
      "data": {
        "user_id": session_id,
        "ats_id": ats_id
      }
    }
    $.ajax(settings).done(function (result) {
        if(result.code == "200"){
            //Register Success
            successAlert("Item <i><b>"+sku+"</b></i> succesfully deleted from shipment.");
            load_item();
        } else if(result.code == "402"){
            //Unauthorized
            errorAlert("Unauthorized access");
        } else {
            //Something When Wrong
            errorAlert("Failed to delete item,<br> something when wrong.");
        }
    });

}
//function confirmation delete
function confirmDelete(ats_id, sku){
    swal({
        title: "Are you sure?",
        text: "You will delete item "+sku+" from shipment list!",
        type: "warning",
        showCancelButton: true,
        confirmButtonColor: "#DD6B55",
        confirmButtonText: "Delete ! ",
        cancelButtonText: "Cancel !",
        closeOnConfirm: true,
        closeOnCancel: true
    },
    function (isConfirm) {
        if (isConfirm) {
            delete_item(ats_id, sku);
        } else {
            //nothing
        }
    });
}
function emptyItem(){
    resultHTML = "<tr><td colspan='15' class='text-center'>There is no data right now.</td></tr>";
    $('#table-list').html(resultHTML);
}
function emptyItemModal(){
    resultHTML = "<tr><td colspan='15' class='text-center'>There is no data right now.</td></tr>";
    $('#table-mlist').html(resultHTML);
}
function checkSessionStat(){
    var status = sessionStorage.getItem("alert_status");
    var message = sessionStorage.getItem("alert_message");
    if(status == "success"){
        successAlert(message);
        sessionStorage.removeItem("alert_status");
        sessionStorage.removeItem("alert_message");
    } else if(status == "failed"){
        errorAlert(message);
        sessionStorage.removeItem("alert_status");
        sessionStorage.removeItem("alert_message");
    }
}
//load new item on scroll modal box
jQuery(function($) {
    $('.madd-table').on('scroll', function() {
        if($(this).scrollTop() + $(this).innerHeight() >= $(this)[0].scrollHeight) {
            var cur_page = $("#madd-page").val();
            var cur_remaining = $("#madd-remaining").val();
            if(cur_remaining > 0){
                var now_page = eval(cur_page) + eval(1);
                load_item_modal(now_page);
            }
        }
    })
});
//START SAVING FORM
$("#btn-submit").click(function(){
    toggleDisableForm("disable");
    if(validateForm()){
        insert_data();
        //toggleDisableForm("enable");
    } else {
        toggleDisableForm("enable");
    }
});
function toggleDisableForm(param){
    if(param == "disable"){
        $("#btn-submit").addClass("disable-state");
        $("#btn-submit").html("<i class='fa fa-spinner fa-spin'></i> Loading");
        $("#form-insert .form-control").addClass("disable-input");
    } else {
        $("#btn-submit").removeClass("disable-state");
        $("#btn-submit").html("<i class='fa fa-save'></i> Confirm Data");
        $("#form-insert .form-control").removeClass("disable-input");
    }
}
function insert_data(){
    var type = $("#input-type").val();//shipment type in/out
    var order_id = $("#input-order").val();
    var via = $("#input-via").val();
    var otype = $("#input-otype").val();//order type for sale / no sale
    var market_name = $("#input-mname").val();//marketplace name like shopee/tokopedia/dll
    var cname = $("#input-cname").val();//courier name
    var cservice = $("#input-cservice").val();//courier service
    var pickup_date = $("#input-pickup_date").val();
    var deliver_date = $("#input-deliver_date").val();
    var address_name = $("#input-address_name").val();
    var contact = $("#input-contact").val();
    var phone = $("#input-phone").val();
    var address = $("#input-address").val();
    var notes = $("#input-notes").val();
    var session_token = $("#session-token").val();

    var session_id = $("#session-id").val();
    var redir_url = $("#redir-url").val();

    var url = api_shipment_insert;
    var settings = {
      "async": true,
      "crossDomain": true,
      "url": url,
      "method": "POST",
      "headers": {
        "content-type": "application/x-www-form-urlencoded"
      },
      "data": {
        "user_id": session_id,
        "type": type,
        "order_id": order_id,
        "via": via,
        "otype": otype,
        "mname": market_name,
        "cname": cname,
        "cservice": cservice,
        "pickup_date": pickup_date,
        "address_name": address_name,
        "contact": contact,
        "phone": phone,
        "address": address,
        "notes": notes,
        "order_token": session_token,
      }
    }
    $.ajax(settings).done(function (result) {
        console.log(result);
        if(result.code == "200"){
            var shipment_id = result.shipment;
            //Register Success
            sessionStorage.setItem("alert_status", "success");
            sessionStorage.setItem("alert_message", "New Shipment <i><b>"+shipment_id+"</b></i> Succesfully Created.");
            window.location.href = redir_url+type+"/";
        } else if(result.code == "401"){
            //Exist Barcode
            errorAlert("Failed to create shipment,<br> Please check your item Stock.");
            toggleDisableForm("enable");
        } else if(result.code == "402"){
            //Unauthorized
            errorAlert("Unauthorized access");
            toggleDisableForm("enable");
        } else {
            //Something When Wrong
            errorAlert("Failed to create shipment,<br> something when wrong.");
            toggleDisableForm("enable");
        }
    });
};
function validateForm(){
    var type = $("#input-type").val();//shipment type in/out
    var order_id = $("#input-order").val();
    var via = $("#input-via").val();
    var otype = $("#input-otype").val();//order type for sale / no sale
    var mname = $("#input-mname").val();//marketplace name like shopee/tokopedia/dll
    var cname = $("#input-cname").val();//courier name
    var cservice = $("#input-cservice").val();//courier service
    var pickup_date = $("#input-pickup_date").val();
    var deliver_date = $("#input-deliver_date").val();
    var address_name = $("#input-address_name").val();
    var contact = $("#input-contact").val();
    var phone = $("#input-phone").val();
    var address = $("#input-address").val();
    var notes = $("#input-notes").val();
    var session_token = $("#session-token").val();
    var total_item = $(".rqty").length;

    var mailformat = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/;
    var numFormat = /^\+?[\d+ ]*$/;
    var urlFormat = /^HTTP|HTTP|http(s)?:\/\/(www\.)?[A-Za-z0-9]+([\-\.]{1}[A-Za-z0-9]+)*\.[A-Za-z]{2,40}(:[0-9]{1,40})?(\/.*)?$/;


    //alert(total_item);
    if(type != ""){
        $("#error-type").html("");
        $("#error-type").hide();
    } else {
        $("#error-type").show();
        $("#error-type").html("<i class='fa fa-warning'></i> This field is required.");
        $("#input-type").focus();
        return false;
    }
    if(order_id != ""){
        $("#error-order").html("");
        $("#error-order").hide();
    } else {
        $("#error-order").show();
        $("#error-order").html("<i class='fa fa-warning'></i> This field is required.");
        $("#input-order").focus();
        return false;
    }
    if(via != ""){
        $("#error-via").html("");
        $("#error-via").hide();
    } else {
        $("#error-via").show();
        $("#error-via").html("<i class='fa fa-warning'></i> This field is required.");
        $("#input-via").focus();
        return false;
    }
    if(otype != ""){
        $("#error-otype").html("");
        $("#error-otype").hide();
    } else {
        $("#error-otype").show();
        $("#error-otype").html("<i class='fa fa-warning'></i> This field is required.");
        $("#input-otype").focus();
        return false;
    }
    if(via == "3rd"){
        if(cname != ""){
            $("#error-cname").html("");
            $("#error-cname").hide();
        } else {
            $("#error-cname").show();
            $("#error-cname").html("<i class='fa fa-warning'></i> This field is required.");
            $("#input-cname").focus();
            return false;
        }
        if(cservice != ""){
            $("#error-cservice").html("");
            $("#error-cservice").hide();
        } else {
            $("#error-cservice").show();
            $("#error-cservice").html("<i class='fa fa-warning'></i> This field is required.");
            $("#input-cservice").focus();
            return false;
        }
    }
    if(pickup_date != ""){
        $("#error-pickup_date").html("");
        $("#error-pickup_date").hide();
    } else {
        $("#error-pickup_date").show();
        $("#error-pickup_date").html("<i class='fa fa-warning'></i> This field is required.");
        $("#input-pickup_date").focus();
        return false;
    }
    if(otype == "marketplace"){
        if(mname != ""){
            $("#error-mname").html("");
            $("#error-mname").hide();
        } else {
            $("#error-mname").show();
            $("#error-mname").html("<i class='fa fa-warning'></i> This field is required.");
            $("#input-mname").focus();
            return false;
        }
    }
    if(address_name != ""){
        $("#error-address_name").html("");
        $("#error-address_name").hide();
    } else {
        $("#error-address_name").show();
        $("#error-address_name").html("<i class='fa fa-warning'></i> This field is required.");
        $("#input-address_name").focus();
        return false;
    }
    if(contact != ""){
        $("#error-contact").html("");
        $("#error-contact").hide();
    } else {
        $("#error-contact").show();
        $("#error-contact").html("<i class='fa fa-warning'></i> This field is required.");
        $("#input-contact").focus();
        return false;
    }
    if(phone != ""){
        $("#error-phone").html("");
        $("#error-phone").hide();
    } else {
        $("#error-phone").show();
        $("#error-phone").html("<i class='fa fa-warning'></i> This field is required.");
        $("#input-phone").focus();
        return false;
    }
    if(address != ""){
        $("#error-address").html("");
        $("#error-address").hide();
    } else {
        $("#error-address").show();
        $("#error-address").html("<i class='fa fa-warning'></i> This field is required.");
        $("#input-address").focus();
        return false;
    }
    if(total_item > 0){
        //nothing
    } else {
        errorAlert("Please add min 1 item to create shipment!");
        return false;
    }
    return true;
}
function get_brand(){

    var url = api_select_brand;
    var session_id = $("#session-id").val();
    var brand = "";
    var data = {
        user_id : session_id,
        keyword : brand
    }
    $.ajax({type: "POST",url: url,data : data, success:function(result){
        var code = result.code;
        if(code == 200){
            var datas = result.data;
            $('#brand-select').html(show_brand(datas));
        } else {
            $('#brand-select').html("<option value=''>-All Brand-</option>");
        }
    }});
    
};
function get_category(){

    var url = api_select_category;
    var session_id = $("#session-id").val();
    var brand = $("#brand-select").val();
    var category = "";
    var data = {
        user_id : session_id,
        brand : brand,
        keyword : category
    }
    $.ajax({type: "POST",url: url,data : data, success:function(result){
        var code = result.code;
        var brand_id = result.brand_id;
        if(code == 200){
            var datas = result.data;
            $('#category-select').html(show_category(datas,brand_id));
        } else {
            $('#category-select').html("<option value=''>-All Category-</option>");
        }
    }});
    
};
function show_brand(datas){
    var resultHTML="<option value=''>-All Brand-</option>";
    if(datas != null){
        var obj = datas;
        var num = 1;
        for(var i=0;i < obj.length;i++){
            resultHTML += "<option value='"+obj[i].brand_title+"'>"+obj[i].brand_title.toUpperCase()+"</option>";
            num++;
        }
    }
    return resultHTML;
}
function show_category(datas){
    var resultHTML="<option value=''>-All Category-</option>";
    if(datas != null){
        var obj = datas;
        var num = 1;
        for(var i=0;i < obj.length;i++){
            resultHTML += "<option value='"+obj[i].category_title+"'>"+obj[i].category_title+"</option>";
            num++;
        }
    }
    return resultHTML;
}
$('#brand-select').on('change', function() {
    $("#category-select").val("");
    get_category();
    load_item_modal(1);
});
$('#category-select').on('change', function() {
    load_item_modal(1);
});
$("#input-address_name").keyup(function(){
    get_address();
});
function get_address(){

    var url = api_select_address;
    var session_id = $("#session-id").val();
    var address_name = $("#input-address_name").val();
    var data = {
        user_id : session_id,
        keyword : address_name
    }
    $.ajax({type: "POST",url: url,data : data, success:function(result){
        var code = result.code;
        if(code == 200){
            var datas = result.data;
            $('#list-address').html(show_address(datas));
            $("#view-select").show();
        } else {
            $("#view-select").hide();
        }
    }});
    
};
function show_address(datas){
    var resultHTML="";
    if(datas != null){
        var obj = datas;
        var num = 1;
        for(var i=0;i < obj.length;i++){
            resultHTML += "<li class='address-li' onclick='getDetailAddress(&apos;"+obj[i].address_id+"&apos;,&apos;"+obj[i].address_name+"&apos;)'>";
            resultHTML += "<div class='adr-name'>"+obj[i].address_name+"</div>";
            resultHTML += "<div class='adr-desc'>";
            resultHTML += obj[i].address_desc;
            resultHTML += "</div>";
            resultHTML += "</li>";
            num++;
        }
    }
    return resultHTML;
}
$(document).mouseup(function(e) 
{
    var container = $("#view-select");

    // if the target of the click isn't the container nor a descendant of the container
    if (!container.is(e.target) && container.has(e.target).length === 0) 
    {
        container.hide();
    }
});
function getDetailAddress(param,address_name){

    $("#input-address_name").val(address_name);
    $("#view-select").hide();

    var url = api_detail_address;
    var session_id = $("#session-id").val();
    var address_name = $("#input-address_name").val();
    var data = {
        user_id : session_id,
        address_id : param
    }
    $.ajax({type: "POST",url: url,data : data, success:function(result){
        var code = result.code;
        if(code == 200){
            var datas = result.data;

            $("#input-address").val(datas[0].address_desc);
            $("#input-contact").val(datas[0].address_contact);
            $("#input-phone").val(datas[0].address_phone);

        } else {

            $("#input-address").val("");
            $("#input-contact").val("");
            $("#input-phone").val("");

        }
    }});
    
};