var department_idx = 0;

/**
 * funtion add new line to html table
 */
function addNewDepartmentLine() {
    $('#department-table-body').append(
        '<tr id="tr_department'+department_idx+'" class="new_department">'+
        '<td><input type="checkbox" id="department_check'+department_idx+'" class="department_check" value="'+department_idx+'" name="department_chk[]"></td>' +
        '<td><input type="text" id="department_desc'+department_idx+'" class="form-control department_desc"></td>'+
        '<td style="display:none" class="department_id" id="department_id'+department_idx+'">-1</td>'+
        '<td style="display:none" class="department_idx" id="department_idx'+department_idx+'">'+department_idx+'</td>'+
        '</tr>'
    );

    department_idx++;
}

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

    if( validateDepartment() ){
        var data = { 
                 "type"                 : C_ADD,
				 "index"                : screen_index,
                 "new_department"       : getNewDepartmentTable(),
                 "existing_department"  : getDepartmentTable()
				};
        var url  = "index.pzx?c=" + department_url + "&d=" + new Date().getTime() ;
		callServer(url,"json",data,onResponseDepartmentEntry,null) ;
		return false;
    }else{
        LoadingScreen("hide");
        swal.fire('Warning',"Please fill all description",'warning');
    }
}

/**
 * funtion get table value 
 * return json array
 */
function getNewDepartmentTable() {
    var arrays = [];
    $('#department-table-body tr.new_department').each(function() { 
		var idx = $('.department_idx',this).html() ;
        var data = {     
			"department_id"   : $('.department_id',this).html() ,
			"desc"          : $(".department_desc",this).val(),
        };   

        arrays.push(data);
    }); 

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

function getDepartmentTable() {
    var arrays = [];
    $('#department-table-body tr.existing_department').each(function() { 
		var idx = $('.department_idx',this).html() ;
        var data = {     
			"department_id"   : $('.department_id',this).html() ,
			"desc"          : $(".department_desc",this).val(),
        };   

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

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

    }); 

    return allstatus;    
}

/** 
 * amend all field to be edited
*/
function amendDepartmentLine() {
    $('.department_check').prop('disabled',false);
    $('.department_desc').prop('disabled',false);
}

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

function deleteDepartmentLine() {
    var lines = [];
	$("input[name='department_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($('#department_id'+lines[i]).html() == -1){
                    $('#tr_department'+lines[i]).remove();
                }else{
                    arrays.push($('#department_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=" + department_url + "&d=" + new Date().getTime() ;
                callServer(url,"json",data,onResponseDepartmentEntry,null) ;
            }
		  break;
		}
		});
	} else {
		return;
    }
}

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

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