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

var sub_domain_manager_mode 	= true;
var show_all_sd_records			= false;

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

var domain_table_jqgrid         = null;
var selected_rowids_for_reload  = "";

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

var DOMAINGRID_MULTI_SELECT     = true;
var DOMAINGRID_MULTI_BOX_ONLY   = true;

var DGA_SUBDOMAIN_MGR_GRID  	= "sdmg";

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

var glb_menu_panels	= [ 
"columnsetup", "useradmin", "userselfadmin", "mpanel-download", "mpanel-addsubd",
"processqueue", "uisetup", "mpanel-lookup", "mpanel-bulkedit", "mpanel-categorize",
"navbarmenu", "userguide"

];

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

$(function()
{
	initInterfaceDivs();
	
	// Init the mouse handling outside Navbar Menu
	$(document).mouseup(function (e)
	{
		var container = $("#navbarmenu");
		if (container.is(':visible') 
			&& !container.is(e.target) // if the target of the click isn't the container...
			&& container.has(e.target).length === 0) // ... nor a descendant of the container
		{
			hidePanelWithId('navbarmenu');
		}
	});
	
	// Prevent backspace from going to previous page in browser.
	$(document).on("keydown", function (e) 
	{
		if (e.which === 8 && !$(e.target).is("input, textarea")) {
			e.preventDefault();
		}
	});
	
	$("body").fadeIn(1000);
	setupPanes();
	setupTabs();
	themeChanged();
	initUISetup();
	
	if(getCookieInt("popmenu", 1))
	{
		if($('#popmenu').is(':visible') == false)
			togglePopupMenu();
	}
	
	initUploadDomainsBox();
	
	$('#addsubd-submit').click(function(event) { event.preventDefault(); addSubDomains(); });
	$('#bulkedit-submit').click(function(event) {event.preventDefault(); bulkEditSubmit();});
	$('#bulkedit-resetmanedit').click(function(event) {event.preventDefault(); bulkEditResetManEdit();});
	$('#addtocategories').click(function(event) {event.preventDefault(); addToCategories();});
	$('#removefromcategories').click(function(event) {event.preventDefault(); removeFromCategories();});
	$("#ludomains").click(function(event) {event.preventDefault(); DoLookups();});
	
	LoadDomainDataGrid(false);
	setDefaultFontSizes();
	
	$('.btn-nav').click(function(event)
	{
		var cpid = jQuery(this).attr("id");
		event.preventDefault();
		var btnid = cpid.replace("nb_", "");
		hideAllExcept("dummy");
		$("#" + btnid).click();
	});
	
	$('.btn-dgroup').click(function(event)
	{
		var cpid = jQuery(this).attr("id");
		event.preventDefault();
		var btnid = cpid.replace("nb_", "");
		hidePanelWithId("navbarmenu");
		if(btnid == "sedmenu")
			togglePopupMenu();
		else if(btnid == "showauditlog")
			window.location = 'audit.php';
		else
			$("#btn_" + btnid).click();
	});
	
	$('.btn-menu').click(function(event)
	{
		var cpid = jQuery(this).attr("id");
		event.preventDefault();
		var btnid = cpid.replace("btn_", "");
		if(!is_an_admin_user && btnid == "useradmin")
			btnid = "userselfadmin";
		if(btnid != "" && btnid != cpid)
		{
			if(!hidePanelWithId(btnid))
			{
				if($('#popmenu').is(':visible')) 
					$('.panel-outer').css('right', 48);
				else
					$('.panel-outer').css('right', 0);
				
				if(btnid.lastIndexOf("mpanel-", 0) === 0 && btnid != "mpanel-download" && btnid != "mpanel-addsubd")
					if(!stopIfNotEnoughDomainsSelected(false, "Select some domains first!"))
						return;
				
				$('#'+btnid).show("drop",  {direction:'right'}, 200 );
				
				hideAllExcept(btnid);
				
				if(btnid == "columnsetup")
				{
					positionColumnSetupWindow();
					onAfterSDColumnSetupWindowPopup();
				}
				else if(btnid == "useradmin")
					onAfterUserAdminWindowPopup();
				else if(btnid == 'mpanel-addsubd')
					onAfterAddSubdomainsWindowPopup();
				else if(btnid == "processqueue")
					onAfterProcessQueueWindowPopup();
				else if(btnid == "mpanel-bulkedit")
					onAfterBulkEditWindowPopup('');
				else if(btnid == "mpanel-categorize")
					onAfterCategorizeWindowPopup();
			}
		}
		else if(cpid == "uploadcsv")
		{
			showUploadDomains();
		}
		else if(cpid == "showauditlog")
		{
			window.location = 'audit.php';
		}
		else if(cpid == "deletedomains")
		{
			$('#del_DomainTable').click();
		}
		else if(cpid == "main")
		{
			window.location = 'main.php';
		}
		else if(cpid == "nossl")
		{
			custom_alert("You are not using an encrypted connection. You may want to protect any sensitive information by installing an SSL certificate at your server.", "");
		}
	});
	
	$('.btn-navtb').click(function(event)
	{
		var cpid = jQuery(this).attr("id");
		event.preventDefault();
		var btnid = cpid.replace("btn_", "");
		if(btnid == "sedmenu")
			togglePopupMenu();
		else if(btnid == "navbarmenu")
		{
			toggleNavbarMenu();
			hideAllExcept(btnid);
			return;
		}
		else if(btnid == "main")
			window.location='main.php';
		else if(btnid == "appmenu")
			window.location='menu.php';
		else if(btnid == "allsd")
			showAllRecordsInGrid(true);
		else if(btnid == "norootsd")
			showAllRecordsInGrid(false);
		else if(btnid == "logout")
			window.location = 'main.php?logout&redir=sdmgr.php';
		else if(btnid == "nologin")
			custom_alert("This application is not password protected. You can enable password protection using the 'user admin' button <img src=\"lib/css/images/16/vcard.png\"> in the right pane.", "Alert");
		hideAllExcept("dummy");
	});
	
	// Handle closing of panels on ESC key press.
	$(window).keydown(function(event) 
	{
		if(!HandleEscapeKey(event))
			return false;
	});
	
	// Handle closing of panels on 'close' button click.
	$(".close-button").click(function(event)
	{
		var cpid = jQuery(this).attr("id");
		event.preventDefault();
		for(index = 0; index < glb_menu_panels.length; ++index) 
		{
			if(cpid == glb_menu_panels[index] + "-close")
				hidePanelWithId(glb_menu_panels[index]);
		}
	});
	
	$(".btn-navtb").hover(function(e) 
	{ 
		var btnid = show_all_sd_records ? "btn_allsd" : "btn_norootsd";
		var cpid = jQuery(this).attr("id");
		if(cpid !== btnid)
		{
			var btnbackground = $('.ui-state-default').css('background-color');
			var btnhovercolor = $('.ui-state-active').css('background-color');
			$(this).css("background-color", e.type === "mouseenter" ? btnhovercolor : btnbackground); 
		}
	});
	
	$("#ui_download_data").click(function(event)
	{
		if(downloadRows($("#csv-download-radio :radio:checked").attr('id')))
			hidePanelWithId("mpanel-download");
	});
	
	$('#ui_display_column_update').click(function(event)
	{
		updateDisplayColumns(false);
		onAfterSDColumnSetupWindowPopup();
	});
	
	$('#ui_display_column_reset').click(function(event)
	{
		updateDisplayColumns(true);
		onAfterSDColumnSetupWindowPopup();
	});
	
	$('.subgriddata').hide();
	
	setupTableColumns('tablecolumns', 'column_label', 'column_width', 'selectedcolumn', sub_domain_manager_mode);
	$(window).bind('resize', function() {fixDivSizes(); setTimeout(function(){fixDivSizes();}, 50);}).trigger('resize');
});

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

function showAllRecordsInGrid(sw)
{
	if(show_all_sd_records != sw)
	{
		show_all_sd_records = sw;
		var durl = getDomainDataURL();
		jQuery("#DomainTable").setGridParam({url:durl});
		$("#DomainTable").trigger("reloadGrid");  
		var btnbgcolor = $('.ui-state-default').css('background-color');
		var btnhighlightcolor = $('.ui-state-highlight').css('background-color');
		$('.btn-navtb').css("background-color", btnbgcolor);
		if(sw)
			$('#btn_allsd').css("background-color", btnhighlightcolor);
		else
			$('#btn_norootsd').css("background-color", btnhighlightcolor);
	}
}

/////////////////////////////////////////////////////////////////////////////////////////
// The width percentages are tricky. Make sure that 
// the width calculated from percentage is not less 
// than the minSize (in pixels) specified

function setupPanes()
{
	var lp01 = getCookiePercent("left-pane-width", 20);
	if(lp01 < 20)
		lp01 = 20;
	var lp02 = 100 - lp01;
	Split(['#leftpane', '#rightpane'], {
		sizes: [lp01, lp02],
		minSize: [150,150],
		snapOffset: 10,
		gutterSize: 6,
		onDragEnd: function() {
			var lw = $("#leftpane").width();
			var rw = $("#rightpane").width();
			var p = lw * 100 / (lw+rw);
			saveCookie("left-pane-width", p);
			fixDivSizes();
		}
	});
	
	$(window).scroll(function () 
	{
		fixDivSizes();
	});
}

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

function setupTabs()
{
	$('#CategoryTabView').tabs(
	{
		activate: function(event ,ui) 
		{
			var active = $('#CategoryTabView').tabs('option', 'active');
			$.cookie('category_tab', active);
			fixDivSizes();
			fixDivSizes();
		}
    });
	var cti = getCookieInt('category_tab', 0);
	if(cti >= 0 && cti < 3)
		$( "#CategoryTabView" ).tabs("option", "active", cti);
}

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

function fixDivSizes()
{
	positionMainInterface();
	
	var domain_title_height = $('#rightpane').find('.ui-jqgrid-titlebar').outerHeight();
	var domain_header_height = $('#rightpane').find('.ui-jqgrid-htable').outerHeight();
	var domain_pager_height = $('#pg_DomainTablePager').height();
	
	var domaintablewidth = $("#rightpane").width()-(11*2);
	var domaintableheight = $("#rightpane").height()-domain_title_height-domain_pager_height-domain_header_height-20-4;
	jQuery("#DomainTable").setGridWidth(domaintablewidth, true); 
	jQuery("#DomainTable").setGridHeight(domaintableheight);
		
	var lph = $("#leftpane").height();
	var tabh = $(".ui-tabs-nav").height() + 6; 
	var ctw = $("#leftpane").width()-(10*2);
	
	if($('#DomainCategoryTable').is(':visible'))
	{
		domain_pager_height = $('#pg_DomainCategoryTablePager').height();
		domain_header_height = $('#gbox_DomainCategoryTable').find('.ui-jqgrid-htable').outerHeight();
		var cth = $("#leftpane").height()-domain_pager_height-domain_header_height-tabh-20-4;
		jQuery("#DomainCategoryTable").setGridWidth(ctw, true); 
		jQuery("#DomainCategoryTable").setGridHeight(cth); 
	}
	else if($('#DomainQueryTable').is(':visible'))
	{
		domain_pager_height = $('#pg_DomainQueryTablePager').height();
		domain_header_height = $('#gbox_DomainQueryTable').find('.ui-jqgrid-htable').outerHeight();
		var qth = $("#leftpane").height()-domain_pager_height-domain_header_height-tabh-20-4;
		jQuery("#DomainQueryTable").setGridWidth(ctw, true); 
		jQuery("#DomainQueryTable").setGridHeight(qth); 
	}
	
	if($('#columnsetup').is(':visible'))
		positionColumnSetupWindow();
	
	if($('#useradmin').is(':visible'))
		positionUserAdminWindow();
	
	if($('#mpanel-bulkedit').is(':visible'))
		positionBulkEditWindow();
	
	// Custom Queries is always visible.
	positionCustomQueriesWindow();
	
	positionHider();
}

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

function positionColumnSetupWindow()
{
	var dheight = $('.panel-outer').outerHeight()-140;
	$('#displaylist').css('max-height', dheight);
	/*
	var bw = 0;
	var fh = 0;
	if($('#footer').is(':visible'))
		fh = $('#footer').outerHeight();
	var dheight = $(window).height()-fh-$("#header").outerHeight()-150;
	var eh = $("#columnsetup-info").height();
	$('#columnsetup-control').css('height', dheight-16-10-eh-bw);
	$('#displaylist').css('height', dheight-16-10-eh-bw);
	*/
}

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

function themeChanged()
{
	var bgcolor = $('.ui-widget-content').css('background-color');
	var color = $('.ui-widget-content').css('color');
	var abgcolor = bgcolor;
	if(abgcolor.indexOf('a') == -1)
		abgcolor = abgcolor.replace(')', ', 0.9)').replace('rgb', 'rgba');
	$('body').css('background-color', bgcolor);
	$('#header').css('background-color', bgcolor);
	$('#footer').css('background-color', bgcolor);
	$('#header').css('color', color);
	$('#footer').css('color', color);
	
	var altrowcolor = 'rgba(255,255,255,0.2)';
	if(bgcolor.indexOf('a') == -1)
	{
		var ic = getContrastYIQ(bgcolor);
		if(ic > 125)
		{
			$("#logo").attr("src", logo_image_dark);
			$("#menu-logo").attr("src", logo_image_dark);
		}
		else
		{
			$("#logo").attr("src", logo_image_light);
			$("#menu-logo").attr("src", logo_image_light);
		}
		if(ic >= 60)
			altrowcolor = ColorLuminance(rgb2hex(bgcolor), -0.05);
	}
	$('.gridAltRowClass').css('background-color', altrowcolor);

	bgcolor = $('.ui-state-default').css('background-color');
	color = $('.ui-state-default').css('color');
	abgcolor = bgcolor;
	if(abgcolor.indexOf('a') == -1)
		abgcolor = abgcolor.replace(')', ', 0.5)').replace('rgb', 'rgba');
	var brcolor = $('.ui-state-default').css('border-color');
	
	var btncolor = $('.ui-state-default').css('background-color');
	var btnbordercolor = ColorLuminance(rgb2hex(bgcolor), -0.3);
	var btnmenucolor = ColorLuminance(rgb2hex(bgcolor), -0.1);
	$('.btn-navtb').css('background-color', btncolor);
	$('.btn-navtb').css('border-color', btnbordercolor);
	$('.btn-menu').css('background-color', btnmenucolor);
	$('.btn-menu').css('border-color', btncolor);
	var btnhighlightcolor = $('.ui-state-highlight').css('background-color');
	var btnid = show_all_sd_records ? "btn_allsd" : "btn_norootsd";
	$('#'+btnid).css("background-color", btnhighlightcolor);
	
	var bg = $('.ui-widget-header').css('background');
	if(bg == "")
	{
		var bg2 = $('.ui-widget-header').css('background-image');
		var bg3 = $('.ui-widget-header').css('background-repeat');
		var bg4 = $('.ui-widget-header').css('background-color');
		bg = bg2+" "+bg3+" "+bg4;
	}
		
	var n = bg.search(/repeat /i);
	if(n >= 0)
		$('#popmenu').css('background', bg);
	else
		$('#popmenu').css('background-color', bgcolor);
	$('#popmenu').css('color', color);
		
	bgcolor = $('.ui-widget-header').css('background-color');
	color = $('.ui-widget-header').css('color');
	var contrast = getContrastYIQ(bgcolor);
	abgcolor = bgcolor;
	if(abgcolor.indexOf('a') == -1)
		abgcolor = abgcolor.replace(')', ', 0.5)').replace('rgb', 'rgba');
	$('.gutter').css('background-color', abgcolor);
	$('#header').css('border-color', abgcolor);
	$('#footer').css('border-color', abgcolor);
	if(contrast > 125)
	{
		$('.gutter.gutter-vertical').css('background-image', 'url(' + split_hgrip_image_dark + ')');
		$('.gutter.gutter-horizontal').css('background-image', 'url(' + split_vgrip_image_dark + ')');
	}
	
	$('#DetailsPane h3').css('border-bottom-color', bgcolor);
	$('#DetailsTabView').css('padding', 0);
	
	bgcolor = $('.ui-state-default').css('background-color');
	color = $('.ui-state-default').css('color');
	abgcolor = bgcolor;
	if(abgcolor.indexOf('a') == -1)
		abgcolor = abgcolor.replace(')', ', 0.5)').replace('rgb', 'rgba');
	$('.panel').css('background-color', bgcolor);
	$('.panel').css('color', color);
	$('.panel h3').css('border-bottom', "0px dotted " + color);
	$('hr.panelruler').css('border-bottom', "1px dotted " + color);
	$('.categorychecklist').css('border', "1px dotted " + color);
	$('.panel-outer').css('background-color', abgcolor);
	$('.panel-outer-opaque').css('background-color', bgcolor);
	$('.panelwell').css('background-color', abgcolor);
	$('.panelwell').css('border-color', color);
	$('.panelwell').css('color', color);
	abgcolor = bgcolor;
	if(abgcolor.indexOf('a') == -1)
		abgcolor = abgcolor.replace(')', ', 0.7)').replace('rgb', 'rgba');
	$('#navbarmenu .panel').css('background-color', abgcolor);
	$('.navruler').css('border-color', color);
	
	$('.dialogWithShadow  > .ui-dialog-content').css('background-color', bgcolor);
	$('.dialogWithShadow  > .ui-dialog-content').css('color', color);
	$('.dialogWithShadow  > .ui-dialog-buttonpane').css('background-color', bgcolor);
	$('.dialogWithShadow  > .ui-dialog-buttonpane').css('color', color);
	$('.dialogWithShadow  > .ui-dialog-buttonpane').css('border-top-color', color);
	$('.dialogWithShadow').css('border', '8px solid ' + abgcolor);
	btnbordercolor = ColorLuminance(rgb2hex(bgcolor), -0.3);
	$('.dialogWithShadow .ui-button').css('border', '1px solid ' + btnbordercolor);
	
	$('.ui-jqdialog-content').css('background-color', bgcolor);
	$('.ui-jqdialog-content').css('color', color);
	
	bgcolor = $('.ui-widget-header').css('background-color');
	color = $('.ui-widget-header').css('color');
	$('.panel h3').css('background-color', bgcolor);
	$('.panel h3').css('color', color);
	
	//$('.btn-nav, .btn-dgroup').css('background-color', bgcolor);
	//$('.btn-nav, .btn-dgroup').css('color', color);
}

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

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 getGridRowHeight (targetGrid) 
{
    var height = 23; // Default
    try
	{
		count = $("#DomainTable").getGridParam("reccount");
		if(count)
			height = $('#DomainTable').height() / count;
    }
    catch(e){
    }
    return height;
}

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

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 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();
	
	var rowsperpage = getCookieInt('domain_sd_rows_per_page', 100);
	var rowlist = [10,50,100,250,500,1000,2000,5000,10000];
	if(jQuery.inArray(rowsperpage, rowlist) < 0)
		rowsperpage = 100;
	
	var sortname = getCookie('current_sd_sort_column', "hid");
	var sortorder = getCookie('current_sd_sort_order', "desc");
	domain_table_jqgrid = jQuery("#DomainTable").jqGrid(
	{
		height: $("#rightpane").height()-120,
		width: $("#rightpane").width()-24,
		altRows:true,
		hidegrid: false,
		altclass: "gridAltRowClass",
		url: durl,
		editurl: base_grid_ajax_url + '?sdmge',
		shrinkToFit: false,
		pager: "#DomainTablePager",
		jsonReader : {repeatitems: false},
		rownumWidth: 50,
		rowList: rowlist,
		datatype: "json",
		sortname: sortname,
		sortorder: sortorder,
		colModel: subdomgrid_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}",
		loadError: function (jqXHR, textStatus, errorThrown) 
		{
			gridSessionTimedoutError(jqXHR);
		},
		beforeRequest: function() 
		{
			setDomainTableCaption();
		},
		loadComplete : function () 
		{
			themeChanged();
			fixDivSizes();
			fixDivSizes();
			// If this is not done the selection is lost after a row edit.
			if(!$('#editmodDomainTable').is(':visible'))
				scrollToCurrentRow();
        },
		gridComplete : function()
		{
			domainGridGridComplete();
		},
		onSelectRow: function(ids) 
		{
			$.cookie('current_sd_domain', String(ids)); 
			highlightCategoriesOfCurrentDomain();
		},
		onSelectAll: function(ids, status)
		{
			highlightCategoriesOfCurrentDomain();
		}
	});
	
	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: 500,
		closeOnEscape:true,
		beforeShowForm: function ($form) 
		{
			hideModalPanels();
			var dlist = getSelectedSubdomainList(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() 
		{
		}
	},
	{
		// 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()
			{ 
				onPanelButtonClick('mpanel-addsubd');
				onAfterAddSubdomainsWindowPopup();
				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'
	});
	
	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 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_sd_sort_column', domain_sort_column_name); 
	saveCookie('current_sd_sort_order', domain_sort_order_name); 

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

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

function getDomainDataURL()
{
	var columns = "";
	for(i = 0; i < subdomgrid_columns_array.length; i++)
	{
		if(subdomgrid_columns_array[i].name != "rn" && subdomgrid_columns_array[i].name != "cb")
		{
			columns += encodeURIComponent(subdomgrid_columns_array[i].name);
			columns += ",";
		}
	}

	var durl = base_grid_ajax_url + "?" + DGA_SUBDOMAIN_MGR_GRID + "&columns=" + columns;
	
	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;
	if(show_all_sd_records == false)
		durl += "&noroot";
	return durl;
}

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

function scrollToCurrentRow()
{
	var sel_rowid = 0;
	var allIDs = jQuery("#DomainTable").getDataIDs(); 
	if(allIDs.length > 0)
		sel_rowid = allIDs[0];
		
	var cdomain = parseInt($.cookie("current_sd_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);
		scrollToRow($("#DomainTable"), sids[0]);
	}
	else
	{
		$("#DomainTable").setGridParam({scrollrows:false}); 
		var selids = jQuery("#DomainTable").getGridParam("selarrrow"); 
		if(selids.length == 0)
			$("#DomainTable").setSelection(sel_rowid, true);
		scrollToRow($("#DomainTable"), sel_rowid);
	}
	selected_rowids_for_reload = "";
}

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

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

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

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

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

function uploadCSVFile()
{
	$("#csverrors").css("height", "150px");
	data = new FormData($('#csv-upload')[0]);
	$("#csverrors").html("Please wait...");
	var cid = getCookieInt('current_category', 0);
	if(data != "")
	{
		$.ajax({
			type: 'POST',
			url: 'lib/php/ajax/datagrid.php?' + DGA_SUBDOMAIN_CSV_UPLOAD + '&cid=' + cid,
			data: data,
			cache: false,
			contentType: false,
			processData: false
		}).done(function(data) 
		{
			var x = jQuery.parseJSON(data);
			if(x.validate == 1)
				sessionRestart("timeout");
			else if(x.validate == -1)
				sessionRestart("badsession");
			$("#csverrors").html(x.msg);
			if(x.status != "Error")
				$("#DomainTable").trigger("reloadGrid");
		}).fail(function(jqXHR,status, errorThrown) 
		{
			if(jqXHR.status == 403)
				custom_alert("Access Denied! No permission to edit.", "Problem");
			else if(jqXHR.status == 400)
				custom_alert("Invalid Session. Please login again.", "Problem");
			else if(jqXHR.status == 408)
				custom_alert("Session timeout. Please login again.", "Problem");
		});
	}
	else
		$("#csverrors").html("Nothing to upload!");
}

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

function getUniqueSelectedDomainIds(asarray)
{
	var rowKey = jQuery("#DomainTable").getGridParam("selarrrow"); 
	var dlist = [];
	var rl = rowKey.length;
	// Get unique domain names
	for(i = 0; i < rl; i++)
	{
		var rowData = jQuery("#DomainTable").jqGrid ('getRowData', rowKey[i]);
		var td = rowData.sid;
		dlist.push(td);
		jQuery.unique(dlist);
	}
	if(asarray)
		return dlist;
	else
		return dlist.join(",");
}

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

function getSingleUniqueSelectedDomainId()
{
	var rowKey = jQuery("#DomainTable").getGridParam("selarrrow"); 
	var rl = rowKey.length;
	for(i = 0; i < rl; i++)
	{
		var rowData = jQuery("#DomainTable").jqGrid ('getRowData', rowKey[i]);
		return rowData.sid;
	}
	return 0;
}

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

function getSelectedDomainList(dcount)
{
	var dmsg = "<code>no domains selected</code>";
	var rowKey = jQuery("#DomainTable").getGridParam("selarrrow"); 
	var dlist = [];
	var rl = rowKey.length;
	if(dcount > 25)
		dcount = 25;
	
	// Get unique domain names
	for(i = 0; i < rl; i++)
	{
		var rowData = jQuery("#DomainTable").jqGrid ('getRowData', rowKey[i]);
		var td = rowData.domain;
		dlist.push(td);
		jQuery.unique(dlist);
		if(i > 200)
			break;
	}
	rl = dlist.length;
	
	if(rl)
	{
		dmsg = "";
		if(dcount > rl)
			dcount = rl;
		for(i = 0; i < dcount; i++)
		{
			dmsg += dlist[i];
			if(i == (dcount-2) && rl == dcount)
				dmsg += " &amp; ";
			else if(i != (dcount-1))
				dmsg += ", ";
			else if(i == (dcount-1) && dcount < rl)
				dmsg += " and <b>" + (rl-dcount) + " more domains</b>";
		}
	}
	return dmsg;
}

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

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

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

function showSelectedSubdomains(dcount)
{
	var rowKey = jQuery("#DomainTable").getGridParam("selarrrow"); 
	var rl = rowKey.length;
	var dlist = rl + " selected subdomain entries";
	//dlist += " of " + getSelectedDomainList(dcount);
	$('.selecteddomains').html(dlist);
}

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

function getSelectedSubdomainList(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]);
		if(rowData.subdomain == '@')
			dlist += rowData.domain + " [" + rowData.record_type + " " + rowData.ip + "]";
		else
			dlist += rowData.subdomain + "." + 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 entries</b>";
	}
	return dlist;
}

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

function onAfterSDColumnSetupWindowPopup()
{
	$('#column_label').val('');
	$('#column_width').val('');
	current_dg_field_name = "";
	$('#selectedcolumn').html('-');
	$('#tablecolumns').html("Please Wait");
	
	var durl = 'lib/php/ajax/appsetup.php?sdcol';
	$.ajax({
			type: 'POST',
			url: durl,
			cache: false
		}).done(function(data) 
		{
			var x = jQuery.parseJSON(data);
			if(x.validate == 1)
				sessionRestart("timeout");
			else if(x.validate == -1)
				sessionRestart("badsession");
			$('#tablecolumns').html(x.data);
			$('#columnsetup-title').html(x.title);
		}).fail(function(jqXHR,status, errorThrown) 
		{
			console.log(errorThrown);
			console.log(jqXHR.responseText);
			console.log(jqXHR.status);
		});
}

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

function updateDisplayColumns(setdefault)
{
	var checkedIds = $("#tablecolumns :checkbox:checked").map(function() {
        return this.id;
    }).get();
	
	var turl = "lib/php/ajax/appsetup.php?";
	var datastr = "";
	if(setdefault == false)
	{
		var colsetup = "";
		var length = checkedIds.length;
		var columns = new Array();
		for (var i = 0; i < length; i++) 
		{
		  columns[i] = checkedIds[i].replace("cb-", "");
		  colsetup += columns[i];
		  if(i != (length-1))
			colsetup += ";";
		}
		datastr = "entry=" + colsetup;
		turl += "sdcolset=sub_domain_columns";
	}
	else
		turl += "sdcolreset=sub_domain_columns";

	var request = $.ajax({type: "POST",	url: turl, data: datastr});
	request.done(function(msg) 
	{
		var x = jQuery.parseJSON(msg);
		if(x.validate == 1)
			sessionRestart("timeout");
		else if(x.validate == -1)
			sessionRestart("badsession");
		gurl = "lib/php/ajax/appsetup.php?sdget=sub_domain_columns";
		var creq = $.ajax({type: "POST", url: gurl});
		creq.done(function(cmdata) 
		{
			var x2 = jQuery.parseJSON(cmdata);
			if(x2.validate == 1)
				sessionRestart("timeout");
			else if(x2.validate == 1)
				sessionRestart("badsession");
			subdomgrid_columns_array = x2.colmodel;
			LoadDomainDataGrid(true);
		});
		
	});
	request.fail(function(jqXHR, textStatus) 
	{
		if(jqXHR.status == 403)
			custom_alert("Access Denied! No permission to edit.", "Problem");
	});
	saveColumnLabelAndWidth("", current_dg_field_name, $('#column_label').val(), $('#column_width').val(), sub_domain_manager_mode);
}

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

function downloadRows(dlType)
{
	var rowText = "";
	var tablecolumns = [];
	var columns = jQuery("#DomainTable").getGridParam("colModel");
	var colnum = columns.length;
	
	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("#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['subdomain'] != "undefined")
			rowText += rowData['subdomain'] + "\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>');
	$("#exportdata").val(rowText);
	$("#exportform").submit().remove();
	return true; 
}

jQuery.extend($.fn.fmatter , 
{
    booleanFormatter : function(cellvalue, options, rowdata) 
	{
		if(cellvalue != 0)
			return '<span title="' + cellvalue + '" class="glyphicon glyphicon-ok" style="display:inline-block;">';
		else
			return '<span title="' + cellvalue + '" class="glyphicon glyphicon-remove" style="display:inline-block;">';
	},
	highlightFormatter : function(cellvalue, options, rowdata) 
	{
		if(cellvalue == 17 && cellvalue != null)
			return '<img title="Nearing expiry" src="lib/css/images/16/registry-expiry-alert.png" alt="' + cellvalue + '">';
		else if(cellvalue == 10 && cellvalue != null)
			return '<img title="Manually edited" src="lib/css/images/16/manually-edited.png" alt="' + cellvalue + '">';
		else
			return '<span title="Unknown" class="glyphicon" style="display:inline-block;">';
	},
});

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

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

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