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

var current_dg_field_name = "";
var custom_columns = {fields: null, types: null, widths: null};
var domain_columns = null;

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

var glb_menu_panels	= [ 
"uisetup", "columnsetup", "whoissetup", "navbarmenu", 
"mpanel-download", "mpanel-lookup", "mpanel-parsewhois",
"mpanel-regalias", "processqueue", "useradmin", "userselfadmin",
"mpanel-bulkedit", "mpanel-categorize", "appsetup", "userguide",
"customcolumns", "mpanel-addsubd", "dnscolsetup", "sslcolsetup"
];

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

$(function()
{
	initInterfaceDivs();
	initKeysAndMouse();
	
	initDomainLinksTab();
	initLookupQueueTab();
	
	initUISetup();
	initAddDomainsBox();
	initUploadDomainsBox();
	initAliasSetup();
	initWhoisSetupBox();
	initAppSetupWindow();
	
	initAboutTab();
});

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

function remove_license()
{
	setMasterOptionAndReload('license_key_code_v3', '');
}

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

function initAboutTab()
{
	reloadAboutTab();
	$('#remlicense_button').click(function(event)
	{
		alert_and_exec("<p>This will remove your existing license.</p><p>Do this only if you are removing the installation or if you are going to replace the current license code with a new one.</p><p>Are you sure?</p>", remove_license);
	});
}

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

function initKeysAndMouse()
{
	// 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();
		//}
		if (e.which === 8 && !$(e.target).is("input:not([readonly]):not([type=radio]):not([type=checkbox]), textarea, [contentEditable], [contentEditable=true]"))
		{
			e.preventDefault();
		}
	});
	
	// Init the mouse handling outside Navbar Menu
	$(document).mouseup(function (e)
	{
		/*
		for(index = 0; index < glb_menu_panels.length; ++index) 
		{
			container = $('#' + glb_menu_panels[index]);
			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(glb_menu_panels[index]);
			}
		}
		*/
		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');
		}
	});
	
	// 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]);
		}
	});
	
	// Sidebar menu
	initSidebarMenu();
	
	// The toolbar in the top nav
	initNavToolbar();
	
	// Main navigation popup menu
	initMainNavigationMenu();
}

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

function initSidebarMenu()
{
	$('.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(btnid == "mpanel-regalias")
				{
					if(stopIfNotEnoughDomainsSelected(true, "Select a single domain to specify the alias for that domain's registrar."))
					{
						var rowKey = jQuery("#DomainTable").getGridParam("selarrrow"); 
						var sid = rowKey[0];
						getRegistrarAlias(sid);
					}
					else
						return;
				}
				else if(btnid == "columnsetup")
					fillColumnNameRowsForColumnSetup(getCookie('display-group', "date_columns_array"));
				else if(btnid == "dnscolsetup")
					onAfterDNSColumnSetupWindowPopup();
				else if(btnid == "sslcolsetup")
					onAfterSSLColumnSetupWindowPopup();
					
				if(btnid.lastIndexOf("mpanel-", 0) === 0 && btnid != "mpanel-download")
					if(!stopIfNotEnoughDomainsSelected(false, "Select some domains first!"))
						return;
					
				if($('#popmenu').is(':visible')) 
					$('.panel-outer').css('right', 48);
				else
					$('.panel-outer').css('right', 0);
				
				$('#'+btnid).show("drop",  {direction:'right'}, 200 );
				
				hideAllExcept(btnid);
				if(btnid == "columnsetup")
					positionColumnSetupWindow();
				else if(btnid == "dnscolsetup")
					positionDNSColumnSetupWindow();
				else if(btnid == "sslcolsetup")
					positionSSLColumnSetupWindow();
				else if(btnid == "processqueue")
					onAfterProcessQueueWindowPopup();
				else if(btnid == "mpanel-categorize")
					onAfterCategorizeWindowPopup();
				else if(btnid == "useradmin")
					onAfterUserAdminWindowPopup();
				else if(btnid == "customcolumns")
					onAfterCustomColumnsWindowPopup();
				else if(btnid == "mpanel-bulkedit")
					onAfterBulkEditWindowPopup('');
				else if(btnid == "appsetup")
					onAfterAppSetupWindowPopup();
				else if(btnid == "mpanel-parsewhois")
					showSelectedDomains(4);
				else if(btnid == "mpanel-download")
					onAfterDownloadWindowPopup();
			}
		}
		else if(cpid == "adddomains")
		{
			showAddDomains();
		}
		else if(cpid == "deletedomains")
		{
			$('#del_DomainTable').click();
		}
		else if(cpid == "uploadcsv")
		{
			showUploadDomains();
		}
		else if(cpid == "subdmanager")
		{
			window.location = 'sdmgr.php';
		}
		else if(cpid == "showauditlog")
		{
			window.location = 'audit.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.", "");
		}
		else
			custom_alert(cpid, "Coming Soon!!!");
	});
}

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

function initMainNavigationMenu()
{
	$('.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 if(btnid == "appmenu")
			window.location = 'menu.php';
		else
			$("#btn_" + btnid).click();
	});
}

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

function initNavToolbar()
{
	$('.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 == "logout")
			window.location = 'main.php?logout';
		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");
		else if(btnid == "subdmanager")
			window.location = 'sdmgr.php';
		else if(btnid == "appmenu")
			window.location = 'menu.php';
		else
		{
			var dgroup = btnid.replace("_group", "_array");
			if(dgroup.indexOf("_array") > -1)
			{
				saveCookie("display-group", dgroup);
				LoadDomainDataGrid(false);
				var btnbgcolor = $('.ui-state-default').css('background-color');
				var btnhighlightcolor = $('.ui-state-highlight').css('background-color');
				$('.btn-navtb').css("background-color", btnbgcolor);
				$('#'+cpid).css("background-color", btnhighlightcolor);
			}
			else
				custom_alert(cpid, "Coming Soon");
		}
		hideAllExcept("dummy");
	});
}

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

function initDomainLinksTab()
{
	$('.toolsButton').button();
	$('.toolsButton').click(function()
	{
		var selids = jQuery("#DomainTable").getGridParam("selarrrow"); 
		if(selids.length == 1)
		{
			var domainname = jQuery("#DomainTable").getCell(selids[0], "domain"); 
			var tname = $(this).data('name');
			var turl = $(this).data('url');
			turl = turl.replace(/{{domain}}/g, domainname);
			window.open(turl);
		}
		else
			custom_alert("Please select a domain", "Problem");
	});
}

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

function initAppSetupWindow()
{
	$('#appsettingstab').tabs();
	
	$('#do_dns_record_lookup').click(function(event) {saveOnOffSetting('do_dns_record_lookup');});
	$('#requeue_on_empty_whois').click(function(event) {saveOnOffSetting('requeue_on_empty_whois');});
	$('#fix_host_domain_names').click(function(event) {saveOnOffSetting('fix_host_domain_names');});
	$('#do_subdomain_ext_lookup').click(function(event) {saveOnOffSetting('do_subdomain_ext_lookup');});
	
	$('#config_subdomain_entry-submit').click(function(event) {saveTextSetting('config_subdomain_entry');});
	$('#default_sub_domains-submit').click(function(event) {saveTextSetting('default_sub_domains');});
	$('#home_page_max_redirs-submit').click(function(event) {saveNumSetting('home_page_max_redirs');});
	
	$('#auth_timeout_minutes-submit').click(function(event) {saveNumSetting('auth_timeout_minutes');});
	$('#max_login_attempts-submit').click(function(event) {saveNumSetting('max_login_attempts');});
	$('#login_lockout_minutes-submit').click(function(event) {saveNumSetting('login_lockout_minutes');});
	$('#cli_auth_key_code-submit').click(function(event) {saveTextSetting('cli_auth_key_code');});
	$('#auth_queue_processing').click(function(event) {saveOnOffSetting('auth_queue_processing');});
	
	$('#home_screen_application').on('change',function() {saveTextSetting('home_screen_application');});
	$('#custom_tools_file-submit').click(function(event) {saveTextSetting('custom_tools_file');});
	$('#main_logo_image-submit').click(function(event) {saveBrandingLogo('main_logo_image');});
	
	initEnterKeyHandler('main_logo_image', 'main_logo_image-submit');
	initEnterKeyHandler('custom_tools_file', 'custom_tools_file-submit');
	initEnterKeyHandler('cli_auth_key_code', 'cli_auth_key_code-submit');
	initEnterKeyHandler('config_subdomain_entry', 'config_subdomain_entry-submit');
	initEnterKeyHandler('default_sub_domains', 'default_sub_domains-submit');
	initEnterKeyHandler('home_page_max_redirs', 'home_page_max_redirs-submit');
	initEnterKeyHandler('auth_timeout_minutes', 'auth_timeout_minutes-submit');
	initEnterKeyHandler('max_login_attempts', 'max_login_attempts-submit');
	initEnterKeyHandler('login_lockout_minutes', 'login_lockout_minutes-submit');
	initEnterKeyHandler('bulkedit-value', 'bulkedit-submit');
	
	$('#contact_page_link-submit').click(function(event) {saveTextSetting('contact_page_link');});
	$('#support_page_link-submit').click(function(event) {saveTextSetting('support_page_link');});
	$('#product_page_link-submit').click(function(event) {saveTextSetting('product_page_link');});
	initEnterKeyHandler('contact_page_link', 'contact_page_link-submit');
	initEnterKeyHandler('support_page_link', 'support_page_link-submit');
	initEnterKeyHandler('product_page_link', 'product_page_link-submit');
	
	$('#default_lookup_types input[type=checkbox]').change(function() 
	{ 
		var selected = getLookupTypeCheckBoxList('default_lookup_types', 'dlt-');
		setMasterOption('default_lookup_types', selected);
	});
	$('#high_preference_lookups input[type=checkbox]').change(function() 
	{ 
		var selected = getLookupTypeCheckBoxList('high_preference_lookups', 'hpl-');
		setMasterOption('high_preference_lookups', selected);
	});
	
	$('#email_send_method').on('change', function() 
	{
		showOrHideSMTPSettings();
	});
	
	$('#submitemailsetup').click(function(event) {saveEmailSettings();});
}

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

function showOrHideSMTPSettings()
{
	if($('#email_send_method').val().toLowerCase() == "smtp")
		$('.smtpsetup').show();
	else
		$('.smtpsetup').hide();
}

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

function initLookupQueueTab()
{
	updateLookupQueueTab();
	$('.btn-wipe').click(function(event) 
	{
		var cpid = jQuery(this).attr("id");
		event.preventDefault();
		var btnid = cpid.replace("luqw-", "");
		wipeQueue(btnid);
	});
	
	$('.btn-queue').click(function() 
	{
		var cpid = jQuery(this).attr("id");
		event.preventDefault();
		var btnid = cpid.replace("luqa-", "");
		addToQueue(btnid);
	});
}

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

function initAddDomainsBox()
{
	$('#dialog-add-domains').dialog
	({
		resizable: false,
		autoOpen: false,
		width: 'auto',
		modal: true,
		dialogClass: 'dialogWithShadow',
		buttons: {
			Clear: function() {
				clear_form_elements("#dialog-add-domains");
				$("#domainadddata").focus();
			},
			'OK': function() {
				
				var user_entry_data = "data=" + encodeURIComponent($('#domainadddata').val());
				var catid = getCookieInt('current_category', 0);
				if($('#catadd').is(':checked') == false && catid > 1)
					catid = 0;
				if($('#catempty').is(':checked') == true && catid > 1 && is_an_admin_user)
					empty_cat_and_add_domains(user_entry_data, catid);
				else
					add_domains(user_entry_data, catid);
				$(this).dialog('close');	
			},
			Cancel: function() {
				$(this).dialog('close');
			}
		}
	});
}

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

function initAliasSetup()
{
	initEnterKeyHandler('alias', 'setalias');
	
	$('#setalias').click(function(event)
	{
		var rowKey = jQuery("#DomainTable").getGridParam("selarrrow"); 
		if(rowKey.length == 1)
		{
			var sid = rowKey[0];
			var alias = $('#alias').val();
			setRegistrarAlias(sid, alias);
		}
	});
}

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

function initWhoisSetupBox()
{
	$('#whoissetuptab').tabs();
	initEnterKeyHandler('whoisdiag-tld', 'whoisdiag-tld-submit');
	initEnterKeyHandler('whoisdiag-server', 'whoisdiag-server-submit');
	$('#whoisdiag-tld-submit').click(function(event) {whoisSetupTLDCheck();});
	$('#whoisdiag-server-submit').click(function(event) {whoisSetupServerCheck();});
	$('#whoissetup-submit').click(function(event) {whoisSetupSubmit();});
	$('#whoissetup-xlate-submit').click(function(event) {whoisSetupXlateSubmit();});
	$('#whoissetup-resetlastconnect').click(function(event) {whoisSetupResetConnectTime();});
	$('#whoisdiag-serverandtld').click(function(event) {whoisSetupTLDAndServer();});
}

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