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

var split_vgrip_image_dark  = "lib/js/split/grips/vertical-dark.png";
var split_hgrip_image_dark  = "lib/js/split/grips/horizontal-dark.png";

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

var pqCloseTimer = null;

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

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;

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

$(function()
{
	$(".btn-menu").hover(function(e) 
	{ 
		bgcolor = $('.ui-state-default').css('background-color');
		var btnmenubg = ColorLuminance(rgb2hex(bgcolor), -0.1);
		var hovercolor = $('.ui-state-active').css('background-color');
		$(this).css("background-color", e.type === "mouseenter" ? hovercolor : btnmenubg); 
	});
	
	addPopOversInPopMenu();
});

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

function positionMainInterface()
{
	var fh = 0;
	if($('#footer').is(':visible'))
		fh = $('#footer').outerHeight();
	
	var popwidth = 48; // pop-menu width + 6px gap.
	if($(window).height() < 520)
		$('#navbarmenu').css('max-height', $(window).height()-20);
	else
		$('#navbarmenu').css('max-height', 500);
	if(getCookieInt("popmenu", 1))
	{
		if($(window).height() < 612)
			$('#popmenu').hide();
		else
			$('#popmenu').show();
	}
	var popmgap = ($('#popmenu').is(':visible')) ? popwidth : 0;
	$('#content').css('margin-right', popmgap);
	var maxpanelwidth = $(window).width()-popmgap;
	$('.panel-outer').css('width',maxpanelwidth > 750 ? 750 : maxpanelwidth);
	$('.panel-outer').css('right', popmgap);
	$('.navmenu-outer').css('width', $(window).width()-20);
	$('.ui-dialog').css('width',maxpanelwidth > 750 ? 750 : maxpanelwidth);
	
	var headheight = $("#header").outerHeight();
	var dheight = $(window).height()-fh-headheight;
	if($(window).height() <= 612) 
		dheight = 612-fh-headheight;
	
	jQuery("#content").height(dheight, true); 
	$('#popmenu').css('top', headheight);
	$('#popmenu').css('right', 0);
	$('#popmenu').css('width', popwidth);
	$('#popmenu').css('height', dheight);
	$(".mainiface").css('height', dheight);
	
	$('.panel-outer').css('max-height', dheight);
	$('.ui-dialog').css('max-height', dheight);
}

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

function togglePopupMenu()
{
	if($('#popmenu').is(':visible'))
	{
		$('#popmenu').hide("drop",  {direction:'right'}, 100 );
		saveCookie("popmenu", 0);
	}
	else
	{
		$('#popmenu').show("drop",  {direction:'right'}, 100 );
		saveCookie("popmenu", 1);
	}
	setTimeout(function(){fixDivSizes();}, 150);
}

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

function toggleNavbarMenu()
{
	if($('#navbarmenu').is(':visible'))
	{
		$('#navbarmenu').hide("drop",  {direction:'up'}, 100 );
		saveCookie("navbarmenu", 0);
	}
	else
	{
		$('#navbarmenu').show("drop",  {direction:'up'}, 100 );
		saveCookie("navbarmenu", 1);
	}
	setTimeout(function(){fixDivSizes();}, 150);
}

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

function positionCustomQueriesWindow()
{
	var lph = $("#leftpane").height();
	var tabh = $('#CategoryTabView').find(".ui-tabs-nav").height() + 6; 
	var panel_height = lph-tabh-20-4;
	$("#customqueries").css('max-height', panel_height);
	
	var offset = 0;
	if($("#customqueries-box").height() >= panel_height)
		offset = 24;
	
	var ctw = $("#customqueries").width() - offset;
	$('#customqueries-customsql').css('width', ctw);
	$('#customqueries-catbox').css('width', ctw);
	$('#customqueries-string').css('width', ctw);
	$('#customqueries-refresh').css('width', ctw);
	$('#customqueries-reset').css('width', ctw);
	$('#customqueries-name').css('width', ctw);
	$('#customqueries-save').css('width', ctw);
}

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

function positionBulkEditWindow()
{
	var ht = $('#bulkedit-edit').height();
	$('#bulkeditcolumns').css('max-height', ht);
}

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

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

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

function setTableFontSize(fs)
{
	var hfs = fs-1;
	// Change the font size in the jqgrid (titlebar, grid and pager)
	$('.ui-jqgrid-btable').css('font-size', fs+'px');
	$('.ui-pg-table').css('font-size', fs+'px');
	$('.ui-jqgrid-htable').css('font-size', hfs+'px');
	$('.ui-search-input > input').css('font-size', fs+'px');
	// Change the Tab View font size.
	var tbfs = fs-1;
	$('#CategoryTabView').css('font-size', tbfs+'px');
	$('#DetailsTabView').css('font-size', tbfs+'px');
	
	$('.ui-jqdialog').css('font-size', fs+'px');
	$('.ui-autocomplete').css('font-size', fs+'px');
	
	if(getCookieInt('use_custom_font_family', 1))
		$('#content .ui-widget-content').css('font-family', "\'Droid Sans\',sans-serif");
}

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

function addCSVTableDownloadButton()
{
	$("#DomainTable").navSeparatorAdd("#DomainTablePager",{})
	.navButtonAdd('#DomainTablePager',
	{
		caption:"", 
		buttonicon:"ui-icon-arrowthickstop-1-s", 
		onClickButton: function()
		{ 
			$('#btn_mpanel-download').click();
			return false;
		}, 
		position:"last",
		title:'Download CSV...'
	});
}

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

function initCustomSQLTab()
{
	$('#customqueries-string').val(getCookie('customqueries-string', ""));
	$('#customqueries-customsql').val(getCookie('customqueries-customsql', ""));
	$('#customqueries-name').val(getCookie('customqueries-autoquery', ""));
		
	var turl = "lib/php/ajax/appsetup.php?gclcb&append=cq";
	var request = $.ajax({type: "POST",	url: turl});
	request.done(function(msg) 
	{  
		var x = jQuery.parseJSON(msg);
		if(x.validate == 1)
			sessionRestart("timeout");
		else if(x.validate == -1)
			sessionRestart("badsession");
		if(x.status == "ok")
		{
			$('#customqueries-categories').html(x.catlist);
			var catids = getCookie('customqueries-categories', "").split(",");
			for(i = 0; i < catids.length; i++)
			{
				var catid = "cq" + catids[i];
				$('#'+catid).prop('checked', true);
			}
			$('#cqselectall').change(function () 
			{
				$('.cq').each(function() 
				{
					$('#'+this.id).prop('checked', $('#cqselectall').is(':checked'));
				});
			});
			var availableTags = x.dfields;
			setupCustomQueryAutoComplete(availableTags);
		}
	});
	request.fail(function(jqXHR, textStatus) {});
}

/////////////////////////////////////////////////////////////////////////////////////////
//  MIT License : Copyright (c) 2014 johncarmichael

function setupCustomQueryAutoComplete(availableTags)
{
	var minWordLength = 2;
	function split(val) {
		return val.split(' ');
	}

	function extractLast(term) 
	{
		return split(term).pop();
	}
	$("#customqueries-customsql")
	// don't navigate away from the field on tab when selecting an item
	.bind("keydown", function(event) {
		if (event.keyCode === $.ui.keyCode.TAB && $(this).data("ui-autocomplete").menu.active) {
			event.preventDefault();
		}
	}).autocomplete({
		minLength: minWordLength,
		source: function(request, response) {
			// delegate back to autocomplete, but extract the last term
			var term = extractLast(request.term);
			if(term.length >= minWordLength){
				response($.ui.autocomplete.filter( availableTags, term ));
			}
		},
		focus: function() {
			// prevent value inserted on focus
			return false;
		},
		select: function(event, ui) {
			var terms = split(this.value);
			// remove the current input
			terms.pop();
			// add the selected item
			terms.push(ui.item.value);
			// add placeholder to get the comma-and-space at the end
			terms.push("");
			this.value = terms.join(" ");
			return false;
		}
	});
}

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

function centerDialog(dlgid)
{
	var dlgDiv = $("#"+dlgid);
	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";
}

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

function setGridDialogColors()
{
	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');
	$('.ui-jqdialog-content').css('background-color', bgcolor);
	$('.ui-jqdialog-content').css('color', color);
	$('.ui-jqdialog').css('border', '8px solid ' + abgcolor);
	$('.ui-jqdialog-content').css('border', '1px solid rgba(200,200,200,0.7)');
}

/////////////////////////////////////////////////////////////////////
// Will remove rtoken from the ids. catd23 will become 24

function getAllCategoryIDsFromList(listid, rtoken)
{
	var catids = "";
	$('#' + listid + ' input').each(function() 
	{
		var id = $(this).attr('id');
		if($('#'+id).is(':checked'))
		{
			if(catids != "")
				catids += ",";
			catids += id.replace(rtoken, '');
		}
	});
	
	return catids;
}

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

function setupTableColumns(listid, labelid, widthid, selid, sdmode)
{
	$( "#"+listid ).sortable();
		$( "#"+listid ).sortable({ handle: ".handle" })
		.selectable({
		selecting: function (e, ui) 
		{
            // force single selection
            $(e.target).find('.ui-selectee.ui-selecting').not(ui.selecting).removeClass('ui-selecting');
            $(e.target).find('.ui-selectee.ui-selected').not(ui.selecting).removeClass('ui-selected');
        },
		stop: function() 
		{
			$('#'+listid+' li').each(function() {
				$(this).removeClass('ui-state-highlight');
			});
			$( ".ui-selected", this ).each(function() 
			{
				var oldfield = current_dg_field_name;
				var oldlabel = $('#'+labelid).val();
				var oldwidth = $('#'+widthid).val();
				
				$('#'+labelid).val('');
				$('#'+widthid).val('');
				
				var sf = 'sfield';
				var gf = 'gfield';
				if(sdmode)
				{
					sf = 'sdsf';
					gf = 'sdgf';
				}
				$(this).addClass('ui-state-highlight');
				var field = $(this).text();
				var datastr = "slabel=" + encodeURIComponent(oldlabel) + "&swidth=" + oldwidth + "&" + sf + "=" + oldfield + "&" + gf + "=" + field;
				var turl = "lib/php/ajax/appsetup.php";

				current_dg_field_name = "";
				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");
					if(x.status == "done")
					{
						current_dg_field_name = field;
						$('#'+selid).html(field);
						$('#'+labelid).val(x.label);
						$('#'+widthid).val(x.width);
					}
				});
				request.fail(function(jqXHR, textStatus) {});
			});
		}
	})
    .find("li")
	.addClass( "ui-corner-all" );
}

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

function initEnterKeyHandler(inpdiv, trigid)
{
	$("#"+inpdiv).keydown(function(event) 
	{
		if(!HandleEnterKey(event, trigid))
			return false;
	});
}

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

function HandleEnterKey(e, submitid)
{
	var keycode = (e.keyCode ? e.keyCode : (e.which ? e.which : e.charCode));
	if (keycode == 13)
	{
		if(submitid != "")
			$("#" + submitid).click();
		return false;
	}
	return true;
}

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

function HandleEscapeKey(e)
{
	var hidden = 0;
	var keycode = (e.keyCode ? e.keyCode : (e.which ? e.which : e.charCode));
	if (keycode == 27)
	{
		for (index = 0; index < glb_menu_panels.length; ++index) 
		{
			if(hidePanelWithId(glb_menu_panels[index]))
			{
				e.stopPropagation();
				return false;
			}
		}
	}
	return true;
}

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

function gridSessionTimedoutError(jqXHR)
{
	if(jqXHR.status == 408 || jqXHR.status == 400)
	{
		if(jqXHR.status == 408)
			sessionRestart("timeout");
		else if(jqXHR.status == 400)
			sessionRestart("badsession");
		return true;
	}
	return false;
}

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

function sessionRestart(reason)
{
	var location = "login.php?r=" + reason;
	if(sub_domain_manager_mode)
		location += "&redir=sdmgr.php";
	window.location = location;
}

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

function sessionValidate(status)
{
	if(status == 1 || status == -1)
	{
		reason = (status == 1 ? "timeout" : "badsession");
		var location = "login.php?r=" + reason;
		if(sub_domain_manager_mode)
			location += "&redir=sdmgr.php";
		window.location = location;
		return false;
	}
	return true;
}

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

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

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

function SaveCustomQuery()
{
	var gurl = "lib/php/ajax/appsetup.php?" + ASA_SAVE_QUERY_AS_AUTOQUERY;
	var catids = getAllCategoryIDsFromList('customqueries-categories', 'cq');
	var query = $('#customqueries-customsql').val();
	var dstring = $('#customqueries-string').val();
	var aqname = $('#customqueries-name').val();
	var datastr = "&qs=" + encodeURIComponent(dstring);
	datastr += "&qcids=" + catids;
	datastr += "&q=" + encodeURIComponent(query);
	datastr += "&aqname=" + encodeURIComponent(aqname);
	$.cookie('customqueries-autoquery', aqname);
	$.ajax({
		type: 'POST',
		url: gurl,
		data: datastr,
		cache: false
	}).done(function(data) 
	{
		var x = jQuery.parseJSON(data);
		if(x.validate == 1)
			sessionRestart("timeout");
		else if(x.validate == -1)
			sessionRestart("badsession");
		else if(x.status != "ok")
		{
			custom_alert(x.message, x.heading);
		}
		else 
		{
			$("#DomainQueryTable").trigger("reloadGrid"); 
			custom_alert(x.message, "Success");
		}
	}
	).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");
	});
}

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

function initUploadDomainsBox()
{
	$('#dialog-csv-upload').dialog
	({
		resizable: false,
		autoOpen: false,
		width: 550,
		modal: true,
		dialogClass: 'dialogWithShadow',
		buttons: {
			Clear: function() {
				$("#csverrors").html("<p>&nbsp;</p>")
			},
			'Upload': function() {
				uploadCSVFile();
			},
			Close: function() {
				$(this).dialog('close');
			}
		}
	});
	
	$(document).on('change', '.btn-file :file', function() 
	{
		var filename = $('#csv_file').val();
		filename = filename.replace(/^.*[\\\/]/, '');
		$('#csv_name').val(filename);
	});
}

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

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

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

function onPanelButtonClick(btnid)
{
	if(!hidePanelWithId(btnid))
	{
		if($('#popmenu').is(':visible')) 
			$('.panel-outer').css('right', 48);
		else
			$('.panel-outer').css('right', 0);
		
		$('#'+btnid).show("drop",  {direction:'right'}, 200 );
		
		hideAllExcept(btnid);
	}
}

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

function addSubDomains()
{
	var data = encodeURIComponent($('#addsubd-data').val());
	var cid = getCookieInt('current_category', 0);
	var rowKey = jQuery("#DomainTable").getGridParam("selarrrow"); 
	if(sub_domain_manager_mode)
		rowKey = getUniqueSelectedDomainIds(false);
	var datastr = "data=" + data + "&sids=" + rowKey;
	var durl = 'lib/php/ajax/datagrid.php?sdmge&oper=add&cid=' + cid;
	if(data != "")
	{
		$.ajax({
			type: 'POST',
			url: durl,
			data: datastr,
			cache: false
		}).done(function(data) 
		{
			var x = jQuery.parseJSON(data);
			if(x.status == "ok")
			{
				if(x.added > 0)
				{
					$("#DomainTable").trigger("reloadGrid");
					hidePanelWithId('mpanel-addsubd');
				}
				else
					custom_alert("Nothing was added! Please enter full hostnames or (subdomain,domain) pairs.", "");
			}
			else
			{
			}
		}).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");
		});
	}
}

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

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

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

function onAfterProcessQueueWindowPopup()
{
	if(pqCloseTimer != null)
		clearTimeout(pqCloseTimer);
	pqCloseTimer = null;
	$('#processqueue-error').html('<img src=\"lib/css/images/16/wheel-loader.gif\">');
	$('#pqp-queuesize').html('');
	$('#pqp-processed').html('');
	$('#pqp-startfrom').html('');
	$('#pqp-maxcount').html('');
	$('#pqp-exectime').html('');
	$('#runqinfo').hide();
		
	var turl = "runq.php?ajax";
	var request = $.ajax({type: "POST",	url: turl});
	request.done(function(msg) 
	{  
		var x = jQuery.parseJSON(msg);
		if(x.validate == 1)
			sessionRestart("timeout");
		else if(x.validate == -1)
			sessionRestart("badsession");
		$('#pqp-queuesize').html(x.queuesize);
		$('#pqp-processed').html(x.processed);
		$('#pqp-startfrom').html(x.startfrom);
		$('#pqp-maxcount').html(x.maxcount);
		$('#pqp-exectime').html(x.exectime);
		$('#processqueue-error').html('Done. This panel will close in 5 seconds.');
		$('#runqinfo').show();
		show_queue_count(0);
		if(x.processed)
			$("#DomainTable").trigger("reloadGrid"); 
		pqCloseTimer = setTimeout(function(){hidePanelWithId("processqueue");},5000);
	});
	request.fail(function(jqXHR, textStatus) {});
}

function show_queue_count(swipein) 
{
	var gurl = base_grid_ajax_url + "?gqi";
	if(!swipein)
		gurl += "&nsi";
	$.ajax({
		type: 'POST',
		url: gurl,
		cache: false
	}).done(function(data) {
		var x = jQuery.parseJSON(data);
		if(x.validate == 1)
			sessionRestart("timeout");
		else if(x.validate == -1)
			sessionRestart("badsession");
		else
		{
			$("#qs-all").html(x.queue_size);
			$("#server_time").html(x.server_time);
			$("#queue_last_proc").html(x.last_queue_proc);
			$("#qs-dw").html(x.dw_size);
			$("#qs-sdw").html(x.sdw_size);
			$("#qs-ipw").html(x.ipw_size);
			$("#qs-alexa").html(x.alexa_size);
			$("#qs-ip").html(x.ip_size);
			$("#qs-gpr").html(x.gpr_size);
			$("#qs-dns").html(x.dns_size);
			$("#qs-gi").html(x.gi_size);
			$("#qs-ping").html(x.ping_size);
			$("#qs-http").html(x.http_size);
			$("#qs-mx").html(x.mx_size);
			$("#qs-ssl").html(x.ssl_size);
			$("#timeout").html(x.timeout);
			$("#server_time_zone").html(x.server_time_zone);
			
			$("#luqw-dw").attr('disabled', (x.dw_size > 0) ? false : true);
			$("#luqw-sdw").attr('disabled', (x.sdw_size > 0) ? false : true);
			$("#luqw-mx").attr('disabled', (x.mx_size > 0) ? false : true);
			$("#luqw-ssl").attr('disabled', (x.ssl_size > 0) ? false : true);
			$("#luqw-ip").attr('disabled', (x.ip_size > 0) ? false : true);
			$("#luqw-ipw").attr('disabled', (x.ipw_size > 0) ? false : true);
			$("#luqw-gpr").attr('disabled', (x.gpr_size > 0) ? false : true);
			$("#luqw-gi").attr('disabled', (x.gi_size > 0) ? false : true);
			$("#luqw-ping").attr('disabled', (x.ping_size > 0) ? false : true);
			$("#luqw-http").attr('disabled', (x.http_size > 0) ? false : true);
			$("#luqw-alexa").attr('disabled', (x.alexa_size > 0) ? false : true);
			$("#luqw-dns").attr('disabled', (x.dns_size > 0) ? false : true);
		}
	}
	).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");
	});
}

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

function initUISetup()
{
	if(getCookieInt('use_custom_font_family', 1))
		$('#useCustomFont').prop('checked', true);
	else
		$('#useCustomFont').prop('checked', false);
	
	if(getCookieInt("footer", 1))
		$('#showfooter').prop('checked', true);
	else
	{
		$('#showfooter').prop('checked', false);
		$('#footer').hide();
	}
	
	if(getCookieInt("domaingrid_auto_width", 1))
		$('#gridautowidth').prop('checked', true);
	else
		$('#gridautowidth').prop('checked', false);
	
	$('#highlight-status-codes').val(highlight_status_codes);
	$('#highlight-status-codes-submit').click(function(event) {setHighlightStatusCodes();});
	initEnterKeyHandler('highlight-status-codes', 'highlight-status-codes-submit');
	initEnterKeyHandler('domdateformat', 'setdomdateformat');
	
	$('#domdateformat').val(domtable_date_format);
	$('#setdomdateformat').click(function(event) {setDomainTableDateFormat();});
	
	var fs = getCookieInt("table-font-size", DEFAULT_TABLE_FONT_SIZE);
	$("#table-font-size-slider").slider({
		min: 1,
		max: 6,
		value: fs-10,
		change: function(event, ui) 
		{
			var srow = domain_table_jqgrid.jqGrid ('getGridParam', 'selrow');
			var fs = ui.value + 10;
			setTableFontSize(fs);
			saveCookie("table-font-size", fs);
			fixDivSizes();
			scrollToRow($("#DomainTable"), srow);
			setTimeout(function(){fixDivSizes();}, 50);
        }
	});
	
	var exphd = getCookieInt("domain_highlight_days", 30);
	$('#exp-alert-days').html(exphd);
	$('#expiry-highlight-days-slider').slider({
		min: 7,
		max: 180,
		value: exphd,
		change: function(event, ui) 
		{
			var exphd = ui.value;
			$('#exp-alert-days').html(exphd);
			saveCookie("domain_highlight_days", exphd);
			var durl = '';
			if(sub_domain_manager_mode)
				durl = getDomainDataURL();
			else
				durl = getDomainDataURL(getColModelFromGroupName(getCookie('display-group', "date_columns_array")));
			jQuery("#DomainTable").setGridParam({url:durl});
			$("#DomainTable").trigger("reloadGrid"); 
		}
	});
	
	$('#showfooter').click(function(event)
	{
		if($('#showfooter').prop('checked'))
		{
			$('#footer').show();
			saveCookie("footer", 1);
		}
		else
		{
			$('#footer').hide();
			saveCookie("footer", 0);
		}
		fixDivSizes();
	});
	
	$('#gridautowidth').click(function(event)
	{
		if($('#gridautowidth').prop('checked'))
			saveCookie("domaingrid_auto_width", 1);
		else
			saveCookie("domaingrid_auto_width", 0);
		fixDivSizes();
	});
	
	$('#useCustomFont').click(function(event)
	{
		if($('#useCustomFont').prop('checked'))
			saveCookie("use_custom_font_family", 1);
		else
			saveCookie("use_custom_font_family", 0);
		location.reload();
	});
	
	$('#themes_list').on('change', function() 
	{
		var ntheme = this.value;
		selectNewTheme(ntheme);
	});
}

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

function reloadGrid()
{
	$("#DomainTable").trigger("reloadGrid");
}

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

function reloadPage()
{
	location.reload();
}

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

function setMasterOptionAndReload(key, value)
{
	setMasterOptionAndCall(key, value, reloadPage);
}

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

function setMasterOptionAndCall(key, value, callbackfunc)
{
	var durl = "lib/php/ajax/appsetup.php";
	var datastr = 'value=' + encodeURIComponent(value) + "&opset=" + encodeURIComponent(key);
	$.ajax({
			type: 'POST',
			url: durl,
			data: datastr,
			cache: false
		}).done(function(data) 
		{
			var x = jQuery.parseJSON(data);
			if(x.validate == 1)
				sessionRestart("timeout");
			else if(x.validate == -1)
				sessionRestart("badsession");
			else if(x.status == "ok")
				callbackfunc();
		}).fail(function(jqXHR,status, errorThrown) 
		{
			console.log(errorThrown);
			console.log(jqXHR.responseText);
			console.log(jqXHR.status);
			if(jqXHR.status == 403)
				custom_alert("Permission denied.", "Problem");
		});
}

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

function selectNewTheme(ntheme)
{
	setMasterOptionAndReload('ui_theme', ntheme);
}

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

function onAfterBulkEditWindowPopup(editcolumn)
{
	if(!sub_domain_manager_mode)
		showSelectedDomains(10);
	else
		showSelectedSubdomains(10);
	
	$('#bulkedit-column').html('');
	$('#bulkedit-value').val('');
	
	positionBulkEditWindow();
	var gurl = "lib/php/ajax/appsetup.php?";
	if(sub_domain_manager_mode)
		gurl += ASA_GET_EDITABLE_SUBDOMAIN_COLUMNS;
	else
		gurl += ASA_GET_EDITABLE_DOMAIN_COLUMNS;
	$.ajax({
		type: 'POST',
		url: gurl,
		cache: false
	}).done(function(data) {
		var x = jQuery.parseJSON(data);
		if(x.validate == 1)
			sessionRestart("timeout");
		else if(x.validate == -1)
			sessionRestart("badsession");
		else
		{
			$('#bulkeditcolumns').html(x.columnlist);
			makeBulkEditListSelectable();
			if(editcolumn != "")
			{
				$('#bulkeditcolumns li').each(function() 
				{
					if($.text([this]) === editcolumn)
					{
						$(this).addClass('ui-state-highlight');
						$('#bulkedit-column').html($(this).text());
						$('#bulkeditcolumns').scrollTop($(this).position().top);
						$('#bulkedit-value').focus();
						var eval = decodeURIComponent($('#edit-detailv-' + editcolumn).val());
						$('#bulkedit-value').val(eval);
					}
					else
						$(this).removeClass('ui-state-highlight');
				});
			}
		}
	}
	).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");
	});
}

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

function makeBulkEditListSelectable()
{
	$( "#bulkeditcolumns" ).selectable(
	{
		stop: function() 
		{
			$('#bulkeditcolumns li').each(function() {
				$(this).removeClass('ui-state-highlight');
			});
			$( ".ui-selected", this ).each(function() 
			{
				$(this).addClass('ui-state-highlight');
				$('#bulkedit-column').html($(this).text());
			});
		},
		selecting: function (e, ui) {
            // force single selection
            $(e.target).find('.ui-selectee.ui-selecting').not(ui.selecting).removeClass('ui-selecting');
            $(e.target).find('.ui-selectee.ui-selected').not(ui.selecting).removeClass('ui-selected');
        }
    });
}

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

function bulkEditResetManEdit()
{
	var rowkey = jQuery("#DomainTable").getGridParam("selarrrow"); 
	var gurl = "lib/php/ajax/appsetup.php";
	var datastr = ASA_RESET_DOMAIN_MANUAL_EDIT;
	if(sub_domain_manager_mode)
		datastr = ASA_RESET_SUBDOMAIN_MANUAL_EDIT;
	datastr += "=" + rowkey;
	$.ajax({
		type: 'POST',
		data: datastr,
		url: gurl,
		cache: false
	}).done(function(data) {
		var x = jQuery.parseJSON(data);
		if(x.validate == 1)
			sessionRestart("timeout");
		else if(x.validate == -1)
			sessionRestart("badsession");
		else
		{
			if(x.count)
			{
				saveRowIdsForReload();
				$("#DomainTable").trigger("reloadGrid"); 
				hidePanelWithId("mpanel-bulkedit");
			}
		}
	}
	).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");
	});
}

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

function bulkEditSubmit()
{
	var value = $('#bulkedit-value').val();
	var field = $('#bulkedit-column').text();
	if(field != "")
	{
		var rowkey = jQuery("#DomainTable").getGridParam("selarrrow"); 
		var gurl = "lib/php/ajax/appsetup.php";
		var datastr = ASA_BULK_EDIT_COLUMN;
		if(sub_domain_manager_mode)
			datastr = ASA_BULK_EDIT_SD_COLUMN;
		datastr += "=" + encodeURIComponent(field) + "&v=" + encodeURIComponent(value);
		datastr += "&ids=" + rowkey;
		$.ajax({
			type: 'POST',
			data: datastr,
			url: gurl,
			cache: false
		}).done(function(data) {
			var x = jQuery.parseJSON(data);
			if(x.validate == 1)
				sessionRestart("timeout");
			else if(x.validate == -1)
				sessionRestart("badsession");
			else
			{
				if(x.status == "ok")
				{
					saveRowIdsForReload();
					$("#DomainTable").trigger("reloadGrid"); 
					hidePanelWithId("mpanel-bulkedit");
				}
				else
				{
					$('#bulkedit-error').html(x.error);
				}
			}
		}
		).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
		custom_alert("Please select a column to edit", "Problem");
}

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

function stopIfNotEnoughDomainsSelected(single, errormsg)
{
	var rowKey = jQuery("#DomainTable").getGridParam("selarrrow"); 
	if(rowKey.length == 1 && single)
		return true;
	else if(rowKey.length > 0 && !single)
		return true;
	else
	{
		custom_alert(errormsg, "Problem");
		return false;
	}
}

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

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

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

function DoLookups()
{
	var luw = 0;
	luw |= $('#luwhois').is(':checked') ? LOOKUP_DOMAIN_WHOIS : 0;
	luw |= $("#ludns").is(':checked') ? LOOKUP_DOMAIN_IP : 0;
	luw |= $("#luhttp").is(':checked') ? LOOKUP_HTTP_HOMEPAGE : 0;
	luw |= $("#lualexa").is(':checked') ? LOOKUP_ALEXA_DATA : 0;
	luw |= $("#lugpr").is(':checked') ? LOOKUP_GOOGLE_PR : 0;
	luw |= $("#lumx").is(':checked') ? LOOKUP_MX_RECORDS : 0;
	luw |= $("#luping").is(':checked') ? LOOKUP_PING_RESPONSE : 0;
	luw |= $("#luipwhois").is(':checked') ? LOOKUP_IP_WHOIS : 0;
	luw |= $("#lugindex").is(':checked') ? LOOKUP_GOOGLE_INDEX : 0;
	luw |= $("#lusubdom").is(':checked') ? LOOKUP_SUB_DOMAINS : 0;
	luw |= $("#lussl").is(':checked') ? LOOKUP_SSL_CERTS : 0;
	var luint = $("#luint").val();
	if(luint == "")
		luint = 1440;
	$('#lookup-error').html('');
	if(luw != 0)
	{	
		if(luint < 0)
			luint = 1440;
		var rowKey = jQuery("#DomainTable").getGridParam("selarrrow"); 
		if(sub_domain_manager_mode)
			rowKey = getUniqueSelectedDomainIds(false);
		var turl = base_grid_ajax_url + "?" + DGA_DOMAIN_LOOKUP;
		var datastr = "what=" + luw + "&id=" + rowKey + "&ri=" + luint;
		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");
			if(x.status == "done" && x.lucount > 0)
				hidePanelWithId("mpanel-lookup");
			else if(x.status == "done" && x.lucount == 0)
				$('#lookup-error').html("<p style=\"margin-bottom:0;\" class=\"ui-state-error ui-corner-all\">Nothing queued. The domain may already be in queue, otherwise change the minimum refresh interval to force.</p>");
			else
				$('#lookup-error').html("<p style=\"margin-bottom:0;\" class=\"ui-state-error ui-corner-all\">" + x.msg + "</p>");
			show_queue_count(1);
		});
		request.fail(function(jqXHR, textStatus) 
		{
		});
	}
	else
		$('#lookup-error').html('<p class=\"ui-state-error ui-corner-all\">Nothing to do!</p>');
}

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

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

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

function moveCategoryUpDown(incr)
{
	var cid = getCookieInt('current_category', 0);
	
	if(cid != 0 && cid != 1)
	{
		$.ajax({
			type: "POST",
			cache: false,
			url: base_grid_ajax_url,
			data: "oc=" + cid + "&i=" + incr,
			success: function(html)
			{
				var x = jQuery.parseJSON(html);
				if(x.validate == 1)
					sessionRestart("timeout");
				else if(x.validate == -1)
					sessionRestart("badsession");
				$("#DomainCategoryTable").trigger("reloadGrid"); 
				$("#DomainCategoryTable").setSelection(cid, false);
			},
			error: function(XMLHttpRequest, textStatus, errorThrown) 
			{ 
				if(XMLHttpRequest.status == 403)
					alert("Access Denied! No permission.");
				else if(!gridSessionTimedoutError(XMLHttpRequest.status))
					alert("Error: " + errorThrown + ', ' + textStatus); 
			} 
		});
	}
}

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

function onAfterCategorizeWindowPopup()
{
	showSelectedDomains(10);
	
	var gurl = "lib/php/ajax/appsetup.php?gclcb&append=catd";
	$.ajax({
		type: 'POST',
		url: gurl,
		cache: false
	}).done(function(data) {
		var x = jQuery.parseJSON(data);
		if(x.validate == 1)
			sessionRestart("timeout");
		else if(x.validate == -1)
			sessionRestart("badsession");
		else
		{
			$('#categorize-category').html(x.catlist);
			
			$('#catdselectall').change(function () 
			{
				$('.catd').each(function() 
				{
					$('#'+this.id).prop('checked', $('#catdselectall').is(':checked'));
				});
			});
		}
	}
	).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");
	});
}

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

function addToCategories()
{
	$('#categorize-error').html("");
	var catids = getAllCategoryIDsFromList('categorize-category', 'catd');
	var rowkey = jQuery("#DomainTable").getGridParam("selarrrow"); 
	if(sub_domain_manager_mode)
		rowkey = getUniqueSelectedDomainIds(false);
	var gurl = "lib/php/ajax/appsetup.php";
	var datastr = ASA_ADD_TO_CATEGORIES + "=" + catids + "&id=" + rowkey;
	$.ajax({
		type: 'POST',
		url: gurl,
		data: datastr,
		cache: false
	}).done(function(data) 
	{
		var x = jQuery.parseJSON(data);
		if(x.validate == 1)
			sessionRestart("timeout");
		else if(x.validate == -1)
			sessionRestart("badsession");
		else if(x.status == "notok")
			$('#categorize-error').html("Nothing changed");
		else
		{
			hidePanelWithId("mpanel-categorize");
			highlightCategoriesOfCurrentDomain();
		}
	}
	).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");
	});
}

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

function removeFromCategories()
{
	var catids = getAllCategoryIDsFromList('categorize-category', 'catd');
	var rowkey = jQuery("#DomainTable").getGridParam("selarrrow"); 
	if(sub_domain_manager_mode)
		rowKey = getUniqueSelectedDomainIds(false);
	var gurl = "lib/php/ajax/appsetup.php";
	var datastr = ASA_REMOVE_FROM_CATEGORIES + "=" + catids + "&id=" + rowkey;
	$.ajax({
		type: 'POST',
		url: gurl,
		data: datastr,
		cache: false
	}).done(function(data) {
		var x = jQuery.parseJSON(data);
		if(x.validate == 1)
			sessionRestart("timeout");
		else if(x.validate == -1)
			sessionRestart("badsession");
		else if(x.status == "notok")
			$('#categorize-error').html("Nothing changed");
		else
		{
			hidePanelWithId("mpanel-categorize");
			$("#DomainTable").trigger("reloadGrid"); 
			highlightCategoriesOfCurrentDomain();
		}
	}
	).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");
	});
}

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

function highlightCategoriesOfCurrentDomain()
{
	var selid = 0;
	if(sub_domain_manager_mode)
		selid = getSingleUniqueSelectedDomainId();
	else
	{
		var selids = jQuery("#DomainTable").getGridParam("selarrrow"); 
		selid = (selids.length == 1 ? selids[0] : 0);
	}
	var ids = jQuery("#DomainCategoryTable").jqGrid('getDataIDs');
	if(selid > 0)
	{
		$.ajax({
			type: "GET",
			cache: false,
			url: base_grid_ajax_url + '?' + GET_CATEGORIES_FOR_DOMAIN + '=' + selid,
			success: function(html)
			{
				var x = jQuery.parseJSON(html);
				if(x.validate == 1)
					sessionRestart("timeout");
				else if(x.validate == -1)
					sessionRestart("badsession");
				else
				{
					var thelist = x.cids;
					var catArray = thelist.map(Number);
					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");
		}
	}
}

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

function setMasterOption(okey, ovalue)
{
	if (!$("#appsetup-error").css('visibility') !== 'hidden')
		$("#appsetup-error").html('');
	var durl = "lib/php/ajax/appsetup.php";
	var datastr = 'value=' + encodeURIComponent(ovalue) + "&opset=" + encodeURIComponent(okey);
	$.ajax(
	{
		type: 'POST',
		url: durl,
		data: datastr,
		cache: false
	}
	).done(function(data) 
	{
		var x = jQuery.parseJSON(data);
		if(x.validate == 1)
			sessionRestart("timeout");
		else if(x.validate == -1)
			sessionRestart("badsession");
		else if(x.status == "ok")
		{
			if (!$("#appsetup-error").css('visibility') !== 'hidden')
				$("#appsetup-error").html('ok');
		}
		else
		{
			if (!$("#appsetup-error").css('visibility') !== 'hidden')
				$("#appsetup-error").html('Error');
		}
	}).fail(function(jqXHR, status, errorThrown) 
	{
		console.log(errorThrown);
		console.log(jqXHR.responseText);
		console.log(jqXHR.status);
		if(jqXHR.status == 403)
			custom_alert("Permission denied.", "Problem");
	});
}

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

function saveColumnLabelAndWidth(gfield, sfield, slabel, swidth, sdmode)
{
	var sf = 'sfield';
	var gf = 'gfield';
	if(sdmode)
	{
		sf = 'sdsf';
		gf = 'sdgf';
	}
	var datastr = "slabel=" + encodeURIComponent(slabel) + "&swidth=" + swidth + "&" + sf + "=" + sfield + "&" + gf + "=" + gfield;
	var turl = "lib/php/ajax/appsetup.php";
	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");
		if(x.status == "done")
		{
		}
	});
	request.fail(function(jqXHR, textStatus) {});
}

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

function setDomainTableDateFormat()
{
	var ddate = encodeURIComponent($('#domdateformat').val());
	if(ddate != "")
	{
		var durl = "lib/php/ajax/appsetup.php";
		var datastr = 'value=' + ddate + "&opset=" + 'cell_date_format';
		$.ajax(
		{
			type: 'POST',
			url: durl,
			data: datastr,
			cache: false
		}
		).done(function(data) 
		{
			var x = jQuery.parseJSON(data);
			if(x.validate == 1)
				sessionRestart("timeout");
			else if(x.validate == -1)
				sessionRestart("badsession");
			else if(x.status == "ok")
			{
				location.reload();
			}
		}).fail(function(jqXHR, status, errorThrown) 
		{
			console.log(errorThrown);
			console.log(jqXHR.responseText);
			console.log(jqXHR.status);
			if(jqXHR.status == 403)
				custom_alert("Permission denied.", "Problem");
		});
	}
}

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

function setHighlightStatusCodes()
{
	var hs = $('#highlight-status-codes').val();
	if(sub_domain_manager_mode == false)
		setMasterOptionAndCall('highlight_status_codes', hs, reloadGrid);
	else
		setMasterOption('highlight_status_codes', hs);
}

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

function addPopOversInPopMenu()
{
	$('#popmenu').find('a').each(function() 
	{
		var bid = $(this).attr('id');
		var title = $('#' + bid).find("img").attr('title');
		$('#' + bid).find("img").removeAttr("title");
		$('#' + bid).popover({content: title, container: 'body', placement: 'left', trigger: 'hover'});
	});
	$('.user-cat-hint').popover({title: "Important", content: "The domain table will be <b>empty</b> for non-admin users if you don't pick any category here or if the picked categories don't contain any domains.", container: 'body', placement: 'top', trigger: 'hover', html: true});
}

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