function OpenDetail(param){
    var redir_url = $("#redir-detail").val();
    window.location.href = redir_url+param+"/";
}
$(document).ready(function() {
    checkSessionStat();
    load_item(1);
    get_region();
    setTimeout( function(){ 
        detectFilter();
    }, 1500 );
});
// START PAGINATION JS
function createPagination(total_page, total_data){
    $('#pag-list').html("");
    $("#mod-pagination").hide();
    var opage = $("#cur-page").val();
    batch = getBatch(opage);
    if(batch < 1){batch = 1;}
    prevLimit = 1 +(5*(batch-1));
    nextLimit = 5 * batch;
    if(nextLimit > total_page){
        nextLimit = total_page;
    }

    var resultHTML= "";
    var active = "";
    for(var i=prevLimit;i <= nextLimit;i++){
        if(opage == i){
            active = "active";
        } else {
            active = "";
        }
        resultHTML += "<li id='pagenum-"+i+"' class='pag-link "+active+"'>";
        resultHTML += "<a href='javascript:void(0);' onclick='load_item(&apos;"+i+"&apos;)'>"+i+"</a>";
        resultHTML += "</li>";
    }

    //previous button
    if(opage > 1){
        $("#pag-prev").show();
    } else {
        $("#pag-prev").hide();
    }

    //next button
    if(total_page > 1 && (opage < total_page)){
        $("#pag-next").show();
    } else {
        $("#pag-next").hide();
    }

    $("#mod-pagination").show();
    $('#pag-list').append(resultHTML);
}
$("#btn-prev").click(function(){
    var opage = $("#cur-page").val();
    var page = eval(opage) - 1;
    load_item(page);
});
$("#btn-next").click(function(){
    var opage = $("#cur-page").val();
    var page = eval(opage) + 1;
    load_item(page);
});
// END PAGINATION JS
function load_item(page){
    $("#table-list").html("");
    $(".pag-link").removeClass("active");
    if(page != 1){
        $("#table-loader").fadeIn();
    } else {
        $("#table-loader").show();
    }
    $("#pagenum-"+page).addClass("active");
    get_item(page);
}
function get_item(page){
    var item_perpage = 10;//item perpage

    var url = api_client_list;
    var session_id = $("#session-id").val();
    var region = $("#region-select").val();
    var search_key = $("#search-input").val();
    
    var data = {
        user_id : session_id,
        item : item_perpage,
        region : region,
        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;
        if(total_data > 0){
            $("#label-total").html(total_data);
            var total_page = result.total_page;
            createPagination(total_page, total_data);
            setTimeout(function() {
                var datas = result.data;
                $("#table-loader").hide();
                $("#table-list").html("");
                $('#table-list').append(show_data(datas, page, item_perpage));
            }, 300);
            $("#total-label").text(total_data);
        } else {
            $("#label-total").html(0);
            setTimeout(function() {
                emptyItem();
                $("#table-loader").fadeOut();
                createPagination(0, 0);
            }, 300);
        }
    }});
};
function emptyItem(){
    resultHTML = "<tr><td colspan='15' class='text-center'>There is no data right now.</td></tr>";
    $('#table-list').html(resultHTML);
}
function show_data(datas,page,item_perpage){
    var redir_url = $("#redir-url").val();
    var acsc_edit = $("#acsc-edit").val();
    var acsc_delete = $("#acsc-delete").val();
    var redir_detail = redir_url+"detail/";
    var resultHTML='';
    if(datas != null){
        var obj = datas;
        var num = 1;
        for(var i=0;i < obj.length;i++){
            if(obj[i].stock < 1){
                var css_red = "bg-red";
            } else {
                var css_red = "";
            }
            var number = (page-1)*item_perpage+num;

            if(obj[i].client_active == 'yes'){
                var label_stat = "<span class='label labe-xs label-info'>active</span>"
            } else {
                var label_stat = "<span class='label labe-xs label-warning'>inactive</span>"
            }

            resultHTML += "<tr>";
            resultHTML += "<td class='text-center'>"+number+"</td>";
            resultHTML += "<td class='text-center'>"+obj[i].client_name+"</td>";
            resultHTML += "<td class='text-center'>"+obj[i].client_phone+"</td>";
            resultHTML += "<td class='text-center'>"+obj[i].client_email+"</td>";
            // resultHTML += "<td class='text-center' style='text-transform: capitalize;'>"+obj[i].region_title+"</td>";
            resultHTML += "<td class='text-center'>"+label_stat+"</td>";
            resultHTML += "<td class='text-center'>"+dateFormat(obj[i].client_create_date, "dd mmmm yyyy, H:MM")+"</td>";
            resultHTML += "<td class='text-center'>";
            resultHTML += "<div class='btn-group'>";
            if(acsc_edit == 1){
            resultHTML += "<a href='"+redir_detail+obj[i].client_id+"/' class='btn btn-info btn-xs btn-flat'>";
            resultHTML += "<i class='fa fa-edit'></i> Edit";
            resultHTML += "</a>";
            } else {
            resultHTML += "<a href='#' class='btn btn-default btn-xs btn-flat disable-state'>";
            resultHTML += "<i class='fa fa-edit'></i> Edit";
            resultHTML += "</a>";
            }
            if(acsc_delete == 1){
            resultHTML += "<a href='javascript:void(0);'  onclick='confirmDelete(&apos;"+obj[i].client_id+"&apos;, &apos;"+obj[i].client_name+"&apos;);' class='btn btn-danger btn-xs btn-flat'>";
            resultHTML += "<i class='fa fa-trash'></i> Delete";
            resultHTML += "</a>";
            } else {
            resultHTML += "<a href='#' class='btn btn-default btn-xs btn-flat disable-state'>";
            resultHTML += "<i class='fa fa-trash'></i> Delete";
            resultHTML += "</a>";
            }
            resultHTML += "</div>";
            resultHTML += "</td>";
            resultHTML += "</tr>";
            num++;
        }
    }
    return 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");
    }
}
function get_region(){

    var url = api_region_select;
    var session_id = $("#session-id").val();
    var region = "";
    var data = {
        user_id : session_id,
        keyword : region
    }
    $.ajax({type: "POST",url: url,data : data, success:function(result){
        var code = result.code;
        if(code == 200){
            var datas = result.data;
            $('#region-select').html(show_region(datas));
        } else {
            $('#region-select').html("<option value=''>-All Region-</option>");
        }
    }});
    
};
function show_region(datas){
    var resultHTML="<option value=''>-All Region-</option>";
    if(datas != null){
        var obj = datas;
        var num = 1;
        for(var i=0;i < obj.length;i++){
            resultHTML += "<option value='"+obj[i].region_id+"'>"+obj[i].region_title.toUpperCase()+"</option>";
            num++;
        }
    }
    return resultHTML;
}
$('#region-select').on('change', function() {
    $("#client-select").val("");
    load_item(1);
    detectFilter();
});
$('#input-eregion').on('change', function() {
    $("#input-eclient").val("");
    get_ecat();
});
$('#client-select').on('change', function() {
    load_item(1);
    detectFilter();
});
$("#search-input").keyup(function(){
    load_item(1);
    detectFilter();
});
$("#btn-clear").click(function(){
    clearFilter();
    detectFilter();
});
function clearFilter(){
    $("#region-select").val("");
    $("#search-input").val("");
    load_item(1);
}
function detectFilter(){
    //var region = $("#region-select").val();
    var search_key = $("#search-input").val();

    $("#btn-clear").css("display","none");
    // if(region != ""){
    //     $("#btn-clear").css("display","inline-block");
    // }
    if(search_key != ""){
        $("#btn-clear").css("display","inline-block");
    }

}
$("#btn-submit").click(function(){
    var title = $("#input-title").val();
    $("#btn-submit").addClass("disable-state");
    $("#btn-submit").html("<i class='fa fa-spinner fa-spin'></i> Loading");
    $("#form-insert .form-control").addClass("disable-input");
    if(title != ""){
        $("#error-title").html("");
        $("#error-title").hide();
        $("#input-title").removeClass("input-error");
        //insert
        insert_data();
    } else {
        $("#error-title").show();
        $("#error-title").html("<i class='fa fa-warning'></i> This field is required.");
        $("#input-title").addClass("input-error");
        $("#input-title").focus();

        $("#btn-submit").removeClass("disable-state");
        $("#btn-submit").html("<i class='fa fa-save'></i> Save Data");
        $("#form-insert .form-control").removeClass("disable-input");

        return false;
    }
});
$("#btn-esubmit").click(function(){
    var title = $("#input-etitle").val();
    $("#btn-esubmit").addClass("disable-state");
    $("#btn-esubmit").html("<i class='fa fa-spinner fa-spin'></i> Loading");
    $("#form-edit .form-control").addClass("disable-input");
    if(title != ""){
        $("#error-etitle").html("");
        $("#error-etitle").hide();
        $("#input-etitle").removeClass("input-error");
        //update
        update_data();
    } else {
        $("#error-etitle").show();
        $("#error-etitle").html("<i class='fa fa-warning'></i> This field is required.");
        $("#input-etitle").addClass("input-error");
        $("#input-etitle").focus();

        $("#btn-esubmit").removeClass("disable-state");
        $("#btn-esubmit").html("<i class='fa fa-save'></i> Save Changes");
        $("#form-edit .form-control").removeClass("disable-input");

        return false;
    }
});
$('#modal-insert').on('hidden.bs.modal', function (e) {
    $("#error-title").html("");
    $("#error-title").hide();
    $("#input-title").removeClass("input-error");
});
function openEdit(region_id,item_id,title){
    $("#input-eregion").val(region_id);
    $("#input-item_id").val(item_id);
    $("#input-etitle").val(title);
    $('#modal-edit').modal('show');
}
$('#modal-edit').on('hidden.bs.modal', function (e) {
    $("#error-etitle").html("");
    $("#error-etitle").hide();
    $("#input-etitle").removeClass("input-error");
    $("#input-item_id").val("");
    $("#input-etitle").val("");
});
function confirmDelete(param, title){
    var url_page = $("#redir-url").val();
    var redir_url = url_page+"?action=delete&id="+param+"&title="+title;
    swal({
        title: "Are you sure delete "+title+"?",
        text: "You will not be able to recover this file!",
        type: "warning",
        showCancelButton: true,
        confirmButtonColor: "#DD6B55",
        confirmButtonText: "Delete ! ",
        cancelButtonText: "Cancel !",
        closeOnConfirm: true,
        closeOnCancel: true
    },
    function (isConfirm) {
        if (isConfirm) {
            window.location.href = redir_url;
        } else {
            //nothing
        }
    });
}
function insert_data(){
    var region = $("#input-iregion").val();
    var title = $("#input-title").val();

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

    var url = api_client_insert;
    var settings = {
      "async": true,
      "crossDomain": true,
      "url": url,
      "method": "POST",
      "headers": {
        "content-type": "application/x-www-form-urlencoded"
      },
      "data": {
        "user_id": session_id,
        "region": region,
        "title": title,
      }
    }
    $.ajax(settings).done(function (result) {
        if(result.code == "200"){

            //Register Success
            sessionStorage.setItem("alert_status", "success");
            sessionStorage.setItem("alert_message", "Category <i><b>"+title+"</b></i> Succesfully Created.");
            window.location.href = redir_url;

        } else if(result.code == "402"){

            //Unauthorized
            errorAlert("Unauthorized access");
            $("#btn-submit").removeClass("disable-state");
            $("#btn-submit").html("<i class='fa fa-save'></i> Save Data");
            $("#form-insert .form-control").removeClass("disable-input");
            $("#modal-insert").modal('hide');

        } else {

            //Something When Wrong
            errorAlert("Failed to create client,<br> something when wrong.");
            $("#btn-submit").removeClass("disable-state");
            $("#btn-submit").html("<i class='fa fa-save'></i> Save Data");
            $("#form-insert .form-control").removeClass("disable-input");
            $("#modal-insert").modal('hide');

        }
    });
};
function update_data(){
    var item_id = $("#input-item_id").val();
    var region = $("#input-eregion").val();
    var title = $("#input-etitle").val();

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

    var url = api_client_edit;
    var settings = {
      "async": true,
      "crossDomain": true,
      "url": url,
      "method": "POST",
      "headers": {
        "content-type": "application/x-www-form-urlencoded"
      },
      "data": {
        "user_id": session_id,
        "item_id": item_id,
        "region": region,
        "title": title,
      }
    }
    $.ajax(settings).done(function (result) {
        if(result.code == "200"){
            
            //Register Success
            sessionStorage.setItem("alert_status", "success");
            sessionStorage.setItem("alert_message", "Category <i><b>"+title+"</b></i> Succesfully Edited.");
            window.location.href = redir_url;

        } else if(result.code == "402"){

            //Unauthorized
            errorAlert("Unauthorized access");
            $("#btn-esubmit").removeClass("disable-state");
            $("#btn-esubmit").html("<i class='fa fa-save'></i> Save Changes");
            $("#form-edit .form-control").removeClass("disable-input");
            $("#modal-edit").modal('hide');

        } else {

            //Something When Wrong
            errorAlert("Failed to edit client,<br> something when wrong.");
            $("#btn-esubmit").removeClass("disable-state");
            $("#btn-esubmit").html("<i class='fa fa-save'></i> Save Changes");
            $("#form-edit .form-control").removeClass("disable-input");
            $("#modal-edit").modal('hide');

        }
    });
};
function delete_data(param,title){
    win_loader('open');
    var session_id = $("#session-id").val();
    var redir_url = $("#redir-url").val();

    var url = api_client_delete;
    var settings = {
      "async": true,
      "crossDomain": true,
      "url": url,
      "method": "POST",
      "headers": {
        "content-type": "application/x-www-form-urlencoded"
      },
      "data": {
        "user_id": session_id,
        "item_id": param,
      }
    }
    $.ajax(settings).done(function (result) {
        if(result.code == "200"){
            
            //Register Success
            sessionStorage.setItem("alert_status", "success");
            sessionStorage.setItem("alert_message", "Category <i><b>"+title+"</b></i> Succesfully Deleted.");
            window.location.href = redir_url;

        } else if(result.code == "402"){

            //Unauthorized
            errorAlert("Unauthorized access");
            win_loader('close');

        } else {

            //Something When Wrong
            errorAlert("Failed to delete client,<br> something when wrong.");
            win_loader('close');

        }
    });
};