var business_nature_idx = 0;

/**
 * funtion add new line to html table
 */
function addNewBusinessNatureLine() {
    $('#businessNature-table-body').append(
        '<tr id="tr_business_nature'+business_nature_idx+'" class="new_business_nature">'+
        '<td><input type="checkbox" id="business_nature_check'+business_nature_idx+'" class="business_nature_check" value="'+business_nature_idx+'" name="business_nature_chk[]"></td>' +
        '<td><input type="text" id="business_nature_desc'+business_nature_idx+'" class="form-control business_nature_desc"></td>'+
        '<td style="display:none" class="business_nature_id" id="business_nature_id'+business_nature_idx+'">-1</td>'+
        '<td style="display:none" class="business_nature_idx" id="business_nature_idx'+business_nature_idx+'">'+business_nature_idx+'</td>'+
        '</tr>'
    );

    business_nature_idx++;
}

/**
 * funtion save table value to database
 * callback to onResponseBusinessNatureEntry()
 */
function saveBusinessNature() {
    LoadingScreen("show");

    if( validateBusinessNature() ){
        var data = { 
                 "type"                     : C_ADD,
				 "index"                    : screen_index,
                 "new_business_nature"      : getNewBusinessNatureTable(),
                 "existing_business_nature" : getBusinessNatureTable()
				};
        var url  = "index.pzx?c=" + business_nature_url + "&d=" + new Date().getTime() ;
		callServer(url,"json",data,onResponseBusinessNatureEntry,null) ;
		return false;
    }else{
        LoadingScreen("hide");
        swal.fire('Warning',"Please fill all description",'warning');
    }
}

/**
 * funtion get table value 
 * return json array
 */
function getNewBusinessNatureTable() {
    var arrays = [];
    $('#businessNature-table-body tr.new_business_nature').each(function() { 
		var idx = $('.business_nature_idx',this).html() ;
        var data = {     
			"business_nature_id"  : $('.business_nature_id',this).html() ,
			"desc"              : $(".business_nature_desc",this).val(),
        };   

        arrays.push(data);
    }); 

    if(arrays == ""){
        return "";
    }else{
        return JSON.stringify(arrays) ;
    }
    
}

function getBusinessNatureTable() {
    var arrays = [];
    $('#businessNature-table-body tr.existing_business_nature').each(function() { 
		var idx = $('.business_nature_idx',this).html() ;
        var data = {     
			"business_nature_id"  : $('.business_nature_id',this).html() ,
			"desc"              : $(".business_nature_desc",this).val(),
        };   

        arrays.push(data);
    }); 
    
    return JSON.stringify(arrays) ;
}

/**
 * funtion validate data
 * check if have empty value on the table
 * return boolean
 */
function validateBusinessNature() {
    var allstatus = true;
    $('#currency-master-table-body tr').each(function() { 
		var desc = $(".business_nature_desc",this).val();
        if(desc=="" || desc==undefined){
            
            allstatus = false;
        }

    }); 

    return allstatus;    
}

/** 
 * amend all field to be edited
*/
function amendBusinessNatureLine() {
    $('.business_nature_check').prop('disabled',false);
    $('.business_nature_desc').prop('disabled',false);
}

/**
 * delete record on table
 * check if id value = -1
 * if not have to remove from database first
 */
function resetBusinessNaturePassword() {
    var lines = [];
	$("input[name='business_nature_chk[]']:checked").each(function(i){
		lines[i] = $(this).val();
	});
  
    //confirmation and delete column
	if(lines.length > 0) {
		swal.fire("System Confirmation", "Are you sure you want to reset the password of selected business nature?", "warning", {
			buttons: {
				ok: true,
				cancel: "Cancel",
			},
		})
		.then(function(result) {
		switch (result) {
		  case "ok":
            var arrays =[];
            var count = 0;
            for(var i = 0; i < lines.length; i++) {
               
                if($('#business_nature_id'+lines[i]).html() == -1){
                    count++;
                }else{
                    arrays.push($('#business_nature_id'+lines[i]).html());
                }
            }
      
            if(arrays.length > 0){
                LoadingScreen("show");
                var data = { "type": C_CHANGE, "id": JSON.stringify(arrays), "index":screen_index };		
                var url  = "index.pzx?c=" + business_nature_url + "&d=" + new Date().getTime() ;
                callServer(url,"json",data,onResponseBusinessNatureEntry,null) ;
            }else if(count > 0){
                swal.fire("warning", "Selected business nature hasnt been saved into database");
            }
		  break;
		}
		});
	} else {
		return;
    }
}

function deleteBusinessNatureLine() {
    var lines = [];
	$("input[name='business_nature_chk[]']:checked").each(function(i){
		lines[i] = $(this).val();
	});
  
    //confirmation and delete column
	if(lines.length > 0) {
		swal.fire("System Confirmation", "Are you sure you want to delete the selected record?", "warning", {
			buttons: {
				ok: true,
				cancel: "Cancel",
			},
		})
		.then(function(result) {
		switch (result) {
		  case "ok":
            var arrays =[];
            for(var i = 0; i < lines.length; i++) {
               
                if($('#business_nature_id'+lines[i]).html() == -1){
                    $('#tr_business_nature'+lines[i]).remove();
                }else{
                    arrays.push($('#business_nature_id'+lines[i]).html());

                }
            }
      
            if(arrays.length > 0){
                LoadingScreen("show");
                var data = { "type": C_DELETE, "id": JSON.stringify(arrays), "index":screen_index };		
                var url  = "index.pzx?c=" + business_nature_url + "&d=" + new Date().getTime() ;
                callServer(url,"json",data,onResponseBusinessNatureEntry,null) ;
            }
		  break;
		}
		});
	} else {
		return;
    }
}

/**
 * get analysis setting record/ filter
 * callback to onResponseBusinessNatureEntry()
 */
function businessNatureFilter() {    
    LoadingScreen("show");
    var data = { "type": C_LIST,
				 "index": screen_index,
                 "sorts": sorts,
				};
    var url  = "index.pzx?c=" + business_nature_url + "&d=" + new Date().getTime() ;
	callServer(url,"json",data,onResponseBusinessNatureEntry,null) ;
}

/**
 * response callback from above function
 */
function onResponseBusinessNatureEntry(obj,resp) {
    LoadingScreen("hide");
    if(resp.status!=C_OK){
		swal.fire('Warning',resp.mesg,'warning');
		return;
	}
    if(resp.type == C_ADD){
        swal.fire('Success',resp.mesg,'success');
        businessNatureFilter();
    }else if(resp.type == C_LIST){
        
        $('#businessNature-table-body').html(resp.data.html);
        business_nature_idx = resp.data.idx;
        
    }else if(resp.type == C_DELETE ){
        swal.fire('Success',resp.mesg,'success');
        businessNatureFilter();
    }else if(resp.type == C_CHANGE ){
        swal.fire('Success',resp.mesg,'success');
    }
}