/*
 * Copyright 2010-2011, Softnik Technologies
 * http://www.softnik.com/
 */


///////////////////////////////////////////////////////////////////////////////
var domain_table_grid_id    = "DomainTableGrid";
var domain_table_pager_id   = "DomainTablePager";
var lastsel_domainrow_id    = 0;
var lastsel_categoryrow_id  = 0;
var last_sel_autoquery_id   = 0;

var domain_sort_column_name = "sid";
var domain_sort_order_name  = "desc";

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

var LOOKUP_DOMAIN_WHOIS		= 1;
var LOOKUP_DOMAIN_IP		= 2;
var LOOKUP_HTTP_HOMEPAGE	= 4;
var LOOKUP_ALEXA_DATA		= 16;
var LOOKUP_GOOGLE_PR		= 32;
var LOOKUP_MX_RECORDS       = 128;
var LOOKUP_PING_RESPONSE    = 256;
var LOOKUP_SSL_CERTS		= 2048;
var LOOKUP_IP_WHOIS			= 4096;
var LOOKUP_SUB_DOMAINS      = 16384;
var LOOKUP_GOOGLE_INDEX		= 32768;
var LOOKUP_BING_INDEX		= 65536;
var LOOKUP_YAHOO_INDEX		= 131072;

var LOOKUP_MOZ_DATA			= 262144;
var LOOKUP_ESTIBOT_DATA		= 524288;
var LOOKUP_SIMILARWEB_DATA	= 1048576;

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

var current_columns_array  = date_columns_array;
var domain_row_num = 100;

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

var domain_table_multi_select = true;
var domain_table_multi_box_only = true;
var show_domain_details    = true;

//  Forces reload of the domain table. Mostly used when a domain category changes.
var reload_domain_grid_data_url = true;
var reload_subdomain_grid_data_url = true;

// Restore category selection from last session.
var ccategory = parseInt($.cookie("current_category"));
if ( !isNaN(ccategory) )
	lastsel_categoryrow_id = ccategory;
	
// scroll offset for domain grid

var domGridScrollOffset = 18;

if(!$.browser.msie && !$.browser.mozilla)
	domGridScrollOffset += 56;
	
///////////////////////////////////////////////////////////////////////////////
	
var sort_column = $.cookie('current_sort_column'); 
var sort_order  = $.cookie('current_sort_order'); 
if(sort_column != "" && sort_column != null)
	domain_sort_column_name = sort_column;
if(sort_order != "" && sort_order != null)
	domain_sort_order_name = sort_order;
	
var domain_rows = $.cookie('domain_row_num'); 
if(domain_rows != 0 && domain_rows <= 2000 && domain_rows != null)
	domain_row_num = domain_rows;
	
	///////////////////////////////////////////////////////////////////////////////
	
var subdomain_columns_array_01 = [
			{label:'Sub-domain', name:'subdomain', width:50,sortable:true,editable:true,editoptions:{readonly:true}},
			{label:'Type', name:'record_type',width:50,sortable:true,editable:true},
			{label:'SSL Valid From', name:'ssl_valid_from', width:50,sortable:true,editable:false},
			{label:'SSL Valid Till', name:'ssl_valid_to',width:50,sortable:true,editable:false},
			{label:'SSL Issued To', name:'ssl_issued_to',width:50,sortable:true,editable:false},
			{label:'SSL Issued By', name:'ssl_issued_by',width:50,sortable:true,editable:false}, 
			{label:'IP', name:'ip',width:50,sortable:true,editable:false},
			{label:'Notes', name:'notes_a',width:50,sortable:true,editable:true,editoptions:{size:43}}
];

var subdomain_columns_array_02 = [
			{label:'Record', name:'subdomain', width:50,sortable:true,editable:true,editoptions:{readonly:true}},
			{label:'Type', name:'record_type',width:50,sortable:true,editable:true},
			{label:'Target', name:'record_value',width:70,sortable:true,editable:true,editoptions:{size:43}},
			{label:'TTL', name:'ttl',width:30,sortable:true,editable:true},
			{label:'IP', name:'ip',width:50,sortable:true,editable:false},
			{label:'Notes A', name:'notes_a',width:50,sortable:true,editable:true,editoptions:{size:43}},
			{label:'Notes B', name:'notes_b',width:50,sortable:true,editable:true,editoptions:{size:43}}
];

current_subdomain_columns = subdomain_columns_array_02;
if($.cookie('current_subdomain_column_group') == "1")
	current_subdomain_columns = subdomain_columns_array_01;
	
///////////////////////////////////////////////////////////////////////////////

$(function()
{
	LoadSubDomainGrid();
	LoadDomainGrid();
	LoadCategoryGrid();
	LoadQueryGrid();
	
	LoadVersionInfo(true);
	
	$("#DetailsPane").bind('resize', function() { fixDomainDataGridSizes();	}).trigger('resize');
	$("#DomainTablePane").bind('resize', function() { fixDomainDataGridSizes();	}).trigger('resize');
	$("#CategoryPane").bind('resize', function() { FixCategoryGridSizes(); }).trigger('resize'); 	
	
	$('#DomainDetailTabView').tabs();
	$('#CategoryTabView').tabs();
	
	$("#SubDomainTable").trigger("reloadGrid"); 
	
	// Adding these to fix the search dialog 
	// when it is dragged around. (it was getting hidden by category and details panes)
	if(domain_grid_search_enable)
	{
		$("#DomainTablePane").css('z-index', '50');
		//$("#RightPane").css('z-index', '50');
		//$("#CategoryPane").css('z-index', '50');
	}
	
	$("#bt-field-set").change(function() 
	{
		onBulkFieldChange();
	});
});

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

function FixCategoryGridSizes()
{
	jQuery("#DomainCategoryTable").setGridWidth($("#CategoryPane").width()-24-4, true); 
	jQuery("#DomainCategoryTable").setGridHeight($("#CategoryPane").height()-94-36); 
	
	jQuery("#DomainQueryTable").setGridWidth($("#CategoryPane").width()-24-4, true); 
	jQuery("#DomainQueryTable").setGridHeight($("#CategoryPane").height()-94-36); 
}

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

function fixDomainDataGridSizes()
{
	var autoShrink = true;
	if($("#DomainTablePane").width() < 500)
		autoShrink = false;
	jQuery("#"+domain_table_grid_id).setGridWidth($("#DomainTablePane").width()-24, autoShrink); 
	jQuery("#"+domain_table_grid_id).setGridHeight($("#DomainTablePane").height()-120); 
	
	jQuery("#DomainDetailTabView").width($("#DetailsPane").width()-27, true); 
	jQuery("#DomainDetailTabView").height($("#DetailsPane").height()-26);
	
	jQuery("#SubDomainTable").setGridWidth($("#DomainDetailTabView").width()-36, autoShrink); 
	jQuery("#SubDomainTable").setGridHeight($("#DomainDetailTabView").height()-120-32); 
}

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

function fixSubDomainDataGridSizes()
{
	var autoShrink = true;
	if($("#DomainTablePane").width() < 500)
		autoShrink = false;
	jQuery("#SubDomainTable").setGridWidth($("#DomainDetailTabView").width()-36, autoShrink); 
	jQuery("#SubDomainTable").setGridHeight($("#DomainDetailTabView").height()-120-32); 
}

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

function showWhoisData(status, ids)
{
	if(status == MULTI_DOMAIN_SELECTION)
	{
		jQuery("#registrywhois").html("Multiple domains selected");
		jQuery("#registrarwhois").html("Multiple domains selected");
		jQuery("#ipdata").html("Multiple domains selected");
		jQuery("#oltooldomain").html("<h2>Multiple domains selected</h2>");
		$( ".toolsButton" ).button( "option", "disabled", true );
	}
	else if(status == NO_DOMAIN_SELECTION)
	{
		jQuery("#registrywhois").html("No domain is selected");
		jQuery("#registrarwhois").html("No domain is selected");
		jQuery("#ipdata").html("No domain is selected");
		jQuery("#oltooldomain").html("<h2>No domain is selected</h2>");
		$( ".toolsButton" ).button( "option", "disabled", true );
	}
	else
	{
		var domainname = jQuery("#"+domain_table_grid_id).getCell(ids, "domain"); 
		var heading = "<h2>" + domainname + "</h2>";
		jQuery("#oltooldomain").html(heading);
		$( ".toolsButton" ).button( "option", "disabled", false );
		
		$.ajax({
			type: "GET",
			cache: false,
			dataType: 'json',
			url: grid_url_base + "?mode=wd&id=" + ids,
			success: function(html)
			{
				$("#registrywhois").html(heading + html.rows[0].registry_whois);
				$("#registrarwhois").html(heading + html.rows[0].registrar_whois);
				$("#ipdata").html(heading + html.rows[0].ip_whois);
			}
		});
		
		var dsptype = "SSL Records";
		if(current_subdomain_columns == subdomain_columns_array_02)
			dsptype = "DNS Records";
		jQuery("#SubDomainTable").setCaption(dsptype + " for " + domainname);
	}
	$("#SubDomainTable").trigger("reloadGrid"); 
}

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

function ToggleDomainGrid()
{
	if(current_columns_array === date_columns_array)
		ShowHttpGrid();
	else
		ShowDateGrid();
}

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

function ShowDateGrid()
{
	if(current_columns_array !== date_columns_array)
	{
		current_columns_array = date_columns_array;
		$("#" + domain_table_grid_id).GridUnload(); 
		reload_domain_grid_data_url = true;
		LoadDomainGrid();
		fixDomainDataGridSizes();
	}
}

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

function ShowCustomDataGrid01()
{
	if(current_columns_array !== custom_columns01_array)
	{
		current_columns_array = custom_columns01_array;
		$("#" + domain_table_grid_id).GridUnload(); 
		reload_domain_grid_data_url = true;
		LoadDomainGrid();
		fixDomainDataGridSizes();
	}
}

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

function ShowCustomDataGrid02()
{
	if(current_columns_array !== custom_columns02_array)
	{
		current_columns_array = custom_columns02_array;
		$("#" + domain_table_grid_id).GridUnload(); 
		reload_domain_grid_data_url = true;
		LoadDomainGrid();
		fixDomainDataGridSizes();
	}
}

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

function ShowHttpGrid()
{
	if(current_columns_array !== http_columns_array)
	{
		current_columns_array = http_columns_array;
		$("#" + domain_table_grid_id).GridUnload(); 
		reload_domain_grid_data_url = true;
		LoadDomainGrid();
		fixDomainDataGridSizes();
	}
}

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

function ShowRegistrarGrid()
{
	if(current_columns_array !== registrar_columns_array)
	{
		current_columns_array = registrar_columns_array;
		$("#" + domain_table_grid_id).GridUnload(); 
		reload_domain_grid_data_url = true;
		LoadDomainGrid();
		fixDomainDataGridSizes();
	}
}

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

function ShowSitePopGrid() {ShowGrid(sitepop_columns_array);}
function ShowNetworkGrid() {ShowGrid(network_columns_array);}
function ShowNotesGrid()   {ShowGrid(notes_columns_array);}
function ShowIPDataGrid()  {ShowGrid(ipdata_columns_array);}

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

function ShowGrid(grid_array)
{
	if(current_columns_array !== grid_array)
	{
		current_columns_array = grid_array;
		$("#" + domain_table_grid_id).GridUnload(); 
		reload_domain_grid_data_url = true;
		LoadDomainGrid();
		fixDomainDataGridSizes();
	}
}

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

function LoadDomainGrid()
{
	// The main domain table
	jQuery("#" + domain_table_grid_id).jqGrid({
		editurl: grid_url_base,
		altRows:true,
		altclass: "gridAltRowClass",
		height: $("#DomainTablePane").height()-120,
		width: $("#DomainTablePane").width()-24,
		loadtext: "Working...",
		datatype: "json",
		colModel: current_columns_array,
		rowNum: domain_row_num,
		rownumWidth: 50,
		rowList:[10,50,100,250,500,1000,2000],
		//rowTotal: 100,
		pager: "#"+domain_table_pager_id,
		sortname: domain_sort_column_name,
		rownumbers: true,
		viewrecords: true,
		recordtext: "Domains {0} - {1} of {2}",
		sortorder: domain_sort_order_name,
		mtype: 'GET',
		multiselect: domain_table_multi_select,
		multiboxonly: domain_table_multi_box_only,
		gridView: true,
		scrollOffset: domGridScrollOffset,
		shrinkToFit: false,
		caption:"Domain Name Portfolio",
		
		jsonReader : {repeatitems: false},
		
		beforeRequest: function() 
		{
			// If searching and in auto query, reset it and reload the grid again.
			if(jQuery("#"+domain_table_grid_id).getGridParam("search") && last_sel_autoquery_id > 0)
			{
				reload_domain_grid_data_url = true;
				last_sel_autoquery_id = 0;
			}
			
			// Show the caption
			var dtCaption = "Domain Name Portfolio";
			if(last_sel_autoquery_id > 0)
			{
				dtCaption += " - Custom Query";
				var rowData = $('#DomainQueryTable').jqGrid('getRowData', last_sel_autoquery_id);
				if (typeof rowData['Name'] != 'undefined') 
					dtCaption += " [" + rowData['Name'] + "]";
			}
			else if(lastsel_categoryrow_id > 1)
			{
				var rowData = $('#DomainCategoryTable').jqGrid('getRowData', lastsel_categoryrow_id);
				var categoryName = rowData['CategoryName'];
				if (typeof categoryName != 'undefined') 
					dtCaption += " [" + categoryName + "]";
				else 
					dtCaption += " - Category";
				if(jQuery("#"+domain_table_grid_id).getGridParam("search"))
					dtCaption += " - Search Results";
			}
			else if(jQuery("#"+domain_table_grid_id).getGridParam("search"))
				dtCaption += " - Search Results";
			jQuery("#"+domain_table_grid_id).setCaption(dtCaption);
			//
			
			if(reload_domain_grid_data_url == true)
			{
				// Hide the sort icons if we are doing an auto-query. Show otherwise.
				if(last_sel_autoquery_id > 0)
					$("#gbox_"+domain_table_grid_id + " .s-ico span").css("display", "none");
				else
					$("#gbox_"+domain_table_grid_id + " .s-ico span").css("display", "inline");	
					
				var columns = jQuery("#"+domain_table_grid_id).getGridParam("colModel");
				var colnum = columns.length;
				var durl = grid_url_base + "?mode=dd&CategoryID=" + lastsel_categoryrow_id + "&columns=sid,";
				for(i = 0; i < colnum; i++)
				{
					if(columns[i].name != "rn" && columns[i].name != "cb")
					{
						durl += encodeURIComponent(columns[i].name);
						durl += ",";
						
						// If in auto query, disable sorting on column, enable otherwise
						if(last_sel_autoquery_id > 0)
							jQuery("#"+domain_table_grid_id).setColProp(columns[i].name, {sortable: false});
						else
							jQuery("#"+domain_table_grid_id).setColProp(columns[i].name, {sortable: true});
					}
				}
				if(last_sel_autoquery_id > 0)
					durl += "&aqid=" + last_sel_autoquery_id;
				jQuery("#"+domain_table_grid_id).setGridParam({url:durl});
				reload_domain_grid_data_url = false;
			}
		},
		
		onSelectAll: function(ids, status)
		{
			if(show_domain_details == true)
			{
				reload_subdomain_grid_data_url = true;
				if(status == false)
				{
					showWhoisData(NO_DOMAIN_SELECTION);
				}
				else
				{
					var allIDs  = jQuery("#"+domain_table_grid_id).getDataIDs(); 
					if(allIDs.length == 1)
					{
						showWhoisData(SINGLE_DOMAIN_SELECTION, allIDs[0]); 
					}
					else 
					{
						showWhoisData(MULTI_DOMAIN_SELECTION);
					}
				}
			}
		},
		
		onSelectRow: function(ids) 
		{
			if(show_domain_details == true)
			{
				reload_subdomain_grid_data_url = true;
				if(ids == null || ids == 0)
					showWhoisData(NO_DOMAIN_SELECTION);
				else  
				{
					var selids = jQuery("#"+domain_table_grid_id).getGridParam("selarrrow"); 
					if(selids.length > 1)
						showWhoisData(MULTI_DOMAIN_SELECTION);
					else
						showWhoisData(SINGLE_DOMAIN_SELECTION, ids);
				}
			}
			lastsel_domainrow_id = ids;
			$.cookie('current_domain', String(ids)); 
			ShowDomainCategories();
		},
		
		gridComplete: function()
		{
			$("#registrywhois").html("");
			$("#registrarwhois").html("");
		
			var sel_rowid = 0;
			var allIDs = jQuery("#"+domain_table_grid_id).getDataIDs(); 
			if(allIDs.length > 0)
				sel_rowid = allIDs[0];
				
			var cdomain = parseInt($.cookie("current_domain"));
			if ( !isNaN(cdomain) )
				sel_rowid = cdomain;
			$("#"+domain_table_grid_id).setSelection(sel_rowid, true);
			$("#"+domain_table_grid_id).setGridParam({scrollrows:false}); 
			
			// Cookie the sort column and order
			domain_sort_column_name = $("#"+domain_table_grid_id).jqGrid('getGridParam','sortname');
			domain_sort_order_name  = $("#"+domain_table_grid_id).jqGrid('getGridParam','sortorder');
			if(last_sel_autoquery_id <= 0)
			{
				$.cookie('current_sort_column', domain_sort_column_name, { expires: 30 }); 
				$.cookie('current_sort_order', domain_sort_order_name, { expires: 30 }); 
			}
			
			domain_row_num = $("#"+domain_table_grid_id).jqGrid('getGridParam','rowNum');
			$.cookie('domain_row_num', domain_row_num, { expires: 30 }); 
		},
		
		loadComplete: function()
		{
		},
		
		loadError: function (jqXHR, textStatus, errorThrown) 
		{
			//alert('HTTP status code: ' + jqXHR.status + '\n' + 'textStatus: ' + textStatus + '\n' + 'errorThrown: ' + errorThrown);
			if(jqXHR.status == 408 || jqXHR.status == 400)
			{
				var rcode = "";
				if(jqXHR.status == 408)
					rcode = 'timeout';
				else if(jqXHR.status == 400)
					rcode = 'invsession';
				window.location = "lib/php/login.php?r=" + rcode;
			}
		},
		
		ondblClickRow: function(rowid) 
		{
			jQuery(this).jqGrid('editGridRow', rowid);
		}
	});
	
	// We use our own "add records" because we want to allow only domain names to be added.
	
	jQuery("#"+domain_table_grid_id)
	.navGrid('#'+domain_table_pager_id,{add:false,edit:true,del:true,search:domain_grid_search_enable},
	{ 
		width: 400,
		closeOnEscape:true,
		afterShowForm: function(form) 
		{
			var dlgDiv = $("#editmod" + domain_table_grid_id);
			var parentDiv = dlgDiv.parent(); 
			var dlgWidth = dlgDiv.width();
			var parentWidth = parentDiv.width();
			var dlgHeight = dlgDiv.height();
			var parentHeight = parentDiv.height();
			// TODO: change parentWidth and parentHeight in case of the grid
			//       is larger as the browser window
			dlgDiv[0].style.top = Math.round((parentHeight-dlgHeight)/2) + "px";
			dlgDiv[0].style.left = Math.round((parentWidth-dlgWidth)/2) + "px";
		}
	},
	{closeOnEscape:true},
	{
		// Delete Options
		width: 350,
		closeOnEscape:true,
		beforeShowForm: function ($form) 
		{
			var dlist = domainsToDelete();
			$("td.delmsg", $form[0]).html("<div style=\"white-space:normal;\"><p><b>Do you really want to delete</b> </p>" +
				 dlist + "</div>");
		}
	},
	{multipleSearch:true,overlay:false,closeOnEscape:true})
	.navSeparatorAdd("#"+domain_table_pager_id,{})
	.navButtonAdd('#'+domain_table_pager_id,
	{
		caption:"", 
		buttonicon:"ui-icon-check", 
		onClickButton: function()
		{ 
			var rowKey = jQuery("#"+domain_table_grid_id).getGridParam("selarrrow"); 
			if(rowKey.length > 0)
				$('#dialog-lookup-what').dialog('open');
			return false;
		}, 
		position:"last",
		title:'Lookup Domain'
	})
	.navSeparatorAdd("#"+domain_table_pager_id,{})
	.navButtonAdd('#'+domain_table_pager_id,
	{
		caption:"", 
		buttonicon:"ui-icon-transferthick-e-w", 
		onClickButton: function()
		{ 
			var rowKey = jQuery("#"+domain_table_grid_id).getGridParam("selarrrow"); 
			if(rowKey.length > 0)
				$('#dialog-parse-whois').dialog('open');
			return false;
		}, 
		position:"last",
		title:'Parse Domain Whois'
	})
	.navButtonAdd('#'+domain_table_pager_id,
	{
		// Add domain names
		caption:"", 
		buttonicon:"ui-icon-plus", 
		onClickButton: function()
		{ 
			$('#dialog-add-domains').dialog('open');
			return false;
		}, 
		position:"first"
	}
	);
	
	jQuery("#"+domain_table_grid_id).jqGrid(
		'filterToolbar',{
			stringResult: true,searchOnEnter : false,
			beforeSearch: function() 
			{
				var url = jQuery("#"+domain_table_grid_id).getGridParam('url');
				var newurl = url;
				var pos = url.search("&aqid=");
				if(pos > 0)
					newurl = url.substring(0,pos);
				jQuery("#"+domain_table_grid_id).setGridParam({url:newurl});
				return false;
			}
		}
	);
	
	if(is_an_admin_user)
		addRegistrarAliasButton();
	if(user_access_rights == 1 || user_access_rights == 3 || is_an_admin_user)
		addCSVTableDownloadButton();
		
	//jQuery("#"+domain_table_grid_id).jqGrid('setLabel', 'r_h_disp', '<img src="lib/css/img/alert-head.png" width="12" height="14">');
	jQuery("#"+domain_table_grid_id).jqGrid('setLabel', 'availability', '<img src="lib/css/img/avail-head.png" width="12" height="14">');
	jQuery("#"+domain_table_grid_id).jqGrid('setLabel', 'page_token_found', '<img src="lib/css/img/htmltoken-head.png" width="12" height="14">');
}

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

function DoLookups(luw, luint)
{
	if(luint < 0)
		luint = 1440;
	//var luw = LOOKUP_DOMAIN_WHOIS | LOOKUP_DOMAIN_IP | LOOKUP_HTTP_HOMEPAGE	| LOOKUP_ALEXA_DATA | LOOKUP_GOOGLE_PR | LOOKUP_MX_RECORDS | LOOKUP_PING_RESPONSE | LOOKUP_IP_WHOIS;
	var rowKey = jQuery("#"+domain_table_grid_id).getGridParam("selarrrow"); 
	var lurl = grid_url_base + "?mode=qd&what=" + luw + "&id=" + rowKey + "&ri=" + luint;
	//if(rowKey.length <= 2)
	//	lurl += "&ri=0";
	$.ajax({
		type: "GET",
		cache: false,
		dataType: 'json',
		url: lurl,
		success: function(html)
		{
			
		}
	});
}

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

function ConfigRegistrarWhois()
{
	window.location = 'wconfig.php';
}

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

function DoBulkAction()
{
	if(is_an_admin_user)
	{
		$('#bt-field-set').removeAttr('disabled'); 
		$('#bt-cat-add').removeAttr('disabled'); 
		$('#bt-cat-delete').removeAttr('disabled'); 
	}
	else
	{
		$('#bt-field-set').attr('disabled', 'disabled'); 
		$('#bt-cat-add').attr('disabled', 'disabled'); 
		$('#bt-cat-delete').attr('disabled', 'disabled'); 
	}

	var catAddList = '<option value="' + '-' + '">' + '-' + '</option>';
	var catRemoveList = '<option value="' + '-' + '">' + '-' + '</option>';
	var ids = jQuery("#DomainCategoryTable").jqGrid('getDataIDs');
	for (var i = 0; i < ids.length; i++) 
	{
		var rowId = ids[i];
		if(rowId != 1)
		{
			var rowData = jQuery('#DomainCategoryTable').jqGrid ('getRowData', rowId);
			catAddList += '<option value="' + rowData.CategoryName + '">' + rowData.CategoryName + '</option>';
			catRemoveList += '<option value="' + rowData.CategoryName + '">' + rowData.CategoryName + '</option>';
		}
	}
	$('#bt-cat-add').html(catAddList);
	$('#bt-cat-delete').html(catRemoveList);
	var fieldsEdit = get_editable_columns();
	$('#bt-field-set').html(fieldsEdit);
	onBulkFieldChange();

	var rowKey = jQuery("#"+domain_table_grid_id).getGridParam("selarrrow"); 
	if(rowKey != null && rowKey.length > 0) 
	{
		if(rowKey.length == 1)
			$('#bt-domain-info').html("<p>" + rowKey.length + " domain selected.</p>");
		else
			$('#bt-domain-info').html("<p>" + rowKey.length + " domains selected.</p>");
		$('#dialog-bulk-action').dialog('open');
	}
}

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

function AddDomains()
{
	$('#dialog-add-domains').dialog('open');
	return false;
}

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

function ImportDomainsFromCSV()
{
	$("#csverrors").css("height", "10px");
	$("#csverrors").html("&nbsp;");
	$('#csverrors').addClass('ui-state-default ui-corner-all');
	if ($.browser.msie  && parseInt($.browser.version, 10) < 10) 
		alert("CSV upload is not supported in IE9 and below.");
	else
		$('#dialog-csv-upload').dialog('open');
	return false;
}

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

function domainsToDelete()
{
	var rowKey = jQuery("#"+domain_table_grid_id).getGridParam("selarrrow"); 
	var dlist = "<p>";
	var rl = rowKey.length;
	if(rl > 25)
		rl = 25;
	for(i = 0; i < rl; i++)
	{
		var rowData = jQuery("#"+domain_table_grid_id).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>";
	}
	dlist += "?</p>";
	return dlist;
}

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

function DeleteDomains()
{
	$('#del_' + domain_table_grid_id).click();
	//var rowKey = jQuery("#"+domain_table_grid_id).getGridParam("selarrrow"); 
	//if(rowKey != null && rowKey.length > 0) 
    //   jQuery("#"+domain_table_grid_id).delGridRow(rowKey,{reloadAfterSubmit:true});  
}
	
///////////////////////////////////////////////////////////////////////////////

function LoadCategoryGrid()
{
	jQuery("#DomainCategoryTable").jqGrid({
		loadtext: "Working...",
		height: 400,
		width: 150,
		altRows:true,
		altclass: "catGridAltRowClass",
		url: grid_url_base + '?mode=cd',
		editurl: grid_url_base + '?mode=cd',
		datatype: "json",
		colNames:['Category Names'],
		colModel:[
			{name:'CategoryName', width:118,sortable:false,editable:true,editoptions:{size:35}, classes:"dccell category-name-cell"}
			//{name:'dummy',fixed:true, width:32,sortable:false,editable:false,classes:"dccell category-name-cell"}
		],
		rowNum:100,
		rowList:[100,200,500],
		rownumbers: true,
		viewrecords: true,
		recordtext: "{0} - {1} of {2}",
		caption:"Domain Categories",
		multiselect: false,
		pager: "#pagerCatView",
		scrollOffset:18,
		sortname: 'SortOrder',
		sortorder: 'desc',
		scroll:1,
		
		loadComplete: function()
		{
			jQuery("#CategoryPane").trigger('resize');
		},
		
		onSelectRow: function(ids) 
		{
			if(ids == null) 
				ids = 0;
			lastsel_categoryrow_id = ids;
			reload_domain_grid_data_url = true;
			last_sel_autoquery_id = 0;
			$("#"+domain_table_grid_id).trigger("reloadGrid");  
			$.cookie('current_category', String(ids));
			setCategoryNameInAddDlg();
		},
		
		gridComplete: function()
		{
			var sel_rowid = 0;
			var allIDs = jQuery("#DomainCategoryTable").getDataIDs(); 
			if(allIDs.length > 0)
				sel_rowid = allIDs[0];
			//alert(allIDs);
			//alert(lastsel_categoryrow_id);
			//alert(jQuery.inArray(lastsel_categoryrow_id, allIDs));
			if(lastsel_categoryrow_id != 0) 
				sel_rowid = lastsel_categoryrow_id;
			// if the category id cookie is wrong, force a refresh of the domain table.
			if(allIDs.length == 0 && lastsel_categoryrow_id != 0)
			{
				lastsel_categoryrow_id = 0;
				last_sel_autoquery_id = 0;
				reload_domain_grid_data_url = true;
				$("#"+domain_table_grid_id).trigger("reloadGrid");
				$.cookie('current_category', String(0));
			}
			$("#DomainCategoryTable").setSelection(sel_rowid, false);
			$("#DomainCategoryTable").setGridParam({scrollrows:false}); 
			setCategoryNameInAddDlg();
			ShowDomainCategories();
		}
	}).navGrid('#pagerCatView',{add:true,edit:true,del:true,search:false},
	{ 
		width: 350,
		closeOnEscape:true,
		afterShowForm: function(form) 
		{
			var dlgDiv = $("#editmod" + "DomainCategoryTable");
			var parentDiv = dlgDiv.parent(); 
			var dlgWidth = dlgDiv.width();
			var parentWidth = parentDiv.width();
			var dlgHeight = dlgDiv.height();
			var parentHeight = parentDiv.height();
			// TODO: change parentWidth and parentHeight in case of the grid
			// is larger as the browser window
			dlgDiv[0].style.top = Math.round((parentHeight-dlgHeight)/2) + "px";
			dlgDiv[0].style.left = Math.round((parentWidth-dlgWidth)/2) + "px";
		}
	},
	{
		width: 350,
		closeOnEscape:true,
		afterShowForm: function(form) 
		{
			var dlgDiv = $("#editmod" + "DomainCategoryTable");
			var parentDiv = dlgDiv.parent(); 
			var dlgWidth = dlgDiv.width();
			var parentWidth = parentDiv.width();
			var dlgHeight = dlgDiv.height();
			var parentHeight = parentDiv.height();
			// TODO: change parentWidth and parentHeight in case of the grid
			// is larger as the browser window
			dlgDiv[0].style.top = Math.round((parentHeight-dlgHeight)/2) + "px";
			dlgDiv[0].style.left = Math.round((parentWidth-dlgWidth)/2) + "px";
		}
	}
	);
	
	if(is_an_admin_user)
		addCategoryOrderButtons();
}
	
///////////////////////////////////////////////////////////////////////////////

function LoadQueryGrid()
{
	jQuery("#DomainQueryTable").jqGrid({
		loadtext: "Working...",
		height: 400,
		width: 50,
		altRows:true,
		altclass: "catGridAltRowClass",
		url: grid_url_base + '?mode=aqd',
		editurl: grid_url_base + '?mode=aqd',
		datatype: "json",
		colNames:['Auto Queries'],
		colModel:[
			{name:'Name', width:50,sortable:true,editable:true, classes:"aqcell auto-query-cell"},
		],
		rowNum:100,
		rowList:[100,200,500],
		rownumbers: true,
		viewrecords: true,
		recordtext: "{0} - {1} of {2}",
		caption:"Domain Queries",
		multiselect: false,
		pager: "#pagerQueryView",
		scrollOffset:18,
		sortname: 'Name',
		scroll:1,
		shrinkToFit: false,
		
		loadComplete: function()
		{
			jQuery("#CategoryPane").trigger('resize');
		},
		
		onSelectRow: function(ids) 
		{
			if(ids == null) 
				ids = 0;
			last_sel_autoquery_id = ids;
			clearSearchFilter();
			reload_domain_grid_data_url = true;
			$("#"+domain_table_grid_id).trigger("reloadGrid");
			$("#DomainQueryTable").resetSelection();
			$("#DomainCategoryTable").resetSelection();
		},
		
		gridComplete: function()
		{
			$("#DomainQueryTable").setGridParam({scrollrows:false}); 
		}
	}).navGrid('#pagerQueryView',{add:false,edit:false,del:false,search:false,alertcap:"Alert"});
}
	
///////////////////////////////////////////////////////////////////////////////

function LoadSubDomainGrid()
{
	jQuery("#SubDomainTable").jqGrid({
		loadtext: "Working...",
		altRows:true,
		altclass: "gridAltRowClass",
		height: 400,
		width: 50,
		gridView:true,
		url: grid_url_base + '?mode=sdd',
		editurl: grid_url_base + '?mode=sdd',
		datatype: "json",
		colModel: current_subdomain_columns,
		rowNum:100,
		rowList:[100,200,500],
		rownumbers: true,
		viewrecords: true,
		recordtext: "{0} - {1} of {2}",
		caption:"Sub-domains",
		multiselect: domain_table_multi_select,
		multiboxonly: domain_table_multi_box_only,
		pager: "#pagerSubDomainView",
		scrollOffset: domGridScrollOffset,
		sortname: 'subdomain',
		mtype: 'GET',
		scroll:1,
		shrinkToFit: false,
		jsonReader : {repeatitems: false},
		
		beforeRequest: function() 
		{
			var sid = 1000000000;
			var selids = jQuery("#"+domain_table_grid_id).getGridParam("selarrrow"); 
			if(selids != null && selids.length == 1)
				sid = selids[0];
			if(reload_subdomain_grid_data_url == true)
			{
				var columns = jQuery("#SubDomainTable").getGridParam("colModel");
				var colnum = columns.length;
				var edurl = grid_url_base + "?mode=sdd&sid=" + sid;
				var durl = grid_url_base + "?mode=sdd&sid=" + sid + "&columns=hid,";
				for(i = 0; i < colnum; i++)
				{
					if(columns[i].name != "rn" && columns[i].name != "cb")
					{
						durl += encodeURIComponent(columns[i].name);
						durl += ",";
					}
				}
				jQuery("#SubDomainTable").setGridParam({url:durl});
				jQuery("#SubDomainTable").setGridParam({editurl:edurl});
				reload_subdomain_grid_data_url = false;
			}
		},
		
		loadComplete: function()
		{
			if(current_subdomain_columns == subdomain_columns_array_01)
			{
				rowKey  = jQuery("#SubDomainTable").getDataIDs(); 
				var rl = rowKey.length;
				for(i = 0; i < rl; i++)
				{
					var rowData = jQuery("#SubDomainTable").jqGrid ('getRowData', rowKey[i]);
					if(rowData['ssl_issued_to'] == "")
					{
						$("#"+rowKey[i],"#SubDomainTable").css({display:"none"});
					}
				}
			}
			else if(current_subdomain_columns == subdomain_columns_array_02)
			{
				rowKey  = jQuery("#SubDomainTable").getDataIDs(); 
				var rl = rowKey.length;
				for(i = 0; i < rl; i++)
				{
					var rowData = jQuery("#SubDomainTable").jqGrid ('getRowData', rowKey[i]);
					if(rowData['record_type'] == "" && rowData['subdomain'] == "@")
					{
						$("#"+rowKey[i],"#SubDomainTable").css({display:"none"});
					}
				}
			}
		},
		
		onSelectRow: function(ids) 
		{
			if(ids == null) 
				ids = 0;
		},
		
		gridComplete: function()
		{
		}
	});
	
	jQuery("#SubDomainTable")
	.navGrid('#pagerSubDomainView',{add:false,edit:true,del:true,search:false},{width: 360,closeOnEscape:true},{},{},{})
	.navSeparatorAdd("#pagerSubDomainView",{})
	.navButtonAdd('#pagerSubDomainView',
	{
		caption:"", 
		buttonicon:"ui-icon-locked", 
		onClickButton: function()
		{ 
			var selids = jQuery("#"+domain_table_grid_id).getGridParam("selarrrow"); 
			var sid = -1;
			if(selids.length == 1)
			{
				var luw = LOOKUP_SSL_CERTS;
				sid = selids[0];
				var lurl = grid_url_base + "?mode=qd&what=" + luw + "&id=" + sid;
				if(sid.length <= 10)
					lurl += "&ri=0";
				$.ajax({
					type: "GET",
					cache: false,
					dataType: 'json',
					url: lurl,
					success: function(html)
					{
						
					}
				});
			}
		}, 
		position:"last",
		title:'Check SSL Certificates'
	})
	.navSeparatorAdd("#pagerSubDomainView",{})
	.navButtonAdd('#pagerSubDomainView',
	{
		caption:"", 
		buttonicon:"ui-icon-search", 
		onClickButton: function()
		{ 
			var selids = jQuery("#"+domain_table_grid_id).getGridParam("selarrrow"); 
			var sid = -1;
			if(selids.length == 1)
			{
				var luw = LOOKUP_SUB_DOMAINS;
				sid = selids[0];
				var lurl = grid_url_base + "?mode=qd&what=" + luw + "&id=" + sid;
				if(sid.length <= 10)
					lurl += "&ri=0";
				$.ajax({
					type: "GET",
					cache: false,
					dataType: 'json',
					url: lurl,
					success: function(html)
					{
						
					}
				});
			}
		}, 
		position:"last",
		title:'DNS Check'
	})
	.navButtonAdd('#pagerSubDomainView',
	{
		// Add domain names
		caption:"", 
		buttonicon:"ui-icon-plus", 
		onClickButton: function()
		{ 
			$('#dialog-add-subdomains').dialog('open');
			return false;
		}, 
		position:"first"
	})
	.navSeparatorAdd("#pagerSubDomainView",{})
	.navButtonAdd('#pagerSubDomainView',
	{
		caption:"", 
		buttonicon:"ui-icon-star", 
		onClickButton: function()
		{ 
			$("#SubDomainTable").GridUnload(); 
			var dsptype = "SSL Records";
			if(current_subdomain_columns == subdomain_columns_array_01)
			{
				current_subdomain_columns = subdomain_columns_array_02;
				$.cookie('current_subdomain_column_group', "2"); 
				dsptype = "DNS Records";
			}
			else
			{
				current_subdomain_columns = subdomain_columns_array_01;
				$.cookie('current_subdomain_column_group', "1"); 
			}
			reload_subdomain_grid_data_url = true;
			LoadSubDomainGrid();
			fixSubDomainDataGridSizes();
			selids = jQuery("#"+domain_table_grid_id).getGridParam("selarrrow"); 
			if(selids.length == 1)
			{
				var domainname = jQuery("#"+domain_table_grid_id).getCell(selids, "domain"); 
				jQuery("#SubDomainTable").setCaption(dsptype + " for " + domainname);
			}
			return false;
		}, 
		position:"last",
		title:'Switch Between SSL and DNS Records'
	});
}

function LoadVersionInfo(doexppopup)
{
	var turl = grid_url_base + "?mode=ver";
	request = $.ajax({type: "POST",	url: turl});
	request.done(function(msg) 
	{  
		if(msg != "")
		{
			$("#version_build_date").html("<p>" + msg + "</p>");
			if(doexppopup && (msg.indexOf("Expired Demo") > -1 || msg.indexOf("Expired Code") > -1))
				expired_alert();
		}
		$('#buynow').button({text: true, label:"Buy Now"});
		$("#buynow").click(function(){window.open('lib/php/links.php?r=buynow');});
		$('#upgradepro').button({text: true, label:"Upgrade To Pro Edition"});
		$("#upgradepro").click(function(){window.open('lib/php/links.php?r=upgpro');});
		$('#upgradestd').button({text: true, label:"Upgrade To Std Edition"});
		$("#upgradestd").click(function(){window.open('lib/php/links.php?r=upgstd');});
	});
}

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

jQuery.extend($.fn.fmatter , 
{
    booleanFormatter : function(cellvalue, options, rowdata) 
	{
		if(cellvalue != 0)
			return '<img src="lib/css/img/yes.png" alt="1">';
		else
			return '<img src="lib/css/img/no.png" alt="1">';
	},
	domAvailFormatter : function(cellvalue, options, rowdata) 
	{
		if(cellvalue == "Available")
			return '<img src="lib/css/img/yes.png" alt="Available">';
		else if(cellvalue == "Not Available")
			return '<img src="lib/css/img/no.png" alt="Not Available">';
		else if(cellvalue == "Setup Error")
			return '<img src="lib/css/img/setuperror.png" alt="Setup Error">';
		else
			return cellvalue;
	},
	registrarFormatter : function(cellvalue, options, rowdata) 
	{
		if (typeof registrar_aliases != 'undefined')
		{
			for (var i = 0; i < (registrar_aliases.length)/2; i++) 
			{
				if(registrar_aliases[i*2] == cellvalue)
					return registrar_aliases[i*2+1];
			}
		}
		return cellvalue;
	}
});

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

function addCategoryOrderButtons()
{
	$("#DomainCategoryTable").navSeparatorAdd("#pagerCatView",{})
	.navButtonAdd('#pagerCatView',
	{
		caption:"", 
		buttonicon:"ui-icon-arrow-1-n", 
		onClickButton: function()
		{ 
			moveCategoryUpDown(-1);
		},
		position:"last",
		title:'Move Category Up'
	});
	
	$("#DomainCategoryTable")
	.navButtonAdd('#pagerCatView',
	{
		caption:"", 
		buttonicon:"ui-icon-arrow-1-s", 
		onClickButton: function()
		{ 
			moveCategoryUpDown(1);
		},
		position:"last",
		title:'Move Category Down'
	});
}

function moveCategoryUpDown(incr)
{
	if(lastsel_categoryrow_id != 0 && lastsel_categoryrow_id != 1)
	{
		$.ajax({
			type: "POST",
			cache: false,
			dataType: 'json',
			url: "lib/php/bulktool.php",
			data: "catorder=" + lastsel_categoryrow_id + "&incr=" + incr,
			success: function(html)
			{
				$("#DomainCategoryTable").trigger("reloadGrid"); 
				$("#DomainCategoryTable").setSelection(lastsel_categoryrow_id, false);
			},
			error: function(XMLHttpRequest, textStatus, errorThrown) 
			{ 
				if(XMLHttpRequest.status == 403)
					alert("Access Denied! No permission to add domains.");
				else
					alert("Error: " + errorThrown); 
			} 
		});
	}
}

function setCategoryNameInAddDlg()
{
	var categoryName = "";
	$("#catempty").attr('disabled','disabled');
	if(lastsel_categoryrow_id > 1)
	{
		var rowData = $('#DomainCategoryTable').jqGrid('getRowData', lastsel_categoryrow_id);
		categoryName = "&quot;<b>" + rowData['CategoryName'] + "</b>&quot;"
		if(is_an_admin_user)
			$("#catempty").removeAttr('disabled');
		$("#catadd").removeAttr('disabled');
	}
	else
		$("#catadd").attr('disabled','disabled');
	$(".adc-catname").html(categoryName);
}

function addRegistrarAliasButton()
{
	$("#" + domain_table_grid_id).navSeparatorAdd("#"+domain_table_pager_id,{})
	.navButtonAdd('#'+domain_table_pager_id,
	{
		caption:"", 
		buttonicon:"ui-icon-tag", 
		onClickButton: function()
		{ 
			var rowKey = jQuery("#"+domain_table_grid_id).getGridParam("selarrrow"); 
			if(rowKey.length == 1)
			{
				sid = rowKey[0];
				$.ajax({
					type: "GET",
					cache: false,
					url: "lib/php/regalias.php?get&id=" + sid,
					success: function(html)
					{
						var x = jQuery.parseJSON(html);
						if(x.name != "")
							$("#dialog-regalias-editor").data('info', html).dialog('open');
					},
					statusCode: {
					   403: function() { 
							alert("Permission denied.");
					   }
					}
				});
			}
			//else
			//	alert("Multiple Selection");
			return false;
		}, 
		position:"last",
		title:'Edit Registrar Alias'
	});
}

function setRegistrarAlias(registrar, alias)
{
	if (typeof registrar_aliases != 'undefined')
	{
		var found = false;
		for (var i = 0; i < (registrar_aliases.length)/2; i++) 
		{
			if(registrar_aliases[i*2] == registrar)
			{
				registrar_aliases[i*2+1] = alias;
				found = true;
				break;
			}
		}
		if(!found)
		{
			registrar_aliases.push(registrar);
			registrar_aliases.push(alias);
		}
	}
	else
	{
		registrar_aliases = new Array(); 
		registrar_aliases[0] = registrar;
		registrar_aliases[1] = alias;
	}
		
}

function addCSVTableDownloadButton()
{
	$("#" + domain_table_grid_id).navSeparatorAdd("#"+domain_table_pager_id,{})
	.navButtonAdd('#'+domain_table_pager_id,
	{
		caption:"", 
		buttonicon:"ui-icon-arrowthickstop-1-s", 
		onClickButton: function()
		{ 
			$('#dialog-csv-download').dialog('open');
			return false;
		}, 
		position:"last",
		title:'Download CSV...'
	});
}

function csvWrapQuotes(ptext)
{
	if(typeof ptext === 'undefined' || ptext == "" || ptext == null)
		return "";
	else
	{
		ptext = ptext.trim();
		if(ptext.indexOf("\"") > -1)
		{
			while (ptext.indexOf("\"") > -1)
				ptext = ptext.replace("\"", "{{^&}}")
			while (ptext.indexOf("{{^&}}") > -1)
				ptext = ptext.replace("{{^&}}", "\"\"")
			return '"' + ptext + '"';
		}
		if (ptext.indexOf(",") > -1 || ptext.indexOf("'") > -1)
		   return '"' + ptext + '"';
		 return ptext;
	}
}

function downloadRows(dlType)
{
	var rowText = "";
	var tablecolumns = [];
	var columns = jQuery("#"+domain_table_grid_id).getGridParam("colModel");
	var colnum = columns.length;
	
	if(dlType == "selecteddnsrows" || dlType == "alldnsrows")
	{
		var ids = null;
		if(dlType == "alldnsrows")
			ids  = jQuery("#"+domain_table_grid_id).getDataIDs(); 
		else
			ids = jQuery("#"+domain_table_grid_id).getGridParam("selarrrow");
		if(ids != null && ids != 0)
		{
			var url = "lib/php/dnloadcsv.php" + "?dnsdata";
			$("#csvdnload").append('<form id="exportform" action="' + url + '" method="post"><input type="hidden" id="rowid" name="rowid"></form>');
			$("#rowid").val(ids);
			$("#exportform").submit().remove();
		}
		return true;
	}
	
	if(dlType == "selectedsslrows" || dlType == "allsslrows")
	{
		var ids = null;
		if(dlType == "allsslrows")
			ids  = jQuery("#"+domain_table_grid_id).getDataIDs(); 
		else
			ids = jQuery("#"+domain_table_grid_id).getGridParam("selarrrow");
		if(ids != null && ids != 0)
		{
			var url = "lib/php/dnloadcsv.php" + "?ssldata";
			$("#csvdnload").append('<form id="exportform" action="' + url + '" method="post"><input type="hidden" id="rowid" name="rowid"></form>');
			$("#rowid").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")
			{
				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("#"+domain_table_grid_id).getGridParam("selarrrow");
	else if(dlType == "allrows" || dlType == "alldomainnames")
		rowKey  = jQuery("#"+domain_table_grid_id).getDataIDs(); 
	var rl = rowKey.length;
	for(i = 0; i < rl; i++)
	{
		var rowData = jQuery("#"+domain_table_grid_id).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 = "lib/php/dnloadcsv.php";
	if(dlType == "alldomainnames" || dlType == "selecteddomainnames")
		posturl += "?txt";
	$("#csvdnload").append('<form id="exportform" action="' + posturl + '" method="post"><input type="hidden" id="exportdata" name="exportdata"></form>');
    $("#exportdata").val(rowText);
    $("#exportform").submit().remove();
    return true; 
}

function get_editable_columns()
{
	var columns = jQuery("#"+domain_table_grid_id).getGridParam("colModel");
	var colnum = columns.length;
	var showText = '<option value="f-none">-</option>\n';
	for(i = 0; i < colnum; i++)
	{
		if(columns[i].name != "rn" && columns[i].name != "cb" && columns[i].name != "r_h_disp" 
		&& columns[i].name != "notes_a" && columns[i].name != "notes_b" && columns[i].name != "notes_c" && columns[i].name != "notes_d")
		{
			var edt = columns[i].editoptions;
			var readonly = false;
			var editable = false;
			var label = columns[i].name;
			if(typeof columns[i].label !== 'undefined')
				label = columns[i].label;
			if(typeof columns[i].editable !== 'undefined')
				editable = columns[i].editable;
			if (typeof edt !== 'undefined') 
			{
				if (typeof edt.readonly !== 'undefined') 
					readonly = edt.readonly;
			}
			if(readonly === false && editable === true)
				showText += '<option value="f-' + columns[i].name + '">' + label + '</option>' + '\n';
		}
	}
	return showText;
}

function onBulkFieldChange()
{
	var ftype = $("#bt-field-set").val().toLowerCase();
	if(ftype == "f-none")
		$("#field_set").attr('disabled', 'disabled'); 
	else
		$("#field_set").removeAttr('disabled'); 
}

function ShowDomainCategories()
{
	var selids = jQuery("#"+domain_table_grid_id).getGridParam("selarrrow"); 
	var ids = jQuery("#DomainCategoryTable").jqGrid('getDataIDs');
	if(selids.length == 1)
	{
		$.ajax({
			type: "GET",
			cache: false,
			dataType: 'json',
			url: 'lib/php/bulktool.php?domcat=' + selids[0],
			success: function(html)
			{
				var catArray = html.map(Number);
				//console.log(catArray);
				for (var i = 0; i < ids.length; i++) 
				{
					var rowId = 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");
					}
				}

			}
		});	
	}
	else
	{
		for (var i = 0; i < ids.length; i++) 
		{
			var rowId = ids[i];
			var grid = $("#DomainCategoryTable");
			tr = grid[0].rows.namedItem(rowId), 
			$(tr).removeClass("jqboldrow");
		}
	}
}