var destination_idx = 0;

/**
 * funtion add new line to html table
 */
function addNewDestinationLine() {
    $('#destination-table-body').append(
        '<tr id="tr_destination'+destination_idx+'" class="new_destination">'+
        '<td><input type="checkbox" id="destination_check'+destination_idx+'" class="destination_check" value="'+destination_idx+'" name="destination_chk[]"></td>' +
        '<td><input type="text" id="destination_name'+destination_idx+'" class="form-control destination_name"></td>'+
        '<td><input type="text" id="destination_link'+destination_idx+'" class="form-control destination_link" value=""></td>'+
        '<td style="display:none" class="destination_id" id="destination_id'+destination_idx+'">-1</td>'+
        '<td style="display:none" class="destination_idx" id="destination_idx'+destination_idx+'">'+destination_idx+'</td>'+
        '</tr>'
    );

    destination_idx++;
}

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

    if( validateDestination() ){
        var data = { 
                 "type"                : C_ADD,
				 "index"               : screen_index,
                 "new_destination"     : getNewDestinationTable(),
                 "existing_destination": getDestinationTable()
				};
        var url  = "index.pzx?c=" + destination_url + "&d=" + new Date().getTime() ;
		callServer(url,"json",data,onResponseDestinationEntry,null) ;
		return false;
    }else{
        LoadingScreen("hide");
        swal.fire('Warning',"Please fill all description",'warning');
    }
}

/**
 * funtion get table value 
 * return json array
 */
function getNewDestinationTable() {
    var arrays = [];
    $('#destination-table-body tr.new_destination').each(function() { 
		var idx = $('.destination_idx',this).html() ;
        var data = {     
			"destination_id" : $('.destination_id',this).html() ,
			"name"           : $(".destination_name",this).val(),
			"link"           : $(".destination_link",this).val(),	
        };   

        arrays.push(data);
    }); 

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

function getDestinationTable() {
    var arrays = [];
    $('#destination-table-body tr.existing_destination').each(function() { 
		var idx = $('.destination_idx',this).html() ;
        var data = {     
			"destination_id" : $('.destination_id',this).html() ,
			"name"           : $(".destination_name",this).val(),
			"link"           : $(".destination_link",this).val(),	
        };   

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

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

    }); 

    return allstatus;    
}

/** 
 * amend all field to be edited
*/
function amendDestinationLine() {
    $('.destination_check').prop('disabled',false);
    $('.destination_link').prop('disabled',false);
}

function deleteDestinationLine() {
    var lines = [];
	$("input[name='destination_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($('#destination_id'+lines[i]).html() == -1){
                    $('#tr_destination'+lines[i]).remove();
                }else{
                    arrays.push($('#destination_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=" + destination_url + "&d=" + new Date().getTime() ;
                callServer(url,"json",data,onResponseDestinationEntry,null) ;
            }
		  break;
		}
		});
	} else {
		return;
    }
}

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

/**
 * response callback from above function
 */
function onResponseDestinationEntry(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');
        destinationFilter();
    }else if(resp.type == C_LIST){
        destination_name_list = [];
        var myObj = JSON.parse(resp.data);
        showDestinationList(myObj);
        // $('#destination-table-body').html(resp.data.html);
        // destination_idx = resp.data.idx;
    }else if(resp.type == C_DELETE ){
        swal.fire('Success',resp.mesg,'success');
        destinationFilter();
    }
}

function showDestinationList(myObj) {
    destination_idx = 0;
    destination_id = 0;
    $('#destination-table-body').html('');

    for (i in myObj) {
        id      = myObj[i].id;
        destination_name    = myObj[i].name;
        destination_link    = myObj[i].link;

        destination_name_list.push(destination_name);
        $('#destination-table-body').append(
            '<tr id="tr_destination'+destination_idx+'" class="existing_destination">' +
                '<td><input type="checkbox" id="destination_check'+destination_idx+'" class="destination_check" value="'+destination_idx+'" name="destination_chk[]" disabled></td>' +
                '<td><input type="text" id="destination_code'+destination_idx+'" class="form-control destination_name" value="'+destination_name+'"  disabled></td>' +
                '<td><input type="text" id="destination_desc'+destination_idx+'" class="form-control destination_link" value="'+destination_link+'"  disabled></td>' +
                '<td style="display:none" class="destination_id" id="destination_id'+destination_idx+'">'+id+'</td>' +
                '<td style="display:none" class="destination_idx" id="destination_idx'+destination_idx+'">'+destination_idx+'</td>' +
            '</tr>'
        );

        destination_idx++;
    }
}