var business_sector_idx = 0;

/**
 * funtion add new line to html table
 */
function addNewBusinessSectorLine() {
    $('#businessSector-table-body').append(
        '<tr id="tr_business_sector'+business_sector_idx+'" class="new_business_sector">'+
        '<td><input type="checkbox" id="business_sector_check'+business_sector_idx+'" class="business_sector_check" value="'+business_sector_idx+'" name="business_sector_chk[]"></td>' +
        '<td><input type="text" id="business_sector_desc'+business_sector_idx+'" class="form-control business_sector_desc"></td>'+
        '<td style="display:none" class="business_sector_id" id="business_sector_id'+business_sector_idx+'">-1</td>'+
        '<td style="display:none" class="business_sector_idx" id="business_sector_idx'+business_sector_idx+'">'+business_sector_idx+'</td>'+
        '</tr>'
    );

    business_sector_idx++;
}

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

    if( validateBusinessSector() ){
        var data = { 
                 "type"                     : C_ADD,
				 "index"                    : screen_index,
                 "new_business_sector"      : getNewBusinessSectorTable(),
                 "existing_business_sector" : getBusinessSectorTable()
				};
        var url  = "index.pzx?c=" + business_sector_url + "&d=" + new Date().getTime() ;
		callServer(url,"json",data,onResponseBusinessSectorEntry,null) ;
		return false;
    }else{
        LoadingScreen("hide");
        swal.fire('Warning',"Please fill all description",'warning');
    }
}

/**
 * funtion get table value 
 * return json array
 */
function getNewBusinessSectorTable() {
    var arrays = [];
    $('#businessSector-table-body tr.new_business_sector').each(function() { 
		var idx = $('.business_sector_idx',this).html() ;
        var data = {     
			"business_sector_id"  : $('.business_sector_id',this).html() ,
			"desc"              : $(".business_sector_desc",this).val(),
        };   

        arrays.push(data);
    }); 

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

function getBusinessSectorTable() {
    var arrays = [];
    $('#businessSector-table-body tr.existing_business_sector').each(function() { 
		var idx = $('.business_sector_idx',this).html() ;
        var data = {     
			"business_sector_id"  : $('.business_sector_id',this).html() ,
			"desc"              : $(".business_sector_desc",this).val(),
        };   

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

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

    }); 

    return allstatus;    
}

/** 
 * amend all field to be edited
*/
function amendBusinessSectorLine() {
    $('.business_sector_check').prop('disabled',false);
    $('.business_sector_desc').prop('disabled',false);
}

/**
 * delete record on table
 * check if id value = -1
 * if not have to remove from database first
 */
function resetBusinessSectorPassword() {
    var lines = [];
	$("input[name='business_sector_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 sector?", "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_sector_id'+lines[i]).html() == -1){
                    count++;
                }else{
                    arrays.push($('#business_sector_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_sector_url + "&d=" + new Date().getTime() ;
                callServer(url,"json",data,onResponseBusinessSectorEntry,null) ;
            }else if(count > 0){
                swal.fire("warning", "Selected business sector hasnt been saved into database");
            }
		  break;
		}
		});
	} else {
		return;
    }
}

function deleteBusinessSectorLine() {
    var lines = [];
	$("input[name='business_sector_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_sector_id'+lines[i]).html() == -1){
                    $('#tr_business_sector'+lines[i]).remove();
                }else{
                    arrays.push($('#business_sector_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_sector_url + "&d=" + new Date().getTime() ;
                callServer(url,"json",data,onResponseBusinessSectorEntry,null) ;
            }
		  break;
		}
		});
	} else {
		return;
    }
}

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

/**
 * response callback from above function
 */
function onResponseBusinessSectorEntry(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');
        businessSectorFilter();
    }else if(resp.type == C_LIST){
        
        $('#businessSector-table-body').html(resp.data.html);
        business_sector_idx = resp.data.idx;
        
    }else if(resp.type == C_DELETE ){
        swal.fire('Success',resp.mesg,'success');
        businessSectorFilter();
    }else if(resp.type == C_CHANGE ){
        swal.fire('Success',resp.mesg,'success');
    }
}