var industry_idx = 0;

/**
 * funtion add new line to html table
 */
function addNewIndustryLine() {
    $('#industry-table-body').append(
        '<tr id="tr_industry'+industry_idx+'" class="new_industry">'+
        '<td><input type="checkbox" id="industry_check'+industry_idx+'" class="industry_check" value="'+industry_idx+'" name="industry_chk[]"></td>' +
        '<td><input type="text" id="industry_desc'+industry_idx+'" class="form-control industry_desc"></td>'+
        '<td style="display:none" class="industry_id" id="industry_id'+industry_idx+'">-1</td>'+
        '<td style="display:none" class="industry_idx" id="industry_idx'+industry_idx+'">'+industry_idx+'</td>'+
        '</tr>'
    );

    industry_idx++;
}

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

    if( validateIndustry() ){
        var data = { 
                 "type"             : C_ADD,
				 "index"            : screen_index,
                 "new_industry"     : getNewIndustryTable(),
                 "existing_industry": getIndustryTable()
				};
        var url  = "index.pzx?c=" + industry_url + "&d=" + new Date().getTime() ;
		callServer(url,"json",data,onResponseIndustryEntry,null) ;
		return false;
    }else{
        LoadingScreen("hide");
        swal.fire('Warning',"Please fill all description",'warning');
    }
}

/**
 * funtion get table value 
 * return json array
 */
function getNewIndustryTable() {
    var arrays = [];
    $('#industry-table-body tr.new_industry').each(function() { 
		var idx = $('.industry_idx',this).html() ;
        var data = {     
			"industry_id"   : $('.industry_id',this).html() ,
			"desc"          : $(".industry_desc",this).val(),
        };   

        arrays.push(data);
    }); 

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

function getIndustryTable() {
    var arrays = [];
    $('#industry-table-body tr.existing_industry').each(function() { 
		var idx = $('.industry_idx',this).html() ;
        var data = {     
			"industry_id"   : $('.industry_id',this).html() ,
			"desc"          : $(".industry_desc",this).val(),
        };   

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

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

    }); 

    return allstatus;    
}

/** 
 * amend all field to be edited
*/
function amendIndustryLine() {
    $('.industry_check').prop('disabled',false);
    $('.industry_desc').prop('disabled',false);
}

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

function deleteIndustryLine() {
    var lines = [];
	$("input[name='industry_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($('#industry_id'+lines[i]).html() == -1){
                    $('#tr_industry'+lines[i]).remove();
                }else{
                    arrays.push($('#industry_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=" + industry_url + "&d=" + new Date().getTime() ;
                callServer(url,"json",data,onResponseIndustryEntry,null) ;
            }
		  break;
		}
		});
	} else {
		return;
    }
}

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

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