/////////////////////////////////////////////////////////////////////////////////////////

var	default_domain_columns = [];
var	custom_domain_columns  = [];
var domain_column_labels   = [];
var processing_queue       = 0;
var bulkedit_init_column   = "";

/////////////////////////////////////////////////////////////////////////////////////////

function highlightCategories(cids)
{
	var ids = jQuery("#domaincategorytable").jqGrid('getDataIDs');
	var thelist = cids;
	var catArray = thelist.map(Number);
	for (var i = 0; i < ids.length; i++) {
		var rowId = parseInt(ids[i]);
		var found = false;
		if(rowId > 1) {
			for(var j = 0; j < catArray.length; j++) {
				if(catArray[j] == rowId) {
					found = true;
					break;
				}
			}
		}
		if(found)
			jQuery('#domaincategorytable').jqGrid('setRowData', rowId, false, 'jqboldrow');
		else {
			var grid = $("#domaincategorytable");
			tr = grid[0].rows.namedItem(rowId), 
			$(tr).removeClass("jqboldrow");
		}
	}
}

/////////////////////////////////////////////////////////////////////////////////////////

function show_selected_domains()
{
	var dl = "<p class=\"mb-0\">This will affect <span class=\"highlight\">" + getSelectedDomainList(25) + "</span>.</p>";
	$('.selected_domains').html(dl);
}

/////////////////////////////////////////////////////////////////////////////////////////

function init_panel_adddomains()
{
	var categoryName = "";
	$("#catempty").attr('disabled','disabled');
	var cid = getCookieInt('current_category', 0);
	if(cid > 1)
	{
		var rowData = $('#domaincategorytable').jqGrid('getRowData', cid);
		categoryName = "&quot;<b>" + rowData['name'] + "</b>&quot;"
		if(allow_category_edit())
			$("#catempty").removeAttr('disabled');
		$("#catadd").removeAttr('disabled');
	}
	else
		$("#catadd").attr('disabled','disabled');
	$(".adc-catname").html(categoryName);
	
	//var datastr = "c=admin&t=regapi&oper=list";
	var datastr = get_ajax_datastr("admin", "regapi", "list");
	ajax_call(datastr, ajax_regapi_list, null);
	
	return false;
}

/////////////////////////////////////////////////////////////////////////////////////////

function init_panel_deletedomains()
{
	$('#del_domaintable').click();
	// return true to indicate that the click processing is complete.
	return true;
}

/////////////////////////////////////////////////////////////////////////////////////////

function ajax_init_regalias(x, jqXHR, textStatus, params)
{
	if(x != null) {
		if(x.status == 'ok') {
			var rows = x.data.length;
			var registrar = '';
			var sameregistrar = true;
			for(var i=0; i < rows; i++) {
				if(i == 0)
					registrar = x.data[i]['registrar'];
				else if(registrar != x.data[i]['registrar']) {
					sameregistrar = false;
					break;
				}
			}
			if(sameregistrar) {
				$('#alias').val(registrar);
				$('#regalias-registrar').html(registrar);
				$('#registrar').val(registrar);
				if (typeof registrar_aliases != 'undefined') {
					if(registrar in registrar_aliases)
						$('#alias').val(registrar_aliases[registrar]);
				}
				showPanel("panel-regalias", "right");
			}
			else
				showAlert("Please select only a single domain or select domains that have the same registrar");
		}
	}
}

/////////////////////////////////////////////////////////////////////////////////////////

function init_panel_regalias()
{
	var selids = jQuery("#domaintable").getGridParam("selarrrow"); 
	$('#alias').val("");
	if(selids.length > 0) {
		//var datastr = "c=get&t=domain&oper=column";
		var datastr = get_ajax_datastr("get", "domain", "column");
		datastr += "&columns=registrar&id=" + selids;
		ajax_call(datastr, ajax_init_regalias, null);
	}
	return true;
}

/////////////////////////////////////////////////////////////////////////////////////////

function ajax_set_regalias(x, jqXHR, textStatus, params)
{
	if(x != null) {
		if(x.status == 'ok') {
			var registrar = params[0];
			var alias = params[1];
			if (typeof registrar_aliases != 'undefined') {
				registrar_aliases[registrar] = alias;
				$("#domaintable").trigger("reloadGrid"); 
				hidePanelWithId("panel-regalias");
			}
		}
	}
}

/////////////////////////////////////////////////////////////////////////////////////////

function ajax_parsewhois(x, jqXHR, textStatus, params)
{
	if(x != null) {
		if(x.status == 'ok') {
			$("#domaintable").trigger("reloadGrid"); 
		}
		hidePanelWithId("panel-parsewhois");
	}
}

/////////////////////////////////////////////////////////////////////////////////////////

function parsewhois_submit()
{
	var ids = jQuery("#domaintable").getGridParam("selarrrow"); 
	//var datastr = "c=set&t=domain&oper=parse";
	var datastr = get_ajax_datastr("set", "domain", "parse");
	datastr += "&id=" + ids;
	ajax_call(datastr, ajax_parsewhois, null);
}

/////////////////////////////////////////////////////////////////////////////////////////

function regalias_submit()
{
	var alias = $('#alias').val();
	var registrar = $('#registrar').val();
	
	var params = [registrar, alias];
	//var datastr = "c=set&t=regalias&oper=column";
	var datastr = get_ajax_datastr("set", "regalias", "column");
	datastr += "&name=" + registrar + "&alias=" + alias;
	ajax_call(datastr, ajax_set_regalias, params);
}

/////////////////////////////////////////////////////////////////////////////////////////

function init_panel_parsewhois()
{
	show_selected_domains();
}

/////////////////////////////////////////////////////////////////////////////////////////

function init_panel_lookup()
{
	show_selected_domains();
}

/////////////////////////////////////////////////////////////////////////////////////////

function ajax_init_categorize(x, jqXHR, textStatus, params)
{
	if(x != null) {
		var cbdata = '';
		var count = x.ids.length;
		for(var i = 0; i < count; i++) {
			var name = x.ids[i].name;
			var id = x.ids[i].id;
			if(id > 1) {
				cbdata += "<li class=\"list-group-item ui-selectee\" id=\"li-categorize-" + id  + "\">";
				//cbdata += "<div class=\"handle\"><span class=\"ui-icon grip-drag-action-button\"></span></div>";
				cbdata += name + "</li>\n";
				//cbdata += "<li class=\"list-group-item\"><label for=\"cb-categorize-" + id + "\"><input class=\"cb-listgroup\" id=\"cb-categorize-" + id + "\" type=\"checkbox\">" + name + "</label></li>\n";
			}
		}
		$('#categorize-category').html(cbdata);
	}
}

/////////////////////////////////////////////////////////////////////////////////////////

function init_panel_categorize()
{
	var rowKey = jQuery("#domaintable").getGridParam("selarrrow"); 
	if(rowKey.length) {
		show_selected_domains();
		var datastr = get_ajax_datastr("list", "category", "user");
		//var datastr = "c=list&t=category&oper=user";
		datastr += "&id=0";
		ajax_call(datastr, ajax_init_categorize, null);
	}
	else
		return true;
}

/////////////////////////////////////////////////////////////////////////////////////////

function categorize_add()
{
	var datastr = get_ajax_datastr("admin", "category", "add");
	var ids = getSelectedDomainIds();
	datastr += "&id=" + encodeURIComponent(ids.join(","));
	datastr += "&cid=" + encodeURIComponent($('#categorize-catid').val());
	ajax_call(datastr, ajax_submit_categorize, null);
}

/////////////////////////////////////////////////////////////////////////////////////////

function ajax_submit_categorize(x, jqXHR, textStatus, params)
{
	if(x != null) {
		if(x.status == 'ok') {
			saveRowIdsForReload();
			$("#domaintable").trigger("reloadGrid"); 
			$("#domaincategorytable").trigger("reloadGrid"); 
			// TODO
		}
	}
}

/////////////////////////////////////////////////////////////////////////////////////////

function categorize_remove()
{
	var datastr = get_ajax_datastr("admin", "category", "remove");
	var ids = getSelectedDomainIds();
	datastr += "&id=" + encodeURIComponent(ids.join(","));
	datastr += "&cid=" + encodeURIComponent($('#categorize-catid').val());
	ajax_call(datastr, ajax_submit_categorize, null);
}

/////////////////////////////////////////////////////////////////////////////////////////

function ajax_set_csvupload(x, jqXHR, textStatus, params)
{
	if(x != null) {
		if(x.status == 'ok') {
			var colcount = x.columns.length;
			var columns = "";
			var status = '<ul class="list-group list-group-flush">';
			status += '<li class="list-group-item">File: ' + x.data['file'] + "</li>";
			status += '<li class="list-group-item">Type: ' + x.data['type'] + "</li>";
			status += '<li class="list-group-item">Size: ' + x.data['size'] + "Kb</li>";
			
			for(var i = 0; i < colcount; i++) {
				if(columns != "")
					columns += ", ";
				columns += x.columns[i];
			}
			status += '<li class="list-group-item">' + colcount + " columns found (" + columns + ")</li>";
			status += '<li class="list-group-item">' + x.added + " domains added </li>";
			status += '<li class="list-group-item">' + x.existing + " domains already in database</li>";
			status += "</ul>";
			$("#domaintable").trigger("reloadGrid"); 
			$("#domaincategorytable").trigger("reloadGrid");
			$("#csverrors").removeClass('text-center');
			$("#csverrors").html(status);
		}
		else {
			$("#csverrors").html(x.error);
		}
	}
}

/////////////////////////////////////////////////////////////////////////////////////////

function csvupload_submit()
{
	$("#csverrors").addClass('text-center');
	
	var fd = new FormData($('#csv-upload')[0]);
	$("#csverrors").html("<img src=\"\lib/layouts/images/loaders/ajax-loader.gif\" class=\"mx-auto\">&nbsp;");
	var cid = getCookieInt('current_category', 0);
	fd.append('c', "add");
	fd.append('t', "domain");
	fd.append('oper', "csv");
	fd.append('cid', cid);
	//fd.append('csv-luq', $('#csv-luq').val());
	var luq = fd.getAll('csv-luq');
	var sep = fd.getAll('csv_sep');
	ajax_formdata_call(fd, ajax_set_csvupload, null);
}

/////////////////////////////////////////////////////////////////////////////////////////

function ajax_columnsetup_done(x, jqXHR, textStatus, params)
{
	if(x != null) {
		if(x.status == 'ok') {
			// Quick and dirty fix for the json_encode hack in Settings.php
			var i;
			for(i = 0; i < x.colmodel.length; i++) {
				if(typeof x.colmodel[i].editrules != 'undefined') {
					if(typeof x.colmodel[i].editrules.custom_func != 'undefined') {
						if(x.colmodel[i].editrules.custom_func == 'jsf_validateDate_jsf')
							x.colmodel[i].editrules.custom_func = validateDate;
					}
				}
			}
			window[params] = x.colmodel;
			LoadDomainDataGrid(true);
			hidePanelWithId("panel-columnsetup");
			domainGridLoadComplete();
		}
		else
			$('#columnsetup-error').html(x.error);
	}
}

/////////////////////////////////////////////////////////////////////////////////////////

function columnsetup_submit()
{
	var checkedIds = $("#tablecolumns :checkbox:checked").map(function() {
        return this.id;
    }).get();
	
	var dgroup = $('#columnsetup-group').val();
	var datastr = get_ajax_datastr("set", "domain", "colmodel");
	datastr += "&group=" + encodeURIComponent(dgroup);

	var colsetup = "";
	var length = checkedIds.length;
	var columns = new Array();
	for (var i = 0; i < length; i++) 
	{
	  columns[i] = checkedIds[i].replace("cb-", "");
	  colsetup += columns[i];
	  if(i != (length-1))
		colsetup += ";";
	}
	$('#columnsetup-error').html("");
	datastr += "&columns=" + encodeURIComponent(colsetup);
	ajax_call(datastr, ajax_columnsetup_done, dgroup); 
}

/////////////////////////////////////////////////////////////////////////////////////////

function columnsetup_reset()
{
	var dgroup = $('#columnsetup-group').val();
	var datastr = get_ajax_datastr("set", "domain", "colmodel");
	datastr += "&group=" + encodeURIComponent(dgroup);
	datastr += "&columns=";
	ajax_call(datastr, ajax_columnsetup_done, dgroup); 
}

/////////////////////////////////////////////////////////////////////////////////////////

function init_panel_columnsetup()
{
	var dgroup = getCookie('display-group', "date_columns_array");
	fillColumnNameRowsForColumnSetup(dgroup);
}

/////////////////////////////////////////////////////////////////////////////////////////

function ajax_fill_domain_columns(x, jqXHR, textStatus, params)
{
	var list = "";
	if(x != null) {
		if(x.status == 'ok') {
			var exists = [];
			var datacolumns = getColModelFromGroupName(params);
			var colnum = datacolumns.length;
			for(i = 0; i < colnum; i++) {
				if(datacolumns[i].name != "rn" && datacolumns[i].name != "cb" && datacolumns[i].name != "domain") {
					var key = datacolumns[i].name;
					label = datacolumns[i].label;
					exists.push(key);
					var custom = 'button';
					if(x.columns.hasOwnProperty(key)) 
						custom = parseInt(x.columns[key]['custom']) ? 'custom' : 'button';
					if(key !== 'r_h_disp' && key !== 'd.r_h_disp') {
						list += "<li><div class=\"handle\"><span class=\"ui-icon grip-drag-action-" + custom + "\"></span></div>\n"; //  + label + "</li>";
						list += "<label for=\"cb-" + key + "\"><input id=\"cb-" + key + "\" type=\"checkbox\" checked>" + label + "</label></li>\n";
					}
				}
			}
			
			for (var key in x.columns) {
				if (key === 'length' || !x.columns.hasOwnProperty(key) || key == "domain") continue;
				var custom = parseInt(x.columns[key]['custom']);
				if(!custom) continue;
				if(exists.indexOf(key) >= 0 || exists.indexOf(key.replace("d.", "")) >= 0 || exists.indexOf("d."+key) >= 0)
					continue;
				var label = x.columns[key]['label'];
				var ftype = x.columns[key]['fieldtype'];
				var gridview = parseInt(x.columns[key]['gridview']);
				var editable = parseInt(x.columns[key]['editable']);
				if(gridview != 0 && key != "r_h_disp" && key !== 'd.r_h_disp' && exists.indexOf(key) < 0) {
					list += "<li><div class=\"handle\"><span class=\"ui-icon grip-drag-action-button grip-drag-action-custom\"></span></div>\n"; //  + label + "</li>";
					list += "<label for=\"cb-" + key + "\"><input id=\"cb-" + key + "\" type=\"checkbox\">" + label + "</label></li>\n";
				}
			}
			
			for (var key in x.columns) {
				if (key === 'length' || !x.columns.hasOwnProperty(key) || key == "domain") continue;
				var custom = parseInt(x.columns[key]['custom']);
				if(custom) continue;
				if(exists.indexOf(key) >= 0 || exists.indexOf(key.replace("d.", "")) >= 0 || exists.indexOf("d."+key) >= 0)
					continue;
				var label = x.columns[key]['label'];
				var ftype = x.columns[key]['fieldtype'];
				var gridview = parseInt(x.columns[key]['gridview']);
				var editable = parseInt(x.columns[key]['editable']);
				if(gridview != 0 && key != "r_h_disp" && key !== 'd.r_h_disp' && exists.indexOf(key) < 0) {
					list += "<li><div class=\"handle\"><span class=\"ui-icon grip-drag-action-button\"></span></div>\n"; //  + label + "</li>";
					list += "<label for=\"cb-" + key + "\"><input id=\"cb-" + key + "\" type=\"checkbox\">" + label + "</label></li>\n";
				}
			}
		}
	}
	$('#tablecolumns').html(list);
}

/////////////////////////////////////////////////////////////////////////////////////////

function fillColumnNameRowsForColumnSetup(dgroup)
{
	$('#tablecolumns').html("<img src=\"\lib/layouts/images/loaders/ajax-loader.gif\" class=\"mx-auto\">&nbsp;");
	$('#columnsetup-group').val(dgroup);
	var datastr = get_ajax_datastr("list", "domain", "columns");
	ajax_call(datastr, ajax_fill_domain_columns, dgroup);
}

/////////////////////////////////////////////////////////////////////

function setupTableColumns(listid, sdmode)
{
	//$( "#"+listid ).sortable();
		$( "#"+listid ).sortable({ handle: ".handle" })
		.selectable({
		selecting: function (e, ui) {
            // force single selection
            $(e.target).find('.ui-selectee.ui-selecting').not(ui.selecting).removeClass('ui-selecting');
            $(e.target).find('.ui-selectee.ui-selected').not(ui.selecting).removeClass('ui-selected');
        },
		stop: function() 
		{
			$('#'+listid+' li').each(function() {
				$(this).removeClass('ui-state-highlight');
			});
			$( ".ui-selected", this ).each(function() 
			{
			});
		}
	})
    .find("li").addClass( "ui-corner-all" );
}

/////////////////////////////////////////////////////////////////////
// Custom Columns

function customFieldEditor(status)
{
	if(!status) {
		$( "#field_type" ).attr( "disabled", true );
		$( "#field_width" ).attr( "disabled", true );
		$( "#field_default" ).attr( "disabled", true );
		$( "#field_index" ).attr( "disabled", true );
		$( ".custom-secondary" ).addClass( "disabled", true );
	}
	else {
		$( "#field_type" ).attr( "disabled", false );
		$( "#field_width" ).attr( "disabled", false );
		$( "#field_default" ).attr( "disabled", false );
		$( "#field_index" ).attr( "disabled", false );
		$( ".custom-secondary" ).removeClass( "disabled" );
	}
}

/////////////////////////////////////////////////////////////////////
// Custom Columns

function customFieldNameChanged()
{
	var fname = $('#field_name').val().trim();
	if(jQuery.inArray(fname.toLowerCase(),default_domain_columns) != -1 || fname == "") {
		customFieldEditor(false);
		$( "#customcolumns-remove" ).hide();
		$( "#customcolumns-wipe" ).hide();
		$( "#customcolumns-submit" ).hide();
	}
	else {
		$( "#customcolumns-remove" ).hide();
		$( "#customcolumns-wipe" ).hide();
		if(jQuery.inArray(fname.toLowerCase(),custom_domain_columns) != -1) {
			$( "#customcolumns-remove" ).show();
			$( "#customcolumns-wipe" ).show();
			$( "#customcolumns-submit" ).hide();
			customFieldEditor(false);
		}
		else {
			$( "#customcolumns-submit" ).show();
			customFieldEditor(true);
		}
	}
}

/////////////////////////////////////////////////////////////////////

function makeListSelectable(listid, selecteditem)
{
	//$('#'+listid).selectable( "destroy" );
	$('#'+listid).selectable({
		stop: function() {
			$('#' + listid + ' li').each(function() {
				$(this).removeClass('ui-state-highlight');
			});
			$( ".ui-selected", this ).each(function() {
				$(this).addClass('ui-state-highlight');
				if(selecteditem != "") {
					if(selecteditem == "field_name") {
						var key = $(this).text();
						var label = domain_column_labels[key];
						if(jQuery.inArray(key.toLowerCase(),default_domain_columns) != -1) {
							$('#field_name').val('');
							$('#field_name').focus();
						}
						else {
							$('#field_name').val($(this).text());
							$('#field_name').blur();
						}
						customFieldNameChanged();
					}
					else if(selecteditem == "bulkedit-column") {
						$('#bulkedit-column').html(domain_column_labels[$(this).text()]);
						$('#bulkedit-field').val($(this).text());
					}
					else if(selecteditem == "uadmin_uid") {
						var key = $(this).text();
						$('#uadmin_uid').val($(this).text());
						userSelected();
					}
					else if(selecteditem == "font-preview") {
						var fontname = $(this).text();
						var fontindex = $('#fontindex').val();
						showGoogleFont(fontindex, fontname);
					}
					else if(selecteditem == "categorize-selected") {
						$('#'+selecteditem).html($(this).text());
						var catid = $(this).attr('id').replace("li-categorize-", "");
						$('#categorize-catid').val(catid);
					}
					else if(selecteditem == "cateditor-category") {
						categoryEditorSelected($(this).attr("id"));
					}
					else if(selecteditem == "queryeditor-name") {
						queryEditorSelected($(this).attr("id"));
					}
					else if(selecteditem == "caticon-name") {
						categoryIconSelected($(this).attr("id"));
					}
				}
				if(listid == "regapisetuplist") {
					regapi_selected($(this).attr("id"));
				}
			});
		},
		selecting: function (e, ui) {
            // force single selection
            $(e.target).find('.ui-selectee.ui-selecting').not(ui.selecting).removeClass('ui-selecting');
            $(e.target).find('.ui-selectee.ui-selected').not(ui.selecting).removeClass('ui-selected');
        }
    });
}

/////////////////////////////////////////////////////////////////////////////////////////

function get_domain_column_list(columns)
{
	default_domain_columns = [];
	custom_domain_columns = [];
	domain_column_labels = [];
	for (var key in columns) {
		if (key === 'length' || !columns.hasOwnProperty(key)) continue;
		var label = columns[key]['label'];
		var ftype = columns[key]['fieldtype'];
		var gridview = parseInt(columns[key]['gridview']);
		var editable = parseInt(columns[key]['editable']);
		var custom = parseInt(columns[key]['custom']);
		if(!custom) 
			default_domain_columns.push(key);
		else 
			custom_domain_columns.push(key);
		domain_column_labels[key] = decodeURIComponent(label);
	}
	return construct_domain_list_entries();
}

/////////////////////////////////////////////////////////////////////////////////////////

function construct_domain_list_entries()
{
	var list = '';
	for(var i = 0; i < custom_domain_columns.length; i++)
		list += '<li class="list-group-item ui-selectee">' + custom_domain_columns[i] + '</li>'; 
	for(var i = 0; i < default_domain_columns.length; i++)
		list += '<li class="list-group-item ui-selectee defaultcolumn">' + default_domain_columns[i] + '</li>'; 
	
	return list;
}

/////////////////////////////////////////////////////////////////////////////////////////

function ajax_set_customcolumns(x, jqXHR, textStatus, params)
{
	if(x != null) {
		if(x.status == 'ok') {
			var list = get_domain_column_list(x.columns);
			$('#customcolumns-columns').html(list);
			makeListSelectable('customcolumns-columns', 'field_name');
			$('#field_name').val('');
			$('#field_name').focus();
			customFieldNameChanged();
			$('#customcolumns-error').html('');
			var ht = $('#customcolumns-editor').height();
			if($(window).width() < 768)
				ht = 220;
			$('#customcolumns-columns').css('max-height', ht-20);
		}
		else {
			$('#customcolumns-error').html(x.error);
		}
	}
}

/////////////////////////////////////////////////////////////////////////////////////////

function init_panel_customcolumns()
{
	//var datastr = "c=list&t=domain&oper=columns";
	var datastr = get_ajax_datastr("list", "domain", "columns");
	ajax_call(datastr, ajax_set_customcolumns, null);
}

/////////////////////////////////////////////////////////////////////////////////////////

function ajax_add_customcolumn(x, jqXHR, textStatus, params)
{
	if(x != null) {
		if(x.status == 'ok') {
			var list = get_domain_column_list(x.columns);
			$('#customcolumns-columns').html(list);
			makeListSelectable('customcolumns-columns', 'field_name');
			customFieldNameChanged();
			$('#customcolumns-error').html('');
		}
		else
			$('#customcolumns-error').html(x.error);
	}
}


/////////////////////////////////////////////////////////////////////////////////////////

function customcolumns_submit()
{
	var datastr = get_ajax_datastr("admin", "custom", "add");
	datastr += "&name=" + encodeURIComponent($('#field_name').val());
	datastr += "&type=" + encodeURIComponent($('#field_type').val());
	datastr += "&width=" + encodeURIComponent($('#field_width').val());
	datastr += "&default=" + encodeURIComponent($('#field_default').val());
	datastr += "&index=" + encodeURIComponent($('#field_index').val());
	datastr += "&columns=true";
	ajax_call(datastr, ajax_add_customcolumn, null);
}

/////////////////////////////////////////////////////////////////////////////////////////

function ajax_remove_customcolumn(x, jqXHR, textStatus, params)
{
	if(x != null) {
		if(x.status == 'ok') {
			var list = get_domain_column_list(x.columns);
			$('#customcolumns-columns').html(list);
			makeListSelectable('customcolumns-columns', 'field_name');
			customFieldNameChanged();
		}
	}
}

/////////////////////////////////////////////////////////////////////////////////////////


function customcolumns_wipe()
{
	var datastr = get_ajax_datastr("admin", "custom", "del");
	datastr += "&name=" + encodeURIComponent($('#field_name').val());
	//datastr += "&c=admin&t=custom&oper=del";
	datastr += "&columns=true&clear=true";
	ajax_call(datastr, ajax_remove_customcolumn, null);
}

/////////////////////////////////////////////////////////////////////////////////////////

function customcolumns_remove()
{
	var datastr = get_ajax_datastr("admin", "custom", "del");
	datastr += "&name=" + encodeURIComponent($('#field_name').val());
	datastr += "&columns=true";
	ajax_call(datastr, ajax_remove_customcolumn, null);
}

///////////////////////////////////////////////////////////////////////////////

function getSelectedDomainIds()
{
	return jQuery("#domaintable").getGridParam("selarrrow"); 
}


/////////////////////////////////////////////////////////////////////////////////////////

function ajax_set_bulkedit(x, jqXHR, textStatus, params)
{
	if(x != null) {
		if(x.status == 'ok') {
			var ht = $('#bulkedit-editor').height();
			if($(window).width() < 768)
				ht = 200;
			$('#bulkedit-columns').css('max-height', ht);
			var list = get_domain_column_list(x.columns);
			$('#bulkedit-columns').html(list);
			makeListSelectable('bulkedit-columns', 'bulkedit-column');
			select_bulkedit_column(bulkedit_init_column);
		}
	}
}

/////////////////////////////////////////////////////////////////////////////////////////

function ajax_submit_bulkedit(x, jqXHR, textStatus, params)
{
	if(x != null) {
		if(x.status == 'ok') {
			if(x.updated > 0) {
				saveRowIdsForReload();
				$("#domaintable").trigger("reloadGrid"); 
				hidePanelWithId("panel-bulkedit");
			}
		}
		else {
			$('#bulkedit-error').html(x.error);
		}
	}
}

/////////////////////////////////////////////////////////////////////////////////////////

function bulkedit_submit()
{
	$('#bulkedit-error').html('');
	var field = $('#bulkedit-field').val();
	var value = $('#bulkedit-value').val();
	var ids = getSelectedDomainIds();
	var datastr = get_ajax_datastr("set", "domain", "edit");
	datastr += "&id=" + encodeURIComponent(ids.join(","));
	datastr += "&columns=" + encodeURIComponent(field);
	datastr += "&data=" + encodeURIComponent(value);
	ajax_call(datastr, ajax_submit_bulkedit, null);
}

/////////////////////////////////////////////////////////////////////////////////////////

function bulkedit_resetmanedit()
{
	var ids = getSelectedDomainIds();
	var datastr = get_ajax_datastr("set", "domain", "edit");
	datastr += "&id=" + encodeURIComponent(ids.join(","));
	datastr += "&columns=" + encodeURIComponent("manual_edited_at");
	datastr += "&data=" + encodeURIComponent("null");
	ajax_call(datastr, ajax_submit_bulkedit, null);
}

/////////////////////////////////////////////////////////////////////////////////////////

function select_bulkedit_column(columnname)
{
	if(columnname != "") {
		$('#bulkedit-columns li').each(function() {
			if($.text([this]) === columnname) {
				$(this).addClass('ui-selected ui-state-highlight');
				$('#bulkedit-column').html($(this).text());
				$('#bulkedit-columns').scrollTop(0);
				$('#bulkedit-columns').scrollTop($(this).position().top);
				$('#bulkedit-value').focus();
				var eval = decodeURIComponent($('.dtabv-' + columnname).text());
				$('#bulkedit-value').val(eval);
			}
			else
				$(this).removeClass('ui-selected ui-state-highlight');
		});
	}
}

/////////////////////////////////////////////////////////////////////////////////////////

function init_panel_bulkedit()
{
	show_selected_domains();
	var datastr = get_ajax_datastr("list", "domain", "columns");
	ajax_call(datastr, ajax_set_bulkedit, null);
}

/////////////////////////////////////////////////////////////////////////////////////////

function addDomainSourceChanged()
{
	var source = $('#select_regapi').val();
	if(source == "manual") {
		$('#domaindata, #domaindata-label, #appendtlds, #appendtlds-label').show();
		$('#regapiselect').hide();
	}
	else {
		$('#domaindata, #domaindata-label, #appendtlds, #appendtlds-label').hide();
		$('#regapiselect').show();
	}
}

/////////////////////////////////////////////////////////////////////////////////////////

function ajax_regapi_list(x, jqXHR, textStatus, params)
{
	if(x != null) {
		if(x.status == 'ok') {
			var count = x.profiles.length;
			var cbdata = "";
			for(var i = 0; i < count; i++) {
				var name = x.profiles[i];
				var params = x.data[name];
				cbdata += '<label class="checkbox-inline no_indent">';
				cbdata += '<input type="checkbox" class="cb-regapilist" name="regapi-' + name + '" id="regapi-' + name + '"> ' + name + '</label>';
			}
			$('#regapichecklist').html(cbdata);
		}
	}
}

/////////////////////////////////////////////////////////////////////////////////////////

function processqueue_submit()
{
	if(!processing_queue) {
		processing_queue++;
		var datastr = get_ajax_datastr("set", "luq", "process");
		$('#processqueue-status').html("<img class=\"mx-auto d-block\" src=\"lib/layouts/images/loaders/ajax-loader.gif\" alt=\"loading\">");
		ajax_call(datastr, ajax_luq_process, null);
	}
	else {
		$('#processqueue-status').html("<p class=\"text-center small\">Busy! <img class=\"mx-auto d-block\" src=\"lib/layouts/images/loaders/ajax-loader.gif\" alt=\"loading\"></p>");
	}
}

/////////////////////////////////////////////////////////////////////////////////////////

function ajax_luq_process(x, jqXHR, textStatus, params)
{
	if(x != null) {
		if(x.status == 'ok') {
			var status = "<ul class=\"list-group list-group-flush\">";
			status += "<li class=\"list-group-item\">Attempted: " + x.attempted + "</li>";
			status += "<li class=\"list-group-item\">Processed: " + x.processed + "</li>";
			status += "<li class=\"list-group-item\">Time: " + x.time + "</li>";
			status += "</ul>";
			$('#processqueue-status').html(status);
			showSessionQueueCount(false);
			$("#domaintable").trigger("reloadGrid"); 
		}
	}
	processing_queue--;
}

/////////////////////////////////////////////////////////////////////////////////////////