/////////////////////////////////////////////////////////////////////////////////////////
// grids.js
// Watch My Domains SED v3
// (c) Softnik Technologies. All rights reserved.
/////////////////////////////////////////////////////////////////////////////////////////

var sub_domain_manager_mode 	= false;

var DOMAINGRID_MULTI_SELECT     = true;
var DOMAINGRID_MULTI_BOX_ONLY   = true;

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

var domain_table_jqgrid         = null;
var selected_rowids_for_reload  = "";
var selected_page_for_reload    = 0;

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

$(function() 
{	
	LoadDomainDataGrid(false);
	setDefaultFontSizes();
});

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

function getDomainDataURL(datacolumns)
{
	var colnum = datacolumns.length;
	var durl = base_grid_ajax_url + "?" + DGA_DOMAIN_GRID + "&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 cqid =  getCookieInt('current_customquery', 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(cqid > 0)
	{
		$("#DomainCategoryTable").resetSelection();
		$("#DomainQueryTable").resetSelection();
		durl += "&cqid=" + cqid;
		var catids = getAllCategoryIDsFromList('customqueries-categories', 'cq');
		var query = $('#customqueries-customsql').val();
		var dstring = $('#customqueries-string').val();
		durl += "&qs=" + encodeURIComponent(dstring);
		durl += "&qcids=" + catids;
		durl += "&q=" + encodeURIComponent(query);
		
		$.cookie('customqueries-string', dstring);
		$.cookie('customqueries-customsql', query);
		$.cookie('customqueries-categories', catids);
	}
	
	durl += "&hd=" + hd;
	return durl;
}

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

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 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 sortname = getCookie('current_sort_column', "sid");
	var sortorder = getCookie('current_sort_order', "desc");
	domain_table_jqgrid = jQuery("#DomainTable").jqGrid(
	{
		height: $("#DomainTablePane").height()-120,
		width: $("#DomainTablePane").width()-24,
		altRows:true,
		hidegrid: false,
		altclass: "gridAltRowClass",
		url: durl,
		editurl: base_grid_ajax_url + '?' + DGA_DOMAIN_GRID_EDIT,
		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: true,
		mtype: 'POST',
		multiselect: DOMAINGRID_MULTI_SELECT,
		multiboxonly: DOMAINGRID_MULTI_BOX_ONLY,
		gridView: true,
		caption:"Domain Name Portfolio",
		recordtext: "{0} - {1} of {2}",
		
		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)
		{
			if(status == false)
			{
				showWhoisData(NO_DOMAIN_SELECTION);
			}
			else
			{
				var allIDs  = jQuery("#DomainTable").getDataIDs(); 
				if(allIDs.length == 1)
				{
					showWhoisData(SINGLE_DOMAIN_SELECTION, allIDs[0]); 
				}
				else 
				{
					showWhoisData(MULTI_DOMAIN_SELECTION);
				}
			}
		},
		onSelectRow: function(ids) 
		{
			if(ids == null || ids == 0)
				showWhoisData(NO_DOMAIN_SELECTION);
			else  
			{
				var selids = jQuery("#DomainTable").getGridParam("selarrrow"); 
				if(selids.length > 1)
					showWhoisData(MULTI_DOMAIN_SELECTION);
				else
					showWhoisData(SINGLE_DOMAIN_SELECTION, ids);
			}
			$.cookie('current_domain', String(ids)); 
			highlightCategoriesOfCurrentDomain();
		},
		loadError: function (jqXHR, textStatus, errorThrown) 
		{
			gridSessionTimedoutError(jqXHR);
		},
		beforeRequest: function() 
		{
			setDomainTableCaption();
		},
		beforeSelectRow: multiSelectHandler
	});
	
	var aedit = (user_access_rights == 0 ? false : true);
	var adel = (user_access_rights == 1 ? true : false);
	jQuery("#DomainTable").navGrid(
	'#DomainTablePager',
	{add:false,edit:aedit,del:adel,search:true,view:false,refreshstate:'current'},
	{ 
		// Edit
		width: 'auto',
		closeOnEscape:true,
		afterShowForm: function(form) 
		{
			centerDialog('editmodDomainTable');
			setGridDialogColors();
		},
		beforeShowForm: function(form)
		{
			setTableFontSize(getCookieInt("table-font-size", DEFAULT_TABLE_FONT_SIZE));
		}
	},
	{
		// Add
		closeOnEscape:true
	},
	{
		// Delete Options
		width: 'auto',
		closeOnEscape:true,
		beforeShowForm: function ($form) 
		{
			hideModalPanels();
			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></div>");
				 setGridDialogColors();
			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() 
		{
			show_queue_count(1);
			showWhoisData(NO_DOMAIN_SELECTION);
		}
	},
	{
		// Search
		multipleSearch:true,
		overlay: false, 
		closeOnEscape: true, 
		tableclass: 'searchform',
		width: 'auto',
		beforeShowSearch: function ($form) 
		{
			setTableFontSize(getCookieInt("table-font-size", DEFAULT_TABLE_FONT_SIZE));
		},
		afterShowSearch: function(form) 
		{
			centerDialog('searchmodfbox_DomainTable');
			setGridDialogColors();
		}
	},
	{	// View
		// closeOnEscape: true,  // TODO: CloseOnEscape causes an exception (Uncaught TypeError: Cannot read property 'style' of undefined)
		width: 640,
		beforeShowForm: function ($form) 
		{
			centerDialog('viewmodDomainTable');
			setGridDialogColors();
			setTableFontSize(getCookieInt("table-font-size", DEFAULT_TABLE_FONT_SIZE));
		}
	}
	);
	
	jQuery("#DomainTable").jqGrid(
		'filterToolbar',{
			stringResult: true,
			searchOnEnter : false
		}
	);
	
	var aadd = $(window).width() >= 800 ? true : false;
	if(aadd && (user_access_rights == 1 || user_access_rights == 3))
	{
		domain_table_jqgrid.navButtonAdd('#DomainTablePager',
		{
			// Add domain names
			caption:"", 
			buttonicon:"ui-icon-plus", 
			onClickButton: function()
			{ 
				showAddDomains();
				return false;
			}, 
			position:"first"
		});
	}
	
	/*
	domain_table_jqgrid.navSeparatorAdd("#DomainTablePager",{})
	.navButtonAdd('#DomainTablePager',
	{
		caption:"", 
		buttonicon:"ui-icon-check", 
		onClickButton: function()
		{ 
			var rowKey = jQuery("#DomainTable").getGridParam("selarrrow"); 
			if(rowKey.length > 0)
				$('#btn_mpanel-lookup').click();
			return false;
		}, 
		position:"last",
		title:'Lookup Domains'
	})
	.navSeparatorAdd("#DomainTablePager",{})
	.navButtonAdd('#DomainTablePager',
	{
		caption:"", 
		buttonicon:"ui-icon-transferthick-e-w", 
		onClickButton: function()
		{ 
			var rowKey = jQuery("#DomainTable").getGridParam("selarrrow"); 
			if(rowKey.length > 0)
				$('#btn_mpanel-parsewhois').click();
			return false;
		}, 
		position:"last",
		title:'Parse Domain Whois'
	})
	
	if(is_an_admin_user)
		addRegistrarAliasButton();
	if(user_access_rights == 1 || user_access_rights == 3 || is_an_admin_user)
		addCSVTableDownloadButton();
	*/
	
	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/css/images/16/full.png">'); 
	
	jQuery("#DomainTable").jqGrid('setLabel', 'availability', '<img src="lib/css/images/16/avail-head.png" width="12" height="14">');
	jQuery("#DomainTable").jqGrid('setLabel', 'page_token_found', '<img src="lib/css/images/16/htmltoken-head.png" width="12" height="14">');
}

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

function multiSelectHandler(sid, e) 
{
    var grid = $(e.target).closest("table.ui-jqgrid-btable");
    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 domainGridLoadComplete()
{
	themeChanged();
	fixDivSizes();
	fixDivSizes();
	
	// If this is not done the selection is lost after a row edit.
	if(!$('#editmodDomainTable').is(':visible'))
		scrollToCurrentRow();
}

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

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 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);
	
	$("#registrywhois").html("");
	$("#registrarwhois").html("");
}

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

function getGridRowHeight (targetGrid) 
{
    var height = 23; // Default
    try
	{
		count = $("#DomainTable").getGridParam("reccount");
		if(count)
			height = $('#DomainTable').height() / count;
    }
    catch(e){
    }
    return height;
}

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

function scrollToRow (targetGrid, id) 
{
    var rowHeight = getGridRowHeight(targetGrid) || 23; // Default height
    var index = jQuery(targetGrid).getInd(id);
	if(index > 5)
		jQuery(targetGrid).closest(".ui-jqgrid-bdiv").scrollTop(rowHeight * index - rowHeight*3);
}

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

function getColModelFromGroupName(dgroup)
{
	if(dgroup == "http_columns_array")
		return http_columns_array;
	else if(dgroup == "date_columns_array")
		return date_columns_array;
	else if(dgroup == "network_columns_array")
		return network_columns_array;
	else if(dgroup == "sitepop_columns_array")
		return sitepop_columns_array;
	else if(dgroup == "notes_columns_array")
		return notes_columns_array;
	else if(dgroup == "custom01_columns_array")
		return custom01_columns_array;
	else if(dgroup == "custom02_columns_array")
		return custom02_columns_array;
	else if(dgroup == "registrar_columns_array")
		return registrar_columns_array;
	else if(dgroup == "ipdata_columns_array")
		return ipdata_columns_array;
	else if(dgroup == "report_columns_array")
		return report_columns_array;
	else
		return date_columns_array;
}

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

function changeCurrentColumnModel(newcolmodel)
{
	var group = getCookie('display-group', "date_columns_array")
	if(group == "http_columns_array")
		http_columns_array = newcolmodel;
	else if(group == "date_columns_array")
		date_columns_array = newcolmodel;
	else if(group == "network_columns_array")
		network_columns_array = newcolmodel;
	else if(group == "sitepop_columns_array")
		sitepop_columns_array = newcolmodel;
	else if(group == "notes_columns_array")
		notes_columns_array = newcolmodel;
	else if(group == "custom01_columns_array")
		custom01_columns_array = newcolmodel;
	else if(group == "custom02_columns_array")
		custom02_columns_array = newcolmodel;
	else if(group == "registrar_columns_array")
		registrar_columns_array = newcolmodel;
	else if(group == "ipdata_columns_array")
		ipdata_columns_array = newcolmodel;
	else if(group == "report_columns_array")
		report_columns_array = newcolmodel;
	else
		return false;
	return true;
}

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

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("#ipdata").html("<h3>Multiple domains selected</h3>"+dl);
		jQuery("#domaindetails").html("<h3>Multiple domains selected</h3>"+dl);
		jQuery("#oltooldomain").html("<h3>Multiple domains selected</h3>"+dl);
		$( ".toolsButton" ).button( "option", "disabled", true );
	}
	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("#domaindetails").html("<h3>No domain is selected</h3>"+dl);
		jQuery("#oltooldomain").html("<h3>No domain is selected</h3>"+dl);
		$( ".toolsButton" ).button( "option", "disabled", true );
	}
	else
	{
		var domainname = jQuery("#DomainTable").getCell(ids, "domain"); 
		var heading = "<h3>" + domainname + "</h3>";
		jQuery("#oltooldomain").html(heading);
		$( ".toolsButton" ).button( "option", "disabled", false );
		
		var turl = base_grid_ajax_url + "?wdd=" + ids;
		$.ajax({
			type: "POST",
			cache: false,
			url: turl,
			success: function(msg)
			{
				var x = jQuery.parseJSON(msg);
				if(x.validate == 1)
					sessionRestart("timeout");
				else if(x.validate == -1)
					sessionRestart("badsession");
				$("#registrywhois").html(heading + x.registry_whois);
				$("#registrarwhois").html(heading + x.registrar_whois);
				$("#ipwhois").html(heading + x.ip_whois);
				$("#domaindetails").html(heading + x.domain_details);
				$('.history-popup').off('click');
				if(x.whois_history != "") {
					$("#whoishistory").html("<h3>whois history</h3>" + x.whois_history);
					$('#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');
				}
				initOrphanDelete();
			},
			error: function(XMLHttpRequest, textStatus, errorThrown) 
			{ 
				if(!gridSessionTimedoutError(XMLHttpRequest.status))
					alert("Error: " + errorThrown + ', ' + textStatus); 
			} 
		});
		
		jQuery("#SubdomainTable").setCaption(domainname);
		jQuery("#SSLTable").setCaption(domainname);
	}
	
	$("#SubdomainTable").trigger("reloadGrid");
	$("#SSLTable").trigger("reloadGrid");
	setTimeout(function(){fixDivSizes();}, 150);  // Move this to within the subgrid load complete ?
}

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

function showWhoisHistoryPopup(did)
{
	var turl = base_grid_ajax_url + "?whistory=" + did;
	$.ajax({
		type: "POST",
		cache: false,
		url: turl,
		success: function(msg)
		{
			var x = jQuery.parseJSON(msg);
			if(x.validate == 1)
				sessionRestart("timeout");
			else if(x.validate == -1)
				sessionRestart("badsession");
			$('.ui-dialog .dialogWithShadow').css('width', '600px');
			whois_history_popup(x.type, x.whois, x.timeat, x.domain); 
		}
	});
}

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

function whois_history_popup(type, whois, timeat, domain)
{
	var maxwidth = $(window).width()-40;
	if(maxwidth > 700) maxwidth = 700;
	var maxheight = $(window).height()-80;
	if(maxheight > 600) maxheight = 600;
    title_msg = type + ' Whois History - ' + timeat + ' - ' + domain;
    if (whois != "")
    {
		$("<div></div>").html(whois).dialog({
			title: title_msg,
			resizable: false,
			modal: true,
			maxHeight: 400,
			height: maxheight,
			width: maxwidth,
			dialogClass: 'dialogWithShadow customAlert',
			create: function( event, ui ) {themeCustomDialog();},
			buttons: {
				"OK": function() 
				{
					$( this ).dialog( "close" );
				}
			}
		});
	}
}

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

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.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 selectCategory(ids)
{
	$.cookie('current_category', String(ids));
	$.cookie('current_autoquery', "0");
	$.cookie('current_customquery', "0");
	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));
	$.cookie('current_customquery', "0");
	clearSearchFilter();
	var durl = getDomainDataURL(getColModelFromGroupName(getCookie('display-group', "date_columns_array")));
	jQuery("#DomainTable").setGridParam({url:durl});
	$("#DomainTable").trigger("reloadGrid");  
	$("#DomainCategoryTable").resetSelection();
	setDomainTableCaption();
}

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

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

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

function setDomainTableCaption()
{
	var dtCaption = "Domain Name Portfolio";
	var captionImage = "full";
	
	var aqid = getCookieInt('current_autoquery', 0);
	var cid = getCookieInt('current_category', 0);
	var cqid =  getCookieInt('current_customquery', 0);
	
	if(aqid > 0)
	{
		dtCaption += " - Auto Query";
		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['CategoryName'];
		if (typeof categoryName != 'undefined') 
			dtCaption += " [" + categoryName + "]";
		else 
			dtCaption += " - Category";
	}
	else if(cqid > 0)
	{
		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/css/images/16/"+captionImage+".png");
}

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

function add_domains(user_entry_data, catid)
{
	$.ajax({
		type: "POST",
		cache: false,
		url: base_grid_ajax_url + "?" + DGA_DOMAIN_GRID_EDIT + "&oper=add",
		data: user_entry_data + "&cid=" + catid,
		success: function(html)
		{
			var x = jQuery.parseJSON(html);
			if(x.validate == 1)
				sessionRestart("timeout");
			else if(x.validate == -1)
				sessionRestart("badsession");
			if(x.added > 0)
			{
				$("#DomainTable").trigger("reloadGrid"); 
				show_queue_count(1);
			}
			else
			{
				if(x.category > 1)
					$("#DomainTable").trigger("reloadGrid");
				setTimeout(function() {custom_alert("<p>No new domains were added! Check if the domains are already in the database.</p>", "");}, 150);
			}
		},
		error: function(XMLHttpRequest, textStatus, errorThrown) 
		{ 
			// Show a better alert.
			if(XMLHttpRequest.status == 403)
				custom_alert("<p>&nbsp;</p><p>Access Denied! No permission to add domains.</p><p>&nbsp;</p>", "Problem");
			else
				custom_alert("Error: " + errorThrown, "Problem"); 
		} 
	});
}

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

function empty_cat_and_add_domains(user_entry_data, catid)
{
	$.ajax({
		type: "POST",
		cache: false,
		url: base_grid_ajax_url,
		data: "ec=" + catid,
		success: function(html)
		{
			var x = jQuery.parseJSON(html);
			if(x.validate == 1)
				sessionRestart("timeout");
			else if(x.validate == -1)
				sessionRestart("badsession");
			else if(x.status == "done")
				add_domains(user_entry_data, catid); 
		},
		error: function(XMLHttpRequest, textStatus, errorThrown) 
		{ 
			if(XMLHttpRequest.status == 403)
				custom_alert("<p>&nbsp;</p><p>Access Denied! No permission to add domains.</p><p>&nbsp;</p>", "Problem");
			else
				custom_alert("Error: " + errorThrown, "Problem"); 
		} 
	});
}

function addRegistrarAliasButton()
{
	$("#DomainTable").navSeparatorAdd("#DomainTablePager",{})
	.navButtonAdd('#DomainTablePager',
	{
		caption:"", 
		buttonicon:"ui-icon-tag", 
		onClickButton: function()
		{ 
			$('#btn_mpanel-regalias').click();
		}, 
		position:"last",
		title:'Edit Registrar Alias'
	});
}

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

function downloadRows(dlType)
{
	var rowText = "";
	var tablecolumns = [];
	var columns = jQuery("#DomainTable").getGridParam("colModel");
	var colnum = columns.length;
	
	if(dlType == "selecteddnsrows" || dlType == "alldnsrows")
	{
		var ids = null;
		if(dlType == "alldnsrows")
			ids  = jQuery("#DomainTable").getDataIDs(); 
		else
			ids = jQuery("#DomainTable").getGridParam("selarrrow");
		if(ids != null && ids != 0)
		{
			var url = base_grid_ajax_url;
			$("#csvdnload").append('<form id="exportform" action="' + url + '" method="post"><input type="hidden" id="dnsdata" name="dnsdata"></form>');
			$("#dnsdata").val(ids);
			$("#exportform").submit().remove();
		}
		return true;
	}
	
	if(dlType == "selectedsslrows" || dlType == "allsslrows")
	{
		var ids = null;
		if(dlType == "allsslrows")
			ids  = jQuery("#DomainTable").getDataIDs(); 
		else
			ids = jQuery("#DomainTable").getGridParam("selarrrow");
		if(ids != null && ids != 0)
		{
			var url = base_grid_ajax_url;
			$("#csvdnload").append('<form id="exportform" action="' + url + '" method="post"><input type="hidden" id="ssldata" name="ssldata"></form>');
			$("#ssldata").val(ids);
			$("#exportform").submit().remove();
		}
		return true;
	}
	
	if(dlType != "alldomainnames" && dlType != "selecteddomainnames")
	{
		for(i = 0; i < colnum; i++)
		{
			if(columns[i].name != "rn" && columns[i].name != "cb" && columns[i].name != "r_h_disp" && columns[i].name != "subgrid")
			{
				tablecolumns.push(columns[i].name);
				var label = columns[i].label;
				rowText += csvWrapQuotes(label);
				if(i !== (colnum-1))
					rowText += ",";
				else
					rowText += "\n";
			}
		}
	}
	
	var clen = tablecolumns.length;
	var rowKey;
	if(dlType == "selectedrows" || dlType == "selecteddomainnames")
		rowKey = jQuery("#DomainTable").getGridParam("selarrrow");
	else if(dlType == "allrows" || dlType == "alldomainnames")
		rowKey  = jQuery("#DomainTable").getDataIDs(); 
	var rl = rowKey.length;
	for(i = 0; i < rl; i++)
	{
		var rowData = jQuery("#DomainTable").jqGrid ('getRowData', rowKey[i]);
		if(dlType != "alldomainnames" && dlType != "selecteddomainnames")
		{
			for(j = 0; j < clen; j++)
			{
				if (typeof tablecolumns[j] != 'undefined') 
				{
					var entry = rowData[tablecolumns[j]];
					rowText += csvWrapQuotes(entry);
				}
				else
					rowText += "-";
				if(j != (clen-1))
					rowText += ",";
				else
					rowText += "\n";
			}
		}
		else if(typeof rowData['domain'] != "undefined")
			rowText += rowData['domain'] + "\n";
	}
	
	var posturl = base_grid_ajax_url;
	if(dlType == "alldomainnames" || dlType == "selecteddomainnames")
		posturl += "?txt";
	$("#csvdnload").append('<form id="exportform" action="' + posturl + '" method="post"><input type="hidden" id="' + DGA_EXPORT_DATA + '" name="' + DGA_EXPORT_DATA + '"></form>');
    $("#" + DGA_EXPORT_DATA).val(rowText);
    $("#exportform").submit().remove();
    return true; 
}

jQuery.extend($.fn.fmatter , 
{
    booleanFormatter : function(cellvalue, options, rowdata) 
	{
		if(cellvalue == 1)
			return '<span title="' + cellvalue + '" class="glyphicon glyphicon-ok" style="display:inline-block;">';
		else if(cellvalue == 0)
			return '<span title="' + cellvalue + '" class="glyphicon glyphicon-remove" style="display:inline-block;">';
		else if(cellvalue == null)
			return "";
	},
	domAvailFormatter : function(cellvalue, options, rowdata) 
	{
		if(cellvalue == "Available")
			return '<span title="' + cellvalue + '" class="glyphicon glyphicon-ok" style="display:inline-block;">';
		else if(cellvalue == "Not Available")
			return '<span title="' + cellvalue + '" class="glyphicon glyphicon-remove" style="display:inline-block;">';
		else if(cellvalue == "Setup Error")
			return '<span title="' + cellvalue + '" class="glyphicon glyphicon-asterix" style="display:inline-block;">';
		else if(cellvalue == null)
			return "";
		else
			return cellvalue;
	},
	registrarFormatter : function(cellvalue, options, rowdata) 
	{
		if(cellvalue == null)
			return "";
		if (typeof registrar_aliases != 'undefined')
		{
			for (var i = 0; i < (registrar_aliases.length)/2; i++) 
			{
				if(registrar_aliases[i*2].toUpperCase() == cellvalue.toUpperCase())
					return registrar_aliases[i*2+1];
			}
		}
		return cellvalue;
	},
	highlightFormatter : function(cellvalue, options, rowdata) 
	{
		if(cellvalue == 15 && cellvalue != null)
			return '<img title="Nearing expiry" src="lib/css/images/16/registry-expiry-alert.png" alt="' + cellvalue + '">';
		else if(cellvalue == 17 && cellvalue != null)
			return '<img title="Past expiry" src="lib/css/images/16/registrar-expiry-alert.png" alt="' + cellvalue + '">';
		else if(cellvalue == 18 && cellvalue != null)
			return '<img title="Domain status alert" src="lib/css/images/16/domain-status-alert.png" alt="' + cellvalue + '">';
		else if(cellvalue == 16 && cellvalue != null)
			return '<img title="Nearing or past expiry" src="lib/css/images/16/registrar-expiry-alert.png" alt="' + cellvalue + '">';
		else if(cellvalue == 14 && cellvalue != null)
			return '<img title="Unknown expiry date" src="lib/css/images/16/unknown-expiry-alert.png" alt="' + cellvalue + '">';
			//return '<span title="No whois lookup yet" class="glyphicon glyphicon-question-sign" style="display:inline-block;">';
		else if(cellvalue == 13 && cellvalue != null)
			return '<span title="No recent whois" class="glyphicon glyphicon-search" style="display:inline-block;">';
		else if(cellvalue == 12 && cellvalue != null)
			return '<span title="Available domain" class="glyphicon glyphicon-ok" style="display:inline-block;">';
		else if(cellvalue == 11 && cellvalue != null)
			return '<span title="Requires whois search token setup" class="glyphicon glyphicon-asterix" style="display:inline-block;">';
		else if(cellvalue == 10 && cellvalue != null)
			return '<img title="Manually edited" src="lib/css/images/16/manually-edited.png" alt="' + cellvalue + '">';
		else if(cellvalue == null)
			return '<span title="Unknown" class="glyphicon glyphicon-question-sign" style="display:inline-block;">';
		else
			return '<span title="Unknown" class="glyphicon" style="display:inline-block;">';
	},
});

jQuery.extend($.fn.fmatter.domAvailFormatter , 
{
    unformat : function(cellvalue, options, cell) 
	{
		if(cellvalue == null)
			return "";
		return $('span', cell).attr('title');
	}
});

jQuery.extend($.fn.fmatter.booleanFormatter , 
{
    unformat : function(cellvalue, options, cell) 
	{
		if(cellvalue == null)
			return "";
		return $('span', cell).attr('title');
	}
});

jQuery.extend($.fn.fmatter.highlightFormatter , 
{
    unformat : function(cellvalue, options, cell) 
	{
		if(cellvalue == null)
			return "";
		return $('span', cell).attr('title');
	}
});

jQuery.extend($.fn.fmatter.registrarFormatter , 
{
    unformat : function(cellvalue, options, cell) 
	{
		if(cellvalue == null)
			return "";
		if (typeof registrar_aliases != 'undefined')
		{
			for (var i = 0; i < (registrar_aliases.length)/2; i++) 
			{
				if(registrar_aliases[i*2+1] == cellvalue)
					return registrar_aliases[i*2];
			}
		}
		return cellvalue;
	}
});

function updateLookupQueueTab()
{
	show_queue_count(0);
	var switcher = setInterval(function() {show_queue_count(0);}, 60000);
	$("#queue_refresh").click(function(e){show_queue_count(1);e.preventDefault();});
}

function wipeQueue(tname)
{
	var turl = "makeq.php?kill&w=" + tname;
	//alert(turl);
	var request = $.ajax({type: "POST",	url: turl});
	request.done(function(msg) 
	{  
		show_queue_count(0);
	});
	request.fail(function(jqXHR, textStatus) {});
}


function addToQueue(tname)
{
	var rdays = $("#qb-refresh-interval").val();
	if(rdays < 0 || rdays == null || rdays == "")
		rdays = 180;
	var dlimit = $("#qb-domain-limit").val();
	if(dlimit < 0)
		dlimit = "8";
	else if(dlimit == null || dlimit=="")
		dlimit = 0;
	var turl = "makeq.php?d=" + rdays + "&w=" + tname;
	if(dlimit != 0)
		turl += "&l=" + dlimit;
	//alert(turl);
	var request = $.ajax({type: "POST",	url: turl});
	request.done(function(msg) 
	{  
		show_queue_count(0);
	});
	request.fail(function(jqXHR, textStatus) {});
}


function hasColumnInModel(columnname)
{
	var columns = jQuery("#DomainTable").getGridParam("colModel");
	var colnum = columns.length;
	for(i = 0; i < colnum; i++)
	{
		if(columns[i].name == columnname)
			return true;
	}
	return false;
}

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

function showAddDomains()
{
	setCategoryNameInAddDlg();
	$('#dialog-add-domains').show();
	$('#dialog-add-domains').dialog('open');
}

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

function showUploadDomains()
{
	setCategoryNameInAddDlg();
	$('#dialog-csv-upload').show();
	$('#dialog-csv-upload').dialog('open');
}

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

function showSelectedDomains(dcount)
{
	var dlist = getSelectedDomainList(dcount) + ".";
	dlist = dlist.replace("and", "<code>and");
	dlist = dlist.replace("more domains", "more domains</code>");
	$('.selecteddomains').html(dlist);
}

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