$(function()
{
	$('#addtocategories').click(function(event) {event.preventDefault(); addToCategories();});
	$('#removefromcategories').click(function(event) {event.preventDefault(); removeFromCategories();});
	$('#bulkedit-submit').click(function(event) {event.preventDefault(); bulkEditSubmit();});
	$('#bulkedit-resetmanedit').click(function(event) {event.preventDefault(); bulkEditResetManEdit();});
	
	$("#insertcolumn").click(function(event) {event.preventDefault(); insertCustomColumn();});
	$("#deletecolumn").click(function(event) {event.preventDefault(); deleteCustomColumn();});
	$("#ludomains").click(function(event) {event.preventDefault(); DoLookups();});
	$('#parsewhois').click(function(event) {event.preventDefault(); parseWhois();});
	
	$("#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);
		fillColumnNameRowsForColumnSetup(getCookie('display-group', "date_columns_array"));
	});
	
	$('#ui_display_column_reset').click(function(event)
	{
		updateDisplayColumns(true);
		fillColumnNameRowsForColumnSetup(getCookie('display-group', "date_columns_array"));
	});
	
	$('#ui_display_dnscol_update').click(function(event)
	{
		updateDNSColumns(false);
		onAfterDNSColumnSetupWindowPopup();
	});
	
	$('#ui_display_dnscol_reset').click(function(event)
	{
		updateDNSColumns(true);
		onAfterDNSColumnSetupWindowPopup();
	});
	
	$('#ui_display_sslcol_update').click(function(event)
	{
		updateSSLColumns(false);
		onAfterSSLColumnSetupWindowPopup();
	});
	
	$('#ui_display_sslcol_reset').click(function(event)
	{
		updateSSLColumns(true);
		onAfterSSLColumnSetupWindowPopup();
	});
	
	setupTableColumns('tablecolumns', 'column_label', 'column_width', 'selectedcolumn', sub_domain_manager_mode);
	setupTableColumns('dnstablecols', 'dnscol_label', 'dnscol_width', 'selecteddnscol', true);
	setupTableColumns('ssltablecols', 'sslcol_label', 'sslcol_width', 'selectedsslcol', true);
});

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

function getRegistrarAlias(sid)
{
	$("#regalias-realname").html("Please wait");
	$("#regalias-error").html("");
	$("#alias").val('');
	var turl = "lib/php/ajax/appsetup.php" + "?gra=" + sid;
	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 == "done")
		{
			$("#regalias-realname").html(x.registrar);
			$("#alias").val(x.alias);
			$("#setalias").prop('disabled', false);
			$("#alias").focus();
		}
		else
		{
			$("#regalias-realname").html('?');
			$("#setalias").prop('disabled', true);
			$("#regalias-error").html("Unable to find the registrar's name. You can't set an alias at this time.");
		}
	});
	request.fail(function(jqXHR, textStatus) {});
}

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

function setRegistrarAlias(sid, newalias)
{
	var turl = "lib/php/ajax/appsetup.php" + "?sra=" + sid + "&alias=" + newalias;
	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 == "done")
		{
			$("#regalias-error").html(x.status);
			setLocalRegistrarAlias(x.registrar, x.alias);
			if(hasColumnInModel("registrar"))
			{
				$("#DomainTable").trigger('reloadGrid');
			}
			hidePanelWithId("mpanel-regalias");
		}
		else
			$("#regalias-error").html(x.status);
	});
	request.fail(function(jqXHR, textStatus) 
	{
		if(jqXHR.status == 403)
			custom_alert("Access Denied! No permission to edit.", "Problem");
	});
}

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

function setLocalRegistrarAlias(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].toUpperCase() == registrar.toUpperCase())
			{
				registrar_aliases[i*2+1] = (alias == "" ? registrar : 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 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_DOMAIN_CSV_UPLOAD + '&cid=' + cid,
			data: data,
			cache: false,
			contentType: false,
			processData: false
		}).done(function(data) 
		{
			var x = jQuery.parseJSON(data);
			$("#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 parseWhois()
{
	var selids = jQuery("#DomainTable").getGridParam("selarrrow"); 
	var datastr = "pwa=" + selids;
	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 == "ok")
		{
			saveRowIdsForReload();
			$("#DomainTable").trigger("reloadGrid");
		}
	});
	request.fail(function(jqXHR, textStatus) {});
}

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

function whoisSetupXlateSubmit()
{
	var server = $('#whoisdiag-server').val();	
	var datastr = DGA_SET_TLD_INFO + "=" + server;
	datastr += '&xlate=' + encodeURIComponent($('#whoissetup-xlate').val());
	setupWhoisServerData(datastr);
}

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

function setupWhoisServerData(datastr)
{
	$('#whoissetup-messages').html('');
	var turl = "lib/php/ajax/datagrid.php";
	$.ajax(
	{
		type: 'POST',
		url: turl,
		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");
		if(x.status == "ok")
		{
		}
	}).fail(function(jqXHR,status, errorThrown) 
	{
		console.log(errorThrown);
		console.log(jqXHR.responseText);
		console.log(jqXHR.status);
		$('#whoissetup-messages').html(jqXHR.responseText);
	});
}

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

function saveServerForTLD()
{
	$('#whoissetup-messages').html('');
	var tld = $('#whoisdiag-tld').val();	
	var server = $('#whoisdiag-server').val();
	if(tld != '' && server != '')
	{
		var turl = "lib/php/ajax/datagrid.php";
		var datastr = DGA_SET_SERVER_FOR_TLD + '=' + encodeURIComponent(tld) + "&server=" + encodeURIComponent(server);
		$.ajax(
		{
			type: 'POST',
			url: turl,
			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");
			if(x.status == "ok")
			{
				$('#whoissetup-messages').html('done');
			}
		}).fail(function(jqXHR,status, errorThrown) 
		{
			console.log(errorThrown);
			console.log(jqXHR.responseText);
			console.log(jqXHR.status);
			$('#whoissetup-messages').html(jqXHR.responseText);
		});
	}
}

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

function whoisSetupTLDAndServer()
{
	$('#whoissetup-messages').html('');
	var tld = $('#whoisdiag-tld').val();	
	var server = $('#whoisdiag-server').val();
	if(tld != '' && server != '')
	{
		var durl = base_grid_ajax_url;
		var datastr = DGA_GET_TLD_INFO + '=' + encodeURIComponent(tld);
		$.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.whoisserver !== server)
				{
					alert_and_exec('Set whois server for ' + tld + ' to ' + server + "?", saveServerForTLD);
				}
			}
		}).fail(function(jqXHR,status, errorThrown) 
		{
		});
	}
}

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

function whoisSetupSubmit()
{
	var server = $('#whoisdiag-server').val();	
	var datastr = DGA_SET_TLD_INFO + "=" + server;
	datastr += '&query=' + encodeURIComponent($('#whoissetup-querystring').val());
	datastr += '&port=' + encodeURIComponent($('#whoissetup-port').val());
	datastr += '&searchtoken=' + encodeURIComponent($('#whoissetup-searchtoken').val());
	datastr += '&bannedtext=' + encodeURIComponent($('#whoissetup-bannedtext').val());
	datastr += '&conninterval=' + encodeURIComponent($('#whoissetup-conninterval').val());
	datastr += '&dateformat=' + encodeURIComponent($('#whoissetup-dateformat').val());
	datastr += '&proxy=' + encodeURIComponent($('#whoissetup-proxy').val());
	var ovalue = $('#whoissetup-stopconn').prop('checked') ? 1 : 0;
	datastr += '&stop_lookups=' + ovalue;
	setupWhoisServerData(datastr);
}

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

function whoisSetupResetConnectTime()
{
	var server = $('#whoisdiag-server').val();	
	var datastr = DGA_SET_TLD_INFO + "=" + server;
	datastr += '&last_connect_at=' + encodeURIComponent('null');
	setupWhoisServerData(datastr);
}

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

function whoisSetupServerCheck()
{
	$('#whoissetup-messages').html('Getting Information');
	var server = $.trim($("#whoisdiag-server").val());
	if(server != "")
	{
		$('#whoisdiag-tld').val('');
		var durl = base_grid_ajax_url;
		var datastr = DGA_GET_SERVER_INFO + '=' + encodeURIComponent(server);
		$.ajax(
		{
			type: 'POST',
			url: durl,
			data: datastr,
			cache: false
		}).done(function(data) 
		{
			$('#whoissetup-messages').html('');
			var x = jQuery.parseJSON(data);
			if(x.validate == 1)
				sessionRestart("timeout");
			else if(x.validate == -1)
				sessionRestart("badsession");
			else
			{
				$('#whoisdiag-server').val(x.whoisserver);
				if(x.whoisserver !== "")
				{
					$('#whoissetup-port').val(x.port);
					$('#whoissetup-querystring').val(x.query);
					$('#whoissetup-searchtoken').val(x.searchtoken);
					$('#whoissetup-dateformat').val(x.dateformat);
					$('#whoissetup-conninterval').val(x.conninterval);
					$('#whoissetup-proxy').val(x.proxy);
					$('#whoissetup-bannedtext').val(x.bannedtext);
					$('#whoissetup-xlate').val(x.xlate);
					$('#whoissetup-lastconnectat').html(x.lastconnectat);
					$('#whoissetup-stopconn').prop('checked', x.stop_lookups == "1" ? true : false);
				}
			}
		}).fail(function(jqXHR,status, errorThrown) 
		{
			console.log(errorThrown);
			console.log(jqXHR.responseText);
			console.log(jqXHR.status);
		});
	}
}

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

function whoisSetupTLDCheck()
{
	$('#tldregistry').html('');
	var tld = $.trim($("#whoisdiag-tld").val());
	if(tld != "")
	{
		$('#whoissetup-messages').html('Trying to find whois server');
		$("#whoisdiag-server").val('');
		var durl = base_grid_ajax_url;
		var datastr = DGA_GET_TLD_INFO + '=' + encodeURIComponent(tld);
		$.ajax(
		{
			type: 'POST',
			url: durl,
			data: datastr,
			cache: false
		}).done(function(data) 
		{
			$('#whoissetup-messages').html('');
			var x = jQuery.parseJSON(data);
			if(x.validate == 1)
				sessionRestart("timeout");
			else if(x.validate == -1)
				sessionRestart("badsession");
			else
			{
				$('#whoisdiag-server').val(x.whoisserver);
				if(x.whoisserver !== "")
				{
					$('#whoissetup-port').val(x.port);
					$('#whoissetup-querystring').val(x.query);
					$('#whoissetup-searchtoken').val(x.searchtoken);
					$('#whoissetup-dateformat').val(x.dateformat);
					$('#whoissetup-conninterval').val(x.conninterval);
					$('#whoissetup-proxy').val(x.proxy);
					$('#whoissetup-bannedtext').val(x.bannedtext);
					$('#whoissetup-xlate').val(x.xlate);
					$('#whoissetup-lastconnectat').html(x.lastconnectat);
					$('#whoissetup-stopconn').prop('checked', x.stop_lookups == "1" ? true : false);
				}
			}
		}).fail(function(jqXHR,status, errorThrown) 
		{
			console.log(errorThrown);
			console.log(jqXHR.responseText);
			console.log(jqXHR.status);
		});
	}
}

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

function fillColumnNameRowsForColumnSetup(dgroup)
{
	$('#column_label').val('');
	$('#column_width').val('');
	current_dg_field_name = "";
	$('#selectedcolumn').html('-');
	$('#tablecolumns').html("Please Wait");
	
	var durl = 'lib/php/ajax/appsetup.php';
	var datastr = 'dgroup=' + dgroup;
	$.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("session");
			$('#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 onAfterDNSColumnSetupWindowPopup()
{
	$('#dnscol_label').val('');
	$('#dnscol_width').val('');
	current_dg_field_name = "";
	$('#selecteddnscol').html('-');
	$('#dnstablecols').html("Please Wait");
	
	var durl = 'lib/php/ajax/appsetup.php?dnscol';
	$.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");
			$('#dnstablecols').html(x.data);
			$('#dnscolsetup-title').html(x.title);
		}).fail(function(jqXHR,status, errorThrown) 
		{
			console.log(errorThrown);
			console.log(jqXHR.responseText);
			console.log(jqXHR.status);
		});
}

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

function onAfterSSLColumnSetupWindowPopup()
{
	$('#sslcol_label').val('');
	$('#sslcol_width').val('');
	current_dg_field_name = "";
	$('#selectedsslcol').html('-');
	$('#ssltablecols').html("Please Wait");
	
	var durl = 'lib/php/ajax/appsetup.php?sslcol';
	$.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");
			$('#ssltablecols').html(x.data);
			$('#sslcolsetup-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 += "dgset=" + getCookie('display-group', "date_columns_array");
	}
	else
		turl += "dgreset=" + getCookie('display-group', "date_columns_array");

	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?dgget=" + getCookie('display-group', "date_columns_array");
		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");
			columns_array = x2.colmodel;
			changeCurrentColumnModel(columns_array);
			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 updateDNSColumns(setdefault)
{
	var checkedIds = $("#dnstablecols :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=dns_subgrid_columns";
	}
	else
		turl += "sdcolreset=dns_subgrid_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=dns_subgrid_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");
			subdomaingrid_columns_array = x2.colmodel;
			LoadSubdomainGrid(true);
		});
		
	});
	request.fail(function(jqXHR, textStatus) 
	{
		if(jqXHR.status == 403)
			custom_alert("Access Denied! No permission to edit.", "Problem");
	});
	saveColumnLabelAndWidth("", current_dg_field_name, $('#dnscol_label').val(), $('#dnscol_width').val(), true);
}

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

function updateSSLColumns(setdefault)
{
	var checkedIds = $("#ssltablecols :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=ssl_subgrid_columns";
	}
	else
		turl += "sdcolreset=ssl_subgrid_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=ssl_subgrid_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");
			sslgrid_columns_array = x2.colmodel;
			LoadSSLGrid(true);
		});
		
	});
	request.fail(function(jqXHR, textStatus) 
	{
		if(jqXHR.status == 403)
			custom_alert("Access Denied! No permission to edit.", "Problem");
	});
	saveColumnLabelAndWidth("", current_dg_field_name, $('#sslcol_label').val(), $('#sslcol_width').val(), true);
}

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

function reloadAboutTab()
{
	var gurl = "lib/php/ajax/appsetup.php?gai";
	$.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
		{
			$("#idversion").html(x.version);
			$("#idbuild").html(x.build);
			$("#idorderid").html(x.orderid == "" ? 'None' : x.orderid);
			$("#idorderdate").html(x.orderdate == "" ? 'None' : x.orderdate);
			$("#idlicensee").html(x.licensee);
			$("#idexpiry").html(x.expiry);
			$('#idlicensetype').html(x.edition);
			
			if (x.edition.toLowerCase().indexOf("demo license") == -1)
				$('#idevalexpiry').hide();
			
			if(x.edition == "Standard Edition")
			{
				$('#upgrade_button').attr('href', 'https://domainpunch.com/sed/buy-std-pro-upgrade.php');
				$('#upgrade_button').text('Upgrade To Pro Edition');
			}
			else if(x.edition == "Professional Edition")
			{
				$('#upgrade_button').hide();
				$('#remlicense_button').hide();
			}
			else
			{
				$('#upgrade_button').attr('href', 'https://domainpunch.com/sed/buy.php');
				$('#upgrade_button').text('Buy Now');
			}
				
		}
	}
	).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 onAfterAppSetupWindowPopup()
{
	$("#appsetup-error").html('');
	var gurl = "lib/php/ajax/appsetup.php?gba";
	$.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
		{
			$('#do_dns_record_lookup').prop('checked', x.do_dns_record_lookup == "1" ? true : false);
			$('#do_subdomain_ext_lookup').prop('checked', x.do_subdomain_ext_lookup == "1" ? true : false);
			$('#requeue_on_empty_whois').prop('checked', x.requeue_on_empty_whois == "1" ? true : false);
			$('#fix_host_domain_names').prop('checked', x.fix_host_domain_names == "1" ? true : false);
			$('#config_subdomain_entry').val(x.config_subdomain_entry);
			$('#default_sub_domains').val(x.default_sub_domains);
			$('#home_page_max_redirs').val(x.home_page_max_redirs);
			
			$('#cli_auth_key_code').val(x.cli_auth_key_code);
			$('#login_lockout_minutes').val(x.login_lockout_minutes);
			$('#max_login_attempts').val(x.max_login_attempts);
			$('#auth_timeout_minutes').val(x.auth_timeout_minutes);
			
			$('#home_screen_application').val(x.home_screen_application);
			$('#main_logo_image').val(x.main_logo_image);
			$('#custom_tools_file').val(x.custom_tools_file);
			
			$('#product_page_link').val(x.product_page_link);
			$('#support_page_link').val(x.support_page_link);
			$('#contact_page_link').val(x.contact_page_link);
			
			setLookupTypeCheckBoxList(x.default_lookup_types, 'default_lookup_types', 'dlt-');
			setLookupTypeCheckBoxList(x.high_preference_lookups, 'high_preference_lookups', 'hpl-');
			
			$('#email_from_address').val(x.email_from_address);
			$('#email_from_name').val(x.email_from_name);
			$('#email_reply_address').val(x.email_reply_address);
			$('#email_reply_name').val(x.email_reply_name);
			$('#email_send_method').val(x.email_send_method);
			
			$('#email_smtp_server').val(x.email_smtp_server);
			$('#email_smtp_secure').val(x.email_smtp_secure);
			$('#email_smtp_port').val(x.email_smtp_port);
			$('#email_smtp_user').val(x.email_smtp_user);
			
			$('#product_page_link').val(x.product_page_link);
			$('#support_page_link').val(x.support_page_link);
			$('#contact_page_link').val(x.contact_page_link);
			
			$('#auth_queue_processing').prop('checked', x.auth_queue_processing == "1" ? true : false);
			
			showOrHideSMTPSettings();
		}
	}
	).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 saveBrandingLogo()
{
	var nlogo = $('#main_logo_image').val();
	setMasterOptionAndReload('main_logo_image', nlogo);
}

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

function getLookupTypeCheckBoxList(cdiv, removetag)
{
	var selected = "";
	$('#' + cdiv + ' input:checked').each(function() 
	{
		var sid = $(this).attr('id');
		sid = sid.replace(removetag, "");
		if(selected != "")
			selected += ",";
		selected += sid;
	});
	return selected;
}

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

function setLookupTypeCheckBoxList(selected, cdiv, removetag)
{
	var seldata = selected + ",";
	$('#' + cdiv + ' :checkbox').each(function() 
	{
		var thisid = $(this).prop('id').replace(removetag, '');
		if(seldata.indexOf(thisid+',') >= 0)
			$(this).prop('checked', true);
		else
			$(this).prop('checked', false);
	});
}

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

function saveEmailSettings()
{
	var mkeys= "";
	var mvals = "";
	
	mkeys += "email_from_address,email_from_name,email_reply_address,email_reply_name,email_send_method";
	
	mvals += $('#email_from_address').val() + ",";
	mvals += $('#email_from_name').val()  + ",";
	mvals += $('#email_reply_address').val() + ",";
	mvals += $('#email_reply_name').val()  + ",";
	mvals += $('#email_send_method').val();
			
	if($('#email_send_method').val().toLowerCase() == "smtp")
	{
		mkeys += ",email_smtp_server,email_smtp_secure,email_smtp_port,email_smtp_user";
		mvals += ","
		mvals += $('#email_smtp_server').val()  + ",";
		mvals += $('#email_smtp_secure').val()  + ",";
		mvals += $('#email_smtp_port').val()  + ",";
		mvals += $('#email_smtp_user').val();
		var pass = $('#email_smtp_password').val();
		if(pass != "")
		{
			mkeys += ",email_smtp_password";
			mvals += "," + pass;
		}
	}
	
	setMasterOption(mkeys, mvals);
}

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

function onAfterCustomColumnsWindowPopup()
{
	$( "#deletecolumn" ).button();
	$( "#insertcolumn" ).button();
	
	$("#field_name").change(function() 
	{
		customFieldNameChanged();
	});
	
	$("#field_type").change(function() 
	{
		var ftype = $("#field_type").val().toLowerCase();
		if(ftype == "varchar")
		{
			$("#field_width").removeAttr("disabled");
			var fw = $("#field_width").val();
			if(fw == "")
				$("#field_width").val("128");
		}
		else
		{
			$("#field_width").attr("disabled",true);
		}
	});
	fillDataForCustomColumns();
}

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

function insertCustomColumn()
{
	var name = $('#field_name').val();
	var type = $('#field_type').val();
	var width = $('#field_width').val();
	
	var gurl = "lib/php/ajax/appsetup.php";
	var datastr = ASA_INSERT_CUSTOM_COLUMN + "=" + name + "&type=" + type + "&width" + width;
	$.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
		{
			fillDataForCustomColumns();
		}
	}
	).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 deleteCustomColumn()
{
	var name = $('#field_name').val();
	
	var gurl = "lib/php/ajax/appsetup.php";
	var datastr = ASA_DELETE_CUSTOM_COLUMN + "=" + name;
	$.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
		{
			$('#field_name').val('');
			fillDataForCustomColumns();
		}
	}
	).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 initOrphanDelete()
{
	$('.del-orphan').off( "click" );
	$('.edit-detail').off( "click" );
	$('.del-orphan').click(function(event)
	{
		var cpid = jQuery(this).attr("id");
		event.preventDefault();
		var colname = cpid.replace("del-orphan-", "");
		if(colname != "")
		{
			var msg = "Delete the column " + colname + "!, Are you sure?";
			$("<div></div>").html(msg).dialog({
				title: "Confirm Delete",
				resizable: false,
				modal: true,
				maxHeight: 400,
				dialogClass: 'dialogWithShadow customAlert',
				create: function( event, ui ) {themeCustomDialog();},
				buttons: {
					"OK": function() 
					{
						$( this ).dialog( "close" );
						deleteOrphanColumn(colname);
					},
					"Cancel": function() 
					{
						$( this ).dialog( "close" );
					}
				}
			});
		}
	});
	
	$('.edit-detail').click(function(event)
	{
		var cpid = jQuery(this).attr("id");
		event.preventDefault();
		var colname = cpid.replace("edit-detail-", "");
		if($('#popmenu').is(':visible')) 
			$('.panel-outer').css('right', 48);
		else
			$('.panel-outer').css('right', 0);
		$('#mpanel-bulkedit').show("drop",  {direction:'right'}, 200 );
		hideAllExcept('mpanel-bulkedit');
		onAfterBulkEditWindowPopup(colname);
	});
}

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

function deleteOrphanColumn(name)
{
	var gurl = "lib/php/ajax/appsetup.php";
	var datastr = ASA_DELETE_ORPHAN_COLUMN + "=" + name;
	$.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
		{
			scrollToCurrentRow();
		}
	}
	).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 fillDataForCustomColumns()
{
	positionCustomColumnsWindow();
	var gurl = "lib/php/ajax/appsetup.php?" + GET_ALL_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
		{
			$('#domaincolumns').html(x.columnlist);
			domain_columns = x.columns;
			custom_columns['fields'] = x.custominfo.fields;
			custom_columns['fields'] = custom_columns['fields'].map(function(elem) { return elem.toLowerCase(); }); 
			custom_columns['types'] = x.custominfo.types;
			custom_columns['widths'] = x.custominfo.widths;
			makeCustomFieldListSelectable();
		}
	}
	).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 makeCustomFieldListSelectable()
{
	$( "#domaincolumns" ).selectable(
	{
		stop: function() 
		{
			$('#domaincolumns li').each(function() {
				$(this).removeClass('ui-state-highlight');
			});
			$( ".ui-selected", this ).each(function() 
			{
				$(this).addClass('ui-state-highlight');
				$('#field_name').val($(this).text());
				var cindex = jQuery.inArray($(this).text().toLowerCase(),custom_columns['fields']);
				
				if(cindex >= 0 && cindex < custom_columns['types'].length)
				{
					$('#field_type').val(custom_columns['types'][cindex]);
					var width = custom_columns['widths'][cindex];
					if(width == "0")
						width = "";
					$('#field_width').val(width);
				}
				customFieldNameChanged();
			});
		},
		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 customFieldNameChanged()
{
	var fname = $('#field_name').val();
	var fwidth = $('#field_width').val();
	var ftype = $('#field_type').val();
	fname = fname.replace(/ /g, "_").toLowerCase();
	var found = false;
	var custom_field = false;
	if(jQuery.inArray(fname,custom_columns['fields']) != -1)
		custom_field = true;
	else if(jQuery.inArray(fname,domain_columns) != -1)
		found = true;
	if(custom_field && fname != "")
	{
		$("#field_type").attr("disabled",true);
		$("#field_width").attr("disabled",true);
		$( "#insertcolumn" ).button( "option", "disabled", true );
		$( "#deletecolumn" ).button( "option", "disabled", false );
	}
	else if(found || fname == "")
	{
		$("#field_type").attr("disabled",true);
		$("#field_width").attr("disabled",true);
		$( "#deletecolumn" ).button( "option", "disabled", true );
		$( "#insertcolumn" ).button( "option", "disabled", true );
	}
	else if(fname != "")
	{
		$("#field_type").attr("disabled",false);
		$("#field_width").attr("disabled",false);
		$( "#deletecolumn" ).button( "option", "disabled", true );
		$( "#insertcolumn" ).button( "option", "disabled", false );
		if(fwidth == "" && ftype == "varchar")
			$('#field_width').val("128");
	}
}

/////////////////////////////////////////////////////////////////////////////////////////
// Should be called just after the download window is popped up.

function onAfterDownloadWindowPopup()
{
	var rowKey = jQuery("#DomainTable").getGridParam("selarrrow"); 
	if(rowKey.length > 0)
	{
		$('#selectedrows').removeAttr('disabled');
		$('#selecteddomainnames').removeAttr('disabled');
		$('#selecteddnsrows').removeAttr('disabled');
		$('#selectedsslrows').removeAttr('disabled');
	}
	else
	{
		$('#selectedrows').attr('disabled', 'true'); 
		$('#selecteddomainnames').attr('disabled', 'true');  
		$('#selecteddnsrows').attr('disabled', 'true');  
		$('#selectedsslrows').attr('disabled', 'true');  
		$( "#allrows" ).prop( "checked", true );
	}
}

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

function saveOnOffSetting(okey)
{
	var ovalue = $('#'+okey).prop('checked') ? 1 : 0;
	setMasterOption(okey, ovalue);
}

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

function saveTextSetting(okey)
{
	var ovalue = $('#'+okey).val();
	setMasterOption(okey, ovalue);
}

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

function saveNumSetting(okey)
{
	var ovalue = $('#'+okey).val();
	ovalue = ovalue.replace(/\D/g,'');
	$('#'+okey).val(ovalue);
	setMasterOption(okey, ovalue);
}

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