var software_idx = 0;

/**
 * funtion add new line to html table
 */
function addNewSoftwareLine() {
    $('#software-table-body').append(
        '<tr id="tr_software'+software_idx+'" class="new_software">'+
        '<td><input type="checkbox" id="software_check'+software_idx+'" class="software_check" value="'+software_idx+'" name="software_chk[]"></td>' +
        '<td><input type="text" id="software_desc'+software_idx+'" class="form-control software_desc"></td>'+
        '<td style="padding: 0px !important;">'+
            '<select id="software_type'+software_idx+'" class="form-control software_type">'+
                '<option value="1">Accounting</option>'+
                '<option value="2">Sales</option>'+
                '<option value="3">Others</option>'+
            '</select>'+
        '</td>'+
        '<td style="display:none" class="software_id" id="software_id'+software_idx+'">-1</td>'+
        '<td style="display:none" class="software_idx" id="software_idx'+software_idx+'">'+software_idx+'</td>'+
        '</tr>'
    );

    software_idx++;
}

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

    if( validateSoftware() ){
        var data = { 
                 "type"              : C_ADD,
				 "index"             : screen_index,
                 "new_software"      : getNewSoftwareTable(),
                 "existing_software" : getSoftwareTable()
				};
        var url  = "index.pzx?c=" + software_url + "&d=" + new Date().getTime() ;
		callServer(url,"json",data,onResponseSoftwareEntry,null) ;
		return false;
    }else{
        LoadingScreen("hide");
        swal.fire('Warning',"Please fill all description",'warning');
    }
}

/**
 * funtion get table value 
 * return json array
 */
function getNewSoftwareTable() {
    var arrays = [];
    $('#software-table-body tr.new_software').each(function() { 
		var idx = $('.software_idx',this).html() ;
        var data = {     
			"software_id"  : $('.software_id',this).html() ,
			"desc"         : $(".software_desc",this).val(),
			"type"         : $(".software_type",this).val(),
        };   

        arrays.push(data);
    }); 

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

function getSoftwareTable() {
    var arrays = [];
    $('#software-table-body tr.existing_software').each(function() { 
		var idx = $('.software_idx',this).html() ;
        var data = {     
			"software_id"  : $('.software_id',this).html() ,
			"desc"         : $(".software_desc",this).val(),
			"type"         : $(".software_type",this).val(),
        };   

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

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

    }); 

    return allstatus;    
}

/** 
 * amend all field to be edited
*/
function amendSoftwareLine() {
    $('.software_check').prop('disabled',false);
    $('.software_desc').prop('disabled',false);
    $('.software_type').prop('disabled',false);
}

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

function deleteSoftwareLine() {
    var lines = [];
	$("input[name='software_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($('#software_id'+lines[i]).html() == -1){
                    $('#tr_software'+lines[i]).remove();
                }else{
                    arrays.push($('#software_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=" + software_url + "&d=" + new Date().getTime() ;
                callServer(url,"json",data,onResponseSoftwareEntry,null) ;
            }
		  break;
		}
		});
	} else {
		return;
    }
}

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

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