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

var DOMAINGRID_MULTI_SELECT     = true;
var DOMAINGRID_MULTI_BOX_ONLY   = true;

var NO_DOMAIN_SELECTION     	= 0; 
var SINGLE_DOMAIN_SELECTION		= 1; 
var MULTI_DOMAIN_SELECTION  	= 2; 

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

var domain_table_jqgrid         = null;
var selected_rowids_for_reload  = "";
var selected_page_for_reload    = 0;
var last_selected_domain_row    = -1;

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

var user_access_rights = parseInt(user_details['rights']);
var base_grid_ajax_url = app_root_url + api_url_path;

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

function LoadDomainDataGrid(preservepage)
{
	selected_page_for_reload = 0;
	gridunloaded = false;
	if(domain_table_jqgrid != null)
	{
		if(preservepage)
			selected_page_for_reload = $('#domaintable').jqGrid('getGridParam', 'page');
		domain_table_jqgrid.GridUnload();
		gridunloaded = true;
	}
	var durl = getDomainDataURL(getColModelFromGroupName(getCookie('display-group', "date_columns_array")));
	
	var ww = $(window).width();
	var rowsperpage = getCookieInt('domain_rows_per_page', 100);
	var rowlist = [10,50,100,250,500,1000,2000];
	if(jQuery.inArray(rowsperpage, rowlist) < 0)
		rowsperpage = 100;
	var viewrecords = true;
	var pginput = true;
	
	if(ww <= 767) {
		viewrecords = false;
		rowlist = [];
		pginput = false;
	}
	
	
	var datastr = get_ajax_datastr("grid", "domain", "");
	var sortname = getCookie('current_sort_column', "sid");
	var sortorder = getCookie('current_sort_order', "desc");
	domain_table_jqgrid = jQuery("#domaintable").jqGrid(
	{
		height: $("#domainpane").height()-120,
		width: $("#domainpane").width()-24,
		altRows:true,
		hidegrid: false,
		altclass: "domain_grid_alt_row",
		url: durl,
		editurl: base_grid_ajax_url + "?" + datastr,
		shrinkToFit: false,
		pager: "#domaintablepager",
		jsonReader : {repeatitems: false},
		rownumWidth: 50,
		rowList: rowlist,
		datatype: "json",
		sortname: sortname,
		sortorder: sortorder,
		colModel: getColModelFromGroupName(getCookie('display-group', "date_columns_array")),
		rowNum: rowsperpage,
		rownumbers: true,
		viewrecords: viewrecords,
		mtype: 'POST',
		multiselect: DOMAINGRID_MULTI_SELECT,
		multiboxonly: DOMAINGRID_MULTI_BOX_ONLY,
		gridView: true,
		pginput: pginput,
		caption:"Domain Name Portfolio",
		recordtext: "{0} - {1} of {2}",
		sortable: {
			options: {
				stop: function(event, ui) {
					save_current_column_model();
				},
				items: ">th:not(:has(#jqgh_domaintable_cb,#jqgh_domaintable_domain,#jqgh_domaintable_rn,#jqgh_domaintable_r_h_disp),:hidden)"
		   }
		},
		loadComplete : function () 
		{
			if(selected_page_for_reload > 1)
			{
				var cpage = selected_page_for_reload;
				selected_page_for_reload = 0;
				if (this.p.datatype === 'json') 
				{
					setTimeout(function() {$("#domaintable").trigger("reloadGrid",[{page:cpage}]);}, 50);
					return;
				}
			}
			domainGridLoadComplete();
        },
		gridComplete : function()
		{
			domainGridGridComplete();
		},
		onPaging: function (pgButton) {
			var pageNumber = $(this).jqGrid("getGridParam", "page");
			saveCookie("domain_table_page", pageNumber);
		},
		onSelectAll: function(ids, status)
		{
			show_selected_domain_info();
		},
		onSelectRow: function(ids) 
		{
			var newrow = parseInt(ids);
			if(newrow != last_selected_domain_row) {
				last_selected_domain_row = newrow;
				show_selected_domain_info();
				$.cookie('current_domain', String(ids));
				if(ids && last_domain_edit_row != ids) {
					jQuery('#domaintable').restoreRow(last_domain_edit_row);
					last_domain_edit_row = -1;
				}
			}
		},
		loadError: function (jqXHR, textStatus, errorThrown) 
		{
			gridSessionTimedoutError(jqXHR);
		},
		beforeRequest: function() 
		{
			setDomainTableCaption();
		},
		ondblClickRow: function () {
            var row_id = $("#domaintable").getGridParam('selrow');
			if(row_id && last_domain_edit_row != row_id) {
				jQuery('#domaintable').restoreRow(last_domain_edit_row);
				last_domain_edit_row = row_id;
			}
			if(bit_test(user_access_rights, ALLOW_EDIT_BITPOS) && grid_enable_inline_edit) {
				jQuery('#domaintable').editRow(row_id, {
					keys : true,
					oneditfunc: null,
					successfunc: function() {
						var datastr = get_ajax_datastr("get", "domain", "");
						datastr += "&id=" + row_id;
						ajax_call(datastr, ajax_domain_info, null);
						return true;
					}
				});
			}
        },
		resizeStop: function(newwidth, index) {
			saveCookie("domaingrid_auto_width", 0);
			var cm = $("#domaintable").jqGrid('getGridParam','colModel');
			$("#domaintable").jqGrid('setColProp',cm[index].name,{width:newwidth});
			set_column_model_widths(cm[index].name, newwidth);
			if(bit_test(user_access_rights, ALLOW_UICHANGE_BITPOS)) {
				var datastr = get_ajax_datastr("admin", "domain", "set");
				datastr += "&width=" + newwidth + "&name=" + cm[index].name;
				ajax_call(datastr, ajax_dummy_return, null);
			}
		},
		onCellSelect: function (rowid, iCol, cellcontent) {
			cellcontent = $("<div/>").html(cellcontent).text();
			$('#table_cell_copy').val(cellcontent);
			if($('#table_cell_auto_copy').is(":checked") && cellcontent != "") {
				$('#table_cell_copy').select();
				document.execCommand("copy");
				$('#table_cell_copy').val('');
				$('#table_cell_copy').val(cellcontent);
			}
		},
		beforeSelectRow: multiSelectHandler
	});
	
	var aedit = bit_test(user_access_rights, ALLOW_EDIT_BITPOS);
	var adel = bit_test(user_access_rights, ALLOW_DELETE_BITPOS);
	jQuery("#domaintable").navGrid(
	'#domaintablepager',
	{add:false,edit:aedit,del:adel,search:true,view:false,refreshstate:'current'},
	{ 
		// Edit
		width: 'auto',
		closeOnEscape:true,
		resize: false,
		afterShowForm: function(form) 
		{
			centerDialog('editmoddomaintable');
		},
		beforeShowForm: function(form)
		{
			setTableFontSize(getCookieInt("table-font-size", DEFAULT_TABLE_FONT_SIZE));
			$('#FrmGrid_domaintable').css('max-height', $(window).height()-250);
		},
		bottominfo: 'Edit may fail if you leave columns without a default value blank.'
	},
	{
		// Add
		resize: false,
		closeOnEscape:true
	},
	{
		// Delete Options
		width: 'auto',
		closeOnEscape:true,
		resize: false,
		beforeShowForm: function ($form) 
		{
			hideAllPanels();
			var dlist = getSelectedDomainList(25);
			$("td.delmsg", $form[0]).html("<div style=\"white-space:normal;\"><p><b>Do you really want to delete</b> </p><p>" + dlist + "?</p><p class=\"errormsg\">This will <b>completely remove the domain(s) from the database</b> (not the category alone)</p></div>");
			setTableFontSize(getCookieInt("table-font-size", DEFAULT_TABLE_FONT_SIZE));
		},
		afterShowForm: function(form) 
		{
			if($(window).width() < 500)
			{
				$('#delmoddomaintable').width($(window).width()-20);
			}
			else
				centerDialog('delmoddomaintable');
		},
		afterComplete:function() 
		{
			//showSessionQueueCount(true);
			show_selected_domain_info();
			$("#domaincategorytable").trigger("reloadGrid");
		}
	},
	{
		// Search
		multipleSearch:true,
		overlay: false, 
		closeOnEscape: true, 
		tableclass: 'searchform',
		width: 'auto',
		resize: false,
		beforeShowSearch: function ($form) 
		{
			setTableFontSize(getCookieInt("table-font-size", DEFAULT_TABLE_FONT_SIZE));
		},
		afterShowSearch: function(form) 
		{
			centerDialog('searchmodfbox_domaintable');
		}
	},
	{	// View
		// closeOnEscape: true,  // TODO: CloseOnEscape causes an exception (Uncaught TypeError: Cannot read property 'style' of undefined)
		width: 640,
		beforeShowForm: function ($form) 
		{
			centerDialog('viewmoddomaintable');
			setTableFontSize(getCookieInt("table-font-size", DEFAULT_TABLE_FONT_SIZE));
		}
	}
	);
	
	jQuery("#domaintable").jqGrid(
		'filterToolbar',{
			stringResult: true,
			searchOnEnter : grid_search_on_enter,
			autosearchDelay: grid_auto_search_delay
		}
	);
	
	var aadd = $(window).width() > 768 ? true : false;
	if(aadd && bit_test(user_access_rights, ALLOW_ADD_BITPOS))
	{
		domain_table_jqgrid.navButtonAdd('#domaintablepager',
		{
			// Add domain names
			caption:"", 
			buttonicon:"ui-icon-plus", 
			onClickButton: function()
			{ 
				init_panel_adddomains();
				showPanel("panel-adddomains", 'right');
				return false;
			}, 
			position:"first"
		});
	}
	
	$("#domaintable").navSeparatorAdd("#domaintablepager",{});
	domain_table_jqgrid.navButtonAdd('#domaintablepager', {
		// Add safe-delete button
		caption:"", 
		title: 'Single Category Delete',
		buttonicon:"ui-icon-minus", 
		onClickButton: function()
		{ 
			safe_delete_selected_domains();
			return false;
		}, 
		position:"last"
	});

	$("#domaintable").navSeparatorAdd("#domaintablepager",{});
	domain_table_jqgrid.navButtonAdd('#domaintablepager', {
		// Add copy button
		caption:"", 
		title: 'copy',
		buttonicon:"ui-icon-copy", 
		onClickButton: function()
		{ 
			copy_selected_domains();
			return false;
		}, 
		position:"last"
	});
	
	if(gridunloaded)
	{
		var fs = getCookieInt("table-font-size", DEFAULT_TABLE_FONT_SIZE);
		setTableFontSize(fs);
	}
	
	//centerGridTitle("domaintable");
	
	// The image in titlebar
	$('#gview_domaintable span.ui-jqgrid-title').after('<img id="jqGridImageDiv" src="lib/layouts/images/icons/captions/full.png">'); 
	
	jQuery("#domaintable").jqGrid('setLabel', 'availability', '<img src="lib/layouts/images/icons/fields/avail-head.png" width="12" height="14">');
	jQuery("#domaintable").jqGrid('setLabel', 'page_token_found', '<img src="lib/layouts/images/icons/fields/htmltoken-head.png" width="12" height="14">');
}

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

function save_current_column_model()
{
	if(bit_test(user_access_rights, ALLOW_UICHANGE_BITPOS)) {
		var dgroup = getCookie('display-group', "date_columns_array");
		var colmodel = $("#domaintable").jqGrid('getGridParam','colModel');
		var colsetup = "";
		for(var i = 0; i < colmodel.length; i++) {
			if(colmodel[i].name != "domain" && colmodel[i].name != "r_h_disp" && colmodel[i].name != "d.r_h_disp" && colmodel[i].name != "rn" && colmodel[i].name != "cb") {
				if(colsetup != "")
					colsetup += ";" + colmodel[i].name;
				else
					colsetup += colmodel[i].name;
			}
		}
		var datastr = get_ajax_datastr("set", "domain", "colmodel");
		datastr += "&group=" + encodeURIComponent(dgroup);
		datastr += "&columns=" + encodeURIComponent(colsetup);
		ajax_call(datastr, ajax_dummy_return, dgroup); 
	}
}

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

function set_column_model_widths(name, newwidth)
{
	var colmodels = [date_columns_array, custom01_columns_array, custom02_columns_array,
				custom03_columns_array, http_columns_array, registrar_columns_array, 
				network_columns_array, sitepop_columns_array, notes_columns_array, 
				ipdata_columns_array];
	for(var i = 0; i < colmodels.length; i++)
		set_column_model_widths_for(colmodels[i], name, newwidth);
}

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

function set_column_model_widths_for(colmodel, name, newwidth)
{
	var len = colmodel.length;
	for(var i = 0; i < len; i++) {
		if(colmodel[i].name == name)
			colmodel[i].width = newwidth;
	}
}

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

function getDomainDataURL(datacolumns)
{
	var colnum = datacolumns.length;
	var datastr = get_ajax_datastr("grid", "domain", "");
	var durl = base_grid_ajax_url + "?" + datastr + "&columns=sid,";
	for(i = 0; i < colnum; i++) {
		if(datacolumns[i].name != "rn" && datacolumns[i].name != "cb") {
			durl += encodeURIComponent(datacolumns[i].name);
			durl += ",";
		}
	}
	
	var aqid = getCookieInt('current_autoquery', 0);
	var cid = getCookieInt('current_category', 0);
	var hd = getCookieInt('domain_highlight_days', 30);

	if(cid > 0) {
		durl += "&cid=" + cid;
		$("#domainquerytable").resetSelection();
	}
	else if(aqid > 0) {
		$("#domaincategorytable").resetSelection();
		durl += "&aqid=" + aqid;
	}
	else if(custom_query_in_use) {
		durl += "&" + getCustomQueryData();
		$("#domainquerytable").resetSelection();
		$("#domaincategorytable").resetSelection();
	}
	
	durl += "&highlight=" + hd;
	return durl;
}

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

function setDefaultFontSizes()
{
	var fs = getCookieInt("table-font-size", DEFAULT_TABLE_FONT_SIZE);
	setTableFontSize(fs);
}

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

function saveRowIdsForReload()
{
	if(selected_rowids_for_reload == "") {
		var srows =  jQuery("#domaintable").getGridParam("selarrrow"); 
		selected_rowids_for_reload = srows.toString();
	}
}

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

function domainGridLoadComplete()
{
	fixDivSizes();
	setTimeout(function(){fixDivSizes();}, 150); 
	
	// If this is not done the selection is lost after a row edit.
	if(!$('#editmoddomaintable').is(':visible'))
		scrollToCurrentRow();

	var ids = $("#domaintable").getGridParam('selrow');
	var newrow = parseInt(ids);
	if(newrow != last_selected_domain_row) {
		last_selected_domain_row = newrow;
		show_selected_domain_info();
	}
}

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

function domainGridGridComplete()
{
	// Cookie the sort column and order
	var domain_sort_column_name = $("#domaintable").jqGrid('getGridParam','sortname');
	var domain_sort_order_name  = $("#domaintable").jqGrid('getGridParam','sortorder');
	saveCookie('current_sort_column', domain_sort_column_name); 
	saveCookie('current_sort_order', domain_sort_order_name); 

	var rowsperpage = $("#domaintable").jqGrid('getGridParam','rowNum');
	saveCookie('domain_rows_per_page', rowsperpage);
}

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

function scrollToCurrentRow()
{
	var sel_rowid = 0;
	var allIDs = jQuery("#domaintable").getDataIDs(); 
	if(allIDs.length > 0)
		sel_rowid = allIDs[0];
		
	var cdomain = parseInt($.cookie("current_domain"));
	if ( !isNaN(cdomain) )
		sel_rowid = cdomain;
	
	var sids = [];
	if(selected_rowids_for_reload != "")
		var sids = selected_rowids_for_reload.split(',');
	
	if(sids.length)
	{
		$("#domaintable").setGridParam({scrollrows:false}); 
		for (i = 0, count = sids.length; i < count; i++) 
			$("#domaintable").setSelection(sids[i], false);
		if(sids.length == 1)
			showWhoisData(SINGLE_DOMAIN_SELECTION, sids[0]);
		else if(sids.length > 1)
			showWhoisData(MULTI_DOMAIN_SELECTION, sids);
		scrollToRow($("#domaintable"), sids[0]);
	}
	else
	{
		$("#domaintable").setGridParam({scrollrows:false}); 
		var selids = jQuery("#domaintable").getGridParam("selarrrow"); 
		if(selids.length == 0)
			$("#domaintable").setSelection(sel_rowid, true);
		else if(selids.length == 1)
			showWhoisData(SINGLE_DOMAIN_SELECTION, selids[0]);
		scrollToRow($("#domaintable"), sel_rowid);
	}
	selected_rowids_for_reload = "";
}

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

function multiSelectHandler(sid, e) 
{
    //var grid = $(e.target).closest("table.ui-jqgrid-btable");
	var grid = $('#domaintable');
    var ts = grid[0], td = e.target;
    var scb = $(td).hasClass("cbox");
    if ((td.tagName == 'INPUT' && !scb) || td.tagName == 'A') {
        return true;
    }
    var sel = grid.getGridParam('selarrrow');
    var selected = $.inArray(sid, sel) >= 0;
    if (e.ctrlKey || (scb && (selected || !e.shiftKey))) {
        //grid.setSelection(sid,true);
    } else {
        if (e.shiftKey) {
            var six = grid.getInd(sid);
            var min = six, max = six;
            $.each(sel, function() {
                    var ix = grid.getInd(this);
                    if (ix < min) min = ix;
                    if (ix > max) max = ix;
                });
            while (min <= max) {
                var row = ts.rows[min++];
                var rid = row.id;
                if (/*rid != sid &&*/ $.inArray(rid, sel)<0) {
                    grid.setSelection(row.id, false);
                }
            }
        } else if (!selected) {
            grid.resetSelection();
        }
        if (!selected) {
            grid.setSelection(sid,true);
        } else {
            var osr = grid.getGridParam('onSelectRow');
            if ($.isFunction(osr)) {
                osr(sid, true);
            }
        }
    }
}

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

function selectCustomQuery(flag)
{
	$.cookie('current_category', "0");
	$.cookie('current_autoquery', "0");
	custom_query_in_use = flag;
	var durl = getDomainDataURL(getColModelFromGroupName(getCookie('display-group', "date_columns_array")));
	jQuery("#domaintable").setGridParam({url:durl});
	$("#domaintable").trigger("reloadGrid");  
	setDomainTableCaption();
}

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

function selectCategory(ids)
{
	$.cookie('current_category', String(ids));
	$.cookie('current_autoquery', "0");
	custom_query_in_use = false;
	var durl = getDomainDataURL(getColModelFromGroupName(getCookie('display-group', "date_columns_array")));
	jQuery("#domaintable").setGridParam({url:durl});
	$("#domaintable").trigger("reloadGrid");  
	setDomainTableCaption();
}

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

function selectAutoQuery(ids)
{
	if(ids == null) 
		ids = 0;
	$.cookie('current_category', "0");
	$.cookie('current_autoquery', String(ids));
	custom_query_in_use = false;
	clearSearchFilter();
	var durl = getDomainDataURL(getColModelFromGroupName(getCookie('display-group', "date_columns_array")));
	jQuery("#domaintable").setGridParam({url:durl});
	$("#domaintable").trigger("reloadGrid");  
	$("#domaincategorytable").resetSelection();
	setDomainTableCaption();
}

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

function clearSearchFilter()
{
    var grid = $("#domaintable");
    grid.jqGrid('setGridParam',{search:false});
    var postData = grid.jqGrid('getGridParam','postData');
    $.extend(postData,{filters:""});
    // for single search you should replace the line with
    // $.extend(postData,{searchField:"",searchString:"",searchOper:""});
	$(':input[id*="gs_"]').val("");
}

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

function setDomainTableCaption()
{
	var dtCaption = "Domain Name Portfolio";
	var captionImage = "full";
	
	var aqid = getCookieInt('current_autoquery', 0);
	var cid = getCookieInt('current_category', 0);
	
	if(aqid > 0)
	{
		captionImage = "auto";
		var rowData = $('#domainquerytable').jqGrid('getRowData', aqid);
		if (typeof rowData['name'] != 'undefined') 
			dtCaption = rowData['name'];
		else 
			dtCaption += " - Auto Filter";
	}
	else if(cid > 1)
	{
		captionImage = "category";
		var rowData = $('#domaincategorytable').jqGrid('getRowData', cid);
		var categoryName = rowData['name'];
		if (typeof categoryName != 'undefined') 
			dtCaption = categoryName;
		else 
			dtCaption += " - Category";
	}
	else if(custom_query_in_use)
	{
		dtCaption += " - Custom Query";
		captionImage = "custom";
	}
	
	if(domain_table_jqgrid)
	{
		if(jQuery("#domaintable").getGridParam("search"))
		{
			dtCaption += " - Search Results";
			captionImage += "search";
		}
		jQuery("#domaintable").setCaption(dtCaption);
	}
	$("#jqGridImageDiv").attr("src", "lib/layouts/images/icons/captions/"+captionImage+".png");
}

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

function cleanupWhoisText(text) {
	text = replaceAll(text, "\n<br>", "\n");
	text = replaceAll(text, "\r<br>", "\n");
	text = replaceAll(text, "<br>", "\n");
	text = replaceAll(text, "&gt;", ">");
	text = replaceAll(text, "&lt;", "<");
	return text;
}

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

function ajax_show_registry_whois_diff(x, jqXHR, textStatus, params) {
	if(x != null) {
		if(x.status == 'ok') {
			var oldtext = cleanupWhoisText(x.history.tvalue);
			var newtext = cleanupWhoisText($('#registrywhoistext').html());
			var textToShow = findTextDiff(oldtext, newtext);
			$('#registrydisplaytext').html(textToShow);
		}
	}
}

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

function ajax_show_registrar_whois_diff(x, jqXHR, textStatus, params) {
	if(x != null) {
		if(x.status == 'ok') {
			var oldtext = cleanupWhoisText(x.history.tvalue);
			var newtext = cleanupWhoisText($('#registrarwhoistext').html());
			var textToShow = findTextDiff(oldtext, newtext);
			$('#registrardisplaytext').html(textToShow);
		}
	}
}

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

function ajax_domain_info(x, jqXHR, textStatus, params)
{
	if(x != null) {
		if(x.status == 'ok') {
			var heading = "<h3>" + x.data['domain'] + "</h3>";
			var registrycontrols = "<div class=\"rw-controls\"><select data-domain=\"" + x.data['sid'] + "\" id=\"registrywhoiscontrols\"class=\"form-control input-sm\">";
			var registrarcontrols = "<div class=\"rw-controls\"><select data-domain=\"" + x.data['sid'] + "\" id=\"registrarwhoiscontrols\" class=\"form-control input-sm\">";

			var historyhtml = "";
			var rc01 = 0;
			var rc02 = 0;
			for(var i=0; i < x.history.length; i++) {
				var h = x.history[i];
				var id = h['id'];
				var ldate = h['lookedup_at'].replace(".000000", "");
				var ft = "1";
				if(h['ftype'] == 256) {
					registrarcontrols += "<option value=\"whid-" + id + "\">" + ldate + "</option>";
					rc02++;
				}
				else if(h['ftype'] == 1) {
					registrycontrols += "<option value=\"whid-" + id + "\">" + ldate + "</option>";
					rc01++;
				}
			}
			registrycontrols += "</select></div>";
			registrarcontrols += "</select></div>";

			if(x.data.registrar_whois == '' || rc02 <= 1)
				registrarcontrols = '';
			if(x.data.registry_whois == '' || rc01 <= 1)
				registrycontrols = '';

			var registrywhois, registrarwhois;
			if(isJson(x.data.registry_whois))
				registrywhois = heading + "<pre>" + x.data.registry_whois + "</pre>";
			else
				registrywhois = heading + registrycontrols + "<div id=\"registrywhoistext\">" + x.data.registry_whois + "</div>" + "<div id=\"registrydisplaytext\">" + x.data.registry_whois + "</div>";
			if(isJson(x.data.registrar_whois))
				registrarwhois = heading + "<pre>" + x.data.registrar_whois + "</pre>";
			else
				registrarwhois = heading + registrarcontrols + "<div id=\"registrarwhoistext\">" + x.data.registrar_whois + "</div>" + "<div id=\"registrardisplaytext\">" + x.data.registrar_whois + "</div>";
			$("#registrywhois").html(registrywhois);
			$("#registrarwhois").html(registrarwhois);

			$("#registrywhoiscontrols").val($("#registrywhoiscontrols option:first").val());
			$("#registrarwhoiscontrols").val($("#registrarwhoiscontrols option:first").val());
			$('#registrywhoiscontrols').off('change');
			$('#registrywhoiscontrols').change(function(event) {
				var hid = $('#registrywhoiscontrols').val().replace("whid-", "");
				var datastr = get_ajax_datastr("get", "domain", "history");
				datastr += "&id=" + encodeURIComponent(hid);
				ajax_call(datastr, ajax_show_registry_whois_diff, null); 
			});
			$('#registrarwhoiscontrols').off('change');
			$('#registrarwhoiscontrols').change(function(event) {
				var hid = $('#registrarwhoiscontrols').val().replace("whid-", "");
				var datastr = get_ajax_datastr("get", "domain", "history");
				datastr += "&id=" + encodeURIComponent(hid);
				ajax_call(datastr, ajax_show_registrar_whois_diff, null); 
			});

			$("#ipwhois").html(heading + x.data.ip_whois);
			$("#domaininfohead").html(heading);
			$('a[href]').attr('target', '_blank');
			var details = "";
			for (var key in x.data) {
				if (key === 'length' || !x.data.hasOwnProperty(key)) continue;
				var value = x.data[key];
				var label = x.info[key]['label'];
				var ftype = x.info[key]['fieldtype'];
				var gridview = parseInt(x.info[key]['gridview']);
				var editable = parseInt(x.info[key]['editable']);
				var imgfile = ftype;
				var img = "<img src=\"lib/layouts/images/icons/fields/" + imgfile + ".png\">";
				if(editable == 1) {
					imgfile += "-edit";
					img = "<a class=\"btn-details\" id=\"edit-" + key + "\"><img src=\"lib/layouts/images/icons/fields/" + imgfile + ".png\"></a>";
				}
				if(gridview == 1 && key != "r_h_disp") {
					details += "<tr><td class=\"control\">" + img + "</td><td class=\"column\">" + label + "</td><td class=\"value\"><div class=\"dtabv dtabv-" + key + "\">" + value + "</div></td></tr>\n";
					if(key == "domain")
						details += "{{SUBDOMAIN}}";
				}
			}
			
			var extra = "";
			var subdomains = "";
			var sid = x.data['sid'];
			if(x.subdomains.length) {
				for(var i = 0; i < x.subdomains.length; i++) {
					if(subdomains != "")
						subdomains += "&nbsp;&nbsp;";
					var sdlink = "<span title=\"click to delete\" class=\"btn-del-subdomain\" id=\"sd-" + sid + "-" + x.subdomains[i] + "\">";
					sdlink += x.subdomains[i];
					sdlink += "</span>";
					subdomains += sdlink;
				}
			}
			var img = "<img src=\"lib/layouts/images/icons/fields/" + "subdomains" + ".png\">";
			if(bit_test(user_access_rights, ALLOW_ADD_BITPOS)) {
				var eimg = "<img src=\"lib/layouts/images/icons/fields/" + "add-sd" + ".png\">";
				img = "<a class=\"btn-details\" id=\"add-subdomains\">" + eimg + "</a>";
			}
			extra += "<tr><td class=\"control\">" + img + "</td><td class=\"column\">" + "Subdomains" + "</td><td class=\"value\"><div class=\"dtabv dtabv-" + "sd" + "\">" + subdomains + "</div></td></tr>\n";
			
			var txtrecords = "";
			if(x.txtrecords.length) {
				for(var i = 0; i < x.txtrecords.length; i++) {
					if(txtrecords != "")
						txtrecords += "&nbsp;&nbsp;";
					var sdlink = "<span title=\"click to delete\" class=\"btn-del-txtname\" id=\"sd-" + sid + "-" + x.txtrecords[i] + "\">";
					sdlink += x.txtrecords[i];
					sdlink += "</span>";
					txtrecords += sdlink;
				}
			}
			img = "<img src=\"lib/layouts/images/icons/fields/" + "txtrecords" + ".png\">";
			if(bit_test(user_access_rights, ALLOW_ADD_BITPOS)) {
				var eimg = "<img src=\"lib/layouts/images/icons/fields/" + "add-tr" + ".png\">";
				img = "<a class=\"btn-details\" id=\"add-txtrecords\">" + eimg + "</a>";
			}
			extra += "<tr><td class=\"control\">" + img + "</td><td class=\"column\">" + "TXT Records" + "</td><td class=\"value\"><div class=\"dtabv dtabv-" + "sd" + "\">" + txtrecords + "</div></td></tr>\n";

			
			details = details.replace("{{SUBDOMAIN}}", extra);
			var table = "<table class=\"dataviewtable\">" + details + "</table>";
			$("#domaindetails").html(table);
			
			var luqinfo = "<ul class=\"list-group list-group-flush\">";
			var lc = x.luq.length;
			for(var i = 0; i < lc; i++) {
				luqinfo += "<li class=\"list-group-item\">" + x.luq[i]['label'] + " | " + x.luq[i]['created_on'] + " | " + x.luq[i]['server'] + "</li>\n";
			}
			if(!lc)
				luqinfo += "<li class=\"list-group-item\">No lookup queue entries found for domain " + x.data['domain'] + "</li>";
			luqinfo += "</ul>";
			$("#domqueuestat").html(luqinfo);
			
			highlightCategories(x.cids);
			$("#webshotthumb").attr("src",app_root_url + "api.php?c=get&t=webshot&domain=" + x.data['domain']);
			
			var historyhtml = "";
			for(var i=0; i < x.history.length; i++) {
				var h = x.history[i];
				var id = h['id'];
				var ldate = replaceAll(h['lookedup_at'], '.000000', '');
				var ft = "1";
				if(h['ftype'] == 256)
					ft = "2";
				historyhtml += "<p><a href=\"#\" id=\"wh_" + id + "\" class=\"btn btn-sm btn-block btn-dlg history-popup\">" + ldate + " (" + ft + ") </a></p>";
				if(i > 20)
					break;
			}

			$('.history-popup').off('click');
			if(x.history.length) {
				$("#whoishistory").html("<h3>whois history</h3>" + historyhtml);
				$('#ddwrap').removeClass('col-sm-12');
				$('#ddwrap').addClass('col-sm-9');
				$('.history-popup').click(function(event) {
					var did = $(this).attr('id');
					did = did.replace("wh_", "");
					showWhoisHistoryPopup(did);
				});
			}
			else {
				$("#whoishistory").html('');
				$('#ddwrap').addClass('col-sm-12');
				$('#ddwrap').removeClass('col-sm-9');
			}
			
			$('.btn-details').off('click');
			$('.btn-details').click(function(event)
			{
				var cpid = jQuery(this).attr("id");
				event.preventDefault();
				if(cpid == "add-subdomains") {
					$('#select_sdtype').val('sd');
					add_subdomains();
				}
				else if(cpid == "add-txtrecords") {
					// Select Txt Record
					$('#select_sdtype').val('txt');
					add_subdomains();
				}
				else {
					var colname = cpid.replace("edit-", "");
					init_panel_bulkedit();
					$('#bulkedit-column').html(colname);
					$('#bulkedit-field').val(colname);
					bulkedit_init_column = colname;
					showPanel("panel-bulkedit");
				}
			});
			
			$('.btn-del-subdomain').off('click');
			$('.btn-del-subdomain').click(function(event)
			{
				var cpid = jQuery(this).attr("id");
				event.preventDefault();
				$('#confirm-message').html("<h4>Are you sure you want to delete the subdomain?</h4>");
				$('#confirm-caller').val("deleteSubdomain");
				$('#confirm-param').val(cpid);
				showPanel("panel-confirm");
			});
			
			$('.btn-del-txtname').off('click');
			$('.btn-del-txtname').click(function(event)
			{
				var cpid = jQuery(this).attr("id");
				event.preventDefault();
				$('#confirm-message').html("<h4>Are you sure you want to delete the TXT record name?</h4>");
				$('#confirm-caller').val("deleteTxtRecord");
				$('#confirm-param').val(cpid);
				showPanel("panel-confirm");
			});
		}
	}
}

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

function deleteSubdomain()
{
	var sidsd = $('#confirm-param').val().replace("sd-", "");;
	var pos = sidsd.indexOf("-");
	if(pos > 0) {
		var sid = sidsd.substring(0, pos);
		var subdomain = sidsd.substring(pos+1);
		var datastr = get_ajax_datastr("del", "subdomain", "");
		datastr += "&id=" + encodeURIComponent(sid);
		datastr += "&subdomain=" + encodeURIComponent(subdomain);
		ajax_call(datastr, ajax_delete_subdomain, null); 
	}
}

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

function deleteTxtRecord()
{
	var sidsd = $('#confirm-param').val().replace("sd-", "");;
	var pos = sidsd.indexOf("-");
	if(pos > 0) {
		var sid = sidsd.substring(0, pos);
		var subdomain = sidsd.substring(pos+1);
		var datastr = get_ajax_datastr("del", "txtrecord", "");
		datastr += "&id=" + encodeURIComponent(sid);
		datastr += "&subdomain=" + encodeURIComponent(subdomain);
		ajax_call(datastr, ajax_delete_subdomain, null); 
	}
}

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

function ajax_delete_subdomain(x, jqXHR, textStatus, params)
{
	if(x != null) {
		if(x.status == 'ok') {
			show_selected_domain_info();
		}
	}
}


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

function showWhoisHistoryPopup(did)
{
	var datastr = get_ajax_datastr("get", "domain", "history");
	datastr += "&id=" + encodeURIComponent(did);
	ajax_call(datastr, ajax_whoishistory_done, null); 
}

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

function ajax_whoishistory_done(x, jqXHR, textStatus, params)
{
	if(x != null) {
		if(x.status == 'ok') {
			showPopup("as on " + x.history.lookedup_at, x.history.tvalue, "Whois History");
		}
	}
}

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

function show_selected_domain_info()
{
	var rowids = $("#domaintable").getGridParam('selarrrow');
	if(rowids == null || rowids.length == 0)
		showWhoisData(NO_DOMAIN_SELECTION, rowids);
	else if(rowids.length == 1)
		showWhoisData(SINGLE_DOMAIN_SELECTION, rowids);
	else
		showWhoisData(MULTI_DOMAIN_SELECTION, rowids);
}

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

function showWhoisData(status, ids)
{
	if(status == MULTI_DOMAIN_SELECTION)
	{
		var dl = "<p>" + getSelectedDomainList(25) + ".</p>";
		jQuery("#registrywhois").html("<h3>Multiple domains selected</h3>"+dl);
		jQuery("#registrarwhois").html("<h3>Multiple domains selected</h3>"+dl);
		jQuery("#ipwhois").html("<h3>Multiple domains selected</h3>"+dl);
		jQuery("#domaininfohead").html("<h3>Multiple domains selected</h3>");
		jQuery("#domaindetails").html(dl);
		$("#whoishistory").html('');
		jQuery("#oltooldomain").html("<h3>Multiple domains selected</h3>"+dl);
		jQuery("#queuedomain").html("<h3>Multiple domains selected</h3>");
		$("#domqueuestat").html('');
		$( "#toolbox" ).hide();
		$("#dnstable").trigger("reloadGrid");
		$("#ssltable").trigger("reloadGrid");
		last_selected_domain_row = -1;
	}
	else if(status == NO_DOMAIN_SELECTION)
	{
		var dl = ""; //"<p>Please select a domain in the table above.</p>";
		jQuery("#registrywhois").html("<h3>No domain is selected</h3>"+dl);
		jQuery("#registrarwhois").html("<h3>No domain is selected</h3>"+dl);
		jQuery("#ipwhois").html("<h3>No domain is selected</h3>"+dl);
		jQuery("#domaininfohead").html("<h3>No domain is selected</h3>");
		jQuery("#domaindetails").html(dl);
		$("#whoishistory").html('');
		jQuery("#oltooldomain").html("<h3>No domain is selected</h3>"+dl);
		jQuery("#queuedomain").html("<h3>No domain is selected</h3>");
		$("#domqueuestat").html('');
		$( "#toolbox" ).hide();
		$("#dnstable").trigger("reloadGrid");
		$("#ssltable").trigger("reloadGrid");
		last_selected_domain_row = -1;
	}
	else
	{
		var domainname = jQuery("#domaintable").getCell(ids, "d.domain"); 
		var heading = "<h3>" + domainname + "</h3>";
		jQuery("#domaininfohead").html(heading);
		jQuery("#domaindetails").html("<img src=\"\lib/layouts/images/loaders/ajax-loader.gif\" class=\"mx-auto\">&nbsp;");
		$("#whoishistory").html('');
		jQuery("#oltooldomain").html(heading);
		jQuery("#queuedomain").html("<h3>" + domainname + " (" + ids + ")</h3>");
		$( "#toolbox" ).show();
		var datastr = get_ajax_datastr("get", "domain", "");
		datastr += "&id=" + ids;
		ajax_call(datastr, ajax_domain_info, null);
		$("#dnstable").trigger("reloadGrid");
		$("#ssltable").trigger("reloadGrid");
	}
	
	showSessionQueueCount(true);
	setTimeout(function(){fixDivSizes();}, 150);  // Move this to within the subgrid load complete ?
}

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

function getColModelFromGroupName(dgroup)
{
	return window[dgroup];
}

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

function getSelectedDomainList(dcount)
{
	var rowKey = jQuery("#domaintable").getGridParam("selarrrow"); 
	var dlist = "";
	var rl = rowKey.length;
	if(dcount > 25)
		dcount = 25;
	if(rl > dcount)
		rl = dcount;
	for(i = 0; i < rl; i++)
	{
		var rowData = jQuery("#domaintable").jqGrid ('getRowData', rowKey[i]);
		dlist += rowData['d.domain'];
		if(i == (rl-2) && rl == rowKey.length)
			dlist += " &amp; ";
		else if(i != (rl-1))
		{
			dlist += ", ";
		}
		else if(i == (rl-1) && rl < rowKey.length)
			dlist += " and <b>" + String(rowKey.length-rl) + " more domains</b>";
	}
	return dlist;
}

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

function safe_delete_domains() {
	var selids = jQuery("#domaintable").getGridParam("selarrrow"); 
	var catid = getCookieInt('current_category', 0);
	var datastr = get_ajax_datastr("del", "domain", "safe");
	datastr += "&id=" + encodeURIComponent(selids) + "&cid=" + catid;
	console.log(datastr);
	ajax_call(datastr, ajax_safe_delete_domains, null);
}

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

function ajax_safe_delete_domains(x, jqXHR, textStatus, params)
{
	if(x != null) {
		if(x.status == 'ok') {
			if(x.deleted > 0) {
				show_selected_domain_info();
				$("#domaintable").trigger("reloadGrid"); 
				$("#domaincategorytable").trigger("reloadGrid");
			}
		}
	}
}

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

function safe_delete_selected_domains() {
	var catid = getCookieInt('current_category', 0);
	if(catid > 1) {
		var dlist = getSelectedDomainList(25);
		if(dlist != '') {
			event.preventDefault();
			$('#confirm-message').html("<h4>Are you sure you want to delete the domains?</h4><p class=\"small text-center\">" + dlist + "</p><p class=\"errormsg small text-justify\">This is a safer delete option that will delete only the domains that belong to the current category and no other. Any domain in the list that is also a member of another category will not be deleted.</p>");
			$('#confirm-caller').val("safe_delete_domains");
			$('#confirm-param').val();
			showPanel("panel-confirm");
		}
	}
	else 
		showAlert("Safe delete option is not available when 'All Domains' is selected");
}

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

function copy_selected_domains() {
	var rowKey = jQuery("#domaintable").getGridParam("selarrrow"); 
	var text = "";
	var rl = rowKey.length;
	for(i = 0; i < rl; i++) {
		var rowData = jQuery("#domaintable").jqGrid ('getRowData', rowKey[i]);
		text += rowData['d.domain'] + "\n";
	}
	copyToClipboard(text);
}

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

function copyToClipboard(text) {
    if (window.clipboardData && window.clipboardData.setData) {
        // Internet Explorer-specific code path to prevent textarea being shown while dialog is visible.
        return window.clipboardData.setData("Text", text);
    }
    else if (document.queryCommandSupported && document.queryCommandSupported("copy")) {
        var textarea = document.createElement("textarea");
        textarea.textContent = text;
        textarea.style.position = "fixed";  // Prevent scrolling to bottom of page in Microsoft Edge.
        document.body.appendChild(textarea);
        textarea.select();
        try {
            return document.execCommand("copy");  // Security exception may be thrown by some browsers.
        }
        catch (ex) {
            console.warn("Copy to clipboard failed.", ex);
            return false;
        }
        finally {
            document.body.removeChild(textarea);
        }
    }
}

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

function ajax_add_domains(x, jqXHR, textStatus, params)
{
	if(x != null) {
		if(x.status == 'ok') {
			if(x.added > 0) {
				$("#domaintable").trigger("reloadGrid"); 
				hideAllPanels();
			}
			else {
				if(x.category > 1)
					$("#domaintable").trigger("reloadGrid");
				$('#adddomains-error').html(x.error);
			}
			$("#domaincategorytable").trigger("reloadGrid");
		}
		else
			$('#adddomains-error').html(x.error);
	}
}

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

function ajax_regapi_add_domains(x, jqXHR, textStatus, params)
{
	ajax_add_domains(x, jqXHR, textStatus, params);
}

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

function add_domains(domaindata, tlds, catid, emptycat) {
	$('#adddomains-error').html('');
	var addmode = $('#select_regapi').val();
	var datastr = get_ajax_datastr("add", "domain", "");
	if(addmode == "manual") {
		datastr += "&data=" + encodeURIComponent(domaindata) + "&cid=" + catid + '&emptycat=' + emptycat;
		datastr += "&tlds=" + encodeURIComponent(tlds ? tlds : "");
		ajax_call(datastr, ajax_add_domains, null);
	}
	else {
		var checkedIds = $("#regapichecklist :checkbox:checked").map(function() {
			return this.id.replace("regapi-", "");
		}).get();
		var ids = checkedIds.join(",");
		var bgproc = $('#add-bgprocess').is(':checked') ? "1" : "0";
		datastr += "&regapi=" + encodeURIComponent(ids) + "&cid=" + catid + '&emptycat=' + emptycat;
		datastr += "&bgproc=" + bgproc;
		ajax_call(datastr, ajax_regapi_add_domains, null);
	}
}

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

function DoLookups()
{
	var luw = 0;
	luw |= $('#luwhois').is(':checked') ? DOMAIN_RECORDS : 0;
	luw |= $("#ludns").is(':checked') ? ROOT_DNS : 0;
	luw |= $("#luhttp").is(':checked') ? HTTP_WEBSITE : 0;
	luw |= $("#lualexa").is(':checked') ? ALEXA_DATA : 0;
	luw |= $("#luping").is(':checked') ? PING_RESPONSE : 0;
	luw |= $("#luipwhois").is(':checked') ? IP_WHOIS : 0;
	luw |= $("#lugindex").is(':checked') ? GOOGLE_INDEX : 0;
	luw |= $("#lusubdom").is(':checked') ? SUB_DOMAINS : 0;
	luw |= $("#lussl").is(':checked') ? SSL_CERTS : 0;
	var luint = $("#luint").val();
	if(luint == "")
		luint = 1440;
	$('#lookup-error').html('');
	if(luw != 0)
	{	
		if(luint < 0)
			luint = 1440;
		var rowKey = jQuery("#domaintable").getGridParam("selarrrow"); 
		//if(sub_domain_manager_mode)
		//	rowKey = getUniqueSelectedDomainIds(false);
		var datastr = get_ajax_datastr("set", "luq", "");
		datastr += "&what=" + luw + "&id=" + rowKey + "&ri=" + luint;
		ajax_call(datastr, ajax_do_lookups, null);
	}
	else
		$('#lookup-error').html('Nothing to do!');
}

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

function ajax_do_lookups(x, jqXHR, textStatus, params)
{
	if(x != null) {
		if(x.status == 'ok') {
			if(x.status == 'ok' && x.count > 0)
				hidePanelWithId("panel-lookup");
			else if(x.status == 'ok' && x.count == 0)
				$('#lookup-error').html("Nothing queued. The domain may already be in queue or write protected, otherwise change the minimum refresh interval to force.");
			else
				$('#lookup-error').html(x.msg);
			//showSessionQueueCount(true);
			show_selected_domain_info();
		}
		else
			$('#lookup-error').html(x.error);
	}
}

/////////////////////////////////////////////////////////////////////////////////////////
// Change the font size of the alert messages (please select row)
// https://stackoverflow.com/questions/11719349/jqgrid-warning-please-select-row-position
//
var orgViewModal = $.jgrid.viewModal;

$.extend($.jgrid, {
    viewModal: function (selector, o) {
        if (selector.indexOf('#alertmod') == 0) {
			setTableFontSize(getCookieInt("table-font-size", DEFAULT_TABLE_FONT_SIZE));
			$(selector + '.ui-widget-content .ui-jqdialog-content').css('padding', "20px 5px");
        }
        orgViewModal.call(this, selector, o);
    }
});

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